openxiangda-contracts 2.73.0 → 2.74.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,9 @@
1
- "use strict";var ca=Object.create;var en=Object.defineProperty;var la=Object.getOwnPropertyDescriptor;var ua=Object.getOwnPropertyNames;var fa=Object.getPrototypeOf,pa=Object.prototype.hasOwnProperty;var ma=(e,t)=>{for(var o in t)en(e,o,{get:t[o],enumerable:!0})},Ui=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ua(t))!pa.call(e,i)&&i!==o&&en(e,i,{get:()=>t[i],enumerable:!(n=la(t,i))||n.enumerable});return e};var _a=(e,t,o)=>(o=e!=null?ca(fa(e)):{},Ui(t||!e||!e.__esModule?en(o,"default",{value:e,enumerable:!0}):o,e)),ga=e=>Ui(en({},"__esModule",{value:!0}),e);var su={};ma(su,{AuthenticatedPublicReadContractError:()=>ut,DATA_AUDIT_METADATA_FIELDS:()=>ht,DATA_BUSINESS_COMMAND_INTENT_MAX_BYTES:()=>jp,DATA_BUSINESS_COMMAND_RESOLUTION_SCHEMA:()=>ea,DATA_BUSINESS_COMMAND_SCHEMA:()=>xl,DATA_EVENT_TYPES_V2:()=>Kn,DATA_FORM_DRAFT_MAX_BYTES:()=>ya,DATA_RESOURCE_MAX_FIELDS:()=>Ji,DATA_SUBTABLE_DEFAULT_TOTAL_ROWS:()=>nn,DATA_SUBTABLE_MAX_ROWS:()=>Le,DATA_SUBTABLE_MAX_TOTAL_ROWS:()=>Be,DATA_SYSTEM_SORT_FIELD_CODES:()=>tr,DATA_TRANSACTION_MAX_BYTES:()=>Ia,DATA_TRANSACTION_MAX_OPERATIONS:()=>po,DATA_TRANSACTION_RECORD_SET_MAX_RECORDS:()=>Mp,DATE_EVENT_RESERVED_DATA_FIELDS_V2:()=>tc,DEVELOPMENT_BACKEND_CONNECTION_TTL_SECONDS:()=>Qp,DEVELOPMENT_BACKEND_ENDPOINT_PATTERN:()=>Ql,DEVELOPMENT_BACKEND_FEATURE:()=>Yl,DEVELOPMENT_BACKEND_INVOCATION_FEATURE:()=>Zl,DEVELOPMENT_BACKEND_INVOCATION_MAX_REQUEST_BYTES:()=>Jp,DEVELOPMENT_BACKEND_INVOCATION_MAX_RESPONSE_BYTES:()=>Hp,DEVELOPMENT_BACKEND_INVOCATION_SCHEMA:()=>ra,DEVELOPMENT_BACKEND_MAX_INFLIGHT:()=>Zp,DEVELOPMENT_BACKEND_MAX_REQUEST_BYTES:()=>Xp,DEVELOPMENT_BACKEND_MAX_RESPONSE_BYTES:()=>Yp,DEVELOPMENT_BACKEND_SCHEMA:()=>Xl,DEVELOPMENT_CONFIGURATION_ENDPOINT:()=>ql,DEVELOPMENT_CONFIGURATION_FEATURE:()=>Gl,DEVELOPMENT_CONFIGURATION_MANIFEST_SCHEMA:()=>Wi,DEVELOPMENT_CONFIGURATION_SCHEMA:()=>oa,DateEventProjectionV2Error:()=>Ft,DevelopmentConfigurationContractError:()=>oo,ManagedConcurrencyContractError:()=>ct,NATIVE_ARTIFACT_CAPACITY_V2:()=>oe,NATIVE_CONFIGURATION_VALIDATOR_DIGEST:()=>ru,NATIVE_CONTRACT_CAPACITY_V2:()=>M,NATIVE_DATA_POLICY_EXPRESSION_MAX_CLAUSES:()=>Df,NATIVE_DATA_POLICY_EXPRESSION_MAX_DEPTH:()=>hf,NATIVE_DATA_POLICY_EXPRESSION_MAX_GROUP_ITEMS:()=>wf,NATIVE_DATA_POLICY_EXPRESSION_MAX_LEAVES:()=>Sf,NATIVE_DATA_POLICY_EXPRESSION_MAX_OCCURRENCES:()=>kf,NATIVE_DATA_QUERY_OPERATORS_V2:()=>ir,NATIVE_HIGH_DENSITY_ARTIFACT_CAPACITY_V2:()=>Ze,NATIVE_ROLE_MEMBERSHIP_BATCH_MAX_BYTES:()=>$p,NATIVE_ROLE_MEMBERSHIP_BATCH_MAX_ITEMS:()=>kp,NATIVE_UNIQUE_KEY_MAX_BYTES:()=>Mu,NATIVE_UNIQUE_KEY_NORMALIZERS:()=>Uo,NativeConfigurationCompilerError:()=>qn,NativeDataFieldContractV2Error:()=>ye,NativeDataPolicyExpressionV2Error:()=>Et,NativeDecimalLifecycleContractError:()=>qe,NativeEventActionContractError:()=>wn,NativeRoleMembershipBatchInputError:()=>eo,NativeScopeSourceFieldPathV2Error:()=>Tn,NativeUniqueKeyContractError:()=>ft,OPENXIANGDA_NATIVE_DATA_FIELD_TYPES_V2:()=>Qi,OPENXIANGDA_NATIVE_DATA_SURFACE_KEYS_V2:()=>Se,OPENXIANGDA_NATIVE_DRAFT_STATE_KEYS_V2:()=>gn,OPENXIANGDA_NATIVE_SYSTEM_FIELDS_V2:()=>un,OPENXIANGDA_NATIVE_SYSTEM_FIELD_MAP_V2:()=>Ge,USER_CANDIDATE_MAX_SELECTIONS:()=>lu,USER_CANDIDATE_SCOPE_FIELD_TYPES:()=>Ki,UserCandidateContractError:()=>Ve,WORKFLOW_APPROVAL_EMPTY_PROVIDERS:()=>ri,WORKFLOW_APPROVED_DELEGATION_MAX_BYTES:()=>mf,WORKFLOW_APPROVED_DELEGATION_MAX_REQUESTS:()=>pf,WORKFLOW_AUTOMATIC_CC_DEFAULT_RECIPIENTS:()=>Fr,WORKFLOW_AUTOMATIC_CC_MAX_RECIPIENTS:()=>xr,WORKFLOW_AUTOMATIC_CC_PROVIDERS:()=>jr,WORKFLOW_BUSINESS_STEP_EVENT:()=>pt,WORKFLOW_BUSINESS_STEP_EVENTS:()=>Ho,WORKFLOW_BUSINESS_STEP_FACTS_KEY:()=>Ld,WORKFLOW_BUSINESS_STEP_MAX_BYTES:()=>Sn,WORKFLOW_BUSINESS_STEP_MAX_RECEIPT_BYTES:()=>Sr,WORKFLOW_CONFIGURABLE_OPERATIONS:()=>Pn,WORKFLOW_CONFIGURABLE_PROVIDERS:()=>Vn,WORKFLOW_EVENT_TYPES_V2:()=>Gn,WORKFLOW_LAUNCH_MAX_INPUTS:()=>fo,WORKFLOW_LAUNCH_PREFLIGHT_PROVIDERS:()=>qr,WORKFLOW_REJECTION_NOTIFICATION_MAX_BYTES:()=>df,WORKFLOW_REJECTION_NOTIFICATION_SCHEMA:()=>Kr,WORKFLOW_ROLE_UNION_MAX_ROLES:()=>Zu,WORKFLOW_ROUTING_MAX_BYTES:()=>Of,WORKFLOW_ROUTING_MAX_MATCHED_RULES:()=>bf,WORKFLOW_ROUTING_MAX_RULES:()=>yf,WORKFLOW_STEP_DATA_COMMAND_SCHEMA:()=>kl,WORKFLOW_STEP_DATA_RESOLUTION_SCHEMA:()=>Ks,WORKFLOW_TASK_PAGE_DEFINITION_MAX_BYTES:()=>Xr,WORKFLOW_TASK_PAGE_MAX_BYTES:()=>jn,WORKFLOW_TASK_PAGE_MAX_FIELDS:()=>Yr,WORKFLOW_TASK_SUBTABLE_MAX_ROWS:()=>Ai,WORKFLOW_TASK_SUBTABLE_MAX_TOTAL_ROWS:()=>_i,WorkflowTaskPageError:()=>Oe,applyWorkflowTaskPageValues:()=>es,applyWorkflowTaskSubtableRows:()=>ic,assertDevelopmentConfigurationManifest:()=>ia,assertDevelopmentConfigurationResult:()=>Hl,assertNativeRoleMembershipBatchInput:()=>vl,assertWorkflowNativeStageGuard:()=>Sd,assertWorkflowNativeStagePolicy:()=>xo,assertWorkflowNativeStageSourceGuard:()=>Dd,assertWorkflowOwnedSubjectCreate:()=>Gt,assertWorkflowOwnedSubjectCreateResources:()=>Oi,canonicalDataBusinessIntent:()=>jl,compileNativeApplicationConfiguration:()=>jc,compileNativeEventAction:()=>Ko,compileNativeEventCapturePlansV2:()=>ks,compileRequiredPlatformCapabilitiesV3:()=>Ds,compileWorkflowBusinessStepHandlers:()=>Dn,createDevelopmentConfigurationManifest:()=>zl,dataOwnedRowLimit:()=>Tt,dateEventProjectionEnvelopeSchemaV2:()=>nc,dateEventProjectionFieldsV2:()=>mi,developmentBackendBase64Bytes:()=>sa,developmentBackendInvocationHeadersValid:()=>da,developmentBackendInvocationRequestValid:()=>iu,developmentBackendInvocationRevision:()=>tu,developmentBackendOperationMatches:()=>aa,developmentConfigurationKey:()=>Jl,evaluateWorkflowTaskPageExpression:()=>$e,formatWorkflowCompletionDeadline:()=>Jd,formatWorkflowExpression:()=>Vt,generatedCrudCapabilityOperations:()=>Ci,hasDataAuditReadPolicy:()=>Io,isDataAuditMetadataField:()=>rt,isDataOwnedRowLimit:()=>it,isDataSystemSortField:()=>yo,isDataTransactionActorAuthorityGuard:()=>Ul,isDataTransactionRecordSetMatchGuard:()=>Kl,isNativeDataQueryOperatorV2:()=>va,isNativeMultiValueFieldV2:()=>Rt,isWorkflowRejectionNotificationSnapshot:()=>Hd,matchesDataActorAuthorityMembership:()=>Ml,materializeNativeDataQueryPathTypesV2:()=>Cd,nativeDataPolicyExpressionLeavesV2:()=>zt,nativeDataPolicyExpressionToCnfV2:()=>Ri,nativeDataQueryPathPlanV2:()=>hd,nativeFieldAggregatePlanV2:()=>Ua,nativeFieldColumnDefinitionV2:()=>nd,nativeFieldDefaultSqlV2:()=>od,nativeFieldHasDefaultV2:()=>rd,nativeFieldIndexStatementsV2:()=>cd,nativeFieldRequiresCreateInputV2:()=>Ct,nativeFieldSequenceGrantStatementsV2:()=>dd,nativeFieldSequenceOwnershipStatementsV2:()=>ad,nativeFieldSequenceStatementsV2:()=>sd,nativeFieldSupportsFilterV2:()=>Ro,nativeFieldSupportsOperatorV2:()=>xa,nativeFieldSupportsSearchV2:()=>mn,nativeFieldSupportsSortV2:()=>at,nativeOperatorsForFieldV2:()=>To,nativePhysicalFieldV2:()=>mr,nativePhysicalFieldsV2:()=>td,nativePhysicalObjectNameV2:()=>ke,nativeScopeSourceFieldValueV2:()=>gd,nativeScopeSourceGrantPathSupportedV2:()=>Lo,nativeScopeSourceSubjectPathSupportedV2:()=>Rn,nativeSubtableConstraintStatementsV2:()=>ld,nativeUniqueKeysContractVersion:()=>Bo,nativeUniqueKeysJsonSchema:()=>$d,normalizeWorkflowOwnedSubjectCreate:()=>_c,parseDataBusinessCommandResolution:()=>Wl,parseDataFieldUserCandidates:()=>Nt,parseDecimalReservationLifecycle:()=>bn,parseNativeDataFieldsV2:()=>fn,parseNativeDataResourceInvariantsV2:()=>Eo,parseNativeUniqueKeys:()=>Mo,parseWorkflowStepDataResolution:()=>$l,projectDataResourceView:()=>na,projectNativeDataResourceViewV2:()=>En,projectWorkflowGraph:()=>Ud,projectWorkflowNodePolicy:()=>ii,quoteNativeIdentifierV2:()=>de,refreshWorkflowTaskPageFacts:()=>rc,requiresAggregateOwnedSubtableCapacity:()=>rn,requiresDateTimeMinutePrecision:()=>cn,requiresDevelopmentBackendCredential:()=>eu,requiresExtendedArtifactCapacity:()=>Jt,requiresExtendedConfigurationBytes:()=>Mn,requiresExtendedDeclarationCapacity:()=>Un,requiresExtendedFieldCapacity:()=>on,requiresExtendedOwnedSubtableCapacity:()=>sn,requiresHighDensityArtifactCapacity:()=>Ht,requiresOwnedSubtableMinimumRows:()=>ln,requiresUserCandidateLaunchScope:()=>tn,requiresWorkflowRoleInputSelection:()=>oi,requiresWorkflowRoleUnion:()=>ti,resolveNativeScopeSourceFieldPathV2:()=>lt,resolveWorkflowUserCandidates:()=>zi,selectWorkflowAssignmentRoutingRules:()=>pc,serializedDataBytes:()=>ba,userCandidateScopeValue:()=>Ea,validateAuthenticatedPublicRead:()=>jo,validateDecimalReservationLifecycles:()=>Po,validateManagedConcurrency:()=>Do,validateNativeDataDraftStateV2:()=>ho,validateNativeDataResourceReferencesV2:()=>Ao,validateNativeDataResourceSurfaceV2:()=>An,validateUserCandidateReferences:()=>lo,validateWorkflowAdministration:()=>Ln,validateWorkflowApprovalEmptyPolicy:()=>Fn,validateWorkflowApprovedDelegation:()=>fi,validateWorkflowAssignmentRoutingBindings:()=>yi,validateWorkflowAssignmentRoutingPolicy:()=>Kt,validateWorkflowAssignmentRoutingRules:()=>uc,validateWorkflowAutomaticCc:()=>$n,validateWorkflowBusinessStepHandlerContract:()=>xd,validateWorkflowBusinessStepRequest:()=>Fd,validateWorkflowBusinessStepResult:()=>$r,validateWorkflowBusinessStepSchema:()=>$t,validateWorkflowBusinessStepSubscriptions:()=>Xo,validateWorkflowBusinessSteps:()=>Pt,validateWorkflowCommandHandlers:()=>li,validateWorkflowCompletionDeadlines:()=>ai,validateWorkflowCorrections:()=>pi,validateWorkflowInitiatorApprovalPolicy:()=>_t,validateWorkflowInstanceCommandPolicies:()=>qo,validateWorkflowLaunchPreflight:()=>xn,validateWorkflowNodeConfigurationPatch:()=>qd,validateWorkflowReadability:()=>ei,validateWorkflowRejectionNotification:()=>ci,validateWorkflowRoleInputSelection:()=>ni,validateWorkflowRoleUnion:()=>Lt,validateWorkflowTaskPages:()=>Ut,validateWorkflowUserCandidateBindings:()=>uo,workflowApprovalCanSkip:()=>zd,workflowApprovedDelegationRequests:()=>Qd,workflowAssignmentRoutingFacts:()=>fc,workflowAssignmentRoutingPolicySchema:()=>lc,workflowAssignmentRoutingSemantic:()=>is,workflowBindingAllowsEmptyUsers:()=>si,workflowBindingRoleCodes:()=>Kd,workflowBusinessCommandInvocationSchema:()=>Yd,workflowBusinessStepFactSchema:()=>vt,workflowBusinessStepHandlerDigest:()=>Fl,workflowBusinessStepInput:()=>jd,workflowBusinessStepPath:()=>vr,workflowBusinessStepReceiptSignatureSuffix:()=>Ll,workflowBusinessStepValueMatches:()=>kt,workflowDelegationMutationRequestSchema:()=>Qs,workflowExpressionPaths:()=>Qo,workflowInitiatorApprovalCanComplete:()=>Md,workflowInstanceCommandDeadlineError:()=>Vd,workflowInstanceTerminateCapabilityAllowed:()=>vd,workflowInstanceWithdrawalReasonRequired:()=>Pd,workflowNativeStagePolicySchema:()=>kd,workflowNodeAllowedOperations:()=>gt,workflowOperationCommentRequired:()=>Wr,workflowOperationReasonRequired:()=>Ur,workflowOwnedSubjectCreateSchema:()=>mc,workflowPolicyTimestamp:()=>Go,workflowRoleCodesSchema:()=>Bd,workflowTaskPageFieldState:()=>Ei,workflowTaskPageReplayCoversInvalidation:()=>sc,workflowTaskSubtableRows:()=>oc,workflowVariableLabel:()=>Vr});module.exports=ga(su);var Mi=require("node:crypto");function Aa(e){if(!e||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function so(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)=>so(n,`${t}[${i}]`)).join(",")}]`;if(Aa(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)}:${so(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 X(e){return so(e,"$")}function Z(e){return(0,Mi.createHash)("sha256").update(X(e)).digest("hex")}var lu=200,Ki=["text.short","uuid","option.single","resource-ref.single"],ao=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,Gi=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,qi=new Set(["__proto__","prototype","constructor"]),co=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[Object.prototype,null].includes(Object.getPrototypeOf(e)),Bi=(e,t)=>Object.keys(e).every(o=>t.includes(o)),ot=(e,t)=>typeof e=="string"&&e.length>0&&e.trim()===e&&e.length<=t,Ve=class extends Error{constructor(o,n){super(`${o}: ${n}`);this.code=o;this.pointer=n}code;pointer};function ne(e,t){throw new Ve(e,t)}function Nt(e,t,o){if(e===void 0)return;["user.single","user.multiple"].includes(t)||ne("DATA_USER_CANDIDATES_FIELD_TYPE_INVALID",o),(!co(e)||!Bi(e,["kind","roleCode","scope","pageSize"])||e.kind!=="app-role"||!ot(e.roleCode,128)||!ao.test(String(e.roleCode)))&&ne("DATA_USER_CANDIDATES_SOURCE_INVALID",o),e.pageSize!==void 0&&(!Number.isSafeInteger(e.pageSize)||Number(e.pageSize)<1||Number(e.pageSize)>50)&&ne("DATA_USER_CANDIDATES_PAGE_SIZE_INVALID",`${o}/pageSize`);let n;if(e.scope!==void 0){let i=e.scope;(!co(i)||!Bi(i,["dimensionCode","operation","field","value","creation"])||!ot(i.dimensionCode,128)||!ao.test(String(i.dimensionCode))||!ot(i.operation,64)||!ao.test(String(i.operation))||Object.hasOwn(i,"field")===Object.hasOwn(i,"value"))&&ne("DATA_USER_CANDIDATES_SCOPE_INVALID",`${o}/scope`),i.creation!==void 0&&(i.creation!=="prospective"||!Object.hasOwn(i,"field"))&&ne("DATA_USER_CANDIDATES_SCOPE_INVALID",`${o}/scope/creation`),Object.hasOwn(i,"field")?((!ot(i.field,63)||!Gi.test(String(i.field))||qi.has(String(i.field)))&&ne("DATA_USER_CANDIDATES_SCOPE_FIELD_INVALID",`${o}/scope/field`),n={dimensionCode:String(i.dimensionCode),operation:String(i.operation),field:String(i.field),...i.creation==="prospective"?{creation:"prospective"}:{}}):(ot(i.value,255)||ne("DATA_USER_CANDIDATES_SCOPE_VALUE_INVALID",`${o}/scope/value`),n={dimensionCode:String(i.dimensionCode),operation:String(i.operation),value:String(i.value)})}return{kind:"app-role",roleCode:String(e.roleCode),...n?{scope:n}:{},...e.pageSize===void 0?{}:{pageSize:Number(e.pageSize)}}}function tn(e){return e.some(t=>t.schema.fields.some(o=>{let n=o.userCandidates?.scope;return n?.creation==="prospective"||!!(n?.field&&t.schema.fields.find(i=>i.code===n.field)?.type==="resource-ref.single")}))}function lo(e,t,o,n){for(let[i,r]of e.entries()){let d=`${n}/${i}/userCandidates`,s=Nt(r.userCandidates,r.type,d);if(s&&(t.has(s.roleCode)||ne("DATA_USER_CANDIDATES_ROLE_UNDECLARED",`${d}/roleCode`),s.scope&&!o.has(s.scope.dimensionCode)&&ne("DATA_USER_CANDIDATES_DIMENSION_UNDECLARED",`${d}/scope/dimensionCode`),s.scope?.field)){let a=e.find(c=>c.code===s.scope.field);(!a||!Ki.some(c=>c===a.type))&&ne("DATA_USER_CANDIDATES_SCOPE_FIELD_INVALID",`${d}/scope/field`)}}}function zi(e,t,o,n){let i=e.subject.factProjection,r=typeof t.inputPath=="string"&&Object.entries(i).some(([c,f])=>(t.inputPath===c||t.inputPath.startsWith(`${c}.`))&&o.get(f)?.userCandidates!==void 0);if(t.candidateField===void 0&&!r)return;(t.provider!=="form_field_users"||!t.candidateField||!Gi.test(t.candidateField)||qi.has(t.candidateField)||!t.inputPath||i[t.inputPath]!==t.candidateField)&&ne("WORKFLOW_USER_CANDIDATES_FIELD_BINDING_REQUIRED",n),(t.roleCode!==void 0||t.scope!==void 0||t.routing!==void 0)&&ne("WORKFLOW_USER_CANDIDATES_SOURCE_OVERRIDE_FORBIDDEN",n);let d=o.get(t.candidateField),s=d&&Nt(d.userCandidates,d.type,`${n}/candidateField`);s||ne("WORKFLOW_USER_CANDIDATES_FIELD_UNDECLARED",`${n}/candidateField`);let a;if(s.scope?.field){let c=Object.entries(i).filter(([,f])=>f===s.scope.field).map(([f])=>f);c.length!==1&&ne("WORKFLOW_USER_CANDIDATES_SCOPE_PROJECTION_REQUIRED",n),a=c[0]}return{fieldCode:d.code,inputPath:t.inputPath,source:s,...a?{scopeInputPath:a}:{}}}function uo(e,t,o,n,i=new Map){for(let[r,d]of Object.entries(t.bindings))zi(e,d,o,`${n}/${r}`);for(let[r,d]of Object.entries(e.taskPages||{})){let s=new Set(d.fields.filter(a=>a.readonly!==!0).map(a=>a.code));for(let a of d.fields){let c=o.get(a.code)?.userCandidates?.scope;if(s.has(a.code)&&c?.field&&s.has(c.field)&&ne("WORKFLOW_USER_CANDIDATES_SCOPE_WRITE_FORBIDDEN",`${n}/taskPages/${r}/${a.code}`),!s.has(a.code)||!a.subtable)continue;let f=o.get(a.code)?.subtable?.resourceCode,u=f?i.get(f):void 0;a.subtable.fields.some(p=>p.readonly!==!0&&u?.get(p.code)?.userCandidates)&&ne("WORKFLOW_USER_CANDIDATES_OWNED_FIELD_UNSUPPORTED",`${n}/taskPages/${r}/${a.code}`)}}}function Ea(e,t){if(!e.scope)return;let o=e.scope.field?t[e.scope.field]:e.scope.value,n=co(o)?o.value:o;return ot(n,255)||ne("DATA_USER_CANDIDATES_SCOPE_VALUE_REQUIRED",e.scope.field||"scope"),String(n)}var Ji=200,fo=205;function on(e,t=[]){return e.some(o=>o.schema.fields.length>100)||t.some(o=>Object.values(o.definition.taskPages||{}).some(n=>(n.fields?.length??0)>64)||[o.launch?.submission?.create,o.launch?.submission?.existing].some(n=>Object.keys(n?.inputs||{}).length>64))}var Le=500,nn=500,Be=1e3,po=2*Be+16,Ia=2*1024*1024,ya=2*1024*1024;function it(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=1&&e<=Be}function Tt(e){if(e.ownedRowLimit===void 0)return nn;if(!it(e.ownedRowLimit))throw new Error("NATIVE_DATA_OWNED_ROW_LIMIT_INVALID");return e.ownedRowLimit}function rn(e){return e.some(t=>(t.schema.ownedRowLimit??nn)>nn)}function sn(e){return e.some(t=>{let o=t.schema.fields.filter(n=>n.type==="subtable").map(n=>n.subtable?.maxRows??20);return o.some(n=>n>100)||o.reduce((n,i)=>n+i,0)>400})}function ba(e){try{return new TextEncoder().encode(JSON.stringify(e)).byteLength}catch{return 1/0}}var Zi=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,go=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Qi=["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"];function cn(e){return e.some(t=>t.schema.fields.some(o=>(o.type==="datetime"||o.type==="datetime-range")&&o.timePrecision==="minute"))}function ln(e){return e.some(t=>t.schema.fields.some(o=>o.type==="subtable"&&(o.subtable?.minRows??0)>0))}var Oa=new Set(Qi),er=new Set(["option.multiple","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","subtable"]),Hi=new Set(["option.single","option.multiple","cascade.single","cascade.multiple"]),Yi=new Set(["resource-ref.single","resource-ref.multiple"]),un=[{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}],Ge=new Map(un.map(e=>[e.code,e])),ye=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.name="NativeDataFieldContractV2Error"}code;pointer};function Rt(e){return er.has(e)}function Ct(e,t={}){return e.type!=="serial-number"&&t.system!==!0&&e.nullable===!1&&(!Rt(e.type)||t.requiredHint===!0)}function fn(e,t,o=500){Array.isArray(e)||k("NATIVE_ARRAY_REQUIRED",t),e.length===0&&k("NATIVE_DATA_FIELDS_REQUIRED",t),e.length>o&&k("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let n=new Set;return e.map((i,r)=>{let d=`${t}/${r}`,s=Ae(i,d);Ie(s,["code","type","nullable","indexed","options","source","userCandidates","maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","timePrecision","file","serial","subtable"],d);let a=be(s.code,`${d}/code`,63);Zi.test(a)||k("NATIVE_FIELD_CODE_INVALID",`${d}/code`),n.has(a)&&k("NATIVE_DATA_FIELD_DUPLICATE",`${d}/code`),n.add(a);let c=be(s.type,`${d}/type`,32);Oa.has(c)||k("NATIVE_DATA_FIELD_TYPE_INVALID",`${d}/type`);let f=c,u=_o(s.nullable,`${d}/nullable`),p=_o(s.indexed,`${d}/indexed`);u===!0&&er.has(f)&&k("NATIVE_DATA_MULTI_FIELD_NULLABLE_INVALID",`${d}/nullable`);let _=Ra(s.options,f,d),E=Ca(s.source,f,d),A=Nt(s.userCandidates,f,`${d}/userCandidates`),O=wa(s,f,d),b=_o(s.exactDecimal,`${d}/exactDecimal`);b!==void 0&&f!=="number.decimal"&&k("NATIVE_DATA_FIELD_EXACT_DECIMAL_TYPE_INVALID",`${d}/exactDecimal`);let g=Na(s.rangeBoundary,f,d),I=Sa(s.file,f,d),T=Da(s.serial,f,d),l=ka(s.subtable,f,d);return{code:a,type:f,...u===void 0?{}:{nullable:u},...p===void 0?{}:{indexed:p},..._?{options:_}:{},...E?{source:E}:{},...A?{userCandidates:A}:{},...O,...b===void 0?{}:{exactDecimal:b},...g?{rangeBoundary:g}:{},...I?{file:I}:{},...T?{serial:T}:{},...l?{subtable:l}:{}}})}function Na(e,t,o){let n=`${o}/rangeBoundary`;if(!(t==="date-range"||t==="datetime-range")){e!==void 0&&k("NATIVE_DATA_FIELD_RANGE_BOUNDARY_TYPE_INVALID",n);return}return e!=="closed"&&e!=="half-open"&&k("NATIVE_DATA_FIELD_RANGE_BOUNDARY_REQUIRED",n),e}function Ao(e,t){Array.isArray(e)||k("NATIVE_ARRAY_REQUIRED",t);let o=new Map;e.forEach((n,i)=>{let r=`${t}/${i}`,d=Ae(n,r),s=be(d.code,`${r}/code`,64);(!go.test(s)||o.has(s))&&k("NATIVE_RESOURCE_CODE_INVALID",`${r}/code`);let a=Ae(d.schema,`${r}/schema`);a.ownedRowLimit!==void 0&&!it(a.ownedRowLimit)&&k("NATIVE_DATA_OWNED_ROW_LIMIT_INVALID",`${r}/schema/ownedRowLimit`),o.set(s,{pointer:r,ownedRowLimit:Tt(a),fields:fn(a.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,a)=>s+(a.subtable?.maxRows??20),0)>i.ownedRowLimit&&k("NATIVE_DATA_FIELD_SUBTABLE_AGGREGATE_MAX_ROWS_EXCEEDED",`${i.pointer}/schema/fields`),i.fields.forEach((s,a)=>{let c=`${i.pointer}/schema/fields/${a}`;if(s.source&&Ta(s.source,r,o,`${c}/source`),s.subtable){let f=o.get(s.subtable.resourceCode);(!f||s.subtable.resourceCode===n)&&k("NATIVE_DATA_FIELD_SUBTABLE_TARGET_MISSING",`${c}/subtable/resourceCode`);let u=f.fields.find(_=>_.code===s.subtable?.foreignKey);(!u||u.type!=="uuid"||u.nullable!==!1)&&k("NATIVE_DATA_FIELD_SUBTABLE_FOREIGN_KEY_INVALID",`${c}/subtable/foreignKey`);let p=f.fields.find(_=>_.code===s.subtable?.orderField);(!p||p.type!=="number.integer"||p.nullable!==!1)&&k("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${c}/subtable/orderField`)}})}}function Eo(e,t,o){if(e===void 0)return[];(!Array.isArray(e)||e.length>20)&&k("NATIVE_DATA_RESOURCE_INVARIANTS_INVALID",o);let n=new Map(t.map(r=>[r.code,r])),i=new Set;return e.map((r,d)=>{let s=`${o}/${d}`,a=Ae(r,s);Ie(a,["code","message","expression"],s);let c=be(a.code,`${s}/code`,128);(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(c)||i.has(c))&&k("NATIVE_DATA_RESOURCE_INVARIANT_CODE_INVALID",`${s}/code`),i.add(c);let f=dn(a.message,`${s}/message`,500);f!==void 0&&f.length===0&&k("NATIVE_DATA_RESOURCE_INVARIANT_MESSAGE_INVALID",`${s}/message`);let u=Ae(a.expression,`${s}/expression`);if(u.kind==="nonBlankTextWhenOption"){Ie(u,["kind","optionField","optionValue","textField"],`${s}/expression`);let g=Re(u.optionField,`${s}/expression/optionField`),I=Re(u.textField,`${s}/expression/textField`),T=be(u.optionValue,`${s}/expression/optionValue`,128),l=n.get(g),y=n.get(I);return(!l||!y)&&k("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_UNKNOWN",`${s}/expression`),(l.type!=="option.single"||!["text.short","text.long"].includes(y.type)||!l.options?.some(R=>R.value===T))&&k("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${s}/expression`),{code:c,...f===void 0?{}:{message:f},expression:{kind:"nonBlankTextWhenOption",optionField:g,optionValue:T,textField:I}}}Ie(u,["leftField","operator","rightField"],`${s}/expression`);let p=Re(u.leftField,`${s}/expression/leftField`),_=Re(u.rightField,`${s}/expression/rightField`),E=n.get(p),A=n.get(_);(!E||!A)&&k("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_UNKNOWN",`${s}/expression`),E.type===A.type||["number.integer","number.decimal"].includes(E.type)&&["number.integer","number.decimal"].includes(A.type)||k("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${s}/expression`);let b=String(u.operator);return["eq","neq","gt","gte","lt","lte"].includes(b)||k("NATIVE_DATA_RESOURCE_INVARIANT_OPERATOR_INVALID",`${s}/expression/operator`),!["eq","neq"].includes(b)&&!["number.integer","number.decimal","date","time","datetime","text.short","text.long","text.rich","serial-number","uuid"].includes(E.type)&&k("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${s}/expression`),{code:c,...f===void 0?{}:{message:f},expression:{leftField:p,operator:b,rightField:_}}})}function Ta(e,t,o,n){let i=o.get(e.resourceCode);i||k("NATIVE_DATA_FIELD_SOURCE_TARGET_MISSING",`${n}/resourceCode`);let r=new Map(i.fields.map(s=>[s.code,s])),d=r.get(e.labelField);(!d||!["text.short","text.long"].includes(d.type))&&k("NATIVE_DATA_FIELD_SOURCE_LABEL_INVALID",`${n}/labelField`);for(let s of["searchFields","descriptionFields","snapshotFields"])for(let a of e[s]||[])r.has(a)||k("NATIVE_DATA_FIELD_SOURCE_FIELD_MISSING",`${n}/${s}`);for(let[s,a]of(e.filters||[]).entries())r.has(a.field)||k("NATIVE_DATA_FIELD_SOURCE_FILTER_FIELD_MISSING",`${n}/filters/${s}/field`),"binding"in a&&!t.has(a.binding.field)&&k("NATIVE_DATA_FIELD_SOURCE_BINDING_FIELD_MISSING",`${n}/filters/${s}/binding/field`)}function Ra(e,t,o){let n=`${o}/options`;if(e===void 0){Hi.has(t)&&k("NATIVE_DATA_FIELD_OPTIONS_REQUIRED",n);return}(!Hi.has(t)||!Array.isArray(e))&&k("NATIVE_DATA_FIELD_OPTIONS_TYPE_INVALID",n),(e.length<1||e.length>100)&&k("NATIVE_DATA_FIELD_OPTIONS_INVALID",n);let i=0,r=(d,s,a)=>{a>5&&k("NATIVE_DATA_FIELD_OPTIONS_DEPTH_EXCEEDED",s);let c=new Set;return d.map((f,u)=>{i+=1,i>1e3&&k("NATIVE_DATA_FIELD_OPTIONS_COUNT_EXCEEDED",n);let p=`${s}/${u}`,_=Ae(f,p);Ie(_,["label","value","description","color","children"],p);let E=be(_.label,`${p}/label`,500),A=be(_.value,`${p}/value`,500);c.has(A)&&k("NATIVE_DATA_FIELD_OPTION_VALUE_DUPLICATE",`${p}/value`),c.add(A);let O=dn(_.description,`${p}/description`,2e3),b=dn(_.color,`${p}/color`,64),g;return _.children!==void 0&&((!t.startsWith("cascade.")||!Array.isArray(_.children))&&k("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${p}/children`),(_.children.length<1||_.children.length>100)&&k("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${p}/children`),g=r(_.children,`${p}/children`,a+1)),{label:E,value:A,...O===void 0?{}:{description:O},...b===void 0?{}:{color:b},...g?{children:g}:{}}})};return r(e,n,1)}function Ca(e,t,o){let n=`${o}/source`;if(e===void 0){Yi.has(t)&&k("NATIVE_DATA_FIELD_SOURCE_REQUIRED",n);return}Yi.has(t)||k("NATIVE_DATA_FIELD_SOURCE_TYPE_INVALID",n);let i=Ae(e,n);Ie(i,["kind","resourceCode","labelField","searchFields","descriptionFields","snapshotFields","filters","pageSize","loadMode","clearOnBindingChange"],n),i.kind!=="resource"&&k("NATIVE_DATA_FIELD_SOURCE_KIND_INVALID",`${n}/kind`);let r=be(i.resourceCode,`${n}/resourceCode`,64);go.test(r)||k("NATIVE_RESOURCE_CODE_INVALID",`${n}/resourceCode`);let d=Re(i.labelField,`${n}/labelField`),s=mo(i.searchFields,`${n}/searchFields`,10),a=mo(i.descriptionFields,`${n}/descriptionFields`,10),c=mo(i.snapshotFields,`${n}/snapshotFields`,50),f=Ke(i.pageSize,`${n}/pageSize`,1,100),u;i.loadMode!==void 0&&(["search","all"].includes(String(i.loadMode))||k("NATIVE_DATA_FIELD_SOURCE_LOAD_MODE_INVALID",`${n}/loadMode`),u=i.loadMode);let p=ha(i.filters,`${n}/filters`);return i.clearOnBindingChange!==void 0&&typeof i.clearOnBindingChange!="boolean"&&k("NATIVE_DATA_FIELD_SOURCE_BINDING_RESET_INVALID",`${n}/clearOnBindingChange`),{kind:"resource",resourceCode:r,labelField:d,...s?{searchFields:s}:{},...a?{descriptionFields:a}:{},...c?{snapshotFields:c}:{},...p?{filters:p}:{},...f===void 0?{}:{pageSize:f},...u?{loadMode:u}:{},...i.clearOnBindingChange===void 0?{}:{clearOnBindingChange:i.clearOnBindingChange}}}function ha(e,t){if(e!==void 0)return(!Array.isArray(e)||e.length>20)&&k("NATIVE_DATA_FIELD_SOURCE_FILTERS_INVALID",t),e.map((o,n)=>{let i=`${t}/${n}`,r=Ae(o,i),d=Object.prototype.hasOwnProperty.call(r,"value"),s=Object.prototype.hasOwnProperty.call(r,"binding");Ie(r,d?["field","operator","value"]:["field","operator","binding"],i),d===s&&k("NATIVE_DATA_FIELD_SOURCE_FILTER_VALUE_INVALID",i);let a=Re(r.field,`${i}/field`);["eq","in"].includes(String(r.operator))||k("NATIVE_DATA_FIELD_SOURCE_FILTER_OPERATOR_INVALID",`${i}/operator`);let c=r.operator;if(d)return{field:a,operator:c,value:r.value};let f=Ae(r.binding,`${i}/binding`);return Ie(f,["kind","field"],`${i}/binding`),f.kind!=="field"&&k("NATIVE_DATA_FIELD_SOURCE_BINDING_KIND_INVALID",`${i}/binding/kind`),{field:a,operator:c,binding:{kind:"field",field:Re(f.field,`${i}/binding/field`)}}})}function wa(e,t,o){let n={};if(e.maxLength!==void 0&&(["text.short","text.long","text.rich"].includes(t)||k("NATIVE_DATA_FIELD_MAX_LENGTH_TYPE_INVALID",`${o}/maxLength`),n.maxLength=an(e.maxLength,`${o}/maxLength`,1,1e6)),(e.precision!==void 0||e.scale!==void 0)&&((t!=="number.decimal"||e.precision===void 0)&&k("NATIVE_DATA_FIELD_DECIMAL_CONFIG_INVALID",o),n.precision=an(e.precision,`${o}/precision`,1,1e3),n.scale=e.scale===void 0?0:an(e.scale,`${o}/scale`,0,n.precision)),e.min!==void 0||e.max!==void 0){["number.integer","number.decimal"].includes(t)||k("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_TYPE_INVALID",o);let i=Xi(e.min,`${o}/min`),r=Xi(e.max,`${o}/max`);t==="number.integer"&&[i,r].some(d=>d!==void 0&&!Number.isSafeInteger(d))&&k("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",o),i!==void 0&&r!==void 0&&i>r&&k("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",o),i!==void 0&&(n.min=i),r!==void 0&&(n.max=r)}return e.timePrecision!==void 0&&((!["time","datetime","datetime-range"].includes(t)||!["minute","second"].includes(e.timePrecision))&&k("NATIVE_DATA_FIELD_TIME_PRECISION_INVALID",`${o}/timePrecision`),n.timePrecision=e.timePrecision),n}function Sa(e,t,o){if(e===void 0)return;let n=`${o}/file`;["file","image","signature"].includes(t)||k("NATIVE_DATA_FIELD_FILE_TYPE_INVALID",n);let i=Ae(e,n);Ie(i,["maxCount","maxSizeMb","accept"],n);let r=Ke(i.maxCount,`${n}/maxCount`,1,100);t==="signature"&&r!==void 0&&r!==1&&k("NATIVE_DATA_FIELD_SIGNATURE_COUNT_INVALID",`${n}/maxCount`);let d=Ke(i.maxSizeMb,`${n}/maxSizeMb`,1,1024),s;return i.accept!==void 0&&((!Array.isArray(i.accept)||i.accept.length>50)&&k("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${n}/accept`),s=i.accept.map((a,c)=>be(a,`${n}/accept/${c}`,255)),new Set(s).size!==s.length&&k("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${n}/accept`)),{...r===void 0?{}:{maxCount:r},...d===void 0?{}:{maxSizeMb:d},...s===void 0?{}:{accept:s}}}function Da(e,t,o){let n=`${o}/serial`;if(e===void 0){t==="serial-number"&&k("NATIVE_DATA_FIELD_SERIAL_REQUIRED",n);return}t!=="serial-number"&&k("NATIVE_DATA_FIELD_SERIAL_TYPE_INVALID",n);let i=Ae(e,n);Ie(i,["prefix","digits","start"],n);let r=dn(i.prefix,`${n}/prefix`,64),d=Ke(i.digits,`${n}/digits`,1,32),s=Ke(i.start,`${n}/start`,0,Number.MAX_SAFE_INTEGER);return{...r===void 0?{}:{prefix:r},...d===void 0?{}:{digits:d},...s===void 0?{}:{start:s}}}function ka(e,t,o){let n=`${o}/subtable`;if(e===void 0){t==="subtable"&&k("NATIVE_DATA_FIELD_SUBTABLE_REQUIRED",n);return}t!=="subtable"&&k("NATIVE_DATA_FIELD_SUBTABLE_TYPE_INVALID",n);let i=Ae(e,n);Ie(i,["resourceCode","foreignKey","orderField","minRows","maxRows"],n);let r=be(i.resourceCode,`${n}/resourceCode`,64);go.test(r)||k("NATIVE_RESOURCE_CODE_INVALID",`${n}/resourceCode`);let d=Re(i.foreignKey,`${n}/foreignKey`),s=Re(i.orderField,`${n}/orderField`);s===d&&k("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${n}/orderField`);let a=Ke(i.maxRows,`${n}/maxRows`,1,Le),c=Ke(i.minRows,`${n}/minRows`,0,Le);return(c??0)>(a??20)&&k("NATIVE_DATA_FIELD_SUBTABLE_MIN_ROWS_INVALID",`${n}/minRows`),{resourceCode:r,foreignKey:d,orderField:s,...c===void 0?{}:{minRows:c},...a===void 0?{}:{maxRows:a}}}function mo(e,t,o){if(e===void 0)return;(!Array.isArray(e)||e.length>o)&&k("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t);let n=e.map((i,r)=>Re(i,`${t}/${r}`));return new Set(n).size!==n.length&&k("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t),n}function Re(e,t){let o=be(e,t,63);return Zi.test(o)||k("NATIVE_FIELD_CODE_INVALID",t),o}function Ae(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&k("NATIVE_OBJECT_REQUIRED",t),e}function Ie(e,t,o){let n=new Set(t);for(let i of Object.keys(e))n.has(i)||k("NATIVE_PROPERTY_UNKNOWN",`${o}/${i}`)}function be(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&k("NATIVE_STRING_INVALID",t),e}function dn(e,t,o){if(e!==void 0)return(typeof e!="string"||e.length>o)&&k("NATIVE_STRING_INVALID",t),e}function _o(e,t){if(e!==void 0)return typeof e!="boolean"&&k("NATIVE_BOOLEAN_REQUIRED",t),e}function Ke(e,t,o,n){if(e!==void 0)return an(e,t,o,n)}function Xi(e,t){if(e!==void 0)return(typeof e!="number"||!Number.isFinite(e))&&k("NATIVE_NUMBER_REQUIRED",t),e}function an(e,t,o,n){return(!Number.isSafeInteger(e)||Number(e)<o||Number(e)>n)&&k("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function k(e,t){throw new ye(e,t)}var ht=["created_by","updated_by","created_at","updated_at"];function rt(e){return ht.includes(e)}function Io(e){return ht.some(t=>Object.prototype.hasOwnProperty.call(e.fieldPolicies||{},t))}var tr=un.map(e=>e.code);function yo(e){return tr.includes(e)}var ir=["eq","neq","gt","gte","lt","lte","contains","startsWith","endsWith","in","between","has","hasAny","hasAll","overlaps","containedBy","jsonContains","isEmpty","isNotEmpty"],$a=new Set(ir);function va(e){return $a.has(String(e))}var bo=["eq","neq","contains","startsWith","endsWith","in","isEmpty","isNotEmpty"],wt=["eq","neq","gt","gte","lt","lte","between","in","isEmpty"],Pa=["eq","neq","in","isEmpty"],pn=["eq","neq","in","isEmpty","isNotEmpty"],st=["has","hasAny","hasAll","isEmpty","isNotEmpty"],nr=["overlaps","contains","containedBy","isEmpty"],Oo=["jsonContains","isEmpty","isNotEmpty"],No=["isEmpty","isNotEmpty"],Va={"text.short":bo,"text.long":bo,"text.rich":bo,"number.integer":wt,"number.decimal":wt,boolean:Pa,date:wt,time:wt,datetime:wt,"date-range":nr,"datetime-range":nr,"option.single":pn,"option.multiple":st,"cascade.single":st,"cascade.multiple":st,"user.single":pn,"user.multiple":st,"department.single":pn,"department.multiple":st,"resource-ref.single":pn,"resource-ref.multiple":st,file:No,image:No,signature:No,address:Oo,location:Oo,uuid:["eq","neq","in","isEmpty"],json:Oo,"serial-number":["eq","neq","in","contains","startsWith"],subtable:[]},La=new Set(["text.short","text.long","text.rich","option.single","user.single","department.single","resource-ref.single","serial-number"]),Fa=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","signature","address","location","json","subtable"]);function To(e){return Va[e]}function xa(e,t){return To(e).includes(t)}function mn(e){return La.has(e)}function at(e){return!Fa.has(e)}function Ro(e){return To(e).length>0}var or=new Set(["number.integer","number.decimal"]),rr=new Set(["text.short","text.long","number.integer","number.decimal","date","time","datetime","serial-number"]),ja=new Set([...rr,"boolean","uuid"]),Wa=new Set(["option.single","user.single","department.single","resource-ref.single"]);function Ua(e,t){return t==="sum"||t==="avg"?or.has(e)?{valueExpression:"column",numericResult:!0}:null:t==="min"||t==="max"?rr.has(e)?{valueExpression:"column",numericResult:or.has(e)}:null:Wa.has(e)?{valueExpression:"snapshot-value",numericResult:!0}:ja.has(e)?{valueExpression:"column",numericResult:!0}:null}var gn=["version","maxBytes","fields"];function ho(e,t){if(e===void 0)return;let o=Co(e,t);sr(o,gn,t);let n=_n(o.version,`${t}/version`,1,1e6),i=_n(o.maxBytes,`${t}/maxBytes`,2,196608);(!n||!i)&&le("NATIVE_DATA_DRAFT_STATE_SCHEMA_INVALID",t);let r=Co(o.fields,`${t}/fields`),d=Object.entries(r);(!d.length||d.length>50)&&le("NATIVE_DATA_DRAFT_STATE_FIELDS_INVALID",`${t}/fields`);for(let[s,a]of d){let c=`${t}/fields/${s}`;/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(s)||le("NATIVE_DATA_DRAFT_STATE_FIELD_CODE_INVALID",c);let f=Co(a,c),u=ar(f.type,`${c}/type`,32),p=u==="string"?["type","required","maxLength","enum"]:u==="json.object"?["type","required","maxBytes"]:["type","required"];if(["string","number","integer","boolean","json.object"].includes(u)||le("NATIVE_DATA_DRAFT_STATE_FIELD_TYPE_INVALID",`${c}/type`),sr(f,p,c),Ba(f.required,`${c}/required`),u==="string"){let _=_n(f.maxLength,`${c}/maxLength`,1,196608);_||le("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",c),f.enum!==void 0&&Ma(f.enum,`${c}/enum`,100,!1).some(A=>A.length>_)&&le("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",`${c}/enum`)}else if(u==="json.object"){let _=_n(f.maxBytes,`${c}/maxBytes`,2,65536);(!_||_>i)&&le("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",c)}}}function Ma(e,t,o,n){(!Array.isArray(e)||!n&&e.length===0||e.length>o)&&le("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t);let i=e.map((r,d)=>ar(r,`${t}/${d}`,255));return new Set(i).size!==i.length&&le("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t),i}function Co(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&le("NATIVE_OBJECT_REQUIRED",t),e}function sr(e,t,o){let n=new Set(t);for(let i of Object.keys(e))n.has(i)||le("NATIVE_PROPERTY_UNKNOWN",`${o}/${i}`)}function ar(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&le("NATIVE_STRING_INVALID",t),e}function Ba(e,t){e!==void 0&&typeof e!="boolean"&&le("NATIVE_BOOLEAN_REQUIRED",t)}function _n(e,t,o,n){return(!Number.isSafeInteger(e)||Number(e)<o||Number(e)>n)&&le("NATIVE_INTEGER_INVALID",t),Number(e)}function le(e,t){throw new ye(e,t)}var Ka=500,Se={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","exactDecimal","min","max","rangeBoundary","maxCount","maxSizeMb","accept","options","list","searchable","sortable","source","userCandidates","timePrecision","serial","subtable"],list:["actions","fieldOrder","defaultPageSize","searchableFields","filterFields","defaultSort"],defaultSort:["field","order"],form:["layout","fieldOrder","draftState"],detail:["layout","fieldOrder"],layout:["layout","fieldOrder","draftState"],draftState:gn,mobile:["enabled"]},Ga={"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 An(e,t,o){if(e===void 0)return;let n=ae(e,o);Ce(n,Se.surface,o);let i=n.mutationOwner===void 0?"native":De(n.mutationOwner,`${o}/mutationOwner`,16);["native","action","readonly","workflow","queued-command"].includes(i)||W("NATIVE_DATA_SURFACE_MUTATION_OWNER_INVALID",`${o}/mutationOwner`);let r=n.generated===void 0?{}:ae(n.generated,`${o}/generated`);Ce(r,Se.generated,`${o}/generated`);for(let a of Se.generated)So(r[a],`${o}/generated/${a}`);if(i!=="native")for(let a of["create","update","delete"])r[a]===!0&&W("NATIVE_DATA_SURFACE_MUTATION_OWNER_CONFLICT",`${o}/generated/${a}`);let d=new Map(t.map(a=>[a.code,a])),s=ae(n.fields,`${o}/fields`);for(let a of Object.keys(s))d.has(a)||W("NATIVE_DATA_SURFACE_FIELD_MISSING",`${o}/fields/${a}`);for(let a of t)Object.prototype.hasOwnProperty.call(s,a.code)||W("NATIVE_DATA_SURFACE_FIELD_REQUIRED",`${o}/fields/${a.code}`),za(s[a.code],a,`${o}/fields/${a.code}`);for(let a of["create","update"]){let c=r[a]??i==="native",f=t.some(u=>{let p=ae(s[u.code],`${o}/fields/${u.code}`);return cr(u,p,a)});c&&!f&&W("NATIVE_DATA_SURFACE_WRITABLE_FIELDS_REQUIRED",`${o}/generated/${a}`)}if(Ja(n.list,d,`${o}/list`),dr(n.form,d,`${o}/form`,"form"),dr(n.detail,d,`${o}/detail`,"detail"),n.mobile!==void 0){let a=ae(n.mobile,`${o}/mobile`);Ce(a,Se.mobile,`${o}/mobile`),So(a.enabled,`${o}/mobile/enabled`)}qa(n,t,o)}function En(e,t){let o=e.views?.find(i=>i.code===t);o||W("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 d={...r};delete d.section;let s=n.get(i);return[i,{...d,...s?{section:s}:{},list:o.list.fieldOrder.includes(i)}]}))}}function qa(e,t,o){if(e.views===void 0)return;(!Array.isArray(e.views)||e.views.length>20)&&W("NATIVE_DATA_VIEWS_LIMIT_INVALID",`${o}/views`);let n=new Set;e.views.forEach((i,r)=>{let d=`${o}/views/${r}`,s=ae(i,d);Ce(s,["code","name","generated","list","form","detail","mobile","sections"],d);let a=De(s.code,`${d}/code`,64);(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(a)||n.has(a))&&W("NATIVE_DATA_VIEW_CODE_INVALID",`${d}/code`),n.add(a),De(s.name,`${d}/name`,255),ae(s.generated,`${d}/generated`),ae(s.mobile,`${d}/mobile`);for(let f of["list","detail","create","update","delete"])typeof s.generated[f]!="boolean"&&W("NATIVE_DATA_VIEW_OPERATION_INVALID",`${d}/generated/${f}`);typeof s.mobile.enabled!="boolean"&&W("NATIVE_DATA_VIEW_MOBILE_INVALID",`${d}/mobile/enabled`);for(let f of["list","form","detail"]){let u=ae(s[f],`${d}/${f}`),p=dt(u.fieldOrder,`${d}/${f}/fieldOrder`,500,!0);for(let _ of p){let E=e.fields[_];(!E||(E.hidden??E.system)===!0)&&W("NATIVE_DATA_VIEW_FIELD_INVALID",`${d}/${f}/fieldOrder`)}}if(s.sections!==void 0){(!Array.isArray(s.sections)||s.sections.length>100)&&W("NATIVE_DATA_VIEW_SECTIONS_INVALID",`${d}/sections`);let f=new Set;s.sections.forEach((u,p)=>{let _=`${d}/sections/${p}`,E=ae(u,_);Ce(E,["title","fields"],_),De(E.title,`${_}/title`,255);for(let A of dt(E.fields,`${_}/fields`,100,!0)){let O=e.fields[A];(!O||(O.hidden??O.system)===!0||f.has(A))&&W("NATIVE_DATA_VIEW_FIELD_INVALID",`${_}/fields`),f.add(A)}})}let c=En(e,a);if(An(c,t,d),s.generated.create!==!1&&(e.mutationOwner||"native")==="native")for(let f of t)Ct(f,e.fields[f.code])&&cr(f,e.fields[f.code],"create")&&!s.form.fieldOrder.includes(f.code)&&W("NATIVE_DATA_VIEW_CREATE_REQUIRED_FIELD_MISSING",`${d}/form/fieldOrder`)})}function cr(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 za(e,t,o){let n=ae(e,o);Ce(n,Se.field,o),De(n.label,`${o}/label`,500),n.type!==t.type&&W("NATIVE_DATA_SURFACE_FIELD_TYPE_MISMATCH",`${o}/type`);let i=De(n.widget,`${o}/widget`,64);Ga[t.type].includes(i)||W("NATIVE_DATA_SURFACE_WIDGET_INCOMPATIBLE",`${o}/widget`),Xa(n.section,`${o}/section`,255);for(let r of["requiredHint","system","hidden","list","searchable","sortable"])So(n[r],`${o}/${r}`);n.searchable===!0&&!mn(t.type)&&W("NATIVE_DATA_SURFACE_SEARCH_UNSUPPORTED",`${o}/searchable`),n.sortable===!0&&!at(t.type)&&W("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${o}/sortable`);for(let r of["readCapabilities","createCapabilities","updateCapabilities"])dt(n[r],`${o}/${r}`,100,!0);if(n.maxCount!==void 0&&(!Number.isSafeInteger(n.maxCount)||Number(n.maxCount)<1||Number(n.maxCount)>100)&&W("NATIVE_DATA_SURFACE_MAX_COUNT_INVALID",`${o}/maxCount`),n.maxSizeMb!==void 0&&(!Number.isSafeInteger(n.maxSizeMb)||Number(n.maxSizeMb)<1||Number(n.maxSizeMb)>1024)&&W("NATIVE_DATA_SURFACE_MAX_SIZE_INVALID",`${o}/maxSizeMb`),n.accept!==void 0){let r=Array.isArray(n.accept)?n.accept:[n.accept];dt(r,`${o}/accept`,50,!1)}for(let r of["maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","options","source","userCandidates","timePrecision","serial","subtable"])Ha(n,t,r,o);Ya(n,t,o)}function Ja(e,t,o){if(e===void 0)return;let n=ae(e,o);if(Ce(n,Se.list,o),n.actions!==void 0){let i=ae(n.actions,`${o}/actions`);Ce(i,["import","export"],`${o}/actions`);for(let r of["import","export"])i[r]!==void 0&&typeof i[r]!="boolean"&&W("NATIVE_DATA_SURFACE_LIST_ACTION_INVALID",`${o}/actions/${r}`)}if(n.fieldOrder!==void 0)for(let i of dt(n.fieldOrder,`${o}/fieldOrder`,500,!0))t.has(i)||W("NATIVE_DATA_SURFACE_LIST_FIELD_INVALID",`${o}/fieldOrder`);n.defaultPageSize!==void 0&&(!Number.isSafeInteger(n.defaultPageSize)||Number(n.defaultPageSize)<1||Number(n.defaultPageSize)>200)&&W("NATIVE_DATA_SURFACE_PAGE_SIZE_INVALID",`${o}/defaultPageSize`);for(let[i,r]of[["searchableFields",mn],["filterFields",Ro]]){if(n[i]===void 0)continue;let d=dt(n[i],`${o}/${i}`,100,!0);for(let s of d){let a=t.get(s);(!a||!r(a.type))&&W("NATIVE_DATA_SURFACE_LIST_FIELD_INVALID",`${o}/${i}`)}}if(n.defaultSort!==void 0){let i=ae(n.defaultSort,`${o}/defaultSort`);Ce(i,Se.defaultSort,`${o}/defaultSort`);let r=De(i.field,`${o}/defaultSort/field`,63),d=t.get(r);!yo(r)&&(!d||!at(d.type))&&W("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${o}/defaultSort/field`),i.order!==void 0&&!["asc","desc"].includes(i.order)&&W("NATIVE_DATA_SURFACE_SORT_ORDER_INVALID",`${o}/defaultSort/order`)}}function dr(e,t,o,n){if(e===void 0)return;let i=ae(e,o);if(Ce(i,Se[n],o),i.layout!==void 0&&!["flat","sections"].includes(i.layout)&&W("NATIVE_DATA_SURFACE_LAYOUT_INVALID",`${o}/layout`),i.fieldOrder!==void 0){let r=`${o}/fieldOrder`;(!Array.isArray(i.fieldOrder)||i.fieldOrder.length>t.size||i.fieldOrder.length>Ka)&&W("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",r);let d=i.fieldOrder.map((s,a)=>De(s,`${r}/${a}`,63));new Set(d).size!==d.length&&W("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",r),d.forEach((s,a)=>{t.has(s)||W("NATIVE_DATA_SURFACE_FIELD_ORDER_FIELD_MISSING",`${r}/${a}`)})}n==="form"&&ho(i.draftState,`${o}/draftState`)}function Ha(e,t,o,n){e[o]===void 0&&t[o]===void 0||((e[o]===void 0||t[o]===void 0)&&W("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${n}/${o}`),X(e[o])!==X(t[o])&&W("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${n}/${o}`))}function Ya(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:wo(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)&&W("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${r}`);let d=r==="accept"?wo(i[r]):i[r],s=r==="accept"?wo(n[r]):n[r];X(d)!==X(s)&&W("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${r}`)}}function wo(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 dt(e,t,o,n){(!Array.isArray(e)||!n&&e.length===0||e.length>o)&&W("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t);let i=e.map((r,d)=>De(r,`${t}/${d}`,255));return new Set(i).size!==i.length&&W("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t),i}function ae(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&W("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)||W("NATIVE_PROPERTY_UNKNOWN",`${o}/${i}`)}function De(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&W("NATIVE_STRING_INVALID",t),e}function Xa(e,t,o){e!==void 0&&(typeof e!="string"||e.length>o)&&W("NATIVE_STRING_INVALID",t)}function So(e,t){e!==void 0&&typeof e!="boolean"&&W("NATIVE_BOOLEAN_REQUIRED",t)}function W(e,t){throw new ye(e,t)}var ct=class extends Error{constructor(o,n){super(`${o}: ${n}`);this.pointer=o;this.reason=n}pointer;reason;code="NATIVE_MANAGED_CONCURRENCY_INVALID"};function Do(e,t,o){if(e===void 0)return;let n=(g,I)=>{throw new ct(g,I)},i=(g,I,T)=>((!g||typeof g!="object"||Array.isArray(g)||Object.keys(g).some(l=>!T.includes(l)))&&n(I,"object contains unsupported properties"),g),r=(g,I,T,l)=>{(!Number.isSafeInteger(g)||g<I||g>T)&&n(l,`expected integer ${I}..${T}`)},d=(g,I)=>{(typeof g!="string"||!/^[a-z][a-z0-9_-]{0,63}$/.test(g))&&n(I,"invalid code")},s=(g,I,T)=>((!Array.isArray(g)||g.length>I)&&n(T,"array exceeds bound"),g),a=(g,I)=>{let T=t.find(l=>l.code===g);return T||n(I,"unknown resource"),T},c=(g,I,T)=>{let l=g.schema.fields.find(y=>y.code===I);return!l&&I!=="id"&&n(T,"unknown field"),l},f=(g,I,T=!1)=>{i(g,I,Object.keys(g||{})),Object.keys(g).length>8&&n(I,"at most eight parameters");for(let[l,y]of Object.entries(g))if(d(l,I),i(y,I,["type","values","minimum","maximum","minLength","maxLength"]),y.type==="uuid")Object.keys(y).length!==1&&n(I,"uuid has no options");else if(T&&y.type==="boolean")i(y,I,["type"]);else if(T&&y.type==="string"&&y.values===void 0)i(y,I,["type","minLength","maxLength"]),r(y.maxLength,1,256,I),y.minLength!==void 0&&r(y.minLength,0,y.maxLength,I);else if(y.type==="string"){i(y,I,["type","values"]);let R=s(y.values,100,I);(!R.length||R.some(h=>typeof h!="string"||h.length>128)||new Set(R).size!==R.length)&&n(I,"finite string values required")}else y.type==="integer"?(i(y,I,["type","minimum","maximum"]),r(y.minimum,0,1e6,I),r(y.maximum,y.minimum,y.minimum+1e3,I)):n(I,"unsupported parameter type")},u=(g,I,T,l=!1)=>{i(g,T,["from","key","value"]),!(g.from==="input"&&Object.keys(g).length===2&&Object.hasOwn(I,g.key))&&((g.from==="actor"||l&&g.from==="allocation")&&Object.keys(g).length===1||g.from==="literal"&&Object.keys(g).length===2&&Object.hasOwn(g,"value")&&(g.value===null||["string","boolean"].includes(typeof g.value)||typeof g.value=="number"&&Number.isFinite(g.value))&&JSON.stringify(g.value).length<=512||n(T,"invalid binding"))},p=(g,I,T)=>{u(g,I,T),!(g.from==="input"&&I[g.key].type==="uuid")&&(g.from==="literal"&&typeof g.value=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(g.value)||n(T,"record and allocation identifiers require a UUID binding"))},_=(g,I,T)=>{u(g,I,T),!(g.from==="input"&&I[g.key].type==="integer"&&I[g.key].minimum>=1)&&(g.from==="literal"&&Number.isSafeInteger(g.value)&&g.value>=1||n(T,"expectedRevision requires a positive integer binding"))},E="/data/concurrency";JSON.stringify(e).length>131072&&n(E,"declaration exceeds 128 KiB");let A=i(e,E,["version","admission","reads","quotas","commands"]);A.version!==1&&n(E,"unsupported version"),i(A.admission,E,["perSecond","burst","maxInFlight"]),r(A.admission.perSecond,1,1e3,E),r(A.admission.burst,1,1e3,E),r(A.admission.maxInFlight,1,1e3,E);let O=(g,I)=>{let T=new Set;for(let l of g)d(l?.code,I),T.has(l.code)&&n(I,"duplicate code"),T.add(l.code)};O(s(A.reads,32,E),E),O(s(A.quotas,16,E),E),O(s(A.commands,32,E),E);for(let g of A.reads){let I=`${E}/reads/${g.code}`;i(g,I,["code","resourceCode","parameters","select","where","limit","scope","freshSeconds","staleSeconds","maxKeys","sourcePerSecond","dependencies"]);let T=a(g.resourceCode,I);f(g.parameters,I),["subject","application"].includes(g.scope)||n(I,"invalid cache scope"),g.scope==="application"&&T.dataPolicyCode&&n(I,"shared cache cannot bypass a row policy");let l=s(g.select,32,I);l.length||n(I,"select required"),l.forEach(R=>c(T,R,I));let y=s(g.dependencies,64,I);y.forEach(R=>c(T,R,I));for(let R of s(g.where||[],8,I))i(R,I,["field","value"]),c(T,R.field,I),u(R.value,g.parameters,I),g.scope==="application"&&R.value.from==="actor"&&n(I,"actor requires subject cache"),y.includes(R.field)||n(I,"filter dependency missing");l.some(R=>!y.includes(R))&&n(I,"selected field dependency missing"),r(g.limit,1,100,I),r(g.freshSeconds,1,300,I),r(g.staleSeconds,0,300,I),r(g.maxKeys,1,1e4,I),r(g.sourcePerSecond,1,20,I)}for(let g of A.quotas){let I=`${E}/quotas/${g.code}`;i(g,I,["code","sourceResource","capacityField","allocationResource","allocationField","reservationSeconds"]);let T=a(g.sourceResource,I),l=a(g.allocationResource,I);c(T,g.capacityField,I)?.type!=="number.integer"&&n(I,"capacity must be an integer"),(c(l,g.allocationField,I)?.type!=="uuid"||c(l,g.allocationField,I)?.nullable!==!1)&&n(I,"allocation reference must be a uuid"),l.surface?.mutationOwner!=="queued-command"&&n(I,"allocation model must be command owned"),g.reservationSeconds!==void 0&&r(g.reservationSeconds,10,86400,I)}new Set(A.quotas.map(g=>g.allocationResource)).size!==A.quotas.length&&n(E,"an allocation model has exactly one pool owner");for(let g of A.commands){let I=`${E}/commands/${g.code}`;i(g,I,["code","mode","intake","execution","capability","parameters","resourceKey","admission","deadlineSeconds","guards","operations","quota"]),g.mode!==void 0&&!["permit","durable"].includes(g.mode)&&n(I,"unsupported mode");let T=g.mode==="durable";if(f(g.parameters,I,T),u(g.resourceKey,g.parameters,I),o.some(l=>l.code===g.capability)||n(I,"command capability must be declared"),i(g.admission,I,["perSecond","burst","maxInFlight","maxQueue","maxWaitSeconds","permitSeconds"]),r(g.admission.perSecond,1,A.admission.perSecond,I),r(g.admission.burst,1,A.admission.burst,I),r(g.admission.maxInFlight,1,A.admission.maxInFlight,I),r(g.admission.maxQueue,1,1e4,I),r(g.admission.maxWaitSeconds,1,3600,I),(!T||g.admission.permitSeconds!==void 0)&&r(g.admission.permitSeconds,5,60,I),r(g.deadlineSeconds,10,3600,I),T){(g.operations!==void 0||g.guards!==void 0||g.quota!==void 0)&&n(I,"backend-plan does not accept static operations, guards or quota"),i(g.intake,I,["perSecond","burst","maxInFlight"]);for(let R of["perSecond","burst","maxInFlight"])r(g.intake[R],1,1e3,I);let l=i(g.execution,I,["kind","handlerCode","timeoutMs","resources","directory"]);l.kind!=="backend-plan"&&n(I,"durable requires backend-plan"),d(l.handlerCode,I),r(l.timeoutMs,100,3e4,I);let y=s(l.resources,32,I);y.length||n(I,"execution resources required"),new Set(y.map(R=>R.resourceCode)).size!==y.length&&n(I,"duplicate execution resource");for(let R of y){i(R,I,["resourceCode","readFields","writeOperations","writeFields"]);let h=a(R.resourceCode,I);for(let w of["readFields","writeFields"]){let j=s(R[w],64,I);new Set(j).size!==j.length&&n(I,"duplicate field"),j.forEach(L=>{w==="readFields"&&Ge.has(L)||c(h,L,I)})}let $=s(R.writeOperations,3,I);(new Set($).size!==$.length||$.some(w=>!["create","update","increment"].includes(w)))&&n(I,"unsupported execution operation"),R.writeFields.some(w=>["id","revision","created_by","updated_by","created_at","updated_at"].includes(w))&&n(I,"record metadata is platform owned"),!$.length&&R.writeFields.length&&n(I,"write fields require an operation"),$.length&&!R.writeFields.length&&n(I,"write operations require fields"),A.quotas.some(w=>w.allocationResource===R.resourceCode)&&$.length&&n(I,"allocation references remain owned by their pool command")}if(l.directory!==void 0){i(l.directory,I,["mode","fields"]),l.directory.mode!=="current-initiator"&&n(I,"only current initiator allowed");let R=s(l.directory.fields,5,I);(!R.length||new Set(R).size!==R.length||R.some(h=>!["displayName","employeeNumber","primaryDepartment","departments","phone"].includes(h)))&&n(I,"unsupported directory fields")}continue}(g.execution!==void 0||g.intake!==void 0)&&n(I,"execution and intake require durable mode");for(let l of s(g.guards||[],8,I)){i(l,I,["resourceCode","id","conditions"]);let y=a(l.resourceCode,I);p(l.id,g.parameters,I);for(let R of s(l.conditions,16,I)){i(R,I,["kind","field","operator","value"]);let h=c(y,R.field,I);["eq","neq","lt","lte","gt","gte"].includes(R.operator)||n(I,"unsupported guard"),R.kind==="database-now"?(h?.type!=="datetime"||!["lt","lte","gt","gte"].includes(R.operator)||R.value!==void 0)&&n(I,"database-now requires datetime and an ordering operator"):(R.kind!==void 0&&R.kind!=="value"&&n(I,"unsupported condition kind"),u(R.value,g.parameters,I))}}for(let l of s(g.operations,8,I)){i(l,I,["operation","resourceCode","id","expectedRevision","data"]);let y=a(l.resourceCode,I);y.surface?.mutationOwner!=="queued-command"&&n(I,"command mutations require command owned models");let R=A.quotas.find(h=>h.allocationResource===l.resourceCode);R&&(l.operation==="create"?g.quota?.action!=="allocate"||g.quota.pool!==R.code:Object.hasOwn(l.data||{},R.allocationField))&&n(I,"allocation references are owned by their pool command"),["create","update"].includes(l.operation)||n(I,"unsupported operation"),l.operation==="update"?(p(l.id,g.parameters,I),_(l.expectedRevision,g.parameters,I)):(l.id!==void 0||l.expectedRevision!==void 0)&&n(I,"create has no caller supplied id/revision"),i(l.data,I,Object.keys(l.data||{})),Object.keys(l.data).length>32&&n(I,"too many fields");for(let[h,$]of Object.entries(l.data))h==="id"&&n(I,"record identifiers are platform owned"),c(y,h,I),u($,g.parameters,I,g.quota?.action==="allocate")}if(g.quota){let l=i(g.quota,I,["pool","action","units","mode","allocation"]),y=A.quotas.find(R=>R.code===l.pool);y||n(I,"unknown quota pool"),p(g.resourceKey,g.parameters,I),l.action==="allocate"?(i(l,I,["pool","action","units","mode"]),r(l.units,1,1e3,I),(!["committed","reserved"].includes(l.mode)||l.mode==="reserved"&&!y.reservationSeconds)&&n(I,"invalid allocation mode"),(g.operations.length!==1||g.operations[0].operation!=="create"||g.operations[0].resourceCode!==y.allocationResource||g.operations[0].data[y.allocationField]?.from!=="allocation")&&n(I,"allocation must atomically create its bound business record")):["confirm","release"].includes(l.action)?(i(l,I,["pool","action","allocation"]),p(l.allocation,g.parameters,I),g.operations.length&&n(I,"lifecycle owns allocation state; business reference remains immutable")):n(I,"invalid quota action")}else g.operations.length||n(I,"operations required")}let b=A.commands.filter(g=>g.mode==="durable").map(g=>g.execution.handlerCode);return new Set(b).size!==b.length&&n(E,"handler code must be unique"),JSON.parse(JSON.stringify(A))}var qe=class extends Error{constructor(o,n){super(`\u91D1\u989D\u751F\u547D\u5468\u671F\u58F0\u660E\u65E0\u6548\uFF1A${n}\uFF08${o}\uFF09`);this.pointer=o;this.reason=n}pointer;reason;code="NATIVE_DECIMAL_LIFECYCLE_INVALID"},vo=["parentTransitions","childTransitions","fulfilledChildStatuses","lockedParentStatuses"],lr=["amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode","parentRelationValue","childRelationValue"],yn=e=>!!(e&&typeof e=="object"&&!Array.isArray(e)),In=e=>Array.isArray(e)?e.filter(yn):[],he=(e,t)=>{throw new qe(e,t)},ko=e=>typeof e=="string"&&/^[A-Za-z0-9._:-]{1,128}$/.test(e),$o=(e,t)=>e<t?-1:e>t?1:0;function bn(e,t="/decimalReservationLifecycle"){if(e===void 0)return;if(!yn(e)||Object.keys(e).some(i=>!vo.includes(i))||vo.some(i=>!Object.prototype.hasOwnProperty.call(e,i)))return he(t,"\u5FC5\u987B\u5B8C\u6574\u58F0\u660E\u56DB\u9879\u89C4\u5219\uFF0C\u4E0D\u80FD\u5305\u542B\u672A\u77E5\u5C5E\u6027");let o=i=>{let r=e[i];if(!Array.isArray(r)||r.length>64)return he(`${t}/${i}`,"\u72B6\u6001\u8FB9\u6700\u591A 64 \u6761");let d=new Set;return r.map((s,a)=>{let c=`${t}/${i}/${a}`;if(!yn(s)||Object.keys(s).some(u=>u!=="from"&&u!=="to")||!ko(s.from)||!ko(s.to)||s.from===s.to)return he(c,"\u72B6\u6001\u8FB9\u5FC5\u987B\u5305\u542B\u4E0D\u540C\u7684\u6709\u6548 from/to");let f=JSON.stringify([s.from,s.to]);return d.has(f)?he(c,"\u72B6\u6001\u8FB9\u4E0D\u80FD\u91CD\u590D"):(d.add(f),{from:s.from,to:s.to})}).sort((s,a)=>$o(s.from,a.from)||$o(s.to,a.to))},n=i=>{let r=e[i];return!Array.isArray(r)||r.length<1||r.length>16||r.some(d=>!ko(d))||new Set(r).size!==r.length?he(`${t}/${i}`,"\u72B6\u6001\u96C6\u5408\u5FC5\u987B\u5305\u542B 1 \u5230 16 \u4E2A\u4E0D\u91CD\u590D\u7684\u6709\u6548\u72B6\u6001"):[...r].sort($o)};return{parentTransitions:o("parentTransitions"),childTransitions:o("childTransitions"),fulfilledChildStatuses:n("fulfilledChildStatuses"),lockedParentStatuses:n("lockedParentStatuses")}}function Po(e,t,o="/config/data/resources"){In(e).forEach((n,i)=>{let r=`${o}/${i}/decimalReservationLifecycle`,d=bn(n.decimalReservationLifecycle,r);if(!d)return;let s=In(t).map(u=>u.platformAccess?.decimalReservation).filter(u=>yn(u)&&u.resourceCode===n.code),a=s.find(u=>u.mode==="reserve");if(!a)return he(r,"\u9700\u8981\u540C\u8D44\u6E90\u5DF2\u58F0\u660E\u7684 reserve \u52A8\u4F5C\u6620\u5C04");if(lr.some(u=>typeof a[u]!="string")||s.some(u=>lr.some(p=>u[p]!==a[p])))return he(r,"\u540C\u8D44\u6E90\u989D\u5EA6\u52A8\u4F5C\u7684\u5B57\u6BB5\u6620\u5C04\u5FC5\u987B\u4E00\u81F4");let c=In(n.schema?.fields).find(u=>u.code===a.statusFieldCode);if(c?.type!=="option.single")return he(r,"\u989D\u5EA6\u72B6\u6001\u5B57\u6BB5\u5FC5\u987B\u4E3A option.single");let f=new Set(In(c.options).map(u=>u.value));for(let u of vo)if((u==="parentTransitions"||u==="childTransitions"?d[u].flatMap(_=>[_.from,_.to]):d[u]).some(_=>!f.has(_)))return he(`${r}/${u}`,"\u72B6\u6001\u5FC5\u987B\u6765\u81EA\u989D\u5EA6\u72B6\u6001\u5B57\u6BB5\u7684\u9009\u9879");if(s.some(u=>u.mode==="reserve"&&Array.isArray(u.eligibleParentStatuses)&&u.eligibleParentStatuses.some(p=>d.lockedParentStatuses.includes(String(p)))))return he(`${r}/lockedParentStatuses`,"\u9501\u5B9A\u7236\u72B6\u6001\u4E0D\u80FD\u5141\u8BB8\u65B0\u9884\u7559")})}var fr=require("crypto");var Vo=new Set(["option.single","user.single","department.single","resource-ref.single"]),Za=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","address","location","json"]),pr=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image"]),Qa=new Set(["option.single","user.single","department.single","resource-ref.single","signature","address","location"]),ed=new Set([...Vo,...pr,"signature","address","location","json"]);function td(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=>mr(n,o.has(n.code))).sort((n,i)=>n.code.localeCompare(i.code))}function mr(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:fd(e),index:ud(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 nd(e,t){if(t.type==="subtable")return null;let o=de(t.code),n=_r(e,t),i=[n?` DEFAULT ${n}`:"",pd(o,t),id(o,t)].join("");return`${o} ${t.storage}${i}`}function od(e,t){return _r(e,t)}function id(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 rd(e){return e.type==="serial-number"||Rt(e.type)&&e.type!=="subtable"}function sd(e,t){return t.filter(o=>o.type==="serial-number").map(o=>{let n=Nn(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 ad(e,t){let o=On(e);return t.filter(n=>n.type==="serial-number").map(n=>`ALTER SEQUENCE ${Nn(e,n.code)} OWNED BY ${o}.${de(n.code)}`)}function dd(e,t){return t.filter(o=>o.type==="serial-number").map(o=>`GRANT USAGE, SELECT ON SEQUENCE ${Nn(e,o.code)} TO "openxiangda_data_api"`)}function cd(e,t){let o=On(e),n=[];for(let i of t){if(i.type==="subtable")continue;let r=de(i.code),d=de(ke("idx",e,i.code,i.index));switch(i.index){case"btree":n.push(`CREATE INDEX IF NOT EXISTS ${d} ON ${o} (${r})`);break;case"btree-snapshot-expressions":{let s=de(ke("idx",e,i.code,"snapshot-value")),a=de(ke("idx",e,i.code,"snapshot-label"));n.push(`CREATE INDEX IF NOT EXISTS ${s} ON ${o} ((${r} ->> 'value'))`,`CREATE INDEX IF NOT EXISTS ${a} ON ${o} ((${r} ->> 'label'))`);break}case"gin-jsonb-path":n.push(`CREATE INDEX IF NOT EXISTS ${d} ON ${o} USING GIN (${r} jsonb_path_ops)`);break;case"gist-range":n.push(`CREATE INDEX IF NOT EXISTS ${d} ON ${o} USING GIST (${r})`);break;case"gin-trigram":{let s=Vo.has(i.type)?`((${r} ->> 'label')) gin_trgm_ops`:`${r} gin_trgm_ops`;n.push(`CREATE INDEX IF NOT EXISTS ${d} ON ${o} USING GIN (${s})`);break}case"none":break}if(i.type==="serial-number"){let s=de(ke("uidx",e,i.code,"serial"));n.push(`CREATE UNIQUE INDEX IF NOT EXISTS ${s} ON ${o} (${r})`)}}return n}function ld(e,t,o,n){let i=On(e),r=On(t),d=de(ke("uidx",e,"environment_id","subtable-parent")),s=de(ke("idx",t,o,n,"subtable-child")),a=de(ke("fk",t,o,e)),c=de(o),f=de(n);return[`CREATE UNIQUE INDEX IF NOT EXISTS ${d} ON ${i} ("tenant_id", "app_code", "environment_key", "id")`,`CREATE INDEX IF NOT EXISTS ${s} ON ${r} ("tenant_id", "app_code", "environment_key", ${c}, ${f}, "id")`,`DO $native_subtable$ BEGIN
2
- ALTER TABLE ${r}
1
+ "use strict";var ga=Object.create;var nn=Object.defineProperty;var Aa=Object.getOwnPropertyDescriptor;var Ea=Object.getOwnPropertyNames;var Ia=Object.getPrototypeOf,ya=Object.prototype.hasOwnProperty;var ba=(e,t)=>{for(var o in t)nn(e,o,{get:t[o],enumerable:!0})},Gr=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Ea(t))!ya.call(e,r)&&r!==o&&nn(e,r,{get:()=>t[r],enumerable:!(n=Aa(t,r))||n.enumerable});return e};var Oa=(e,t,o)=>(o=e!=null?ga(Ia(e)):{},Gr(t||!e||!e.__esModule?nn(o,"default",{value:e,enumerable:!0}):o,e)),Na=e=>Gr(nn({},"__esModule",{value:!0}),e);var mu={};ba(mu,{AuthenticatedPublicReadContractError:()=>mt,DATA_AUDIT_METADATA_FIELDS:()=>St,DATA_BUSINESS_COMMAND_INTENT_MAX_BYTES:()=>Yp,DATA_BUSINESS_COMMAND_RESOLUTION_SCHEMA:()=>aa,DATA_BUSINESS_COMMAND_SCHEMA:()=>ql,DATA_EVENT_TYPES_V2:()=>zn,DATA_FORM_DRAFT_MAX_BYTES:()=>ha,DATA_RESOURCE_MAX_FIELDS:()=>Zr,DATA_SUBTABLE_DEFAULT_TOTAL_ROWS:()=>rn,DATA_SUBTABLE_MAX_ROWS:()=>Fe,DATA_SUBTABLE_MAX_TOTAL_ROWS:()=>Ke,DATA_SYSTEM_SORT_FIELD_CODES:()=>ii,DATA_TRANSACTION_MAX_BYTES:()=>Ca,DATA_TRANSACTION_MAX_OPERATIONS:()=>go,DATA_TRANSACTION_RECORD_SET_MAX_RECORDS:()=>Qp,DATE_EVENT_RESERVED_DATA_FIELDS_V2:()=>cc,DEVELOPMENT_BACKEND_CONNECTION_TTL_SECONDS:()=>lm,DEVELOPMENT_BACKEND_ENDPOINT_PATTERN:()=>au,DEVELOPMENT_BACKEND_FEATURE:()=>ru,DEVELOPMENT_BACKEND_INVOCATION_FEATURE:()=>su,DEVELOPMENT_BACKEND_INVOCATION_MAX_REQUEST_BYTES:()=>im,DEVELOPMENT_BACKEND_INVOCATION_MAX_RESPONSE_BYTES:()=>sm,DEVELOPMENT_BACKEND_INVOCATION_SCHEMA:()=>fa,DEVELOPMENT_BACKEND_MAX_INFLIGHT:()=>cm,DEVELOPMENT_BACKEND_MAX_REQUEST_BYTES:()=>dm,DEVELOPMENT_BACKEND_MAX_RESPONSE_BYTES:()=>am,DEVELOPMENT_BACKEND_SCHEMA:()=>iu,DEVELOPMENT_CONFIGURATION_ENDPOINT:()=>eu,DEVELOPMENT_CONFIGURATION_FEATURE:()=>Ql,DEVELOPMENT_CONFIGURATION_MANIFEST_SCHEMA:()=>Kr,DEVELOPMENT_CONFIGURATION_SCHEMA:()=>la,DateEventProjectionV2Error:()=>Ut,DevelopmentConfigurationContractError:()=>so,ManagedConcurrencyContractError:()=>ut,NATIVE_ARTIFACT_CAPACITY_V2:()=>oe,NATIVE_CONFIGURATION_VALIDATOR_DIGEST:()=>pu,NATIVE_CONTRACT_CAPACITY_V2:()=>M,NATIVE_DATA_POLICY_EXPRESSION_MAX_CLAUSES:()=>Hu,NATIVE_DATA_POLICY_EXPRESSION_MAX_DEPTH:()=>qu,NATIVE_DATA_POLICY_EXPRESSION_MAX_GROUP_ITEMS:()=>zu,NATIVE_DATA_POLICY_EXPRESSION_MAX_LEAVES:()=>Ju,NATIVE_DATA_POLICY_EXPRESSION_MAX_OCCURRENCES:()=>Yu,NATIVE_DATA_QUERY_OPERATORS_V2:()=>di,NATIVE_HIGH_DENSITY_ARTIFACT_CAPACITY_V2:()=>et,NATIVE_ROLE_MEMBERSHIP_BATCH_MAX_BYTES:()=>Bp,NATIVE_ROLE_MEMBERSHIP_BATCH_MAX_ITEMS:()=>Mp,NATIVE_UNIQUE_KEY_MAX_BYTES:()=>rf,NATIVE_UNIQUE_KEY_NORMALIZERS:()=>zo,NativeConfigurationCompilerError:()=>Hn,NativeDataFieldContractV2Error:()=>be,NativeDataPolicyExpressionV2Error:()=>pt,NativeDecimalLifecycleContractError:()=>ze,NativeEventActionContractError:()=>kn,NativeParentReadPolicyError:()=>ce,NativeRoleMembershipBatchInputError:()=>oo,NativeScopeSourceFieldPathV2Error:()=>Cn,NativeUniqueKeyContractError:()=>_t,OPENXIANGDA_NATIVE_DATA_FIELD_TYPES_V2:()=>oi,OPENXIANGDA_NATIVE_DATA_SURFACE_KEYS_V2:()=>De,OPENXIANGDA_NATIVE_DRAFT_STATE_KEYS_V2:()=>En,OPENXIANGDA_NATIVE_SYSTEM_FIELDS_V2:()=>pn,OPENXIANGDA_NATIVE_SYSTEM_FIELD_MAP_V2:()=>qe,USER_CANDIDATE_MAX_SELECTIONS:()=>Eu,USER_CANDIDATE_SCOPE_FIELD_TYPES:()=>Jr,UserCandidateContractError:()=>Le,WORKFLOW_APPROVAL_EMPTY_PROVIDERS:()=>ur,WORKFLOW_APPROVED_DELEGATION_MAX_BYTES:()=>Df,WORKFLOW_APPROVED_DELEGATION_MAX_REQUESTS:()=>Sf,WORKFLOW_AUTOMATIC_CC_DEFAULT_RECIPIENTS:()=>Gi,WORKFLOW_AUTOMATIC_CC_MAX_RECIPIENTS:()=>qi,WORKFLOW_AUTOMATIC_CC_PROVIDERS:()=>zi,WORKFLOW_BUSINESS_STEP_EVENT:()=>gt,WORKFLOW_BUSINESS_STEP_EVENTS:()=>tr,WORKFLOW_BUSINESS_STEP_FACTS_KEY:()=>Kd,WORKFLOW_BUSINESS_STEP_MAX_BYTES:()=>$n,WORKFLOW_BUSINESS_STEP_MAX_RECEIPT_BYTES:()=>Fi,WORKFLOW_CONFIGURABLE_OPERATIONS:()=>Fn,WORKFLOW_CONFIGURABLE_PROVIDERS:()=>xn,WORKFLOW_EVENT_TYPES_V2:()=>Jn,WORKFLOW_LAUNCH_MAX_INPUTS:()=>_o,WORKFLOW_LAUNCH_PREFLIGHT_PROVIDERS:()=>es,WORKFLOW_REJECTION_NOTIFICATION_MAX_BYTES:()=>Tf,WORKFLOW_REJECTION_NOTIFICATION_SCHEMA:()=>Zi,WORKFLOW_ROLE_UNION_MAX_ROLES:()=>_f,WORKFLOW_ROUTING_MAX_BYTES:()=>xf,WORKFLOW_ROUTING_MAX_MATCHED_RULES:()=>Ff,WORKFLOW_ROUTING_MAX_RULES:()=>Lf,WORKFLOW_STEP_DATA_COMMAND_SCHEMA:()=>jl,WORKFLOW_STEP_DATA_RESOLUTION_SCHEMA:()=>Xs,WORKFLOW_TASK_PAGE_DEFINITION_MAX_BYTES:()=>is,WORKFLOW_TASK_PAGE_MAX_BYTES:()=>Mn,WORKFLOW_TASK_PAGE_MAX_FIELDS:()=>rs,WORKFLOW_TASK_SUBTABLE_MAX_ROWS:()=>Nr,WORKFLOW_TASK_SUBTABLE_MAX_TOTAL_ROWS:()=>br,WorkflowTaskPageError:()=>Ne,applyWorkflowTaskPageValues:()=>ds,applyWorkflowTaskSubtableRows:()=>fc,assertDevelopmentConfigurationManifest:()=>ua,assertDevelopmentConfigurationResult:()=>ou,assertNativeRoleMembershipBatchInput:()=>Ul,assertWorkflowNativeStageGuard:()=>Fd,assertWorkflowNativeStagePolicy:()=>Ko,assertWorkflowNativeStageSourceGuard:()=>xd,assertWorkflowOwnedSubjectCreate:()=>Ht,assertWorkflowOwnedSubjectCreateResources:()=>wr,canonicalDataBusinessIntent:()=>zl,compileNativeApplicationConfiguration:()=>zc,compileNativeEventAction:()=>Yo,compileNativeEventCapturePlansV2:()=>xs,compileRequiredPlatformCapabilitiesV3:()=>Fs,compileWorkflowBusinessStepHandlers:()=>Pn,createDevelopmentConfigurationManifest:()=>tu,dataOwnedRowLimit:()=>Ct,dateEventProjectionEnvelopeSchemaV2:()=>lc,dateEventProjectionFieldsV2:()=>yr,developmentBackendBase64Bytes:()=>pa,developmentBackendInvocationHeadersValid:()=>_a,developmentBackendInvocationRequestValid:()=>fu,developmentBackendInvocationRevision:()=>cu,developmentBackendOperationMatches:()=>ma,developmentConfigurationKey:()=>nu,evaluateWorkflowTaskPageExpression:()=>Pe,formatWorkflowCompletionDeadline:()=>nc,formatWorkflowExpression:()=>jt,generatedCrudCapabilityOperations:()=>Dr,hasDataAuditReadPolicy:()=>Oo,hasNativeParentReadPolicy:()=>wn,isDataAuditMetadataField:()=>at,isDataOwnedRowLimit:()=>st,isDataSystemSortField:()=>No,isDataTransactionActorAuthorityGuard:()=>Hl,isDataTransactionRecordSetMatchGuard:()=>Zl,isNativeDataQueryOperatorV2:()=>Wa,isNativeMultiValueFieldV2:()=>ht,isWorkflowRejectionNotificationSnapshot:()=>oc,matchesDataActorAuthorityMembership:()=>Yl,materializeNativeDataQueryPathTypesV2:()=>Pd,nativeDataPolicyExpressionLeavesV2:()=>Je,nativeDataPolicyExpressionToCnfV2:()=>Uo,nativeDataQueryPathPlanV2:()=>vd,nativeFieldAggregatePlanV2:()=>Ja,nativeFieldColumnDefinitionV2:()=>cd,nativeFieldDefaultSqlV2:()=>ld,nativeFieldHasDefaultV2:()=>fd,nativeFieldIndexStatementsV2:()=>gd,nativeFieldRequiresCreateInputV2:()=>wt,nativeFieldSequenceGrantStatementsV2:()=>_d,nativeFieldSequenceOwnershipStatementsV2:()=>md,nativeFieldSequenceStatementsV2:()=>pd,nativeFieldSupportsFilterV2:()=>wo,nativeFieldSupportsOperatorV2:()=>Ga,nativeFieldSupportsSearchV2:()=>gn,nativeFieldSupportsSortV2:()=>ct,nativeOperatorsForFieldV2:()=>ho,nativePhysicalFieldV2:()=>Ei,nativePhysicalFieldsV2:()=>dd,nativePhysicalObjectNameV2:()=>$e,nativeScopeSourceFieldValueV2:()=>Nd,nativeScopeSourceGrantPathSupportedV2:()=>jo,nativeScopeSourceSubjectPathSupportedV2:()=>hn,nativeSubtableConstraintStatementsV2:()=>Ad,nativeUniqueKeysContractVersion:()=>Ho,nativeUniqueKeysJsonSchema:()=>Wd,normalizeWorkflowOwnedSubjectCreate:()=>Nc,parseDataBusinessCommandResolution:()=>Jl,parseDataFieldUserCandidates:()=>Rt,parseDecimalReservationLifecycle:()=>Nn,parseNativeDataFieldsV2:()=>mn,parseNativeDataResourceInvariantsV2:()=>bo,parseNativeParentReadPolicy:()=>Ri,parseNativeUniqueKeys:()=>Jo,parseWorkflowStepDataResolution:()=>Wl,projectDataResourceView:()=>ca,projectNativeDataResourceViewV2:()=>yn,projectWorkflowGraph:()=>Hd,projectWorkflowNodePolicy:()=>lr,quoteNativeIdentifierV2:()=>de,refreshWorkflowTaskPageFacts:()=>pc,requiresAggregateOwnedSubtableCapacity:()=>an,requiresDateTimeMinutePrecision:()=>un,requiresDevelopmentBackendCredential:()=>du,requiresExtendedArtifactCapacity:()=>Yt,requiresExtendedConfigurationBytes:()=>Gn,requiresExtendedDeclarationCapacity:()=>Kn,requiresExtendedFieldCapacity:()=>sn,requiresExtendedOwnedSubtableCapacity:()=>dn,requiresHighDensityArtifactCapacity:()=>Xt,requiresOwnedSubtableMinimumRows:()=>fn,requiresUserCandidateLaunchScope:()=>on,requiresWorkflowRoleInputSelection:()=>cr,requiresWorkflowRoleUnion:()=>ar,resolveNativeParentReadBinding:()=>Pt,resolveNativeScopeSourceFieldPathV2:()=>ft,resolveWorkflowUserCandidates:()=>Xr,selectWorkflowAssignmentRoutingRules:()=>bc,serializedDataBytes:()=>wa,userCandidateScopeValue:()=>Ra,validateAuthenticatedPublicRead:()=>Go,validateDecimalReservationLifecycles:()=>Fo,validateManagedConcurrency:()=>Po,validateNativeDataDraftStateV2:()=>Do,validateNativeDataResourceReferencesV2:()=>yo,validateNativeDataResourceSurfaceV2:()=>In,validateNativeParentReadPolicies:()=>Mo,validateUserCandidateReferences:()=>po,validateWorkflowAdministration:()=>jn,validateWorkflowApprovalEmptyPolicy:()=>Wn,validateWorkflowApprovedDelegation:()=>Er,validateWorkflowAssignmentRoutingBindings:()=>Cr,validateWorkflowAssignmentRoutingPolicy:()=>Jt,validateWorkflowAssignmentRoutingRules:()=>Ic,validateWorkflowAutomaticCc:()=>Vn,validateWorkflowBusinessStepHandlerContract:()=>qd,validateWorkflowBusinessStepRequest:()=>Gd,validateWorkflowBusinessStepResult:()=>Wi,validateWorkflowBusinessStepSchema:()=>Lt,validateWorkflowBusinessStepSubscriptions:()=>or,validateWorkflowBusinessSteps:()=>xt,validateWorkflowCommandHandlers:()=>gr,validateWorkflowCompletionDeadlines:()=>pr,validateWorkflowCorrections:()=>Ir,validateWorkflowInitiatorApprovalPolicy:()=>Et,validateWorkflowInstanceCommandPolicies:()=>Zo,validateWorkflowLaunchPreflight:()=>Un,validateWorkflowNodeConfigurationPatch:()=>ec,validateWorkflowReadability:()=>sr,validateWorkflowRejectionNotification:()=>_r,validateWorkflowRoleInputSelection:()=>dr,validateWorkflowRoleUnion:()=>Wt,validateWorkflowTaskPages:()=>Gt,validateWorkflowUserCandidateBindings:()=>mo,workflowApprovalCanSkip:()=>tc,workflowApprovedDelegationRequests:()=>ac,workflowAssignmentRoutingFacts:()=>yc,workflowAssignmentRoutingPolicySchema:()=>Ec,workflowAssignmentRoutingSemantic:()=>fs,workflowBindingAllowsEmptyUsers:()=>fr,workflowBindingRoleCodes:()=>Zd,workflowBusinessCommandInvocationSchema:()=>rc,workflowBusinessStepFactSchema:()=>Ft,workflowBusinessStepHandlerDigest:()=>Gl,workflowBusinessStepInput:()=>zd,workflowBusinessStepPath:()=>Ui,workflowBusinessStepReceiptSignatureSuffix:()=>Kl,workflowBusinessStepValueMatches:()=>Vt,workflowDelegationMutationRequestSchema:()=>sa,workflowExpressionPaths:()=>ir,workflowInitiatorApprovalCanComplete:()=>Yd,workflowInstanceCommandDeadlineError:()=>Bd,workflowInstanceTerminateCapabilityAllowed:()=>Ud,workflowInstanceWithdrawalReasonRequired:()=>Md,workflowNativeStagePolicySchema:()=>jd,workflowNodeAllowedOperations:()=>It,workflowOperationCommentRequired:()=>Ji,workflowOperationReasonRequired:()=>Hi,workflowOwnedSubjectCreateSchema:()=>Oc,workflowPolicyTimestamp:()=>Xo,workflowRoleCodesSchema:()=>Xd,workflowTaskPageFieldState:()=>Tr,workflowTaskPageReplayCoversInvalidation:()=>mc,workflowTaskSubtableRows:()=>uc,workflowVariableLabel:()=>Bi});module.exports=Na(mu);var qr=require("node:crypto");function Ta(e){if(!e||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function lo(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,r)=>lo(n,`${t}[${r}]`)).join(",")}]`;if(Ta(e))return`{${Object.keys(e).filter(r=>e[r]!==void 0).sort((r,i)=>r===i?0:r<i?-1:1).map(r=>`${JSON.stringify(r)}:${lo(e[r],`${t}.${r}`)}`).join(",")}}`;let o=e instanceof Date?"Date":e?.constructor?.name||typeof e;throw new TypeError(`Value is not JSON serializable: ${t} (${o})`)}function X(e){return lo(e,"$")}function Z(e){return(0,qr.createHash)("sha256").update(X(e)).digest("hex")}var Eu=200,Jr=["text.short","uuid","option.single","resource-ref.single"],uo=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,Hr=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Yr=new Set(["__proto__","prototype","constructor"]),fo=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[Object.prototype,null].includes(Object.getPrototypeOf(e)),zr=(e,t)=>Object.keys(e).every(o=>t.includes(o)),it=(e,t)=>typeof e=="string"&&e.length>0&&e.trim()===e&&e.length<=t,Le=class extends Error{constructor(o,n){super(`${o}: ${n}`);this.code=o;this.pointer=n}code;pointer};function ne(e,t){throw new Le(e,t)}function Rt(e,t,o){if(e===void 0)return;["user.single","user.multiple"].includes(t)||ne("DATA_USER_CANDIDATES_FIELD_TYPE_INVALID",o),(!fo(e)||!zr(e,["kind","roleCode","scope","pageSize"])||e.kind!=="app-role"||!it(e.roleCode,128)||!uo.test(String(e.roleCode)))&&ne("DATA_USER_CANDIDATES_SOURCE_INVALID",o),e.pageSize!==void 0&&(!Number.isSafeInteger(e.pageSize)||Number(e.pageSize)<1||Number(e.pageSize)>50)&&ne("DATA_USER_CANDIDATES_PAGE_SIZE_INVALID",`${o}/pageSize`);let n;if(e.scope!==void 0){let r=e.scope;(!fo(r)||!zr(r,["dimensionCode","operation","field","value","creation"])||!it(r.dimensionCode,128)||!uo.test(String(r.dimensionCode))||!it(r.operation,64)||!uo.test(String(r.operation))||Object.hasOwn(r,"field")===Object.hasOwn(r,"value"))&&ne("DATA_USER_CANDIDATES_SCOPE_INVALID",`${o}/scope`),r.creation!==void 0&&(r.creation!=="prospective"||!Object.hasOwn(r,"field"))&&ne("DATA_USER_CANDIDATES_SCOPE_INVALID",`${o}/scope/creation`),Object.hasOwn(r,"field")?((!it(r.field,63)||!Hr.test(String(r.field))||Yr.has(String(r.field)))&&ne("DATA_USER_CANDIDATES_SCOPE_FIELD_INVALID",`${o}/scope/field`),n={dimensionCode:String(r.dimensionCode),operation:String(r.operation),field:String(r.field),...r.creation==="prospective"?{creation:"prospective"}:{}}):(it(r.value,255)||ne("DATA_USER_CANDIDATES_SCOPE_VALUE_INVALID",`${o}/scope/value`),n={dimensionCode:String(r.dimensionCode),operation:String(r.operation),value:String(r.value)})}return{kind:"app-role",roleCode:String(e.roleCode),...n?{scope:n}:{},...e.pageSize===void 0?{}:{pageSize:Number(e.pageSize)}}}function on(e){return e.some(t=>t.schema.fields.some(o=>{let n=o.userCandidates?.scope;return n?.creation==="prospective"||!!(n?.field&&t.schema.fields.find(r=>r.code===n.field)?.type==="resource-ref.single")}))}function po(e,t,o,n){for(let[r,i]of e.entries()){let d=`${n}/${r}/userCandidates`,s=Rt(i.userCandidates,i.type,d);if(s&&(t.has(s.roleCode)||ne("DATA_USER_CANDIDATES_ROLE_UNDECLARED",`${d}/roleCode`),s.scope&&!o.has(s.scope.dimensionCode)&&ne("DATA_USER_CANDIDATES_DIMENSION_UNDECLARED",`${d}/scope/dimensionCode`),s.scope?.field)){let a=e.find(c=>c.code===s.scope.field);(!a||!Jr.some(c=>c===a.type))&&ne("DATA_USER_CANDIDATES_SCOPE_FIELD_INVALID",`${d}/scope/field`)}}}function Xr(e,t,o,n){let r=e.subject.factProjection,i=typeof t.inputPath=="string"&&Object.entries(r).some(([c,f])=>(t.inputPath===c||t.inputPath.startsWith(`${c}.`))&&o.get(f)?.userCandidates!==void 0);if(t.candidateField===void 0&&!i)return;(t.provider!=="form_field_users"||!t.candidateField||!Hr.test(t.candidateField)||Yr.has(t.candidateField)||!t.inputPath||r[t.inputPath]!==t.candidateField)&&ne("WORKFLOW_USER_CANDIDATES_FIELD_BINDING_REQUIRED",n),(t.roleCode!==void 0||t.scope!==void 0||t.routing!==void 0)&&ne("WORKFLOW_USER_CANDIDATES_SOURCE_OVERRIDE_FORBIDDEN",n);let d=o.get(t.candidateField),s=d&&Rt(d.userCandidates,d.type,`${n}/candidateField`);s||ne("WORKFLOW_USER_CANDIDATES_FIELD_UNDECLARED",`${n}/candidateField`);let a;if(s.scope?.field){let c=Object.entries(r).filter(([,f])=>f===s.scope.field).map(([f])=>f);c.length!==1&&ne("WORKFLOW_USER_CANDIDATES_SCOPE_PROJECTION_REQUIRED",n),a=c[0]}return{fieldCode:d.code,inputPath:t.inputPath,source:s,...a?{scopeInputPath:a}:{}}}function mo(e,t,o,n,r=new Map){for(let[i,d]of Object.entries(t.bindings))Xr(e,d,o,`${n}/${i}`);for(let[i,d]of Object.entries(e.taskPages||{})){let s=new Set(d.fields.filter(a=>a.readonly!==!0).map(a=>a.code));for(let a of d.fields){let c=o.get(a.code)?.userCandidates?.scope;if(s.has(a.code)&&c?.field&&s.has(c.field)&&ne("WORKFLOW_USER_CANDIDATES_SCOPE_WRITE_FORBIDDEN",`${n}/taskPages/${i}/${a.code}`),!s.has(a.code)||!a.subtable)continue;let f=o.get(a.code)?.subtable?.resourceCode,u=f?r.get(f):void 0;a.subtable.fields.some(p=>p.readonly!==!0&&u?.get(p.code)?.userCandidates)&&ne("WORKFLOW_USER_CANDIDATES_OWNED_FIELD_UNSUPPORTED",`${n}/taskPages/${i}/${a.code}`)}}}function Ra(e,t){if(!e.scope)return;let o=e.scope.field?t[e.scope.field]:e.scope.value,n=fo(o)?o.value:o;return it(n,255)||ne("DATA_USER_CANDIDATES_SCOPE_VALUE_REQUIRED",e.scope.field||"scope"),String(n)}var Zr=200,_o=205;function sn(e,t=[]){return e.some(o=>o.schema.fields.length>100)||t.some(o=>Object.values(o.definition.taskPages||{}).some(n=>(n.fields?.length??0)>64)||[o.launch?.submission?.create,o.launch?.submission?.existing].some(n=>Object.keys(n?.inputs||{}).length>64))}var Fe=500,rn=500,Ke=1e3,go=2*Ke+16,Ca=2*1024*1024,ha=2*1024*1024;function st(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=1&&e<=Ke}function Ct(e){if(e.ownedRowLimit===void 0)return rn;if(!st(e.ownedRowLimit))throw new Error("NATIVE_DATA_OWNED_ROW_LIMIT_INVALID");return e.ownedRowLimit}function an(e){return e.some(t=>(t.schema.ownedRowLimit??rn)>rn)}function dn(e){return e.some(t=>{let o=t.schema.fields.filter(n=>n.type==="subtable").map(n=>n.subtable?.maxRows??20);return o.some(n=>n>100)||o.reduce((n,r)=>n+r,0)>400})}function wa(e){try{return new TextEncoder().encode(JSON.stringify(e)).byteLength}catch{return 1/0}}var ni=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Io=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,oi=["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"];function un(e){return e.some(t=>t.schema.fields.some(o=>(o.type==="datetime"||o.type==="datetime-range")&&o.timePrecision==="minute"))}function fn(e){return e.some(t=>t.schema.fields.some(o=>o.type==="subtable"&&(o.subtable?.minRows??0)>0))}var Sa=new Set(oi),ri=new Set(["option.multiple","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","subtable"]),Qr=new Set(["option.single","option.multiple","cascade.single","cascade.multiple"]),ei=new Set(["resource-ref.single","resource-ref.multiple"]),pn=[{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}],qe=new Map(pn.map(e=>[e.code,e])),be=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.name="NativeDataFieldContractV2Error"}code;pointer};function ht(e){return ri.has(e)}function wt(e,t={}){return e.type!=="serial-number"&&t.system!==!0&&e.nullable===!1&&(!ht(e.type)||t.requiredHint===!0)}function mn(e,t,o=500){Array.isArray(e)||k("NATIVE_ARRAY_REQUIRED",t),e.length===0&&k("NATIVE_DATA_FIELDS_REQUIRED",t),e.length>o&&k("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let n=new Set;return e.map((r,i)=>{let d=`${t}/${i}`,s=Ee(r,d);ye(s,["code","type","nullable","indexed","options","source","userCandidates","maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","timePrecision","file","serial","subtable"],d);let a=Oe(s.code,`${d}/code`,63);ni.test(a)||k("NATIVE_FIELD_CODE_INVALID",`${d}/code`),n.has(a)&&k("NATIVE_DATA_FIELD_DUPLICATE",`${d}/code`),n.add(a);let c=Oe(s.type,`${d}/type`,32);Sa.has(c)||k("NATIVE_DATA_FIELD_TYPE_INVALID",`${d}/type`);let f=c,u=Eo(s.nullable,`${d}/nullable`),p=Eo(s.indexed,`${d}/indexed`);u===!0&&ri.has(f)&&k("NATIVE_DATA_MULTI_FIELD_NULLABLE_INVALID",`${d}/nullable`);let _=$a(s.options,f,d),E=Pa(s.source,f,d),A=Rt(s.userCandidates,f,`${d}/userCandidates`),O=Va(s,f,d),b=Eo(s.exactDecimal,`${d}/exactDecimal`);b!==void 0&&f!=="number.decimal"&&k("NATIVE_DATA_FIELD_EXACT_DECIMAL_TYPE_INVALID",`${d}/exactDecimal`);let g=Da(s.rangeBoundary,f,d),I=La(s.file,f,d),T=Fa(s.serial,f,d),l=xa(s.subtable,f,d);return{code:a,type:f,...u===void 0?{}:{nullable:u},...p===void 0?{}:{indexed:p},..._?{options:_}:{},...E?{source:E}:{},...A?{userCandidates:A}:{},...O,...b===void 0?{}:{exactDecimal:b},...g?{rangeBoundary:g}:{},...I?{file:I}:{},...T?{serial:T}:{},...l?{subtable:l}:{}}})}function Da(e,t,o){let n=`${o}/rangeBoundary`;if(!(t==="date-range"||t==="datetime-range")){e!==void 0&&k("NATIVE_DATA_FIELD_RANGE_BOUNDARY_TYPE_INVALID",n);return}return e!=="closed"&&e!=="half-open"&&k("NATIVE_DATA_FIELD_RANGE_BOUNDARY_REQUIRED",n),e}function yo(e,t){Array.isArray(e)||k("NATIVE_ARRAY_REQUIRED",t);let o=new Map;e.forEach((n,r)=>{let i=`${t}/${r}`,d=Ee(n,i),s=Oe(d.code,`${i}/code`,64);(!Io.test(s)||o.has(s))&&k("NATIVE_RESOURCE_CODE_INVALID",`${i}/code`);let a=Ee(d.schema,`${i}/schema`);a.ownedRowLimit!==void 0&&!st(a.ownedRowLimit)&&k("NATIVE_DATA_OWNED_ROW_LIMIT_INVALID",`${i}/schema/ownedRowLimit`),o.set(s,{pointer:i,ownedRowLimit:Ct(a),fields:mn(a.fields,`${i}/schema/fields`)})});for(let[n,r]of o){let i=new Map(r.fields.map(s=>[s.code,s]));r.fields.filter(s=>s.type==="subtable").reduce((s,a)=>s+(a.subtable?.maxRows??20),0)>r.ownedRowLimit&&k("NATIVE_DATA_FIELD_SUBTABLE_AGGREGATE_MAX_ROWS_EXCEEDED",`${r.pointer}/schema/fields`),r.fields.forEach((s,a)=>{let c=`${r.pointer}/schema/fields/${a}`;if(s.source&&ka(s.source,i,o,`${c}/source`),s.subtable){let f=o.get(s.subtable.resourceCode);(!f||s.subtable.resourceCode===n)&&k("NATIVE_DATA_FIELD_SUBTABLE_TARGET_MISSING",`${c}/subtable/resourceCode`);let u=f.fields.find(_=>_.code===s.subtable?.foreignKey);(!u||u.type!=="uuid"||u.nullable!==!1)&&k("NATIVE_DATA_FIELD_SUBTABLE_FOREIGN_KEY_INVALID",`${c}/subtable/foreignKey`);let p=f.fields.find(_=>_.code===s.subtable?.orderField);(!p||p.type!=="number.integer"||p.nullable!==!1)&&k("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${c}/subtable/orderField`)}})}}function bo(e,t,o){if(e===void 0)return[];(!Array.isArray(e)||e.length>20)&&k("NATIVE_DATA_RESOURCE_INVARIANTS_INVALID",o);let n=new Map(t.map(i=>[i.code,i])),r=new Set;return e.map((i,d)=>{let s=`${o}/${d}`,a=Ee(i,s);ye(a,["code","message","expression"],s);let c=Oe(a.code,`${s}/code`,128);(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(c)||r.has(c))&&k("NATIVE_DATA_RESOURCE_INVARIANT_CODE_INVALID",`${s}/code`),r.add(c);let f=ln(a.message,`${s}/message`,500);f!==void 0&&f.length===0&&k("NATIVE_DATA_RESOURCE_INVARIANT_MESSAGE_INVALID",`${s}/message`);let u=Ee(a.expression,`${s}/expression`);if(u.kind==="nonBlankTextWhenOption"){ye(u,["kind","optionField","optionValue","textField"],`${s}/expression`);let g=Ce(u.optionField,`${s}/expression/optionField`),I=Ce(u.textField,`${s}/expression/textField`),T=Oe(u.optionValue,`${s}/expression/optionValue`,128),l=n.get(g),y=n.get(I);return(!l||!y)&&k("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_UNKNOWN",`${s}/expression`),(l.type!=="option.single"||!["text.short","text.long"].includes(y.type)||!l.options?.some(R=>R.value===T))&&k("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${s}/expression`),{code:c,...f===void 0?{}:{message:f},expression:{kind:"nonBlankTextWhenOption",optionField:g,optionValue:T,textField:I}}}ye(u,["leftField","operator","rightField"],`${s}/expression`);let p=Ce(u.leftField,`${s}/expression/leftField`),_=Ce(u.rightField,`${s}/expression/rightField`),E=n.get(p),A=n.get(_);(!E||!A)&&k("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_UNKNOWN",`${s}/expression`),E.type===A.type||["number.integer","number.decimal"].includes(E.type)&&["number.integer","number.decimal"].includes(A.type)||k("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${s}/expression`);let b=String(u.operator);return["eq","neq","gt","gte","lt","lte"].includes(b)||k("NATIVE_DATA_RESOURCE_INVARIANT_OPERATOR_INVALID",`${s}/expression/operator`),!["eq","neq"].includes(b)&&!["number.integer","number.decimal","date","time","datetime","text.short","text.long","text.rich","serial-number","uuid"].includes(E.type)&&k("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${s}/expression`),{code:c,...f===void 0?{}:{message:f},expression:{leftField:p,operator:b,rightField:_}}})}function ka(e,t,o,n){let r=o.get(e.resourceCode);r||k("NATIVE_DATA_FIELD_SOURCE_TARGET_MISSING",`${n}/resourceCode`);let i=new Map(r.fields.map(s=>[s.code,s])),d=i.get(e.labelField);(!d||!["text.short","text.long"].includes(d.type))&&k("NATIVE_DATA_FIELD_SOURCE_LABEL_INVALID",`${n}/labelField`);for(let s of["searchFields","descriptionFields","snapshotFields"])for(let a of e[s]||[])i.has(a)||k("NATIVE_DATA_FIELD_SOURCE_FIELD_MISSING",`${n}/${s}`);for(let[s,a]of(e.filters||[]).entries())i.has(a.field)||k("NATIVE_DATA_FIELD_SOURCE_FILTER_FIELD_MISSING",`${n}/filters/${s}/field`),"binding"in a&&!t.has(a.binding.field)&&k("NATIVE_DATA_FIELD_SOURCE_BINDING_FIELD_MISSING",`${n}/filters/${s}/binding/field`)}function $a(e,t,o){let n=`${o}/options`;if(e===void 0){Qr.has(t)&&k("NATIVE_DATA_FIELD_OPTIONS_REQUIRED",n);return}(!Qr.has(t)||!Array.isArray(e))&&k("NATIVE_DATA_FIELD_OPTIONS_TYPE_INVALID",n),(e.length<1||e.length>100)&&k("NATIVE_DATA_FIELD_OPTIONS_INVALID",n);let r=0,i=(d,s,a)=>{a>5&&k("NATIVE_DATA_FIELD_OPTIONS_DEPTH_EXCEEDED",s);let c=new Set;return d.map((f,u)=>{r+=1,r>1e3&&k("NATIVE_DATA_FIELD_OPTIONS_COUNT_EXCEEDED",n);let p=`${s}/${u}`,_=Ee(f,p);ye(_,["label","value","description","color","children"],p);let E=Oe(_.label,`${p}/label`,500),A=Oe(_.value,`${p}/value`,500);c.has(A)&&k("NATIVE_DATA_FIELD_OPTION_VALUE_DUPLICATE",`${p}/value`),c.add(A);let O=ln(_.description,`${p}/description`,2e3),b=ln(_.color,`${p}/color`,64),g;return _.children!==void 0&&((!t.startsWith("cascade.")||!Array.isArray(_.children))&&k("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${p}/children`),(_.children.length<1||_.children.length>100)&&k("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${p}/children`),g=i(_.children,`${p}/children`,a+1)),{label:E,value:A,...O===void 0?{}:{description:O},...b===void 0?{}:{color:b},...g?{children:g}:{}}})};return i(e,n,1)}function Pa(e,t,o){let n=`${o}/source`;if(e===void 0){ei.has(t)&&k("NATIVE_DATA_FIELD_SOURCE_REQUIRED",n);return}ei.has(t)||k("NATIVE_DATA_FIELD_SOURCE_TYPE_INVALID",n);let r=Ee(e,n);ye(r,["kind","resourceCode","labelField","searchFields","descriptionFields","snapshotFields","filters","pageSize","loadMode","clearOnBindingChange"],n),r.kind!=="resource"&&k("NATIVE_DATA_FIELD_SOURCE_KIND_INVALID",`${n}/kind`);let i=Oe(r.resourceCode,`${n}/resourceCode`,64);Io.test(i)||k("NATIVE_RESOURCE_CODE_INVALID",`${n}/resourceCode`);let d=Ce(r.labelField,`${n}/labelField`),s=Ao(r.searchFields,`${n}/searchFields`,10),a=Ao(r.descriptionFields,`${n}/descriptionFields`,10),c=Ao(r.snapshotFields,`${n}/snapshotFields`,50),f=Ge(r.pageSize,`${n}/pageSize`,1,100),u;r.loadMode!==void 0&&(["search","all"].includes(String(r.loadMode))||k("NATIVE_DATA_FIELD_SOURCE_LOAD_MODE_INVALID",`${n}/loadMode`),u=r.loadMode);let p=va(r.filters,`${n}/filters`);return r.clearOnBindingChange!==void 0&&typeof r.clearOnBindingChange!="boolean"&&k("NATIVE_DATA_FIELD_SOURCE_BINDING_RESET_INVALID",`${n}/clearOnBindingChange`),{kind:"resource",resourceCode:i,labelField:d,...s?{searchFields:s}:{},...a?{descriptionFields:a}:{},...c?{snapshotFields:c}:{},...p?{filters:p}:{},...f===void 0?{}:{pageSize:f},...u?{loadMode:u}:{},...r.clearOnBindingChange===void 0?{}:{clearOnBindingChange:r.clearOnBindingChange}}}function va(e,t){if(e!==void 0)return(!Array.isArray(e)||e.length>20)&&k("NATIVE_DATA_FIELD_SOURCE_FILTERS_INVALID",t),e.map((o,n)=>{let r=`${t}/${n}`,i=Ee(o,r),d=Object.prototype.hasOwnProperty.call(i,"value"),s=Object.prototype.hasOwnProperty.call(i,"binding");ye(i,d?["field","operator","value"]:["field","operator","binding"],r),d===s&&k("NATIVE_DATA_FIELD_SOURCE_FILTER_VALUE_INVALID",r);let a=Ce(i.field,`${r}/field`);["eq","in"].includes(String(i.operator))||k("NATIVE_DATA_FIELD_SOURCE_FILTER_OPERATOR_INVALID",`${r}/operator`);let c=i.operator;if(d)return{field:a,operator:c,value:i.value};let f=Ee(i.binding,`${r}/binding`);return ye(f,["kind","field"],`${r}/binding`),f.kind!=="field"&&k("NATIVE_DATA_FIELD_SOURCE_BINDING_KIND_INVALID",`${r}/binding/kind`),{field:a,operator:c,binding:{kind:"field",field:Ce(f.field,`${r}/binding/field`)}}})}function Va(e,t,o){let n={};if(e.maxLength!==void 0&&(["text.short","text.long","text.rich"].includes(t)||k("NATIVE_DATA_FIELD_MAX_LENGTH_TYPE_INVALID",`${o}/maxLength`),n.maxLength=cn(e.maxLength,`${o}/maxLength`,1,1e6)),(e.precision!==void 0||e.scale!==void 0)&&((t!=="number.decimal"||e.precision===void 0)&&k("NATIVE_DATA_FIELD_DECIMAL_CONFIG_INVALID",o),n.precision=cn(e.precision,`${o}/precision`,1,1e3),n.scale=e.scale===void 0?0:cn(e.scale,`${o}/scale`,0,n.precision)),e.min!==void 0||e.max!==void 0){["number.integer","number.decimal"].includes(t)||k("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_TYPE_INVALID",o);let r=ti(e.min,`${o}/min`),i=ti(e.max,`${o}/max`);t==="number.integer"&&[r,i].some(d=>d!==void 0&&!Number.isSafeInteger(d))&&k("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",o),r!==void 0&&i!==void 0&&r>i&&k("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",o),r!==void 0&&(n.min=r),i!==void 0&&(n.max=i)}return e.timePrecision!==void 0&&((!["time","datetime","datetime-range"].includes(t)||!["minute","second"].includes(e.timePrecision))&&k("NATIVE_DATA_FIELD_TIME_PRECISION_INVALID",`${o}/timePrecision`),n.timePrecision=e.timePrecision),n}function La(e,t,o){if(e===void 0)return;let n=`${o}/file`;["file","image","signature"].includes(t)||k("NATIVE_DATA_FIELD_FILE_TYPE_INVALID",n);let r=Ee(e,n);ye(r,["maxCount","maxSizeMb","accept"],n);let i=Ge(r.maxCount,`${n}/maxCount`,1,100);t==="signature"&&i!==void 0&&i!==1&&k("NATIVE_DATA_FIELD_SIGNATURE_COUNT_INVALID",`${n}/maxCount`);let d=Ge(r.maxSizeMb,`${n}/maxSizeMb`,1,1024),s;return r.accept!==void 0&&((!Array.isArray(r.accept)||r.accept.length>50)&&k("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${n}/accept`),s=r.accept.map((a,c)=>Oe(a,`${n}/accept/${c}`,255)),new Set(s).size!==s.length&&k("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${n}/accept`)),{...i===void 0?{}:{maxCount:i},...d===void 0?{}:{maxSizeMb:d},...s===void 0?{}:{accept:s}}}function Fa(e,t,o){let n=`${o}/serial`;if(e===void 0){t==="serial-number"&&k("NATIVE_DATA_FIELD_SERIAL_REQUIRED",n);return}t!=="serial-number"&&k("NATIVE_DATA_FIELD_SERIAL_TYPE_INVALID",n);let r=Ee(e,n);ye(r,["prefix","digits","start"],n);let i=ln(r.prefix,`${n}/prefix`,64),d=Ge(r.digits,`${n}/digits`,1,32),s=Ge(r.start,`${n}/start`,0,Number.MAX_SAFE_INTEGER);return{...i===void 0?{}:{prefix:i},...d===void 0?{}:{digits:d},...s===void 0?{}:{start:s}}}function xa(e,t,o){let n=`${o}/subtable`;if(e===void 0){t==="subtable"&&k("NATIVE_DATA_FIELD_SUBTABLE_REQUIRED",n);return}t!=="subtable"&&k("NATIVE_DATA_FIELD_SUBTABLE_TYPE_INVALID",n);let r=Ee(e,n);ye(r,["resourceCode","foreignKey","orderField","minRows","maxRows"],n);let i=Oe(r.resourceCode,`${n}/resourceCode`,64);Io.test(i)||k("NATIVE_RESOURCE_CODE_INVALID",`${n}/resourceCode`);let d=Ce(r.foreignKey,`${n}/foreignKey`),s=Ce(r.orderField,`${n}/orderField`);s===d&&k("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${n}/orderField`);let a=Ge(r.maxRows,`${n}/maxRows`,1,Fe),c=Ge(r.minRows,`${n}/minRows`,0,Fe);return(c??0)>(a??20)&&k("NATIVE_DATA_FIELD_SUBTABLE_MIN_ROWS_INVALID",`${n}/minRows`),{resourceCode:i,foreignKey:d,orderField:s,...c===void 0?{}:{minRows:c},...a===void 0?{}:{maxRows:a}}}function Ao(e,t,o){if(e===void 0)return;(!Array.isArray(e)||e.length>o)&&k("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t);let n=e.map((r,i)=>Ce(r,`${t}/${i}`));return new Set(n).size!==n.length&&k("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t),n}function Ce(e,t){let o=Oe(e,t,63);return ni.test(o)||k("NATIVE_FIELD_CODE_INVALID",t),o}function Ee(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&k("NATIVE_OBJECT_REQUIRED",t),e}function ye(e,t,o){let n=new Set(t);for(let r of Object.keys(e))n.has(r)||k("NATIVE_PROPERTY_UNKNOWN",`${o}/${r}`)}function Oe(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&k("NATIVE_STRING_INVALID",t),e}function ln(e,t,o){if(e!==void 0)return(typeof e!="string"||e.length>o)&&k("NATIVE_STRING_INVALID",t),e}function Eo(e,t){if(e!==void 0)return typeof e!="boolean"&&k("NATIVE_BOOLEAN_REQUIRED",t),e}function Ge(e,t,o,n){if(e!==void 0)return cn(e,t,o,n)}function ti(e,t){if(e!==void 0)return(typeof e!="number"||!Number.isFinite(e))&&k("NATIVE_NUMBER_REQUIRED",t),e}function cn(e,t,o,n){return(!Number.isSafeInteger(e)||Number(e)<o||Number(e)>n)&&k("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function k(e,t){throw new be(e,t)}var St=["created_by","updated_by","created_at","updated_at"];function at(e){return St.includes(e)}function Oo(e){return St.some(t=>Object.prototype.hasOwnProperty.call(e.fieldPolicies||{},t))}var ii=pn.map(e=>e.code);function No(e){return ii.includes(e)}var di=["eq","neq","gt","gte","lt","lte","contains","startsWith","endsWith","in","between","has","hasAny","hasAll","overlaps","containedBy","jsonContains","isEmpty","isNotEmpty"],ja=new Set(di);function Wa(e){return ja.has(String(e))}var To=["eq","neq","contains","startsWith","endsWith","in","isEmpty","isNotEmpty"],Dt=["eq","neq","gt","gte","lt","lte","between","in","isEmpty"],Ua=["eq","neq","in","isEmpty"],_n=["eq","neq","in","isEmpty","isNotEmpty"],dt=["has","hasAny","hasAll","isEmpty","isNotEmpty"],si=["overlaps","contains","containedBy","isEmpty"],Ro=["jsonContains","isEmpty","isNotEmpty"],Co=["isEmpty","isNotEmpty"],Ma={"text.short":To,"text.long":To,"text.rich":To,"number.integer":Dt,"number.decimal":Dt,boolean:Ua,date:Dt,time:Dt,datetime:Dt,"date-range":si,"datetime-range":si,"option.single":_n,"option.multiple":dt,"cascade.single":dt,"cascade.multiple":dt,"user.single":_n,"user.multiple":dt,"department.single":_n,"department.multiple":dt,"resource-ref.single":_n,"resource-ref.multiple":dt,file:Co,image:Co,signature:Co,address:Ro,location:Ro,uuid:["eq","neq","in","isEmpty"],json:Ro,"serial-number":["eq","neq","in","contains","startsWith"],subtable:[]},Ba=new Set(["text.short","text.long","text.rich","option.single","user.single","department.single","resource-ref.single","serial-number"]),Ka=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","signature","address","location","json","subtable"]);function ho(e){return Ma[e]}function Ga(e,t){return ho(e).includes(t)}function gn(e){return Ba.has(e)}function ct(e){return!Ka.has(e)}function wo(e){return ho(e).length>0}var ai=new Set(["number.integer","number.decimal"]),ci=new Set(["text.short","text.long","number.integer","number.decimal","date","time","datetime","serial-number"]),qa=new Set([...ci,"boolean","uuid"]),za=new Set(["option.single","user.single","department.single","resource-ref.single"]);function Ja(e,t){return t==="sum"||t==="avg"?ai.has(e)?{valueExpression:"column",numericResult:!0}:null:t==="min"||t==="max"?ci.has(e)?{valueExpression:"column",numericResult:ai.has(e)}:null:za.has(e)?{valueExpression:"snapshot-value",numericResult:!0}:qa.has(e)?{valueExpression:"column",numericResult:!0}:null}var En=["version","maxBytes","fields"];function Do(e,t){if(e===void 0)return;let o=So(e,t);li(o,En,t);let n=An(o.version,`${t}/version`,1,1e6),r=An(o.maxBytes,`${t}/maxBytes`,2,196608);(!n||!r)&&ue("NATIVE_DATA_DRAFT_STATE_SCHEMA_INVALID",t);let i=So(o.fields,`${t}/fields`),d=Object.entries(i);(!d.length||d.length>50)&&ue("NATIVE_DATA_DRAFT_STATE_FIELDS_INVALID",`${t}/fields`);for(let[s,a]of d){let c=`${t}/fields/${s}`;/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(s)||ue("NATIVE_DATA_DRAFT_STATE_FIELD_CODE_INVALID",c);let f=So(a,c),u=ui(f.type,`${c}/type`,32),p=u==="string"?["type","required","maxLength","enum"]:u==="json.object"?["type","required","maxBytes"]:["type","required"];if(["string","number","integer","boolean","json.object"].includes(u)||ue("NATIVE_DATA_DRAFT_STATE_FIELD_TYPE_INVALID",`${c}/type`),li(f,p,c),Ya(f.required,`${c}/required`),u==="string"){let _=An(f.maxLength,`${c}/maxLength`,1,196608);_||ue("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",c),f.enum!==void 0&&Ha(f.enum,`${c}/enum`,100,!1).some(A=>A.length>_)&&ue("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",`${c}/enum`)}else if(u==="json.object"){let _=An(f.maxBytes,`${c}/maxBytes`,2,65536);(!_||_>r)&&ue("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",c)}}}function Ha(e,t,o,n){(!Array.isArray(e)||!n&&e.length===0||e.length>o)&&ue("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t);let r=e.map((i,d)=>ui(i,`${t}/${d}`,255));return new Set(r).size!==r.length&&ue("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t),r}function So(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&ue("NATIVE_OBJECT_REQUIRED",t),e}function li(e,t,o){let n=new Set(t);for(let r of Object.keys(e))n.has(r)||ue("NATIVE_PROPERTY_UNKNOWN",`${o}/${r}`)}function ui(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&ue("NATIVE_STRING_INVALID",t),e}function Ya(e,t){e!==void 0&&typeof e!="boolean"&&ue("NATIVE_BOOLEAN_REQUIRED",t)}function An(e,t,o,n){return(!Number.isSafeInteger(e)||Number(e)<o||Number(e)>n)&&ue("NATIVE_INTEGER_INVALID",t),Number(e)}function ue(e,t){throw new be(e,t)}var Xa=500,De={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","exactDecimal","min","max","rangeBoundary","maxCount","maxSizeMb","accept","options","list","searchable","sortable","source","userCandidates","timePrecision","serial","subtable"],list:["actions","fieldOrder","defaultPageSize","searchableFields","filterFields","defaultSort"],defaultSort:["field","order"],form:["layout","fieldOrder","draftState"],detail:["layout","fieldOrder"],layout:["layout","fieldOrder","draftState"],draftState:En,mobile:["enabled"]},Za={"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 In(e,t,o){if(e===void 0)return;let n=ae(e,o);he(n,De.surface,o);let r=n.mutationOwner===void 0?"native":ke(n.mutationOwner,`${o}/mutationOwner`,16);["native","action","readonly","workflow","queued-command"].includes(r)||W("NATIVE_DATA_SURFACE_MUTATION_OWNER_INVALID",`${o}/mutationOwner`);let i=n.generated===void 0?{}:ae(n.generated,`${o}/generated`);he(i,De.generated,`${o}/generated`);for(let a of De.generated)$o(i[a],`${o}/generated/${a}`);if(r!=="native")for(let a of["create","update","delete"])i[a]===!0&&W("NATIVE_DATA_SURFACE_MUTATION_OWNER_CONFLICT",`${o}/generated/${a}`);let d=new Map(t.map(a=>[a.code,a])),s=ae(n.fields,`${o}/fields`);for(let a of Object.keys(s))d.has(a)||W("NATIVE_DATA_SURFACE_FIELD_MISSING",`${o}/fields/${a}`);for(let a of t)Object.prototype.hasOwnProperty.call(s,a.code)||W("NATIVE_DATA_SURFACE_FIELD_REQUIRED",`${o}/fields/${a.code}`),ed(s[a.code],a,`${o}/fields/${a.code}`);for(let a of["create","update"]){let c=i[a]??r==="native",f=t.some(u=>{let p=ae(s[u.code],`${o}/fields/${u.code}`);return pi(u,p,a)});c&&!f&&W("NATIVE_DATA_SURFACE_WRITABLE_FIELDS_REQUIRED",`${o}/generated/${a}`)}if(td(n.list,d,`${o}/list`),fi(n.form,d,`${o}/form`,"form"),fi(n.detail,d,`${o}/detail`,"detail"),n.mobile!==void 0){let a=ae(n.mobile,`${o}/mobile`);he(a,De.mobile,`${o}/mobile`),$o(a.enabled,`${o}/mobile/enabled`)}Qa(n,t,o)}function yn(e,t){let o=e.views?.find(r=>r.code===t);o||W("NATIVE_DATA_VIEW_NOT_FOUND",`/surface/views/${t}`);let n=new Map((o.sections||[]).flatMap(r=>r.fields.map(i=>[i,r.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(([r,i])=>{let d={...i};delete d.section;let s=n.get(r);return[r,{...d,...s?{section:s}:{},list:o.list.fieldOrder.includes(r)}]}))}}function Qa(e,t,o){if(e.views===void 0)return;(!Array.isArray(e.views)||e.views.length>20)&&W("NATIVE_DATA_VIEWS_LIMIT_INVALID",`${o}/views`);let n=new Set;e.views.forEach((r,i)=>{let d=`${o}/views/${i}`,s=ae(r,d);he(s,["code","name","generated","list","form","detail","mobile","sections"],d);let a=ke(s.code,`${d}/code`,64);(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(a)||n.has(a))&&W("NATIVE_DATA_VIEW_CODE_INVALID",`${d}/code`),n.add(a),ke(s.name,`${d}/name`,255),ae(s.generated,`${d}/generated`),ae(s.mobile,`${d}/mobile`);for(let f of["list","detail","create","update","delete"])typeof s.generated[f]!="boolean"&&W("NATIVE_DATA_VIEW_OPERATION_INVALID",`${d}/generated/${f}`);typeof s.mobile.enabled!="boolean"&&W("NATIVE_DATA_VIEW_MOBILE_INVALID",`${d}/mobile/enabled`);for(let f of["list","form","detail"]){let u=ae(s[f],`${d}/${f}`),p=lt(u.fieldOrder,`${d}/${f}/fieldOrder`,500,!0);for(let _ of p){let E=e.fields[_];(!E||(E.hidden??E.system)===!0)&&W("NATIVE_DATA_VIEW_FIELD_INVALID",`${d}/${f}/fieldOrder`)}}if(s.sections!==void 0){(!Array.isArray(s.sections)||s.sections.length>100)&&W("NATIVE_DATA_VIEW_SECTIONS_INVALID",`${d}/sections`);let f=new Set;s.sections.forEach((u,p)=>{let _=`${d}/sections/${p}`,E=ae(u,_);he(E,["title","fields"],_),ke(E.title,`${_}/title`,255);for(let A of lt(E.fields,`${_}/fields`,100,!0)){let O=e.fields[A];(!O||(O.hidden??O.system)===!0||f.has(A))&&W("NATIVE_DATA_VIEW_FIELD_INVALID",`${_}/fields`),f.add(A)}})}let c=yn(e,a);if(In(c,t,d),s.generated.create!==!1&&(e.mutationOwner||"native")==="native")for(let f of t)wt(f,e.fields[f.code])&&pi(f,e.fields[f.code],"create")&&!s.form.fieldOrder.includes(f.code)&&W("NATIVE_DATA_VIEW_CREATE_REQUIRED_FIELD_MISSING",`${d}/form/fieldOrder`)})}function pi(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 ed(e,t,o){let n=ae(e,o);he(n,De.field,o),ke(n.label,`${o}/label`,500),n.type!==t.type&&W("NATIVE_DATA_SURFACE_FIELD_TYPE_MISMATCH",`${o}/type`);let r=ke(n.widget,`${o}/widget`,64);Za[t.type].includes(r)||W("NATIVE_DATA_SURFACE_WIDGET_INCOMPATIBLE",`${o}/widget`),rd(n.section,`${o}/section`,255);for(let i of["requiredHint","system","hidden","list","searchable","sortable"])$o(n[i],`${o}/${i}`);n.searchable===!0&&!gn(t.type)&&W("NATIVE_DATA_SURFACE_SEARCH_UNSUPPORTED",`${o}/searchable`),n.sortable===!0&&!ct(t.type)&&W("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${o}/sortable`);for(let i of["readCapabilities","createCapabilities","updateCapabilities"])lt(n[i],`${o}/${i}`,100,!0);if(n.maxCount!==void 0&&(!Number.isSafeInteger(n.maxCount)||Number(n.maxCount)<1||Number(n.maxCount)>100)&&W("NATIVE_DATA_SURFACE_MAX_COUNT_INVALID",`${o}/maxCount`),n.maxSizeMb!==void 0&&(!Number.isSafeInteger(n.maxSizeMb)||Number(n.maxSizeMb)<1||Number(n.maxSizeMb)>1024)&&W("NATIVE_DATA_SURFACE_MAX_SIZE_INVALID",`${o}/maxSizeMb`),n.accept!==void 0){let i=Array.isArray(n.accept)?n.accept:[n.accept];lt(i,`${o}/accept`,50,!1)}for(let i of["maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","options","source","userCandidates","timePrecision","serial","subtable"])nd(n,t,i,o);od(n,t,o)}function td(e,t,o){if(e===void 0)return;let n=ae(e,o);if(he(n,De.list,o),n.actions!==void 0){let r=ae(n.actions,`${o}/actions`);he(r,["import","export"],`${o}/actions`);for(let i of["import","export"])r[i]!==void 0&&typeof r[i]!="boolean"&&W("NATIVE_DATA_SURFACE_LIST_ACTION_INVALID",`${o}/actions/${i}`)}if(n.fieldOrder!==void 0)for(let r of lt(n.fieldOrder,`${o}/fieldOrder`,500,!0))t.has(r)||W("NATIVE_DATA_SURFACE_LIST_FIELD_INVALID",`${o}/fieldOrder`);n.defaultPageSize!==void 0&&(!Number.isSafeInteger(n.defaultPageSize)||Number(n.defaultPageSize)<1||Number(n.defaultPageSize)>200)&&W("NATIVE_DATA_SURFACE_PAGE_SIZE_INVALID",`${o}/defaultPageSize`);for(let[r,i]of[["searchableFields",gn],["filterFields",wo]]){if(n[r]===void 0)continue;let d=lt(n[r],`${o}/${r}`,100,!0);for(let s of d){let a=t.get(s);(!a||!i(a.type))&&W("NATIVE_DATA_SURFACE_LIST_FIELD_INVALID",`${o}/${r}`)}}if(n.defaultSort!==void 0){let r=ae(n.defaultSort,`${o}/defaultSort`);he(r,De.defaultSort,`${o}/defaultSort`);let i=ke(r.field,`${o}/defaultSort/field`,63),d=t.get(i);!No(i)&&(!d||!ct(d.type))&&W("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${o}/defaultSort/field`),r.order!==void 0&&!["asc","desc"].includes(r.order)&&W("NATIVE_DATA_SURFACE_SORT_ORDER_INVALID",`${o}/defaultSort/order`)}}function fi(e,t,o,n){if(e===void 0)return;let r=ae(e,o);if(he(r,De[n],o),r.layout!==void 0&&!["flat","sections"].includes(r.layout)&&W("NATIVE_DATA_SURFACE_LAYOUT_INVALID",`${o}/layout`),r.fieldOrder!==void 0){let i=`${o}/fieldOrder`;(!Array.isArray(r.fieldOrder)||r.fieldOrder.length>t.size||r.fieldOrder.length>Xa)&&W("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",i);let d=r.fieldOrder.map((s,a)=>ke(s,`${i}/${a}`,63));new Set(d).size!==d.length&&W("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",i),d.forEach((s,a)=>{t.has(s)||W("NATIVE_DATA_SURFACE_FIELD_ORDER_FIELD_MISSING",`${i}/${a}`)})}n==="form"&&Do(r.draftState,`${o}/draftState`)}function nd(e,t,o,n){e[o]===void 0&&t[o]===void 0||((e[o]===void 0||t[o]===void 0)&&W("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${n}/${o}`),X(e[o])!==X(t[o])&&W("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${n}/${o}`))}function od(e,t,o){let n=t.file||{},r={...e.maxCount===void 0?{}:{maxCount:e.maxCount},...e.maxSizeMb===void 0?{}:{maxSizeMb:e.maxSizeMb},...e.accept===void 0?{}:{accept:ko(e.accept)}};for(let i of["maxCount","maxSizeMb","accept"]){if(r[i]===void 0&&n[i]===void 0)continue;(r[i]===void 0||n[i]===void 0)&&W("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${i}`);let d=i==="accept"?ko(r[i]):r[i],s=i==="accept"?ko(n[i]):n[i];X(d)!==X(s)&&W("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${i}`)}}function ko(e){return(Array.isArray(e)?[...e]:[e]).sort((t,o)=>{let n=String(t),r=String(o);return n===r?0:n<r?-1:1})}function lt(e,t,o,n){(!Array.isArray(e)||!n&&e.length===0||e.length>o)&&W("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t);let r=e.map((i,d)=>ke(i,`${t}/${d}`,255));return new Set(r).size!==r.length&&W("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t),r}function ae(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&W("NATIVE_OBJECT_REQUIRED",t),e}function he(e,t,o){let n=new Set(t);for(let r of Object.keys(e))n.has(r)||W("NATIVE_PROPERTY_UNKNOWN",`${o}/${r}`)}function ke(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&W("NATIVE_STRING_INVALID",t),e}function rd(e,t,o){e!==void 0&&(typeof e!="string"||e.length>o)&&W("NATIVE_STRING_INVALID",t)}function $o(e,t){e!==void 0&&typeof e!="boolean"&&W("NATIVE_BOOLEAN_REQUIRED",t)}function W(e,t){throw new be(e,t)}var ut=class extends Error{constructor(o,n){super(`${o}: ${n}`);this.pointer=o;this.reason=n}pointer;reason;code="NATIVE_MANAGED_CONCURRENCY_INVALID"};function Po(e,t,o){if(e===void 0)return;let n=(g,I)=>{throw new ut(g,I)},r=(g,I,T)=>((!g||typeof g!="object"||Array.isArray(g)||Object.keys(g).some(l=>!T.includes(l)))&&n(I,"object contains unsupported properties"),g),i=(g,I,T,l)=>{(!Number.isSafeInteger(g)||g<I||g>T)&&n(l,`expected integer ${I}..${T}`)},d=(g,I)=>{(typeof g!="string"||!/^[a-z][a-z0-9_-]{0,63}$/.test(g))&&n(I,"invalid code")},s=(g,I,T)=>((!Array.isArray(g)||g.length>I)&&n(T,"array exceeds bound"),g),a=(g,I)=>{let T=t.find(l=>l.code===g);return T||n(I,"unknown resource"),T},c=(g,I,T)=>{let l=g.schema.fields.find(y=>y.code===I);return!l&&I!=="id"&&n(T,"unknown field"),l},f=(g,I,T=!1)=>{r(g,I,Object.keys(g||{})),Object.keys(g).length>8&&n(I,"at most eight parameters");for(let[l,y]of Object.entries(g))if(d(l,I),r(y,I,["type","values","minimum","maximum","minLength","maxLength"]),y.type==="uuid")Object.keys(y).length!==1&&n(I,"uuid has no options");else if(T&&y.type==="boolean")r(y,I,["type"]);else if(T&&y.type==="string"&&y.values===void 0)r(y,I,["type","minLength","maxLength"]),i(y.maxLength,1,256,I),y.minLength!==void 0&&i(y.minLength,0,y.maxLength,I);else if(y.type==="string"){r(y,I,["type","values"]);let R=s(y.values,100,I);(!R.length||R.some(h=>typeof h!="string"||h.length>128)||new Set(R).size!==R.length)&&n(I,"finite string values required")}else y.type==="integer"?(r(y,I,["type","minimum","maximum"]),i(y.minimum,0,1e6,I),i(y.maximum,y.minimum,y.minimum+1e3,I)):n(I,"unsupported parameter type")},u=(g,I,T,l=!1)=>{r(g,T,["from","key","value"]),!(g.from==="input"&&Object.keys(g).length===2&&Object.hasOwn(I,g.key))&&((g.from==="actor"||l&&g.from==="allocation")&&Object.keys(g).length===1||g.from==="literal"&&Object.keys(g).length===2&&Object.hasOwn(g,"value")&&(g.value===null||["string","boolean"].includes(typeof g.value)||typeof g.value=="number"&&Number.isFinite(g.value))&&JSON.stringify(g.value).length<=512||n(T,"invalid binding"))},p=(g,I,T)=>{u(g,I,T),!(g.from==="input"&&I[g.key].type==="uuid")&&(g.from==="literal"&&typeof g.value=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(g.value)||n(T,"record and allocation identifiers require a UUID binding"))},_=(g,I,T)=>{u(g,I,T),!(g.from==="input"&&I[g.key].type==="integer"&&I[g.key].minimum>=1)&&(g.from==="literal"&&Number.isSafeInteger(g.value)&&g.value>=1||n(T,"expectedRevision requires a positive integer binding"))},E="/data/concurrency";JSON.stringify(e).length>131072&&n(E,"declaration exceeds 128 KiB");let A=r(e,E,["version","admission","reads","quotas","commands"]);A.version!==1&&n(E,"unsupported version"),r(A.admission,E,["perSecond","burst","maxInFlight"]),i(A.admission.perSecond,1,1e3,E),i(A.admission.burst,1,1e3,E),i(A.admission.maxInFlight,1,1e3,E);let O=(g,I)=>{let T=new Set;for(let l of g)d(l?.code,I),T.has(l.code)&&n(I,"duplicate code"),T.add(l.code)};O(s(A.reads,32,E),E),O(s(A.quotas,16,E),E),O(s(A.commands,32,E),E);for(let g of A.reads){let I=`${E}/reads/${g.code}`;r(g,I,["code","resourceCode","parameters","select","where","limit","scope","freshSeconds","staleSeconds","maxKeys","sourcePerSecond","dependencies"]);let T=a(g.resourceCode,I);f(g.parameters,I),["subject","application"].includes(g.scope)||n(I,"invalid cache scope"),g.scope==="application"&&T.dataPolicyCode&&n(I,"shared cache cannot bypass a row policy");let l=s(g.select,32,I);l.length||n(I,"select required"),l.forEach(R=>c(T,R,I));let y=s(g.dependencies,64,I);y.forEach(R=>c(T,R,I));for(let R of s(g.where||[],8,I))r(R,I,["field","value"]),c(T,R.field,I),u(R.value,g.parameters,I),g.scope==="application"&&R.value.from==="actor"&&n(I,"actor requires subject cache"),y.includes(R.field)||n(I,"filter dependency missing");l.some(R=>!y.includes(R))&&n(I,"selected field dependency missing"),i(g.limit,1,100,I),i(g.freshSeconds,1,300,I),i(g.staleSeconds,0,300,I),i(g.maxKeys,1,1e4,I),i(g.sourcePerSecond,1,20,I)}for(let g of A.quotas){let I=`${E}/quotas/${g.code}`;r(g,I,["code","sourceResource","capacityField","allocationResource","allocationField","reservationSeconds"]);let T=a(g.sourceResource,I),l=a(g.allocationResource,I);c(T,g.capacityField,I)?.type!=="number.integer"&&n(I,"capacity must be an integer"),(c(l,g.allocationField,I)?.type!=="uuid"||c(l,g.allocationField,I)?.nullable!==!1)&&n(I,"allocation reference must be a uuid"),l.surface?.mutationOwner!=="queued-command"&&n(I,"allocation model must be command owned"),g.reservationSeconds!==void 0&&i(g.reservationSeconds,10,86400,I)}new Set(A.quotas.map(g=>g.allocationResource)).size!==A.quotas.length&&n(E,"an allocation model has exactly one pool owner");for(let g of A.commands){let I=`${E}/commands/${g.code}`;r(g,I,["code","mode","intake","execution","capability","parameters","resourceKey","admission","deadlineSeconds","guards","operations","quota"]),g.mode!==void 0&&!["permit","durable"].includes(g.mode)&&n(I,"unsupported mode");let T=g.mode==="durable";if(f(g.parameters,I,T),u(g.resourceKey,g.parameters,I),o.some(l=>l.code===g.capability)||n(I,"command capability must be declared"),r(g.admission,I,["perSecond","burst","maxInFlight","maxQueue","maxWaitSeconds","permitSeconds"]),i(g.admission.perSecond,1,A.admission.perSecond,I),i(g.admission.burst,1,A.admission.burst,I),i(g.admission.maxInFlight,1,A.admission.maxInFlight,I),i(g.admission.maxQueue,1,1e4,I),i(g.admission.maxWaitSeconds,1,3600,I),(!T||g.admission.permitSeconds!==void 0)&&i(g.admission.permitSeconds,5,60,I),i(g.deadlineSeconds,10,3600,I),T){(g.operations!==void 0||g.guards!==void 0||g.quota!==void 0)&&n(I,"backend-plan does not accept static operations, guards or quota"),r(g.intake,I,["perSecond","burst","maxInFlight"]);for(let R of["perSecond","burst","maxInFlight"])i(g.intake[R],1,1e3,I);let l=r(g.execution,I,["kind","handlerCode","timeoutMs","resources","directory"]);l.kind!=="backend-plan"&&n(I,"durable requires backend-plan"),d(l.handlerCode,I),i(l.timeoutMs,100,3e4,I);let y=s(l.resources,32,I);y.length||n(I,"execution resources required"),new Set(y.map(R=>R.resourceCode)).size!==y.length&&n(I,"duplicate execution resource");for(let R of y){r(R,I,["resourceCode","readFields","writeOperations","writeFields"]);let h=a(R.resourceCode,I);for(let w of["readFields","writeFields"]){let j=s(R[w],64,I);new Set(j).size!==j.length&&n(I,"duplicate field"),j.forEach(L=>{w==="readFields"&&qe.has(L)||c(h,L,I)})}let $=s(R.writeOperations,3,I);(new Set($).size!==$.length||$.some(w=>!["create","update","increment"].includes(w)))&&n(I,"unsupported execution operation"),R.writeFields.some(w=>["id","revision","created_by","updated_by","created_at","updated_at"].includes(w))&&n(I,"record metadata is platform owned"),!$.length&&R.writeFields.length&&n(I,"write fields require an operation"),$.length&&!R.writeFields.length&&n(I,"write operations require fields"),A.quotas.some(w=>w.allocationResource===R.resourceCode)&&$.length&&n(I,"allocation references remain owned by their pool command")}if(l.directory!==void 0){r(l.directory,I,["mode","fields"]),l.directory.mode!=="current-initiator"&&n(I,"only current initiator allowed");let R=s(l.directory.fields,5,I);(!R.length||new Set(R).size!==R.length||R.some(h=>!["displayName","employeeNumber","primaryDepartment","departments","phone"].includes(h)))&&n(I,"unsupported directory fields")}continue}(g.execution!==void 0||g.intake!==void 0)&&n(I,"execution and intake require durable mode");for(let l of s(g.guards||[],8,I)){r(l,I,["resourceCode","id","conditions"]);let y=a(l.resourceCode,I);p(l.id,g.parameters,I);for(let R of s(l.conditions,16,I)){r(R,I,["kind","field","operator","value"]);let h=c(y,R.field,I);["eq","neq","lt","lte","gt","gte"].includes(R.operator)||n(I,"unsupported guard"),R.kind==="database-now"?(h?.type!=="datetime"||!["lt","lte","gt","gte"].includes(R.operator)||R.value!==void 0)&&n(I,"database-now requires datetime and an ordering operator"):(R.kind!==void 0&&R.kind!=="value"&&n(I,"unsupported condition kind"),u(R.value,g.parameters,I))}}for(let l of s(g.operations,8,I)){r(l,I,["operation","resourceCode","id","expectedRevision","data"]);let y=a(l.resourceCode,I);y.surface?.mutationOwner!=="queued-command"&&n(I,"command mutations require command owned models");let R=A.quotas.find(h=>h.allocationResource===l.resourceCode);R&&(l.operation==="create"?g.quota?.action!=="allocate"||g.quota.pool!==R.code:Object.hasOwn(l.data||{},R.allocationField))&&n(I,"allocation references are owned by their pool command"),["create","update"].includes(l.operation)||n(I,"unsupported operation"),l.operation==="update"?(p(l.id,g.parameters,I),_(l.expectedRevision,g.parameters,I)):(l.id!==void 0||l.expectedRevision!==void 0)&&n(I,"create has no caller supplied id/revision"),r(l.data,I,Object.keys(l.data||{})),Object.keys(l.data).length>32&&n(I,"too many fields");for(let[h,$]of Object.entries(l.data))h==="id"&&n(I,"record identifiers are platform owned"),c(y,h,I),u($,g.parameters,I,g.quota?.action==="allocate")}if(g.quota){let l=r(g.quota,I,["pool","action","units","mode","allocation"]),y=A.quotas.find(R=>R.code===l.pool);y||n(I,"unknown quota pool"),p(g.resourceKey,g.parameters,I),l.action==="allocate"?(r(l,I,["pool","action","units","mode"]),i(l.units,1,1e3,I),(!["committed","reserved"].includes(l.mode)||l.mode==="reserved"&&!y.reservationSeconds)&&n(I,"invalid allocation mode"),(g.operations.length!==1||g.operations[0].operation!=="create"||g.operations[0].resourceCode!==y.allocationResource||g.operations[0].data[y.allocationField]?.from!=="allocation")&&n(I,"allocation must atomically create its bound business record")):["confirm","release"].includes(l.action)?(r(l,I,["pool","action","allocation"]),p(l.allocation,g.parameters,I),g.operations.length&&n(I,"lifecycle owns allocation state; business reference remains immutable")):n(I,"invalid quota action")}else g.operations.length||n(I,"operations required")}let b=A.commands.filter(g=>g.mode==="durable").map(g=>g.execution.handlerCode);return new Set(b).size!==b.length&&n(E,"handler code must be unique"),JSON.parse(JSON.stringify(A))}var ze=class extends Error{constructor(o,n){super(`\u91D1\u989D\u751F\u547D\u5468\u671F\u58F0\u660E\u65E0\u6548\uFF1A${n}\uFF08${o}\uFF09`);this.pointer=o;this.reason=n}pointer;reason;code="NATIVE_DECIMAL_LIFECYCLE_INVALID"},Lo=["parentTransitions","childTransitions","fulfilledChildStatuses","lockedParentStatuses"],mi=["amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode","parentRelationValue","childRelationValue"],On=e=>!!(e&&typeof e=="object"&&!Array.isArray(e)),bn=e=>Array.isArray(e)?e.filter(On):[],we=(e,t)=>{throw new ze(e,t)},vo=e=>typeof e=="string"&&/^[A-Za-z0-9._:-]{1,128}$/.test(e),Vo=(e,t)=>e<t?-1:e>t?1:0;function Nn(e,t="/decimalReservationLifecycle"){if(e===void 0)return;if(!On(e)||Object.keys(e).some(r=>!Lo.includes(r))||Lo.some(r=>!Object.prototype.hasOwnProperty.call(e,r)))return we(t,"\u5FC5\u987B\u5B8C\u6574\u58F0\u660E\u56DB\u9879\u89C4\u5219\uFF0C\u4E0D\u80FD\u5305\u542B\u672A\u77E5\u5C5E\u6027");let o=r=>{let i=e[r];if(!Array.isArray(i)||i.length>64)return we(`${t}/${r}`,"\u72B6\u6001\u8FB9\u6700\u591A 64 \u6761");let d=new Set;return i.map((s,a)=>{let c=`${t}/${r}/${a}`;if(!On(s)||Object.keys(s).some(u=>u!=="from"&&u!=="to")||!vo(s.from)||!vo(s.to)||s.from===s.to)return we(c,"\u72B6\u6001\u8FB9\u5FC5\u987B\u5305\u542B\u4E0D\u540C\u7684\u6709\u6548 from/to");let f=JSON.stringify([s.from,s.to]);return d.has(f)?we(c,"\u72B6\u6001\u8FB9\u4E0D\u80FD\u91CD\u590D"):(d.add(f),{from:s.from,to:s.to})}).sort((s,a)=>Vo(s.from,a.from)||Vo(s.to,a.to))},n=r=>{let i=e[r];return!Array.isArray(i)||i.length<1||i.length>16||i.some(d=>!vo(d))||new Set(i).size!==i.length?we(`${t}/${r}`,"\u72B6\u6001\u96C6\u5408\u5FC5\u987B\u5305\u542B 1 \u5230 16 \u4E2A\u4E0D\u91CD\u590D\u7684\u6709\u6548\u72B6\u6001"):[...i].sort(Vo)};return{parentTransitions:o("parentTransitions"),childTransitions:o("childTransitions"),fulfilledChildStatuses:n("fulfilledChildStatuses"),lockedParentStatuses:n("lockedParentStatuses")}}function Fo(e,t,o="/config/data/resources"){bn(e).forEach((n,r)=>{let i=`${o}/${r}/decimalReservationLifecycle`,d=Nn(n.decimalReservationLifecycle,i);if(!d)return;let s=bn(t).map(u=>u.platformAccess?.decimalReservation).filter(u=>On(u)&&u.resourceCode===n.code),a=s.find(u=>u.mode==="reserve");if(!a)return we(i,"\u9700\u8981\u540C\u8D44\u6E90\u5DF2\u58F0\u660E\u7684 reserve \u52A8\u4F5C\u6620\u5C04");if(mi.some(u=>typeof a[u]!="string")||s.some(u=>mi.some(p=>u[p]!==a[p])))return we(i,"\u540C\u8D44\u6E90\u989D\u5EA6\u52A8\u4F5C\u7684\u5B57\u6BB5\u6620\u5C04\u5FC5\u987B\u4E00\u81F4");let c=bn(n.schema?.fields).find(u=>u.code===a.statusFieldCode);if(c?.type!=="option.single")return we(i,"\u989D\u5EA6\u72B6\u6001\u5B57\u6BB5\u5FC5\u987B\u4E3A option.single");let f=new Set(bn(c.options).map(u=>u.value));for(let u of Lo)if((u==="parentTransitions"||u==="childTransitions"?d[u].flatMap(_=>[_.from,_.to]):d[u]).some(_=>!f.has(_)))return we(`${i}/${u}`,"\u72B6\u6001\u5FC5\u987B\u6765\u81EA\u989D\u5EA6\u72B6\u6001\u5B57\u6BB5\u7684\u9009\u9879");if(s.some(u=>u.mode==="reserve"&&Array.isArray(u.eligibleParentStatuses)&&u.eligibleParentStatuses.some(p=>d.lockedParentStatuses.includes(String(p)))))return we(`${i}/lockedParentStatuses`,"\u9501\u5B9A\u7236\u72B6\u6001\u4E0D\u80FD\u5141\u8BB8\u65B0\u9884\u7559")})}var gi=require("crypto");var xo=new Set(["option.single","user.single","department.single","resource-ref.single"]),id=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","address","location","json"]),Ai=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image"]),sd=new Set(["option.single","user.single","department.single","resource-ref.single","signature","address","location"]),ad=new Set([...xo,...Ai,"signature","address","location","json"]);function dd(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=>Ei(n,o.has(n.code))).sort((n,r)=>n.code.localeCompare(r.code))}function Ei(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:Id(e),index:Ed(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 cd(e,t){if(t.type==="subtable")return null;let o=de(t.code),n=Ii(e,t),r=[n?` DEFAULT ${n}`:"",yd(o,t),ud(o,t)].join("");return`${o} ${t.storage}${r}`}function ld(e,t){return Ii(e,t)}function ud(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 fd(e){return e.type==="serial-number"||ht(e.type)&&e.type!=="subtable"}function pd(e,t){return t.filter(o=>o.type==="serial-number").map(o=>{let n=Rn(e,o.code),r=o.serial?.start??1;return`CREATE SEQUENCE IF NOT EXISTS ${n} AS bigint MINVALUE ${r} START WITH ${r} CACHE 1`})}function md(e,t){let o=Tn(e);return t.filter(n=>n.type==="serial-number").map(n=>`ALTER SEQUENCE ${Rn(e,n.code)} OWNED BY ${o}.${de(n.code)}`)}function _d(e,t){return t.filter(o=>o.type==="serial-number").map(o=>`GRANT USAGE, SELECT ON SEQUENCE ${Rn(e,o.code)} TO "openxiangda_data_api"`)}function gd(e,t){let o=Tn(e),n=[];for(let r of t){if(r.type==="subtable")continue;let i=de(r.code),d=de($e("idx",e,r.code,r.index));switch(r.index){case"btree":n.push(`CREATE INDEX IF NOT EXISTS ${d} ON ${o} (${i})`);break;case"btree-snapshot-expressions":{let s=de($e("idx",e,r.code,"snapshot-value")),a=de($e("idx",e,r.code,"snapshot-label"));n.push(`CREATE INDEX IF NOT EXISTS ${s} ON ${o} ((${i} ->> 'value'))`,`CREATE INDEX IF NOT EXISTS ${a} ON ${o} ((${i} ->> 'label'))`);break}case"gin-jsonb-path":n.push(`CREATE INDEX IF NOT EXISTS ${d} ON ${o} USING GIN (${i} jsonb_path_ops)`);break;case"gist-range":n.push(`CREATE INDEX IF NOT EXISTS ${d} ON ${o} USING GIST (${i})`);break;case"gin-trigram":{let s=xo.has(r.type)?`((${i} ->> 'label')) gin_trgm_ops`:`${i} gin_trgm_ops`;n.push(`CREATE INDEX IF NOT EXISTS ${d} ON ${o} USING GIN (${s})`);break}case"none":break}if(r.type==="serial-number"){let s=de($e("uidx",e,r.code,"serial"));n.push(`CREATE UNIQUE INDEX IF NOT EXISTS ${s} ON ${o} (${i})`)}}return n}function Ad(e,t,o,n){let r=Tn(e),i=Tn(t),d=de($e("uidx",e,"environment_id","subtable-parent")),s=de($e("idx",t,o,n,"subtable-child")),a=de($e("fk",t,o,e)),c=de(o),f=de(n);return[`CREATE UNIQUE INDEX IF NOT EXISTS ${d} ON ${r} ("tenant_id", "app_code", "environment_key", "id")`,`CREATE INDEX IF NOT EXISTS ${s} ON ${i} ("tenant_id", "app_code", "environment_key", ${c}, ${f}, "id")`,`DO $native_subtable$ BEGIN
2
+ ALTER TABLE ${i}
3
3
  ADD CONSTRAINT ${a}
4
4
  FOREIGN KEY ("tenant_id", "app_code", "environment_key", ${c})
5
- REFERENCES ${i} ("tenant_id", "app_code", "environment_key", "id")
5
+ REFERENCES ${r} ("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 ke(e,...t){return`${e}_${(0,fr.createHash)("sha256").update(t.join(":")).digest("hex").slice(0,32)}`}function de(e){if(!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(e))throw new Error("OPENXIANGDA_NATIVE_IDENTIFIER_INVALID");return`"${e}"`}function ud(e,t){return e.type==="subtable"?"none":t?"gin-trigram":e.indexed?["date-range","datetime-range"].includes(e.type)?"gist-range":Vo.has(e.type)?"btree-snapshot-expressions":Za.has(e.type)?"gin-jsonb-path":"btree":"none"}function fd(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 ed.has(e.type),"jsonb"}}function _r(e,t){if(Rt(t.type)&&t.type!=="subtable")return"'[]'::jsonb";if(t.type!=="serial-number")return"";let o=ur(t.serial?.prefix||""),n=t.serial?.digits??6;return`(${o} || lpad(nextval(${ur(Nn(e,t.code))})::text, ${n}, '0'))`}function pd(e,t){return pr.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'array')`:Qa.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'object')`:""}function On(e){return`"app_data".${de(e)}`}function Nn(e,t){let o=ke("seq",e,t);return`"app_data".${de(o)}`}function ur(e){return`'${e.replace(/'/g,"''")}'`}var gr=new Set(["option.single","option.multiple","user.single","user.multiple","department.single","department.multiple","resource-ref.single","resource-ref.multiple"]),md=new Set([...gr,"cascade.single","cascade.multiple","file","image","signature","address","location","json"]),Ar=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,_d=new Set(["__proto__","prototype","constructor"]),Tn=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 lt(e,t){let o=Er(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 Rn(e){return!!(e&&e.field.type==="user.single"&&e.valuePath==="value")}function Lo(e,t,o){if(!e||!t||!Ad(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 gd(e,t){let o=Er(t);if(!o)throw new Tn(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 Ad(e){let{field:t,valuePath:o}=e;if(!o)return!md.has(t.type);if(o==="value")return gr.has(t.type);if(!o.startsWith("snapshot."))return!1;let n=o.slice(9);return Ar.test(n)&&t.type.startsWith("resource-ref.")&&!!t.source?.snapshotFields?.includes(n)}function Er(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=>!Ar.test(o)||_d.has(o))||t.length===2&&t[1]!=="value"||t.length===3&&t[1]!=="snapshot"?null:t}var Ed=new Set(["option.single","user.single","department.single","resource-ref.single"]),Id=new Set(["text.short","text.long","text.rich","number.integer","number.decimal","boolean","date","time","datetime","uuid","serial-number"]),yd=new Set(["value","label","description","color"]),bd=new Set(["avatarUrl","employeeNo","title","mobile","email"]),Od=new Set(["fullPath","parent.value","parent.label"]),Nd=new Set(["country.value","country.label","province.value","province.label","city.value","city.label","district.value","district.label","street.value","street.label","detail","fullAddress"]),Td=new Set(["longitude","latitude","accuracy"]),Rd=new Set(["address","name","province","city","district","source"]);function Cd(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=wd(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 hd(e,t){if(Ed.has(e.type)&&yd.has(t)||e.type==="user.single"&&bd.has(t)||e.type==="department.single"&&Od.has(t))return St(t);if(e.type==="resource-ref.single"){let o=e.queryPathTypes?.[t];return o?{parts:t.split("."),type:o}:null}if(e.type==="address"&&Nd.has(t))return St(t);if(e.type==="location"){if(Td.has(t))return{parts:[t],type:"number.decimal"};if(Rd.has(t))return St(t);if(t==="capturedAt")return{parts:[t],type:"datetime"}}return null}function wd(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}`,Id.has(i.type)?i.type:"json"]]:[]})):{}}function St(e){return{parts:e.split("."),type:"text.short"}}var br=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Or=(e,t)=>Object.keys(e).length===t.length&&Object.keys(e).every(o=>t.includes(o)),Ir=e=>typeof e=="string"&&/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(e)&&e.length<=100,yr=e=>typeof e=="string"&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(e);function Fo(e){throw new Error(`OPENXIANGDA_WORKFLOW_STAGE_${e}`)}function xo(e){(!br(e)||!Or(e,["workflowCode","resourceCode","actor","runningNodeIds","allowedStatuses"])||!Ir(e.workflowCode)||!Ir(e.resourceCode)||!["initiator","reader"].includes(String(e.actor))||!Array.isArray(e.runningNodeIds)||e.runningNodeIds.length>32||new Set(e.runningNodeIds).size!==e.runningNodeIds.length||e.runningNodeIds.some(t=>typeof t!="string"||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(t))||!Array.isArray(e.allowedStatuses)||e.allowedStatuses.length>5||new Set(e.allowedStatuses).size!==e.allowedStatuses.length||e.allowedStatuses.some(t=>!["approved","rejected","cancelled","terminated","returned"].includes(t))||e.runningNodeIds.length+e.allowedStatuses.length===0)&&Fo("POLICY_INVALID")}function Sd(e){(!br(e)||!Or(e,["instanceId","subjectRecordId","expectedInstanceSequence"])||!yr(e.instanceId)||!yr(e.subjectRecordId)||!Number.isSafeInteger(e.expectedInstanceSequence)||e.expectedInstanceSequence<0)&&Fo("GUARD_INVALID")}function Dd(e,t,o){o?.some(n=>(n.kind==="record-match"||n.kind==="record-assert")&&n.resourceCode===e.resourceCode&&n.id.toLowerCase()===t.subjectRecordId.toLowerCase()&&n.assertions.some(i=>i.kind==="value"&&i.field==="revision"&&i.operator==="eq"&&Number.isSafeInteger(i.value)&&Number(i.value)>0))||Fo("SOURCE_GUARD_REQUIRED")}var kd={type:"object",additionalProperties:!1,required:["workflowCode","resourceCode","actor","runningNodeIds","allowedStatuses"],properties:{workflowCode:{type:"string",pattern:"^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$",maxLength:100},resourceCode:{type:"string",pattern:"^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$",maxLength:100},actor:{enum:["initiator","reader"]},runningNodeIds:{type:"array",maxItems:32,uniqueItems:!0,items:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$"}},allowedStatuses:{type:"array",maxItems:5,uniqueItems:!0,items:{enum:["approved","rejected","cancelled","terminated","returned"]}}},anyOf:[{properties:{runningNodeIds:{minItems:1}}},{properties:{allowedStatuses:{minItems:1}}}]};var ut=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n}code;pointer},ue=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Nr=(e,t)=>e===t||e==="*"||e.endsWith(":*")&&t.startsWith(e.slice(0,-1));function jo(e){let{policy:t,resource:o,baselineRoleCode:n,baselineCapabilities:i,pointer:r}=e,d=A=>A===void 0||A===!0||Array.isArray(A)&&A.length>0&&A.every(O=>typeof O=="string"&&O.length>0&&!e.baselineDeniedCapabilities?.some(b=>Nr(b,O))&&i.some(b=>Nr(b,O))),s=(A,O="")=>{throw new ut(A,`${r}/publicRead${O}`)},a=ue(t.publicRead);(!t.publicRead||Object.keys(a).length!==1||!Object.hasOwn(a,"fields")||!Array.isArray(a.fields)||a.fields.length<1||a.fields.length>1e3||a.fields.some(A=>typeof A!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(A))||new Set(a.fields).size!==a.fields.length)&&s("AUTHENTICATED_PUBLIC_READ_FIELDS_INVALID","/fields"),(!Array.isArray(t.operations)||t.operations.length!==1||t.operations[0]!=="read"||t.readExpression!==void 0||t.writeBoundary!==void 0)&&s("AUTHENTICATED_PUBLIC_READ_POLICY_NOT_READ_ONLY"),(!n||!o||o.code!==t.resourceCode||o.dataPolicyCode!==t.code||!d([ue(o.capabilities).read]))&&s("AUTHENTICATED_PUBLIC_READ_BASELINE_OR_RESOURCE_INVALID");let c=ue(o),f=ue(c.schema).fields;(!Array.isArray(f)||!f.length)&&s("AUTHENTICATED_PUBLIC_READ_RESOURCE_FIELDS_MISSING");let u=new Map(f.map(A=>[String(ue(A).code),ue(A)])),p=new Set(a.fields),_=ue(c.fieldPolicies);for(let A of p){let O=ue(u.get(A));(!u.has(A)||O.system===!0||ue(ue(c.surface).fields)[A]?.system===!0||Ge.has(A))&&s("AUTHENTICATED_PUBLIC_READ_FIELD_NOT_DECLARED",`/fields/${A}`),(O.type==="subtable"||O.subtable!==void 0)&&s("AUTHENTICATED_PUBLIC_READ_SUBTABLE_UNSUPPORTED",`/fields/${A}`),d(ue(_[A]).read)||s("AUTHENTICATED_PUBLIC_READ_FIELD_NOT_BASELINE_READABLE",`/fields/${A}`)}let E=[...u.keys()].filter(A=>!p.has(A));for(let A of E)d(ue(_[A]).read)&&s("AUTHENTICATED_PUBLIC_READ_PRIVATE_FIELD_ACCESSIBLE",`/fields/${A}`);E.length&&ht.some(A=>d(ue(_[A]).read))&&s("AUTHENTICATED_PUBLIC_READ_PRIVATE_HISTORY_ACCESSIBLE")}var Uo=["exact-v1","nfkc-space-v1","nfkc-upper-ascii-v1"],Mu=256,ft=class extends Error{constructor(o,n){super(`\u6761\u4EF6\u552F\u4E00\u952E\u58F0\u660E\u65E0\u6548\uFF1A${n}\uFF08${o}\uFF09`);this.pointer=o;this.reason=n}pointer;reason;code="NATIVE_UNIQUE_KEY_INVALID"},Wo=e=>!!(e&&typeof e=="object"&&!Array.isArray(e)),re=(e,t)=>{throw new ft(e,t)},Cn=(e,t)=>e<t?-1:e>t?1:0,Dt=(e,t,o)=>{Object.keys(e).some(n=>!t.includes(n))&&re(o,"\u4E0D\u652F\u6301\u672A\u77E5\u5C5E\u6027")};function Mo(e,t,o="/uniqueKeys"){if(e===void 0)return;if(!Array.isArray(e)||e.length>8)return re(o,"\u6BCF\u8D44\u6E90\u6700\u591A 8 \u6761\u89C4\u5219");let n=new Map(t.map(r=>[r.code,r])),i=new Set;return e.map((r,d)=>{let s=`${o}/${d}`;if(!Wo(r))return re(s,"\u89C4\u5219\u5FC5\u987B\u662F\u5BF9\u8C61");if(Dt(r,["code","fields","when"],s),typeof r.code!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(r.code)||r.code.length>20||i.has(r.code))return re(`${s}/code`,"\u9700\u8981\u4E0D\u91CD\u590D\u4E14\u4E0D\u8D85\u8FC7 20 \u5B57\u7B26\u7684 lower-kebab-case \u6807\u8BC6");if(i.add(r.code),!Array.isArray(r.fields)||r.fields.length<1||r.fields.length>4)return re(`${s}/fields`,"\u5FC5\u987B\u9009\u62E9 1 \u5230 4 \u4E2A\u5B57\u6BB5");let a=new Set,c=r.fields.map((_,E)=>{let A=`${s}/fields/${E}`;if(!Wo(_))return re(A,"\u5B57\u6BB5\u5FC5\u987B\u662F\u5BF9\u8C61");Dt(_,["fieldCode","normalizer"],A);let O=n.get(_.fieldCode);if(!O||!["text.short","uuid","option.single","resource-ref.single","user.single"].includes(O.type)||a.has(_.fieldCode))return re(`${A}/fieldCode`,"\u9700\u8981\u4E0D\u91CD\u590D\u7684\u77ED\u6587\u672C\u3001UUID\u3001\u5355\u9009\u3001\u5355\u8BB0\u5F55\u5F15\u7528\u6216\u5355\u4EBA\u5B57\u6BB5");a.add(_.fieldCode);let b=_.normalizer===void 0?"exact-v1":_.normalizer;return!Uo.includes(b)||O.type!=="text.short"&&b!=="exact-v1"?re(`${A}/normalizer`,"\u5F52\u4E00\u5316\u65B9\u5F0F\u4E0D\u652F\u6301\u6216\u4E0E\u5B57\u6BB5\u7C7B\u578B\u4E0D\u7B26"):{fieldCode:O.code,normalizer:b}}).sort((_,E)=>Cn(_.fieldCode,E.fieldCode)),f=r.when===void 0?[]:r.when;if(!Array.isArray(f)||f.length>4)return re(`${s}/when`,"\u6700\u591A 4 \u4E2A\u5408\u53D6\u6761\u4EF6");let u=new Set,p=f.map((_,E)=>{let A=`${s}/when/${E}`;if(!Wo(_))return re(A,"\u6761\u4EF6\u5FC5\u987B\u662F\u5BF9\u8C61");let O=n.get(_.fieldCode);if(!O)return re(`${A}/fieldCode`,"\u5B57\u6BB5\u4E0D\u5B58\u5728");let b;if(_.operator==="empty"||_.operator==="nonempty"){if(Dt(_,["fieldCode","operator"],A),O.type!=="text.short")return re(A,"\u7A7A\u503C\u6761\u4EF6\u4EC5\u652F\u6301\u77ED\u6587\u672C");b={fieldCode:O.code,operator:_.operator}}else if(_.operator==="in"||_.operator==="notIn"){Dt(_,["fieldCode","operator","values"],A);let I=new Set((O.options??[]).map(T=>T.value));if(O.type!=="option.single"||!Array.isArray(_.values)||_.values.length<1||_.values.length>16||_.values.some(T=>typeof T!="string"||T.length<1||T.length>128||!I.has(T))||new Set(_.values).size!==_.values.length)return re(A,"\u96C6\u5408\u6761\u4EF6\u9700\u8981 1 \u5230 16 \u4E2A\u4E0D\u91CD\u590D\u7684\u5DF2\u58F0\u660E\u5355\u9009\u503C");b={fieldCode:O.code,operator:_.operator,values:[..._.values].sort(Cn)}}else if(_.operator==="eq"||_.operator==="ne"){if(Dt(_,["fieldCode","operator","value"],A),O.type!=="boolean"||typeof _.value!="boolean")return re(A,"\u7B49\u503C\u6761\u4EF6\u4EC5\u652F\u6301\u5E03\u5C14\u5B57\u6BB5\u548C\u5E03\u5C14\u503C");b={fieldCode:O.code,operator:_.operator,value:_.value}}else return re(`${A}/operator`,"\u53EA\u652F\u6301 empty\u3001nonempty\u3001in\u3001notIn \u548C\u5E03\u5C14 eq\u3001ne");let g=JSON.stringify(b);return u.has(g)?re(A,"\u6761\u4EF6\u4E0D\u80FD\u91CD\u590D"):(u.add(g),b)}).sort((_,E)=>Cn(JSON.stringify(_),JSON.stringify(E)));return{code:r.code,fields:c,when:p}}).sort((r,d)=>Cn(r.code,d.code))}function Bo(e,t){let o=new Set(e.filter(n=>n.type==="user.single").map(n=>n.code));return t?.some(n=>n.fields.some(i=>o.has(i.fieldCode))||n.when?.some(i=>i.operator==="eq"||i.operator==="ne"))?"1.1.0":"1.0.0"}var hn={type:"string",pattern:"^[A-Za-z_][A-Za-z0-9_]{0,62}$"},$d={type:"array",maxItems:8,items:{type:"object",additionalProperties:!1,required:["code","fields"],properties:{code:{type:"string",maxLength:20,pattern:"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"},fields:{type:"array",minItems:1,maxItems:4,uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["fieldCode"],properties:{fieldCode:hn,normalizer:{enum:[...Uo]}}}},when:{type:"array",maxItems:4,uniqueItems:!0,items:{oneOf:[{type:"object",additionalProperties:!1,required:["fieldCode","operator"],properties:{fieldCode:hn,operator:{enum:["empty","nonempty"]}}},{type:"object",additionalProperties:!1,required:["fieldCode","operator","values"],properties:{fieldCode:hn,operator:{enum:["in","notIn"]},values:{type:"array",minItems:1,maxItems:16,uniqueItems:!0,items:{type:"string",minLength:1,maxLength:128}}}},{type:"object",additionalProperties:!1,required:["fieldCode","operator","value"],properties:{fieldCode:hn,operator:{enum:["eq","ne"]},value:{type:"boolean"}}}]}}}}};var Tr={"openxiangda.workflow.instance.completed.v2":"commit","openxiangda.workflow.instance.rejected.v2":"release","openxiangda.workflow.instance.withdrawn.v2":"release"};function Rr(e,t){let o=()=>{throw new Error("NATIVE_EVENT_DECIMAL_RESERVATION_INVALID")},n=p=>!p||typeof p!="object"||Array.isArray(p)?o():p,i=n(e);if(Object.keys(i).some(p=>!["resourceCode","workflowCode","outcomes"].includes(p))||typeof i.resourceCode!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(i.resourceCode)||typeof i.workflowCode!="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(i.workflowCode)||t.execution!==void 0||!Array.isArray(i.outcomes)||!i.outcomes.length||i.outcomes.length>3)return o();let r=t.resources.find(p=>p.code===i.resourceCode),d=t.reservations.find(p=>p.mode==="reserve"&&p.resourceCode===i.resourceCode),s=t.workflows.find(p=>p.code===i.workflowCode);if(!r||!d||!s||s.resourceCode!==r.code)return o();let a=r.fields.find(p=>p.code===d.statusFieldCode);if(a?.type!=="option.single")return o();let c=new Set(a.options?.map(p=>p.value)),f=new Set,u=i.outcomes.map(p=>{let _=n(p),E=_.eventType;return Object.keys(_).some(A=>!["eventType","mode","eligibleChildStatuses"].includes(A))||typeof E!="string"||!Object.prototype.hasOwnProperty.call(Tr,E)||!t.eventTypes.includes(E)||f.has(E)||_.mode!==Tr[E]||!Array.isArray(_.eligibleChildStatuses)||!_.eligibleChildStatuses.length||_.eligibleChildStatuses.length>16||new Set(_.eligibleChildStatuses).size!==_.eligibleChildStatuses.length||_.eligibleChildStatuses.some(A=>typeof A!="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(A)||!c.has(A))?o():(f.add(E),{eventType:E,mode:_.mode,eligibleChildStatuses:[..._.eligibleChildStatuses].sort()})}).sort((p,_)=>p.eventType.localeCompare(_.eventType));return{resourceCode:i.resourceCode,workflowCode:i.workflowCode,outcomes:u}}function Cr(e,t){let o=n=>Array.isArray(n)?n.filter(i=>i&&typeof i=="object"&&!Array.isArray(i)):[];return{eventTypes:Array.isArray(t.eventTypes)?t.eventTypes:[],execution:t.execution,resources:o(e.data?.resources).map(n=>({code:n.code,fields:o(n.schema?.fields).map(i=>({code:i.code,type:i.type,options:o(i.options).map(r=>({value:r.value}))}))})),reservations:o(e.backend?.operations).flatMap(n=>n.platformAccess?.decimalReservation?[n.platformAccess.decimalReservation]:[]),workflows:o(e.workflows?.definitions).map(n=>({code:n.definition?.code,resourceCode:n.definition?.subject?.resourceCode}))}}var wn=class extends Error{constructor(o,n){super(n);this.pointer=o}pointer;code="NATIVE_EVENT_ACTION_INVALID"};function Ko(e,t,o="/events/subscriptions"){if(e.execution===void 0)return;let n=(A,O)=>{throw new wn(`${o}${A}`,O)},i=(A,O,b)=>((!A||typeof A!="object"||Array.isArray(A)||Object.keys(A).some(g=>!b.includes(g)))&&n(O,"Invalid action object or unsupported property"),A),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(A=>!/^openxiangda\.data\.record\.(created|updated|deleted)\.v2$/.test(A)))&&n("/eventTypes","Native data actions require declared data events");let d=e.filter?.resourceCodes;(!Array.isArray(d)||!d.length||d.length>20)&&n("/filter/resourceCodes","Native actions require explicit source resources");let s=new Map(t.map(A=>[A.code,A])),a=d.map(A=>{let O=s.get(A);return O||n("/filter/resourceCodes","Unknown source resource"),new Set((O.schema?.fields||[]).map(b=>b.code))}),c=new Set(e.payload?.fields||[]),f=e.payload?.includeChanges===!0,u=(A,O)=>{let b=i(A,O,["source","path","value"]);if(b.source==="literal"){(!Object.hasOwn(b,"value")||Object.hasOwn(b,"path"))&&n(O,"Literal binding requires only value");let l;try{l=JSON.stringify(b.value)}catch{n(O,"Literal must be JSON")}return(l===void 0||Buffer.byteLength(l)>65536)&&n(O,"Literal is too large or not JSON"),{source:"literal",value:JSON.parse(l)}}(b.source!=="event"||typeof b.path!="string"||Object.hasOwn(b,"value"))&&n(O,"Expected a literal or event binding");let g=b.path.split(".");(g.length>8||g.some(l=>!/^[A-Za-z0-9_-]+$/.test(l)||["__proto__","prototype","constructor"].includes(l)))&&n(O,"Invalid event path");let I=/^data\.projection\.([A-Za-z][A-Za-z0-9_]{0,62})$/.exec(b.path),T=/^data\.changes\.([A-Za-z][A-Za-z0-9_]{0,62})\.(before|after)$/.exec(b.path);if(I||T){let l=(I||T)[1];a.some(y=>!y.has(l))&&n(O,"Source field must exist on every filtered resource"),c.add(l),T&&(f=!0)}else["id","time","type","subject","data.recordId","data.revision","data.operation","data.resourceCode"].includes(b.path)||n(O,"Event path is not part of the data event contract");return{source:"event",path:b.path}};(!Array.isArray(r.operations)||r.operations.length<1||r.operations.length>16)&&n("/execution/operations","Expected 1 to 16 operations");let p={},_=r.operations.map((A,O)=>{let b=`/execution/operations/${O}`,g=i(A,b,["operation","resourceCode","data","id","expectedRevision"]);["create","update","delete"].includes(g.operation)||n(b,"Unsupported Native operation");let I=s.get(g.resourceCode);I||n(b,"Unknown action target resource");let T=new Map((I.schema?.fields||[]).map(y=>[y.code,y])),l=g.data===void 0?{}:i(g.data,`${b}/data`,[...T.keys()]);return Object.keys(l).length>32&&n(b,"Maximum 32 mapped fields per operation"),g.operation==="create"&&(g.id!==void 0||g.expectedRevision!==void 0)&&n(b,"Create does not accept id or expectedRevision"),g.operation==="delete"&&g.data!==void 0&&n(b,"Delete does not accept data"),Object.keys(l).some(y=>T.get(y)?.type==="serial-number")&&n(b,"Generated fields cannot be assigned"),p[g.resourceCode]=Z(I),{operation:g.operation,resourceCode:g.resourceCode,...g.operation==="create"?{}:{id:u(g.id,`${b}/id`),expectedRevision:u(g.expectedRevision,`${b}/expectedRevision`)},...g.operation==="delete"?{}:{data:Object.fromEntries(Object.entries(l).map(([y,R])=>[y,u(R,`${b}/data/${y}`)]))}}});(c.size>32||[...c].some(A=>a.some(O=>!O.has(A))))&&n("/payload/fields","Payload must contain at most 32 declared source fields");let E={kind:"native-data",version:1,operations:_,resourceDigests:p};return Buffer.byteLength(JSON.stringify(E))>65536&&n("/execution","Action plan exceeds 64 KiB"),{execution:{...E,digest:Z(E)},payload:{includeChanges:f,fields:[...c].sort()}}}function Fe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function qo(e,t){if(e?.instanceCommands===void 0)return[];let o=Fe(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 d=Fe(r),s=i==="withdraw"?["beforeFact","reasonRequired"]:["beforeFact","capability"];if(!d||!Object.keys(d).length||Object.keys(d).some(a=>!s.includes(a))||Object.hasOwn(d,"reasonRequired")&&typeof d.reasonRequired!="boolean"){n.push(`WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID:${i}`);continue}if(i==="terminate"){let a=d.capability;(typeof a!="string"||a.length>255||!/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._-]+$/.test(a)||t&&(!a.startsWith(`app:${t.appCode}:`)||!t.capabilities.includes(a)))&&n.push("WORKFLOW_INSTANCE_TERMINATE_CAPABILITY_INVALID")}if(Object.hasOwn(d,"beforeFact")){let a=d.beforeFact,c=Fe(e.inputSchema),f=Fe(Fe(c?.properties)?.[a]),u=Fe(Fe(e.subject)?.factProjection)?.[a],p=t?.fields.get(u);(typeof a!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(a)||!Array.isArray(c?.required)||!c.required.includes(a)||f?.type!=="string"||f?.format!=="date-time"||typeof u!="string"||t&&(p?.type!=="datetime"||p.nullable===!0))&&n.push(`WORKFLOW_INSTANCE_COMMAND_DEADLINE_FACT_INVALID:${i}`)}}return n}function vd(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 Pd(e){return e?.withdraw?.reasonRequired!==!1}function Go(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,d,s]=t,a=t[8],c=new Date(Date.UTC(Number(o),Number(n),0)).getUTCDate();if(Number(n)<1||Number(n)>12||Number(i)<1||Number(i)>c||Number(r)>23||Number(d)>59||Number(s)>59||a!=="Z"&&(Number(a.slice(1,3))>23||Number(a.slice(4))>59))return null;let f=Date.parse(e);return Number.isFinite(f)?f:null}function Vd(e,t,o,n){let i=e?.[t];if(!i||i.beforeFact===void 0)return null;let r=i.beforeFact,d=Fe(o),s=r&&d&&Object.hasOwn(d,r)?Go(d[r]):null,a=n instanceof Date?n.getTime():Go(n);return s===null||a===null||!Number.isFinite(a)?"WORKFLOW_V2_CANCELLATION_DEADLINE_INVALID":a<s?null:"WORKFLOW_V2_CANCELLATION_DEADLINE_PASSED"}var pt="openxiangda.workflow.step.requested.v2",Ho=[pt,"openxiangda.workflow.step.result_received.v2","openxiangda.workflow.step.completed.v2","openxiangda.workflow.step.continuation_failed.v2"],Sn=16384,Sr=2048,Ld="steps",Yo=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,Dr=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,ze=new Set(["__proto__","prototype","constructor"]),K=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[Object.prototype,null].includes(Object.getPrototypeOf(e)),kr=e=>{try{let t=JSON.stringify(e);return t===void 0?1/0:new TextEncoder().encode(t).length}catch{return 1/0}},mt=(e,t,o=0)=>{if(o>32)return!1;if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((r,d)=>mt(r,t[d],o+1));if(!K(e)||!K(t))return!1;let n=Object.keys(e).filter(r=>e[r]!==void 0),i=Object.keys(t).filter(r=>t[r]!==void 0);return n.length===i.length&&n.every(r=>Object.hasOwn(t,r)&&mt(e[r],t[r],o+1))};function zo(e,t){let o=0,n=(i,r)=>++o>1e4||r>8?!1:i===null||typeof i=="boolean"||typeof i=="string"?!0:typeof i=="number"?Number.isFinite(i):Array.isArray(i)?i.length<=200&&i.every(d=>n(d,r+1)):K(i)&&Object.keys(i).length<=32&&Object.keys(i).every(d=>!ze.has(d))&&Object.values(i).every(d=>n(d,r+1));return kr(e)<=t&&n(e,0)}function $r(e){return!K(e)||Object.keys(e).some(t=>!["executionId","handlerVersion","inputDigest","expectedFactRevision","output","receipt"].includes(t))?!1:/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i.test(e.executionId||"")&&Number.isSafeInteger(e.handlerVersion)&&e.handlerVersion>=1&&e.handlerVersion<=1e6&&/^[a-f0-9]{64}$/.test(e.inputDigest||"")&&Number.isSafeInteger(e.expectedFactRevision)&&e.expectedFactRevision>=0&&K(e.output)&&zo(e.output,Sn)&&(e.receipt===void 0||K(e.receipt)&&zo(e.receipt,Sr))}function Fd(e){return K(e)&&Object.keys(e).every(t=>["executionId","nodeId","handlerCode","handlerVersion","mode","dataTransaction","input","inputDigest","expectedFactRevision"].includes(t))&&typeof e.nodeId=="string"&&Yo.test(e.nodeId)&&!ze.has(e.nodeId)&&typeof e.handlerCode=="string"&&/^[a-z][a-z0-9-]{0,100}$/.test(e.handlerCode)&&e.handlerCode.endsWith(`-v${e.handlerVersion}`)&&["pure","reconciled-effect"].includes(e.mode)&&(e.dataTransaction===void 0||e.dataTransaction===!0&&e.mode==="reconciled-effect")&&$r({executionId:e.executionId,handlerVersion:e.handlerVersion,inputDigest:e.inputDigest,expectedFactRevision:e.expectedFactRevision,output:e.input})}function kt(e,t,o=Sn){if(!zo(t,o))return!1;let n=1e4,i=(r,d,s)=>{if(--n<0||s>8||!K(r))return!1;let a=d===null?"null":Array.isArray(d)?"array":typeof d=="number"&&Number.isSafeInteger(d)?"integer":typeof d,c=Array.isArray(r.type)?r.type:[r.type];if(!c.includes(a)&&!(a==="integer"&&c.includes("number"))||r.enum!==void 0&&(!Array.isArray(r.enum)||!r.enum.some(f=>mt(f,d)))||Object.hasOwn(r,"const")&&!mt(r.const,d))return!1;if(typeof d=="number")return Number.isFinite(d)&&(r.minimum===void 0||d>=r.minimum)&&(r.maximum===void 0||d<=r.maximum);if(typeof d=="string"){let f=Array.from(d).length;return(r.minLength===void 0||f>=r.minLength)&&(r.maxLength===void 0||f<=r.maxLength)}return Array.isArray(d)?d.length<=r.maxItems&&(r.minItems===void 0||d.length>=r.minItems)&&d.every(f=>i(r.items,f,s+1)):K(d)?!K(r.properties)||Object.keys(d).some(f=>ze.has(f)||!Object.hasOwn(r.properties,f))||(Array.isArray(r.required)?r.required:[]).some(f=>!Object.hasOwn(d,f))||r.minProperties!==void 0&&Object.keys(d).length<r.minProperties||r.maxProperties!==void 0&&Object.keys(d).length>r.maxProperties?!1:Object.entries(d).every(([f,u])=>i(r.properties[f],u,s+1)):d===null||typeof d=="boolean"};return i(e,t,0)}function vr(e){return typeof e=="string"&&e.length<=256&&e.split(".").length<=8&&e.split(".").every(t=>Yo.test(t)&&!ze.has(t))}function $t(e){let t=0,o=(n,i)=>{if(!K(n)||i>6||++t>256||Object.keys(n).some(s=>!["type","title","description","properties","required","additionalProperties","items","maxItems","minItems","maxLength","minLength","minimum","maximum","enum","const","maxProperties","minProperties"].includes(s)))return!1;let r=Array.isArray(n.type)?n.type:[n.type];if(!r.length||r.length>2||r.some(s=>!["object","array","string","integer","number","boolean","null"].includes(s))||r.length>1&&(!r.includes("null")||new Set(r).size!==r.length))return!1;for(let s of["title","description"])if(n[s]!==void 0&&(typeof n[s]!="string"||n[s].length>2e3))return!1;for(let s of["minimum","maximum"])if(n[s]!==void 0&&(typeof n[s]!="number"||!Number.isFinite(n[s])))return!1;for(let[s,a]of[["maxItems",200],["minItems",200],["maxLength",16384],["minLength",16384],["maxProperties",32],["minProperties",32]])if(n[s]!==void 0&&(!Number.isSafeInteger(n[s])||n[s]<0||n[s]>a))return!1;for(let[s,a]of[["minimum","maximum"],["minItems","maxItems"],["minLength","maxLength"],["minProperties","maxProperties"]])if(n[s]!==void 0&&n[a]!==void 0&&n[s]>n[a])return!1;if(["properties","required","additionalProperties","maxProperties","minProperties"].some(s=>n[s]!==void 0)&&!r.includes("object")||["items","maxItems","minItems"].some(s=>n[s]!==void 0)&&!r.includes("array")||["maxLength","minLength"].some(s=>n[s]!==void 0)&&!r.includes("string")||["minimum","maximum"].some(s=>n[s]!==void 0)&&!r.some(s=>s==="integer"||s==="number")||n.enum!==void 0&&(!Array.isArray(n.enum)||!n.enum.length||n.enum.length>100)||r.includes("object")&&(!K(n.properties)||n.additionalProperties!==!1||Object.keys(n.properties).length>32||Object.keys(n.properties).some(s=>!Dr.test(s)||ze.has(s))||n.required!==void 0&&(!Array.isArray(n.required)||new Set(n.required).size!==n.required.length||n.required.some(s=>typeof s!="string"||!Object.hasOwn(n.properties,s)))||n.minProperties!==void 0&&n.minProperties>Object.keys(n.properties).length||n.maxProperties!==void 0&&n.maxProperties<(n.required?.length||0)||!Object.values(n.properties).every(s=>o(s,i+1)))||r.includes("array")&&(!Number.isSafeInteger(n.maxItems)||!o(n.items,i+1)))return!1;let d={...n};return delete d.enum,delete d.const,!(n.enum!==void 0&&(!n.enum.every(s=>kt(d,s))||n.enum.some((s,a)=>n.enum.slice(0,a).some(c=>mt(s,c))))||Object.hasOwn(n,"const")&&!kt(d,n.const))};return K(e)&&e.type==="object"&&kr(e)<=Sn&&o(e,0)}function vt(e){let t=Object.fromEntries(Object.values(e.nodes||{}).filter(o=>o?.kind==="action").map(o=>[o.id,o.outputSchema]));return Object.keys(t).length?{...e.inputSchema,properties:{...e.inputSchema?.properties,steps:{type:"object",additionalProperties:!1,properties:t}}}:e.inputSchema||{}}function Pr(e,t){let o=e;for(let n of t.split(".")){if(!K(o?.properties)||!Object.hasOwn(o.properties,n))return;o=o.properties[n]}return K(o)?o:void 0}var hr=(e,t)=>!!Pr(e,t);function xd(e){return K(e)&&Object.keys(e).every(t=>["version","mode","dataTransaction","inputSchema","outputSchema"].includes(t))&&Number.isSafeInteger(e.version)&&e.version>=1&&e.version<=1e6&&["pure","reconciled-effect"].includes(e.mode)&&(e.dataTransaction===void 0||e.dataTransaction===!0&&e.mode==="reconciled-effect")&&$t(e.inputSchema)&&$t(e.outputSchema)}function wr(e){return e.kind==="approval"?[e.onApprove,e.onReject]:e.kind==="condition"?[...Array.isArray(e.branches)?e.branches.map(t=>t.target):[],e.otherwise]:e.kind==="cc"||e.kind==="action"?[e.next]:[]}function Jo(e,t=0){return!K(e)||t>16?[]:e.op==="path"?typeof e.path=="string"?[e.path]:[]:["left","right","value"].flatMap(o=>Jo(e[o],t+1)).concat(Array.isArray(e.values)?e.values.flatMap(o=>Jo(o,t+1)):[])}function Pt(e,t){if(!K(e)||!K(e.nodes))return["WORKFLOW_STEP_DEFINITION_INVALID"];let o=e.nodes,n=Object.entries(o).filter(([,s])=>s?.kind==="action");if(!n.length)return[];let i=[];Object.hasOwn(e.inputSchema?.properties||{},"steps")&&i.push("WORKFLOW_STEP_FACT_NAMESPACE_RESERVED");let r=vt(e);for(let[s,a]of n){(Object.keys(a).some(u=>!["id","kind","title","next","handler","inputSchema","outputSchema","inputs"].includes(u))||a.id!==s||!Yo.test(s)||ze.has(s)||typeof a.title!="string"||!a.title.trim()||a.title.length>255||typeof a.next!="string"||!Object.hasOwn(o,a.next))&&i.push(`WORKFLOW_STEP_NODE_INVALID:${s}`);let c=a.handler;(!K(c)||Object.keys(c).some(u=>!["code","version","mode","dataTransaction"].includes(u))||!Number.isSafeInteger(c.version)||c.version<1||c.version>1e6||!/^[a-z][a-z0-9-]{0,100}$/.test(c.code||"")||!String(c.code).endsWith(`-v${c.version}`)||!["pure","reconciled-effect"].includes(c.mode)||c.dataTransaction!==void 0&&(c.dataTransaction!==!0||c.mode!=="reconciled-effect"))&&i.push(`WORKFLOW_STEP_HANDLER_INVALID:${s}`);let f=$t(a.inputSchema);if((!f||!$t(a.outputSchema))&&i.push(`WORKFLOW_STEP_SCHEMA_INVALID:${s}`),!K(a.inputs)||Object.keys(a.inputs).length>32){i.push(`WORKFLOW_STEP_INPUTS_INVALID:${s}`);continue}for(let u of Array.isArray(a.inputSchema?.required)?a.inputSchema.required:[])Object.hasOwn(a.inputs,u)||i.push(`WORKFLOW_STEP_INPUT_REQUIRED:${s}:${u}`);for(let[u,p]of Object.entries(a.inputs)){if(!Dr.test(u)||ze.has(u)||!Object.hasOwn(a.inputSchema?.properties||{},u)||!K(p)){i.push(`WORKFLOW_STEP_INPUT_INVALID:${s}:${u}`);continue}if(p.source==="literal")(!f||Object.keys(p).some(_=>!["source","value"].includes(_))||!Object.hasOwn(p,"value")||!kt(a.inputSchema.properties[u],p.value))&&i.push(`WORKFLOW_STEP_LITERAL_INVALID:${s}:${u}`);else if(p.source!=="fact"||Object.keys(p).some(_=>!["source","path"].includes(_))||!vr(p.path)||!hr(r,p.path))i.push(`WORKFLOW_STEP_FACT_PATH_INVALID:${s}:${u}`);else if(f){let _=Pr(r,p.path),E=a.inputSchema.properties[u],A=Array.isArray(_.type)?_.type:[_.type],O=Array.isArray(E.type)?E.type:[E.type];A.some(b=>!O.includes(b)&&!(b==="integer"&&O.includes("number")))&&i.push(`WORKFLOW_STEP_FACT_TYPE_MISMATCH:${s}:${u}`)}}}let d=(s,a)=>{let c=new Set,f=[e.startAt||""];for(;f.length&&c.size<=200;){let u=f.shift();if(!(u===a||c.has(u)||!o[u])){if(u===s)return!0;c.add(u),f.push(...wr(o[u]))}}return!1};for(let[s,a]of Object.entries(o)){if(!K(a))continue;let c=a.kind==="action"?Object.values(a.inputs||{}).flatMap(u=>u?.source==="fact"?[u.path]:[]):(Array.isArray(a.branches)?a.branches:[]).flatMap(u=>Jo(u?.when)),f=t?.bindings?.[a.binding];f&&c.push(...[f.inputPath,f.departmentIdFrom,f.resourceIdFrom,f.scope?.valueFrom].filter(u=>typeof u=="string"));for(let u of c.filter(p=>typeof p=="string"&&p.startsWith("steps."))){let p=u.split(".")[1];(o[p]?.kind!=="action"||p===s||!hr(r,u)||d(s,p))&&i.push(`WORKFLOW_STEP_OUTPUT_NOT_AVAILABLE:${s}:${u}`)}}if(t)for(let[,s]of n){let a=new Set,c=[s.next];for(;c.length&&a.size<=200;){let f=c.shift();if(a.has(f)||!K(o[f]))continue;a.add(f);let u=o[f];if(!(u.kind==="action"||u.kind==="end")){if(u.kind==="approval"){let p=t.bindings?.[u.binding];p&&["application_provider","initiator_select"].includes(p.provider)&&i.push(`WORKFLOW_STEP_NEXT_PROVIDER_REQUIRES_PREPARED_RESULT:${f}`);continue}c.push(...wr(u))}}}return[...new Set(i)]}function jd(e,t){let o={};for(let[n,i]of Object.entries(e.inputs)){let r=i.source==="literal"?i.value:i.path.split(".").reduce((d,s)=>K(d)&&Object.hasOwn(d,s)?d[s]:void 0,t);r!==void 0&&(o[n]=r)}if(!kt(e.inputSchema,o))throw new Error("WORKFLOW_STEP_INPUT_SCHEMA_INVALID");return o}function Xo(e,t,o){let n=Dn(e),i=[];Object.keys(n).length&&!o&&i.push("WORKFLOW_STEP_BACKEND_REQUIRED");for(let r of Object.keys(n)){let d=t.find(s=>s.code===r);(!d||d.execution||d.action||!Array.isArray(d.eventTypes)||d.eventTypes.length!==1||d.eventTypes[0]!==pt||!K(d.filter)||Object.keys(d.filter).length!==1||!K(d.filter.workflowStep)||Object.keys(d.filter.workflowStep).length!==1||d.filter.workflowStep.handlerCode!==r||!K(d.payload)||d.payload.includeChanges!==!1||!Array.isArray(d.payload.fields)||d.payload.fields.length)&&i.push(`WORKFLOW_STEP_SUBSCRIPTION_INVALID:${r}`)}for(let r of t)(r.eventTypes?.includes(pt)&&!n[r.code]||r.filter?.workflowStep&&!n[r.code])&&i.push(`WORKFLOW_STEP_HANDLER_NOT_DECLARED:${r.code}`);return i}function Dn(e){let t={};for(let o of e){let n=Pt(o);if(n.length)throw new Error(n.join("; "));for(let i of Object.values(o.nodes||{})){if(i.kind!=="action")continue;let r={version:i.handler.version,mode:i.handler.mode,...i.handler.dataTransaction?{dataTransaction:!0}:{},inputSchema:i.inputSchema,outputSchema:i.outputSchema},d=t[i.handler.code];if(d&&!mt(d,r))throw new Error(`WORKFLOW_STEP_HANDLER_CONTRACT_CONFLICT:${i.handler.code}`);t[i.handler.code]=r}}return t}var fe=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Je=(e,t)=>typeof e=="string"&&!!e.trim()&&e.length<=t,Wd=/^[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z][A-Za-z0-9_-]*){0,15}$/,Zo=e=>typeof e=="string"&&e.length<=256&&Wd.test(e)&&!e.split(".").some(t=>["__proto__","prototype","constructor"].includes(t));function kn(e,t){let o=fe(e),n=!0;for(let i of t.split(".")){n&&=Array.isArray(o.required)&&o.required.includes(i);let r=fe(o.properties)[i];if(!r||typeof r!="object")return null;o=fe(r)}return{schema:o,required:n}}function Qo(e){let t=new Set,o=[],n=2048,i=(r,d)=>{if(--n<0||d>20){o.push("WORKFLOW_EXPRESSION_BUDGET_EXCEEDED");return}let s=fe(r);if(s.op==="path")Zo(s.path)?t.add(s.path):o.push("WORKFLOW_EXPRESSION_PATH_INVALID");else{if(s.op==="literal")return;if(s.op==="and"||s.op==="or")if(!Array.isArray(s.values)||!s.values.length||s.values.length>128)o.push("WORKFLOW_EXPRESSION_GROUP_INVALID");else for(let a of s.values){if(n<0)break;i(a,d+1)}else s.op==="not"||s.op==="exists"?i(s.value,d+1):["eq","neq","gt","gte","lt","lte","in","contains"].includes(String(s.op))?(i(s.left,d+1),i(s.right,d+1)):o.push("WORKFLOW_EXPRESSION_OPERATOR_INVALID")}};return i(e,0),{paths:[...t],errors:[...new Set(o)]}}function ei(e){if(e?.readability===void 0)return[];let t=[],o=vt(e),n=fe(e.readability);(Object.keys(n).some(s=>!["variables","logic"].includes(s))||!Object.keys(n).length)&&t.push("WORKFLOW_READABILITY_INVALID");let i=fe(n.variables);n.variables!==void 0&&(typeof n.variables!="object"||Array.isArray(n.variables)||n.variables===null)&&t.push("WORKFLOW_VARIABLES_INVALID"),Object.keys(i).length>128&&t.push("WORKFLOW_VARIABLE_LIMIT_EXCEEDED");for(let[s,a]of Object.entries(i)){let c=fe(a);(!Zo(s)||!kn(o,s))&&t.push(`WORKFLOW_VARIABLE_SOURCE_UNKNOWN:${s}`),(!Je(c.label,160)||Object.keys(c).some(f=>!["label","unit","description"].includes(f))||c.unit!==void 0&&!Je(c.unit,32)||c.description!==void 0&&!Je(c.description,2e3))&&t.push(`WORKFLOW_VARIABLE_METADATA_INVALID:${s}`)}let r=n.logic===void 0?[]:n.logic;(!Array.isArray(r)||r.length>32)&&t.push("WORKFLOW_LOGIC_LIMIT_INVALID");let d=new Set;for(let s of Array.isArray(r)?r.slice(0,32):[]){let a=fe(s),c=String(a.code||"");e.approvedDelegation&&c==="kernel-approved-delegation"&&t.push("WORKFLOW_LOGIC_PLATFORM_CODE_RESERVED"),(!/^[a-z][a-z0-9-]{2,63}$/.test(c)||d.has(c)||!Je(a.title,160)||!Je(a.description,4e3)||Object.keys(a).some(f=>!["code","title","description","phase","nodeId","inputPaths","outputPaths","source"].includes(f)))&&t.push(`WORKFLOW_LOGIC_METADATA_INVALID:${c}`),d.add(c),(!["submission","node_input","completion"].includes(String(a.phase))||a.phase==="node_input"&&!fe(e.nodes)[String(a.nodeId)]||a.phase!=="node_input"&&a.nodeId!==void 0)&&t.push(`WORKFLOW_LOGIC_ANCHOR_INVALID:${c}`);for(let f of["inputPaths","outputPaths"]){let u=a[f];if(!(f==="outputPaths"&&u===void 0))if(!Array.isArray(u)||u.length>32||new Set(u).size!==u.length)t.push(`WORKFLOW_LOGIC_PATHS_INVALID:${c}:${f}`);else for(let p of u)(!Zo(p)||!kn(o,p))&&t.push(`WORKFLOW_LOGIC_SOURCE_UNKNOWN:${c}:${String(p)}`)}if(a.source!==void 0){let f=fe(a.source);(!Je(f.path,256)||String(f.path).startsWith("/")||String(f.path).includes("..")||String(f.path).includes("://")||!/^sha256:[a-f0-9]{64}$/.test(String(f.digest))||f.symbol!==void 0&&!Je(f.symbol,160)||Object.keys(f).some(u=>!["path","symbol","digest"].includes(u)))&&t.push(`WORKFLOW_LOGIC_SOURCE_REFERENCE_INVALID:${c}`)}}for(let s of Object.values(fe(e.nodes))){let a=fe(s),c=Array.isArray(a.branches)?a.branches:[];for(let f of c){let u=Qo(f.when);t.push(...u.errors.map(p=>`${p}:${a.id}`));for(let p of u.paths)kn(o,p)||t.push(`WORKFLOW_VARIABLE_SOURCE_UNKNOWN:${a.id}:${p}`)}}return[...new Set(t)]}function Ud(e,t){let o=vt(e),n=[],i=new Map,r=[];for(let c of Object.values(e.nodes)){if(c.kind==="approval")for(let[f,u,p]of[["approve",c.onApprove,"\u540C\u610F"],["reject",c.onReject,"\u62D2\u7EDD"]])u&&n.push({id:`${c.id}:${f}`,from:c.id,to:u,kind:f,label:p,variablePaths:[]});if(c.kind==="approval")for(let f of new Set(c.returnTargets||[]))e.nodes[f]?.kind==="correction"&&n.push({id:`${c.id}:return:${f}`,from:c.id,to:f,kind:"return",label:"\u9000\u56DE\u53D1\u8D77\u4EBA\u8865\u6B63",variablePaths:[]});if(c.kind==="correction"&&c.next&&n.push({id:`${c.id}:resubmit`,from:c.id,to:c.next,kind:"resubmit",label:"\u91CD\u65B0\u63D0\u4EA4\uFF0C\u4ECE\u8D77\u70B9\u91CD\u7B97",variablePaths:[]}),c.kind==="cc"&&c.next&&n.push({id:`${c.id}:next`,from:c.id,to:c.next,kind:"next",label:"\u6284\u9001\u540E\u7EE7\u7EED",variablePaths:[]}),c.kind==="action"&&c.next){let f=Object.values(c.inputs||{}).flatMap(u=>u.source==="fact"?[u.path]:[]);for(let u of f)i.has(u)||i.set(u,new Set),i.get(u).add(c.id);n.push({id:`${c.id}:next`,from:c.id,to:c.next,kind:"next",label:"\u6210\u529F\u56DE\u6267\u540E\u7EE7\u7EED",variablePaths:f})}if(c.kind==="condition"){for(let[f,u]of(c.branches||[]).entries()){let p=Qo(u.when);for(let _ of p.paths)i.has(_)||i.set(_,new Set),i.get(_).add(c.id);n.push({id:`${c.id}:branch:${f}`,from:c.id,to:u.target,kind:"branch",label:u.label||`\u6761\u4EF6 ${f+1}`,priority:f+1,expression:u.when,variablePaths:p.paths}),r.push(...p.errors.map(_=>({code:_,path:c.id})))}c.otherwise&&n.push({id:`${c.id}:default`,from:c.id,to:c.otherwise,kind:"default",label:"\u5747\u4E0D\u6EE1\u8DB3\u65F6",variablePaths:[]})}}let d=[...e.readability?.logic||[]];if(e.approvedDelegation){let c=e.approvedDelegation,f=c.confirmer==="initiator"?"\u7533\u8BF7\u4EBA\u672C\u4EBA":"\u6240\u9009\u4EE3\u7406\u4EBA";d.push({code:"kernel-approved-delegation",title:"\u6279\u51C6\u540E\u6574\u6279\u6388\u6743\u4EE3\u7406",phase:"completion",inputPaths:[c.requestsField],description:`\u6279\u51C6\u65F6\u6838\u9A8C${f}\u5728\u5F53\u524D\u9000\u56DE\u5468\u671F\u5B8C\u6210\u201C${e.nodes[c.confirmationNodeId]?.title||c.confirmationNodeId}\u201D\u7684\u4EBA\u5DE5\u786E\u8BA4\uFF1B\u968F\u540E\u91CD\u65B0\u6838\u9A8C\u53CC\u65B9\u5F53\u524D\u8D26\u53F7\u3001\u804C\u8D23\u3001\u4FEE\u8BA2\u3001\u8303\u56F4\u4E0E\u5B8C\u6574\u6709\u6548\u671F\uFF0C\u6574\u6279\u6388\u6743\uFF08\u6700\u591A${c.maxRequests}\u884C\uFF09\u3002\u4EFB\u4E00\u884C\u5931\u8D25\uFF0C\u6279\u51C6\u4E0E\u5168\u90E8\u6388\u6743\u4E00\u8D77\u56DE\u6EDA\uFF1B\u539F\u547D\u4EE4\u6062\u590D\u4E0D\u91CD\u65B0\u6FC0\u6D3B\u5DF2\u64A4\u9500\u6388\u6743\u3002`})}let a=[...new Set([...i.keys(),...Object.keys(e.readability?.variables||{}),...d.flatMap(c=>[...c.inputPaths,...c.outputPaths||[]])])].slice(0,128).map(c=>{let f=kn(o,c),u=e.readability?.variables?.[c],p=c.split("."),_=e.subject?.factProjection[p[0]],E=p[0]==="steps"?e.nodes[p[1]]:void 0;return f||r.push({code:"WORKFLOW_VARIABLE_SOURCE_UNKNOWN",path:c}),{path:c,label:u?.label||String(f?.schema.title||c),type:String(f?.schema.type||"unknown"),...u,required:f?.required||!1,usedBy:[...i.get(c)||[]],source:f&&E?.handler?{kind:"step_output",nodeId:E.id,handlerCode:E.handler.code,handlerVersion:E.handler.version}:f&&_&&e.subject?{kind:"subject_field",resourceCode:e.subject.resourceCode,fieldPath:[_,...p.slice(1)].join(".")}:{kind:f?"input":"unknown"}}});return{schemaVersion:"openxiangda.workflow-graph/v2",workflowCode:e.code,definitionDigest:t,startAt:e.startAt,fixedTopology:!0,branchStrategy:"first_match",nodes:Object.values(e.nodes).map(c=>({id:c.id,kind:c.kind,title:c.title||c.id,...c.binding?{binding:c.binding}:{},...c.mode?{mode:c.mode}:{},...c.outcome?{outcome:c.outcome}:{},...c.kind==="cc"?{emptyPolicy:c.emptyPolicy,notify:c.notify!==!1}:{},...c.kind==="approval"?{emptyPolicy:c.emptyPolicy||"block",initiatorApprovalPolicy:c.initiatorApprovalPolicy||"manual",...c.completionDeadline?{completionDeadline:{...c.completionDeadline}}:{}}:{},...c.kind==="action"&&c.handler?{businessStep:{handler:c.handler,inputs:c.inputs||{},outputPaths:Object.keys(fe(c.outputSchema).properties||{}).map(f=>`steps.${c.id}.${f}`)}}:{}})),edges:n,variables:a,logic:d,diagnostics:r}}function Vr(e,t=[]){let o=i=>{let r=t.find(d=>d.path===i)?.label;return r&&r!==i?r:void 0},n=o(e);if(n)return n;for(let i=e.lastIndexOf(".");i>0;i=e.lastIndexOf(".",i-1)){let r=o(e.slice(0,i));if(!r)continue;let d=e.slice(i+1);return d==="value"?`${r}\uFF08\u503C\uFF09`:d==="label"?`${r}\uFF08\u663E\u793A\u540D\u79F0\uFF09`:`${r}.${d}`}return e}function Vt(e,t=[],o=0){if(!e||o>20)return"\u65E0\u6CD5\u8BC6\u522B\u7684\u6761\u4EF6";if(e.op==="path")return Vr(e.path,t);if(e.op==="literal")return JSON.stringify(e.value)??"\u7F3A\u503C";if(e.op==="and"||e.op==="or")return e.values.slice(0,128).map(d=>`\uFF08${Vt(d,t,o+1)}\uFF09`).join(e.op==="and"?" \u4E14 ":" \u6216 ");if(e.op==="not"||e.op==="exists")return`${e.op==="not"?"\u4E0D\u6EE1\u8DB3":"\u5B58\u5728"}\uFF08${Vt(e.value,t,o+1)}\uFF09`;if(!("left"in e))return"\u65E0\u6CD5\u8BC6\u522B\u7684\u6761\u4EF6";let n={eq:"=",neq:"\u2260",gt:">",gte:"\u2265",lt:"<",lte:"\u2264",in:"\u5C5E\u4E8E",contains:"\u5305\u542B"},i=e.left.op==="path"?e.left.path:void 0,r=i&&e.right.op==="literal"&&typeof e.right.value=="number"?t.find(d=>d.path===i)?.unit:void 0;return`${Vt(e.left,t,o+1)} ${n[e.op]} ${Vt(e.right,t,o+1)}${r?` ${r}`:""}`}function Lr(e,t=0){return!Array.isArray(e)||e.length>64||t>1?!1:e.every(o=>{if(!o||typeof o!="object"||Array.isArray(o)||o.readonlyWhen!==void 0)return!1;if(o.subtable!==void 0){let n=o.subtable;return n&&n.create===!1&&n.delete===!1&&n.reorder===!1&&Lr(n.fields,t+1)}return o.readonly===!0})}function _t(e){let t=[];for(let[o,n]of Object.entries(e?.nodes||{}))if(n.initiatorApprovalPolicy!==void 0){if(n.kind!=="approval"||!["manual","auto_approve"].includes(n.initiatorApprovalPolicy)){t.push(`WORKFLOW_INITIATOR_APPROVAL_POLICY_INVALID:${o}`);continue}n.initiatorApprovalPolicy==="auto_approve"&&((n.taskPageCode!==void 0&&(typeof n.taskPageCode!="string"||!Lr(e.taskPages?.[n.taskPageCode]?.fields))||[n.fieldPolicy?.default,...Object.values(n.fieldPolicy?.fields||{})].some(i=>i==="edit"||i==="edit_required"))&&t.push(`WORKFLOW_INITIATOR_APPROVAL_INPUT_REQUIRED:${o}`),n.operationPolicy?.approve?.commentRequired===!0&&t.push(`WORKFLOW_INITIATOR_APPROVAL_COMMENT_REQUIRED:${o}`))}return t}function Md(e,t,o,n,i){return e.kind==="approval"&&e.initiatorApprovalPolicy==="auto_approve"&&_t({nodes:{node:e},...i?{taskPages:i}:{}}).length===0&&t!=="return_review"&&!!o&&n.user_id===o&&n.status==="active"&&n.participant_kind==="primary"&&["resolution","resolution_retry"].includes(n.source||"")&&!n.source_participant_id&&!n.delegate_authorization_id}var Zu=8,Bd={type:"array",minItems:2,maxItems:8,uniqueItems:!0,items:{type:"string",maxLength:128,pattern:"^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$"}};function Lt(e){if(e.roleCodes===void 0)return[];let t=e.roleCodes;if(!["app_role","app_role_in_scope"].includes(e.provider||"")||e.roleCode!==void 0||e.candidateField!==void 0||!Array.isArray(t)||t.length<2||t.length>8||new Set(t).size!==t.length||t.some(o=>typeof o!="string"||o.length>128||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(o)))return["WORKFLOW_V2_BINDING_ROLE_UNION_INVALID"];if(e.provider==="app_role_in_scope"){let o=e.scope,n=typeof o?.value=="string"&&o.value.length>0&&o.value.length<=255&&o.valueFrom===void 0,i=typeof o?.valueFrom=="string"&&o.valueFrom.length<=255&&/^[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z][A-Za-z0-9_-]*)*$/.test(o.valueFrom)&&!o.valueFrom.split(".").some(r=>["__proto__","prototype","constructor"].includes(r))&&o.value===void 0;if(!o||typeof o!="object"||Array.isArray(o)||Object.keys(o).some(r=>!["dimension","value","valueFrom"].includes(r))||typeof o.dimension!="string"||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(o.dimension)||!n&&!i)return["WORKFLOW_V2_BINDING_ROLE_UNION_SCOPE_INVALID"]}else if(e.scope!==void 0)return["WORKFLOW_V2_BINDING_ROLE_UNION_SCOPE_INVALID"];return[]}function Kd(e){return e.roleCodes?[...e.roleCodes]:e.roleCode?[e.roleCode]:[]}function ti(e){return e.some(t=>Object.values(t.binding.bindings).some(o=>o.roleCodes!==void 0))}function ni(e){if(e.selectedInputPath===void 0)return[];let t=e.selectedInputPath;return!["app_role","app_role_in_scope"].includes(e.provider||"")||e.candidateField!==void 0||e.inputPath!==void 0||e.routing!==void 0||e.roleCode===void 0&&e.roleCodes===void 0||typeof t!="string"||t.length>255||!/^[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z][A-Za-z0-9_-]*)*$/.test(t)||t.split(".").some(o=>["__proto__","constructor","prototype"].includes(o))?["WORKFLOW_V2_ROLE_INPUT_SELECTION_INVALID"]:[]}function oi(e){return e.some(t=>Object.values(t.binding.bindings).some(o=>o.selectedInputPath!==void 0))}var Fr=20,xr=200,jr=["fixed_users","initiator","input_users","form_field_users","app_role","app_role_in_scope","previous_node_actor"];function $n(e,t){let o=[];for(let[n,i]of Object.entries(e?.nodes||{})){if(i?.kind!=="cc"||((Object.keys(i).some(a=>!["id","kind","title","binding","next","emptyPolicy","notify","administration"].includes(a))||typeof i.title!="string"||!i.title.trim()||i.title.length>255||typeof i.binding!="string"||!i.binding.trim()||i.binding.length>255||typeof i.next!="string"||!i.next.trim()||!e.nodes?.[i.next]||!["block","skip"].includes(i.emptyPolicy)||i.notify!==void 0&&typeof i.notify!="boolean")&&o.push(`WORKFLOW_CC_NODE_INVALID:${n}`),!t))continue;let r=t.bindings?.[i.binding];if(!r){o.push(`WORKFLOW_CC_BINDING_NOT_FOUND:${n}`);continue}jr.includes(r.provider)||o.push(`WORKFLOW_CC_PROVIDER_INVALID:${n}`);let d=r.min??1,s=r.max??20;(!Number.isSafeInteger(d)||!Number.isSafeInteger(s)||d<1||s<d||s>200||r.provider==="fixed_users"&&(!Array.isArray(r.users)||!r.users.length||r.users.length>s))&&o.push(`WORKFLOW_CC_RECIPIENT_LIMIT_INVALID:${n}`)}return[...new Set(o)]}var Pn=["approve","reject","return","transfer","delegate","add_assignee"],Vn=["fixed_users","app_role","app_role_in_scope"],Gd=["single","any","all","sequence"],xe=e=>!!e&&typeof e=="object"&&!Array.isArray(e),He=(e,t)=>Object.keys(e).every(o=>t.includes(o)),vn=(e,t,o)=>Array.isArray(e)&&e.length>0&&e.length<=o&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n));function gt(e){return e.allowedOperations||[...Pn]}function Wr(e,t){return t?.commentRequired??e==="reject"}function Ur(e,t){return!["transfer","delegate","add_assignee","return"].includes(e)||t?.reasonRequired!==!1}function Mr(e,t,o={},n=!1){return!(!xe(e)||!Object.keys(e).length||!He(e,n?["enabled","label","commentRequired","reasonRequired"]:["label","commentRequired","reasonRequired"])||e.label!==void 0&&(typeof e.label!="string"||!e.label.trim()||e.label.length>40||/[\u0000-\u001f\u007f]/.test(e.label))||e.enabled!==void 0&&(typeof e.enabled!="boolean"||["approve","reject"].includes(t)&&!e.enabled)||e.commentRequired!==void 0&&(typeof e.commentRequired!="boolean"||!["approve","reject"].includes(t)||n&&Wr(t,o)&&!e.commentRequired)||e.reasonRequired!==void 0&&(typeof e.reasonRequired!="boolean"||!["transfer","delegate","add_assignee","return"].includes(t)||n&&Ur(t,o)&&!e.reasonRequired))}function Ln(e,t){let o=[];for(let[n,i]of Object.entries(e?.nodes||{})){if(!xe(i))continue;let r=i.administration,d=i.operationPolicy;if(i.kind==="cc"){(d!==void 0||r!==void 0&&(!xe(r)||!He(r,["assigneeProviders"])))&&o.push(`WORKFLOW_NODE_ADMINISTRATION_INVALID:${n}`),r?.assigneeProviders!==void 0&&!vn(r.assigneeProviders,Vn,3)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_PROVIDERS_INVALID:${n}`),r?.assigneeProviders?.includes("app_role_in_scope")&&t&&!t.bindings[i.binding||""]?.scope&&o.push(`WORKFLOW_NODE_ADMINISTRATION_SCOPE_REQUIRED:${n}`);continue}if(i.kind!=="approval"){(r!==void 0||d!==void 0)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_APPROVAL_REQUIRED:${n}`);continue}if(d!==void 0&&(!xe(d)||Object.keys(d).length>8||Object.entries(d).some(([a,c])=>!Pn.includes(a)||!gt(i).includes(a)||!Mr(c,a)))&&o.push(`WORKFLOW_NODE_OPERATION_POLICY_INVALID:${n}`),r===void 0)continue;if(!xe(r)||!He(r,["modes","assigneeProviders","operations"])){o.push(`WORKFLOW_NODE_ADMINISTRATION_INVALID:${n}`);continue}r.modes!==void 0&&(!vn(r.modes,Gd,4)||!r.modes.includes(i.mode))&&o.push(`WORKFLOW_NODE_ADMINISTRATION_MODES_INVALID:${n}`),r.assigneeProviders!==void 0&&!vn(r.assigneeProviders,Vn,3)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_PROVIDERS_INVALID:${n}`);let s=t?.bindings[i.binding||""];s&&Array.isArray(r.assigneeProviders)&&r.assigneeProviders.includes("app_role_in_scope")&&!s.scope&&o.push(`WORKFLOW_NODE_ADMINISTRATION_SCOPE_REQUIRED:${n}`),r.operations!==void 0&&(!vn(r.operations,Pn,8)||r.operations.some(a=>!gt(i).includes(a)))&&o.push(`WORKFLOW_NODE_ADMINISTRATION_OPERATIONS_INVALID:${n}`)}return o}function qd(e,t,o,n){let i=[];if(!e||!xe(o)||!Object.keys(o).length||!He(o,["title","description","assignee","mode","operations"]))return["WORKFLOW_V2_NODE_CONFIGURATION_PATCH_INVALID"];let r=o;for(let s of["title","description"])r[s]!==void 0&&(typeof r[s]!="string"||r[s].length>(s==="title"?255:1e3)||s==="title"&&!r[s].trim())&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_PATCH_INVALID");let d=e.administration;if(r.mode!==void 0&&(e.kind!=="approval"||!d?.modes?.includes(r.mode))&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_MODE_READONLY"),r.operations!==void 0&&(e.kind!=="approval"||!xe(r.operations)||!Object.keys(r.operations).length||Object.keys(r.operations).length>8||Object.entries(r.operations).some(([s,a])=>!d?.operations?.includes(s)||!gt(e).includes(s)||!Mr(a,s,e.operationPolicy?.[s],!0)))&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_OPERATION_INVALID"),r.assignee!==void 0){let s=r.assignee,a=d?.assigneeProviders||(e.kind==="approval"&&t&&Vn.includes(t.provider)?[t.provider]:[]);if(t?.selectedInputPath&&!["app_role","app_role_in_scope"].includes(s?.provider||"")&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_PROVIDER_READONLY"),!xe(s)||!["approval","cc"].includes(e.kind)||!a.includes(s.provider)||s.provider==="app_role_in_scope"&&!t?.scope)i.push("WORKFLOW_V2_NODE_CONFIGURATION_PROVIDER_READONLY");else if(s.provider==="fixed_users"){let c=e.kind==="cc"?t?.min??1:e.emptyPolicy==="skip"?0:1,f=e.kind==="cc"?Math.min(t?.max??20,200):200;(!He(s,["provider","users"])||!Array.isArray(s.users)||s.users.length<c||s.users.length>f||new Set(s.users).size!==s.users.length||s.users.some(u=>typeof u!="string"||!u.trim()||u.length>255))&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_USERS_INVALID")}else s.roleCodes!==void 0?(!He(s,["provider","roleCodes"])||Lt({...s,...s.provider==="app_role_in_scope"?{scope:t?.scope}:{}}).length)&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_ROLE_INVALID"):(!He(s,["provider","roleCode"])||typeof s.roleCode!="string"||!/^[a-z][a-z0-9_-]{0,127}$/.test(s.roleCode))&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_ROLE_INVALID")}return i.push(..._t({nodes:{node:{...e,operationPolicy:ii(e,r).operationPolicy}},...n?{taskPages:n}:{}})),e.completionDeadline&&ii(e,r).operationPolicy.approve?.commentRequired===!0&&i.push("WORKFLOW_COMPLETION_DEADLINE_INPUT_REQUIRED:node"),i}function ii(e,t){let o=Object.fromEntries(gt(e).flatMap(n=>{let i=n,r=t?.operations?.[i],d={...e.operationPolicy?.[i],...r?.label!==void 0?{label:r.label}:{},...r?.commentRequired!==void 0?{commentRequired:r.commentRequired}:{},...r?.reasonRequired!==void 0?{reasonRequired:r.reasonRequired}:{}};return Object.keys(d).length?[[i,d]]:[]}));return{mode:t?.mode||e.mode,initiatorApprovalPolicy:e.initiatorApprovalPolicy||"manual",allowedOperations:gt(e).filter(n=>t?.operations?.[n]?.enabled!==!1),operationPolicy:o,fieldPolicy:{default:e.fieldPolicy?.default||"readonly",fields:{...e.fieldPolicy?.fields}}}}var ri=["fixed_users","input_users","form_field_users","app_role","app_role_in_scope"];function Fn(e,t){let o=[];for(let[n,i]of Object.entries(e?.nodes||{}))i.kind==="cc"||i.emptyPolicy===void 0||(i.kind!=="approval"||!["block","skip"].includes(i.emptyPolicy)?o.push(`WORKFLOW_APPROVAL_EMPTY_POLICY_INVALID:${n}`):i.emptyPolicy==="skip"&&t&&!ri.includes(t.bindings?.[i.binding||""]?.provider)&&o.push(`WORKFLOW_APPROVAL_EMPTY_PROVIDER_UNSUPPORTED:${n}`));return o}function zd(e,t){return e.kind==="approval"&&e.emptyPolicy==="skip"&&t?.emptyResult==="no_candidates"&&ri.includes(t.provider)&&Array.isArray(t.candidates)&&t.candidates.length===0&&Array.isArray(t.selected)&&t.selected.length===0&&Array.isArray(t.warnings)&&t.warnings.length===0}function si(e,t){let o=Object.values(e.nodes||{}).filter(n=>n.binding===t);return o.length>0&&o.every(n=>n.kind==="approval"&&n.emptyPolicy==="skip")}function Br(e,t=0){return!Array.isArray(e)||e.length>64||t>1?!0:e.some(o=>!o||typeof o!="object"||Array.isArray(o)||o.required===!0||o.requiredWhen!==void 0||o.subtable!==void 0&&(!o.subtable||Br(o.subtable.fields,t+1)))}function Jd(e){let t=e.afterSeconds;return`\u8FDB\u5165\u540E ${t%86400===0?`${t/86400} \u5929`:t%3600===0?`${t/3600} \u5C0F\u65F6`:t%60===0?`${t/60} \u5206\u949F`:`${t} \u79D2`}\u672A\u5B8C\u6210\uFF0C\u81EA\u52A8\u540C\u610F`}function ai(e){let t=[];for(let[o,n]of Object.entries(e?.nodes||{})){if(!n||typeof n!="object"||n.completionDeadline===void 0)continue;let i=n.completionDeadline;if(n.kind!=="approval"||!i||typeof i!="object"||Array.isArray(i)||Object.keys(i).length!==2||Object.keys(i).some(d=>!["afterSeconds","action"].includes(d))||i.action!=="approve"||!Number.isInteger(i.afterSeconds)||i.afterSeconds<1||i.afterSeconds>2592e3){t.push(`WORKFLOW_COMPLETION_DEADLINE_INVALID:${o}`);continue}n.allowedOperations&&!n.allowedOperations.includes("approve")&&t.push(`WORKFLOW_COMPLETION_DEADLINE_APPROVE_UNAVAILABLE:${o}`);let r=n.taskPageCode?e.taskPages?.[n.taskPageCode]:void 0;(n.taskPageCode&&(!r||Br(r.fields))||[n.fieldPolicy?.default,...Object.values(n.fieldPolicy?.fields||{})].includes("edit_required")||n.operationPolicy?.approve?.commentRequired===!0||e.commandHandlers?.approve!==void 0)&&t.push(`WORKFLOW_COMPLETION_DEADLINE_INPUT_REQUIRED:${o}`)}return t}var Kr="openxiangda.workflow-rejection-notification/v1",df=4096;function Gr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function At(e,t){return typeof e=="string"&&e.trim().length>0&&e.length<=t}function di(e,t){return Object.keys(e).sort().join(",")===t.sort().join(",")}function ci(e){let t=e?.rejectionNotification;return t===void 0?[]:!Gr(t)||!di(t,["recipient","title","summary"])||t.recipient!=="record_last_modifier"||!At(t.title,160)||!At(t.summary,500)?["WORKFLOW_REJECTION_NOTIFICATION_INVALID"]:At(e.subject?.resourceCode,63)?[]:["WORKFLOW_REJECTION_NOTIFICATION_SUBJECT_REQUIRED"]}function Hd(e){if(!Gr(e)||e.schemaVersion!==Kr||e.recipient!=="record_last_modifier"||!At(e.title,160)||!At(e.summary,500))return!1;let t=["schemaVersion","recipient","title","summary","status","sourceRevision"];if(e.status==="ready"){if(!di(e,[...t,"userId"])||!At(e.userId,255)||!Number.isSafeInteger(e.sourceRevision)||Number(e.sourceRevision)<1)return!1}else if(e.status==="skipped"){if(!di(e,[...t,"reason"])||!["record_missing","modifier_missing","modifier_ineligible"].includes(String(e.reason))||(e.reason==="record_missing"?e.sourceRevision!==null:!Number.isSafeInteger(e.sourceRevision)||Number(e.sourceRevision)<1))return!1}else return!1;return new TextEncoder().encode(JSON.stringify(e)).byteLength<=4096}function li(e,t){let o=e.commandHandlers;if(o===void 0)return[];if(!o||typeof o!="object"||Array.isArray(o)||!Object.keys(o).length||Object.keys(o).some(i=>!["approve","reject","withdraw","resubmit"].includes(i)))return["WORKFLOW_BUSINESS_COMMAND_HANDLERS_INVALID"];let n=[];o.resubmit&&!Object.values(e.nodes||{}).some(i=>i.kind==="correction")&&n.push("WORKFLOW_BUSINESS_CORRECTION_REQUIRED");for(let[i,r]of Object.entries(o)){if(!r||typeof r!="object"||Array.isArray(r)||Object.keys(r).some(s=>!["operationCode","transitionPolicy","derivedSubjectFields"].includes(s))||r.transitionPolicy!==void 0&&(i!=="approve"||r.transitionPolicy!=="workflow")||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(r.operationCode||"")){n.push("WORKFLOW_BUSINESS_COMMAND_HANDLER_INVALID");continue}if(r.derivedSubjectFields!==void 0){let s=r.derivedSubjectFields,a=new Set(Object.values(e.subject?.factProjection||{}));(i!=="resubmit"||!Array.isArray(s)||s.length<1||s.length>32||new Set(s).size!==s.length||s.some(c=>typeof c!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(c)||!a.has(c)||Ge.has(c)||["createdBy","updatedBy","createdAt","updatedAt"].includes(c)||Object.values(e.taskPages||{}).some(f=>f.fields?.some(u=>u.code===c&&u.readonly!==!0))))&&n.push("WORKFLOW_CORRECTION_DERIVED_SUBJECT_FIELDS_INVALID")}if(!t)continue;let d=t.find(s=>s.code===r.operationCode);if(!d){n.push("WORKFLOW_BUSINESS_COMMAND_OPERATION_MISSING");continue}(d.method!=="POST"||d.browser?.exposure!=="authenticated"||d.browser.behavior!=="controlled"||d.browser.idempotency!=="required"||d.browser.fileIntent||d.browser.subject?.resourceCode!==e.subject?.resourceCode||d.browser.subject?.inputField!=="recordId"||!d.platformAccess?.workflow?.codes?.includes(e.code)||!d.platformAccess.workflow.businessCommands?.includes(i))&&n.push("WORKFLOW_BUSINESS_COMMAND_OPERATION_INVALID")}return["approve","reject","withdraw"].some(i=>Object.hasOwn(o,i))&&Object.values(e.nodes||{}).some(i=>i.kind==="approval"&&(i.emptyPolicy==="skip"||i.initiatorApprovalPolicy==="auto_approve"))&&n.push("WORKFLOW_BUSINESS_COMMAND_AUTOMATIC_DECISION_FORBIDDEN"),[...new Set(n)]}var Yd={type:"object",additionalProperties:!1,required:["workflowCode","target","recordId","expectedRevision","commandToken","idempotencyKey","input"],properties:{workflowCode:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_-]{0,127}$"},target:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","id","command"],properties:{kind:{const:"task"},id:{type:"string",format:"uuid"},command:{enum:["approve","reject","resubmit"]}}},{type:"object",additionalProperties:!1,required:["kind","id","command"],properties:{kind:{const:"instance"},id:{type:"string",format:"uuid"},command:{const:"withdraw"}}}]},recordId:{type:"string",format:"uuid"},expectedRevision:{type:"integer",minimum:1},commandToken:{type:"string",pattern:"^[A-Za-z0-9_-]{43}$"},idempotencyKey:{type:"string",minLength:1,maxLength:128},input:{type:"object",maxProperties:64}}};var qr=["fixed_users","initiator","app_role","app_role_in_scope"],Xd=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function xn(e,t){let o=e?.launchPreflight;if(o===void 0)return[];if(!Xd(o)||Object.keys(o).join(",")!=="requiredApprovalNodes"||!Array.isArray(o.requiredApprovalNodes)||o.requiredApprovalNodes.length<1||o.requiredApprovalNodes.length>20||new Set(o.requiredApprovalNodes).size!==o.requiredApprovalNodes.length||o.requiredApprovalNodes.some(i=>typeof i!="string"||!/^[A-Za-z][A-Za-z0-9_-]{0,127}$/.test(i)))return["WORKFLOW_LAUNCH_PREFLIGHT_INVALID"];let n=[];for(let i of o.requiredApprovalNodes){let r=e.nodes?.[i];if(!r||r.kind!=="approval"){n.push(`WORKFLOW_LAUNCH_PREFLIGHT_NODE_INVALID:${i}`);continue}if(!t)continue;let d=t.bindings?.[r.binding||""];(!d||!qr.includes(d.provider)||d.candidateField!==void 0)&&n.push(`WORKFLOW_LAUNCH_PREFLIGHT_PROVIDER_UNSUPPORTED:${i}`)}return n}var ui=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Zd=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Jr=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,zr=/^membership:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,pf=500,mf=262144;function fi(e){if(e?.approvedDelegation===void 0)return[];let t=e.approvedDelegation;if(!ui(t)||Object.keys(t).some(a=>!["confirmationNodeId","confirmer","requestsField","maxRequests"].includes(a))||!Jr.test(t.confirmationNodeId||"")||!["initiator","delegate"].includes(t.confirmer)||!Zd.test(t.requestsField||"")||!Number.isSafeInteger(t.maxRequests)||t.maxRequests<1||t.maxRequests>500)return["WORKFLOW_APPROVED_DELEGATION_POLICY_INVALID"];let o=[],n=e.nodes?.[t.confirmationNodeId];(!n||n.kind!=="approval"||n.mode!=="single"||n.emptyPolicy==="skip"||n.initiatorApprovalPolicy==="auto_approve"||n.completionDeadline||n.administration?.assigneeProviders?.length||n.administration?.modes?.some(a=>a!=="single")||n.allowedOperations?.some(a=>["transfer","delegate","add_assignee","admin_override"].includes(a)))&&o.push("WORKFLOW_APPROVED_DELEGATION_CONFIRMATION_INVALID");let i=e.inputSchema?.properties?.[t.requestsField];(!i||i.type!=="array"||!Number.isSafeInteger(i.maxItems)||i.maxItems<1||i.maxItems>t.maxRequests||!i.items||i.items.type!=="object"||i.items.additionalProperties!==!1||!e.subject?.factProjection?.[t.requestsField])&&o.push("WORKFLOW_APPROVED_DELEGATION_REQUEST_SCHEMA_INVALID"),Object.values(e.nodes||{}).some(a=>a.kind==="end"&&a.outcome==="approved")||o.push("WORKFLOW_APPROVED_DELEGATION_APPROVED_END_REQUIRED");let d=[e.startAt],s=new Set;for(;d.length;){let a=d.pop();if(a===t.confirmationNodeId||s.has(a))continue;s.add(a);let c=e.nodes?.[a];c&&(c.kind==="end"&&c.outcome==="approved"&&o.push("WORKFLOW_APPROVED_DELEGATION_CONFIRMATION_BYPASS"),c.kind==="approval"&&d.push(c.onApprove,c.onReject),c.kind==="condition"&&d.push(c.otherwise,...(c.branches||[]).map(f=>f.target)),(c.kind==="cc"||c.kind==="action")&&d.push(c.next))}return[...new Set(o)]}function Qd(e,t){let o=t?.data?.[e.requestsField],n=()=>{throw new Error("WORKFLOW_APPROVED_DELEGATION_REQUEST_INVALID")};(!Array.isArray(o)||!o.length||o.length>e.maxRequests||o.length>500||new TextEncoder().encode(JSON.stringify(o)).byteLength>262144)&&n();let i=["key","delegatorRoleSubjectKey","delegatorRoleSubjectRevision","delegate","delegateRoleSubjectKey","expectedDelegateRevision","workflowCode","nodeId","validFrom","validTo","reason"],r=(a,c)=>typeof a=="string"&&a.trim().length>0&&a.length<=c,d=a=>{if(typeof a!="string")return!1;let c=/^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)(?:\.\d{1,3})?(?:Z|[+-](\d\d):(\d\d))$/.exec(a);if(!c)return!1;let[,f,u,p,_,E,A,O,b]=c,g=Number(f),I=Number(u),T=Number(p),y=[31,g%4===0&&(g%100!==0||g%400===0)?29:28,31,30,31,30,31,31,30,31,30,31];return I>=1&&I<=12&&T>=1&&T<=y[I-1]&&Number(_)<=23&&Number(E)<=59&&Number(A)<=59&&(O===void 0||Number(O)<=23&&Number(b)<=59)&&Number.isFinite(Date.parse(a))},s=o.map(a=>ui(a)?((Object.keys(a).some(c=>!i.includes(c))||!r(a.delegatorRoleSubjectKey,255)||!zr.test(a.delegatorRoleSubjectKey)||!r(a.delegateRoleSubjectKey,255)||!zr.test(a.delegateRoleSubjectKey)||!Number.isSafeInteger(a.delegatorRoleSubjectRevision)||a.delegatorRoleSubjectRevision<1||!Number.isSafeInteger(a.expectedDelegateRevision)||a.expectedDelegateRevision<1||!ui(a.delegate)||Object.keys(a.delegate).some(c=>!["value","label"].includes(c))||!r(a.delegate.value,255)||!r(a.delegate.label,200)||!(a.workflowCode===null||r(a.workflowCode,128)&&Jr.test(a.workflowCode))||!(a.nodeId===null||r(a.nodeId,128)&&/^[A-Za-z0-9._:-]{1,128}$/.test(a.nodeId)&&a.workflowCode)||!d(a.validFrom)||!d(a.validTo)||Date.parse(a.validFrom)>=Date.parse(a.validTo)||!r(a.reason,4e3)||a.key!==void 0&&!r(a.key,128))&&n(),{...a,delegate:{value:a.delegate.value,label:a.delegate.label},validFrom:new Date(a.validFrom).toISOString(),validTo:new Date(a.validTo).toISOString()}):n());return e.confirmer==="delegate"&&new Set(s.map(a=>a.delegate.value)).size!==1&&n(),s}var ec=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[null,Object.prototype].includes(Object.getPrototypeOf(e));function pi(e){let t=e?.nodes||{},o=Object.values(t).filter(s=>s?.kind==="correction");if(!o.length)return[];let n=[],i=s=>s?.kind==="approval"?[s.onApprove,s.onReject]:s?.kind==="condition"?[...(Array.isArray(s.branches)?s.branches:[]).map(a=>a.target),s.otherwise]:s?.kind==="action"||s?.kind==="cc"?[s.next]:[],r=new Set,d=[e.startAt];for(;d.length;){let s=d.pop();r.has(s)||(r.add(s),d.push(...i(t[s])))}for(let s of o){(!ec(s)||Object.keys(s).some(c=>!["id","kind","title","taskPageCode","next"].includes(c))||typeof s.id!="string"||!/^[A-Za-z][A-Za-z0-9_-]{0,127}$/.test(s.id)||["__proto__","prototype","constructor"].includes(s.id)||t[s.id]!==s||typeof s.title!="string"||!s.title.trim()||s.title.length>255||typeof s.taskPageCode!="string"||!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(s.taskPageCode))&&n.push("WORKFLOW_CORRECTION_NODE_INVALID"),(s.next!==e.startAt||t[s.next]?.kind==="correction")&&n.push("WORKFLOW_CORRECTION_REPLAY_TARGET_INVALID"),(r.has(s.id)||Object.values(t).some(c=>i(c).includes(s.id)))&&n.push("WORKFLOW_CORRECTION_FORWARD_ENTRY_FORBIDDEN"),Object.values(t).some(c=>c?.kind==="approval"&&r.has(c.id)&&Array.isArray(c.returnTargets)&&c.returnTargets.includes(s.id))||n.push("WORKFLOW_CORRECTION_RETURN_SOURCE_REQUIRED");let a=e.taskPages?.[s.taskPageCode];!a||!Array.isArray(a.fields)?n.push("WORKFLOW_CORRECTION_PAGE_REQUIRED"):a.fields.some(c=>c?.subtable&&Object.values(e.subject?.factProjection||{}).some(f=>f===c.code||f.startsWith(`${c.code}.`)))&&n.push("WORKFLOW_CORRECTION_OWNED_FACTS_UNSUPPORTED")}return[...new Set(n)]}var Ft=class extends Error{constructor(o){super(o);this.code=o}code},tc=["projection","triggerCode","resourceCode","recordId","recordRevision","field","dueAt"];function mi(e,t,o){let n=r=>{throw new Ft(r)};t.length>100&&n("DATE_TRIGGER_PROJECTION_LIMIT");let i=new Set;for(let r of t){let d=r.filter?.resourceCodes||[];if(Array.isArray(d)||n("DATE_TRIGGER_PROJECTION_INVALID"),d.length&&!d.includes(e))continue;let s=r.payload?.fields||[];(!Array.isArray(s)||s.length>32)&&n("DATE_TRIGGER_PROJECTION_LIMIT");for(let a of s)(typeof a!="string"||!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(a)||["__proto__","constructor","prototype"].includes(a))&&n("DATE_TRIGGER_PROJECTION_FIELD_INVALID"),i.add(a)}if(i.size>64&&n("DATE_TRIGGER_PROJECTION_LIMIT"),o!==void 0){let r=o?.schema?.fields??o?.fields;Array.isArray(r)||n("DATE_TRIGGER_PROJECTION_RESOURCE_INVALID");let d=new Map(r.map(s=>[s.code,s]));for(let s of i){let a=d.get(s);a||n("DATE_TRIGGER_PROJECTION_FIELD_UNKNOWN"),a.type==="subtable"&&n("DATE_TRIGGER_PROJECTION_SUBTABLE_FORBIDDEN"),o.fieldPolicies?.[s]?.mask==="omit"&&n("DATE_TRIGGER_PROJECTION_FIELD_SENSITIVE")}}return[...i].sort()}function nc(e,t){if(!t.length)return e;let o=e?.properties?.projection;if(o?.type!=="object"||!o.properties||typeof o.properties!="object"||Array.isArray(o.properties)||o.additionalProperties!==!1||o.required!==void 0&&!Array.isArray(o.required)||t.some(n=>!Object.hasOwn(o.properties,n))||(o.required||[]).some(n=>!t.includes(n)))throw new Ft("DATE_TRIGGER_PROJECTION_SCHEMA_INVALID");return{...e,properties:{...e.properties,projection:{}}}}var Yr=200,jn=1024*1024,Xr=65536,Ai=Le,_i=Be,Ye=new Set(["__proto__","prototype","constructor"]),Zr=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,jt=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Hr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,ce=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[null,Object.prototype].includes(Object.getPrototypeOf(e)),ve=(e,t)=>ce(e)&&Object.keys(e).every(o=>t.includes(o)&&!Ye.has(o)),Wn=e=>{try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 1/0}},Qr=e=>e==null||typeof e=="string"&&!e.trim()||Array.isArray(e)&&e.length===0;function je(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((n,i)=>je(n,t[i]));if(!ce(e)||!ce(t))return!1;let o=Object.keys(e);return o.length===Object.keys(t).length&&o.every(n=>Object.hasOwn(t,n)&&je(e[n],t[n]))}function gi(e,t){let o=t.split(".");if(!(o.some(n=>!Zr.test(n)||Ye.has(n))||o.length>12))return o.reduce((n,i)=>ce(n)&&Object.hasOwn(n,i)?n[i]:void 0,e)}function $e(e,t){switch(e.op){case"literal":return e.value;case"path":return gi({values:t},e.path);case"and":return e.values.every(o=>!!$e(o,t));case"or":return e.values.some(o=>!!$e(o,t));case"not":return!$e(e.value,t);case"exists":return!Qr($e(e.value,t));default:{let o=$e(e.left,t),n=$e(e.right,t);return e.op==="eq"?je(o,n):e.op==="neq"?!je(o,n):e.op==="in"?Array.isArray(n)&&n.some(i=>je(i,o)):e.op==="contains"?Array.isArray(o)?o.some(i=>je(i,n)):typeof o=="string"&&typeof n=="string"&&o.includes(n):typeof o!="number"||typeof n!="number"||!Number.isFinite(o)||!Number.isFinite(n)?!1:e.op==="gt"?o>n:e.op==="gte"?o>=n:e.op==="lt"?o<n:o<=n}}}function xt(e,t,o=0,n={nodes:0}){if(o>8||++n.nodes>64||!ce(e))return!1;if(e.op==="literal")return ve(e,["op","value"])&&Object.hasOwn(e,"value")&&Wn(e.value)<=4096&&Wt(e.value);if(e.op==="path"){if(!ve(e,["op","path"])||typeof e.path!="string")return!1;let i=e.path.split(".");return i[0]==="values"&&i.length>=2&&i.length<=8&&t.has(i[1])&&i.every(r=>jt.test(r)&&!Ye.has(r))}return["not","exists"].includes(e.op)?ve(e,["op","value"])&&xt(e.value,t,o+1,n):["and","or"].includes(e.op)?ve(e,["op","values"])&&Array.isArray(e.values)&&e.values.length>0&&e.values.length<=16&&e.values.every(i=>xt(i,t,o+1,n)):["eq","neq","gt","gte","lt","lte","in","contains"].includes(e.op)&&ve(e,["op","left","right"])&&xt(e.left,t,o+1,n)&&xt(e.right,t,o+1,n)}function Ut(e,t,o,n=_i){let i=[],r=e.taskPages;if(r!==void 0&&(!ce(r)||Object.keys(r).length===0||Object.keys(r).length>16||Wn(r)>Xr))return["WORKFLOW_TASK_PAGES_INVALID"];for(let[d,s]of Object.entries(r||{})){let a=`taskPages.${d}`;if(!Zr.test(d)||Ye.has(d)||!ve(s,["title","fields"])||typeof s.title!="string"||!s.title.trim()||s.title.length>160||!Array.isArray(s.fields)||!s.fields.length||s.fields.length>Yr){i.push(`WORKFLOW_TASK_PAGE_INVALID:${a}`);continue}let c=new Set(s.fields.map(p=>p?.code));c.size!==s.fields.length&&i.push(`WORKFLOW_TASK_PAGE_DUPLICATE_FIELD:${a}`);let f=0,u=new Set;for(let p of s.fields){if(!ve(p,["code","readonly","required","visibleWhen","requiredWhen","subtable"])||!jt.test(p.code)||Ye.has(p.code)||["readonly","required"].some(_=>p[_]!==void 0&&typeof p[_]!="boolean")||p.readonly&&(p.required||p.requiredWhen)){i.push(`WORKFLOW_TASK_PAGE_FIELD_INVALID:${a}`);continue}for(let _ of["visibleWhen","requiredWhen"])p[_]!==void 0&&!xt(p[_],c)&&i.push(`WORKFLOW_TASK_PAGE_EXPRESSION_INVALID:${a}.${p.code}.${_}`);if(t){let _=t.get(p.code);if((!_||_.system||_.hidden||_.type==="serial-number"||!p.readonly&&_.widget==="readonly"||!p.readonly&&_.type==="subtable"&&!p.subtable||p.subtable&&_.type!=="subtable")&&i.push(`WORKFLOW_TASK_PAGE_RESOURCE_FIELD_INVALID:${a}.${p.code}`),p.subtable&&_?.subtable){let E=_.subtable;f+=E.maxRows??20,(u.has(E.resourceCode)||!Number.isSafeInteger(E.maxRows??20)||(E.maxRows??20)<1||(E.maxRows??20)>Ai||!jt.test(E.foreignKey)||!jt.test(E.orderField)||E.foreignKey===E.orderField)&&i.push(`WORKFLOW_TASK_SUBTABLE_RELATION_INVALID:${a}.${p.code}`),u.add(E.resourceCode);let A=o?.get(E.resourceCode);o&&(!A||!["uuid","resource-ref.single"].includes(A.get(E.foreignKey)?.type||"")||A.get(E.orderField)?.type!=="number.integer")&&i.push(`WORKFLOW_TASK_SUBTABLE_RELATION_INVALID:${a}.${p.code}`);for(let O of Array.isArray(p.subtable.fields)?p.subtable.fields:[]){if(!O||typeof O.code!="string")continue;let b=A?.get(O.code);(O.code===E.foreignKey||O.code===E.orderField||A&&(!b||b.system||b.hidden||b.type==="subtable"||!O.readonly&&(b.widget==="readonly"||b.type==="serial-number")))&&i.push(`WORKFLOW_TASK_SUBTABLE_FIELD_UNSUPPORTED:${a}.${p.code}.${O.code}`)}}else p.subtable&&t&&i.push(`WORKFLOW_TASK_SUBTABLE_RELATION_INVALID:${a}.${p.code}`)}p.subtable&&(p.readonly||!ve(p.subtable,["fields","create","delete","reorder"])||["create","delete","reorder"].some(_=>p.subtable?.[_]!==void 0&&typeof p.subtable[_]!="boolean")||!Array.isArray(p.subtable.fields)||p.subtable.fields.some(_=>_?.subtable)?i.push(`WORKFLOW_TASK_SUBTABLE_PAGE_INVALID:${a}.${p.code}`):i.push(...Ut({taskPages:{child:{title:"\u5B50\u884C",fields:p.subtable.fields}}},o?.get(t?.get(p.code)?.subtable?.resourceCode||"")).map(_=>`${_}:${a}.${p.code}`)))}(f>Math.min(n,_i)||f<0||!Number.isSafeInteger(f)||!Number.isSafeInteger(n)||n<1)&&i.push(`WORKFLOW_TASK_SUBTABLE_BUDGET_EXCEEDED:${a}`)}for(let[d,s]of Object.entries(e.nodes||{}))ce(s)&&s.taskPageCode!==void 0&&(!["approval","correction"].includes(s.kind)||typeof s.taskPageCode!="string"||!ce(r)||!Object.hasOwn(r,s.taskPageCode)?i.push(`WORKFLOW_TASK_PAGE_NOT_FOUND:${d}`):Array.isArray(r[s.taskPageCode]?.fields)&&r[s.taskPageCode].fields.some(a=>a&&(s.fieldPolicy?.fields?.[a.code]||s.fieldPolicy?.default)==="hidden")&&i.push(`WORKFLOW_TASK_PAGE_FIELD_HIDDEN:${d}`));return i}function Ei(e,t){return e.fields.map(o=>({code:o.code,visible:o.visibleWhen===void 0||!!$e(o.visibleWhen,t),readonly:o.readonly===!0,required:o.required===!0||o.requiredWhen!==void 0&&!!$e(o.requiredWhen,t)}))}var Oe=class extends Error{constructor(o,n){super(o);this.code=o;this.field=n}code;field;rowIndex;childField};function oc(e,t){return t.map(o=>({key:String(o.id),id:String(o.id),revision:Number(o.revision),state:"persisted",values:Object.fromEntries(Ei({title:"\u5B50\u884C",fields:e.fields},o).filter(n=>n.visible&&!n.readonly).map(n=>[n.code,o[n.code]??null]))}))}function ic(e,t,o,n,i,r=!0,d=0){let s=e.subtable,a=_=>{throw new Oe(_,e.code)};if(!s||!Number.isSafeInteger(t)||t<1||t>Ai||!Number.isSafeInteger(d)||d<0||d>t||!Array.isArray(n)||n.length>2*t||Wn(n)>jn||!Wt(n))return a("WORKFLOW_TASK_SUBTABLE_VALUES_INVALID");let c=new Map(o.map(_=>[String(_.id),_])),f=new Set,u=new Set,p=[];for(let _ of n){if(!ve(_,["key","state","id","revision","values"])||typeof _.key!="string"||!Hr.test(_.key)||f.has(_.key)||!["created","persisted","deleted"].includes(_.state)||!ce(_.values))return a("WORKFLOW_TASK_SUBTABLE_ROW_INVALID");if(f.add(_.key),_.state==="created"){if(!s.create||_.id!==void 0||_.revision!==void 0||c.has(_.key))return a("WORKFLOW_TASK_SUBTABLE_CREATE_FORBIDDEN")}else{if(typeof _.id!="string"||_.id!==_.key||!Hr.test(_.id)||u.has(_.id)||!Number.isSafeInteger(_.revision)||_.revision<1||!c.has(_.id))return a("WORKFLOW_TASK_SUBTABLE_SCOPE_CONFLICT");if(u.add(_.id),r&&Number(c.get(_.id).revision)!==_.revision)return a("WORKFLOW_TASK_SUBTABLE_REVISION_CONFLICT")}if(_.state==="deleted"){if(!s.delete||Object.keys(_.values).length)return a("WORKFLOW_TASK_SUBTABLE_DELETE_FORBIDDEN");continue}try{es({title:e.code,fields:s.fields},_.id?c.get(_.id):{},_.values,i)}catch(E){if(!(E instanceof Oe))throw E;let A=new Oe(E.code,e.code);throw A.rowIndex=p.length,E.field!==void 0&&(A.childField=E.field),A}p.push(_)}if(u.size!==c.size)return a("WORKFLOW_TASK_SUBTABLE_SCOPE_CONFLICT");if(p.length>t)return a("WORKFLOW_TASK_SUBTABLE_MAX_ROWS_EXCEEDED");if(i&&p.length<d)return a("WORKFLOW_TASK_SUBTABLE_MIN_ROWS_NOT_MET");if(!s.reorder){let _=o.filter(A=>p.some(O=>O.id===String(A.id))).map(A=>String(A.id)),E=p.filter(A=>A.state==="persisted").map(A=>A.id);if(!je(_,E)||p.some((A,O)=>A.state==="created"&&p.slice(O+1).some(b=>b.state==="persisted")))return a("WORKFLOW_TASK_SUBTABLE_REORDER_FORBIDDEN")}return n}function Wt(e,t={members:0},o=0){return++t.members>5e4||o>12?!1:e===null||typeof e=="boolean"?!0:typeof e=="string"?e.length<=jn:typeof e=="number"?Number.isFinite(e):Array.isArray(e)?e.length<=1e3&&e.every(n=>Wt(n,t,o+1)):ce(e)&&Object.entries(e).every(([n,i])=>!Ye.has(n)&&Wt(i,t,o+1))}function es(e,t,o,n){if(!ce(o)||Wn(o)>jn||!Wt(o))throw new Oe("WORKFLOW_TASK_FORM_VALUES_INVALID");let i={...t,...o},r=new Map(Ei(e,i).map(d=>[d.code,d]));for(let d of Object.keys(o)){let s=r.get(d);if(!s||s.readonly||!s.visible)throw new Oe("WORKFLOW_TASK_FORM_FIELD_NOT_EDITABLE",d)}if(n)for(let d of r.values()){let s=i[d.code],a=e.fields.find(c=>c.code===d.code)?.subtable&&Array.isArray(s)?s.every(c=>ce(c)&&c.state==="deleted"):Qr(s);if(d.visible&&!d.readonly&&d.required&&a)throw new Oe("WORKFLOW_TASK_FORM_REQUIRED",d.code)}return i}function rc(e,t,o){let n=JSON.parse(JSON.stringify(t));for(let[d,s]of Object.entries(e.subject?.factProjection||{})){let a=d.split(".");if(!a.length||a.length>12||d.length>128||a[0]==="steps"||a.some(f=>!jt.test(f)||Ye.has(f)))throw new Oe("WORKFLOW_TASK_FORM_FACT_PROJECTION_INVALID");if(!Object.hasOwn(o,s))throw new Oe("WORKFLOW_TASK_FORM_FACT_FIELD_MISSING",s);let c=n;for(let f of a.slice(0,-1))c=c[f]=ce(c[f])?c[f]:{};c[a.at(-1)]=o[s]===void 0?void 0:JSON.parse(JSON.stringify(o[s]))}let i=new Set,r=Object.values(e.nodes||{}).filter(d=>d.kind==="action");for(let d=0;d<=r.length;d++){let s=!1;for(let a of r)ce(n.steps)&&Object.hasOwn(n.steps,a.id)&&Object.values(a.inputs||{}).some(c=>c.source==="fact"&&!je(gi(t,c.path),gi(n,c.path)))&&(delete n.steps[a.id],i.add(a.id),s=!0);if(!s)break}return{facts:n,invalidatedNodeIds:[...i].sort()}}function sc(e,t,o){let n=e.nodes||{};for(let i of o){let r=new Set,d=new Map,s=a=>{if(a===i)return!0;if(d.has(a))return d.get(a);if(r.has(a)||r.size>200)return!1;let c=n[a];if(!ce(c)||c.kind==="end")return!1;r.add(a);let f=c.kind==="approval"?[c.onApprove]:c.kind==="condition"?[...(c.branches||[]).map(p=>p.target),c.otherwise]:[c.next],u=f.length>0&&f.every(p=>typeof p=="string"&&s(p));return r.delete(a),d.set(a,u),u};if(!s(t))return!1}return!0}var yf=256,bf=64,Of=262144,ac=/^[a-z][a-z0-9_-]{0,127}$/,dc=/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*$/,ns=new Set(["__proto__","prototype","constructor"]),we=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Bt=(e,t)=>Object.keys(e).every(o=>t.includes(o)),Xe=(e,t)=>typeof e=="string"&&e.trim().length>0&&e.length<=t&&!/[\u0000-\u001f\u007f]/.test(e),Pe=e=>typeof e=="string"&&ac.test(e)&&!ns.has(e),os=e=>typeof e=="string"&&e.length<=255&&dc.test(e)&&!e.split(".").some(t=>ns.has(t)),cc=e=>we(e)&&Bt(e,["dimension","valueFrom","value"])&&Pe(e.dimension)&&(Xe(e.value,255)&&e.valueFrom===void 0||os(e.valueFrom)&&e.value===void 0),ts=e=>typeof e=="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/.test(e)&&Number.isFinite(Date.parse(e)),Mt={type:"string",pattern:"^[a-z][a-z0-9_-]{0,127}$"},Ii={type:"string",minLength:1,maxLength:128},lc={type:"object",additionalProperties:!1,required:["policyCode","title","strategy","dimensions","sources"],properties:{policyCode:Mt,title:Ii,strategy:{enum:["replace_then_append","replace_only"]},dimensions:{type:"object",maxProperties:8,propertyNames:Mt,additionalProperties:{type:"object",additionalProperties:!1,required:["title","valueFrom"],properties:{title:Ii,valueFrom:{type:"string",minLength:1,maxLength:255}}}},sources:{type:"object",minProperties:1,maxProperties:16,propertyNames:Mt,additionalProperties:{type:"object",additionalProperties:!1,required:["title","provider","roleCode"],properties:{title:Ii,provider:{enum:["app_role","app_role_in_scope"]},roleCode:Mt,scope:{type:"object",additionalProperties:!1,required:["dimension"],properties:{dimension:Mt,value:{type:"string",minLength:1,maxLength:255},valueFrom:{type:"string",minLength:1,maxLength:255}}}}}}}};function Kt(e){if(!we(e)||!Bt(e,["policyCode","title","strategy","dimensions","sources"])||!Pe(e.policyCode)||!Xe(e.title,128)||!["replace_then_append","replace_only"].includes(e.strategy))return["WORKFLOW_V2_ROUTING_POLICY_INVALID"];let t=[];return(!we(e.dimensions)||Object.keys(e.dimensions).length>8||Object.entries(e.dimensions).some(([o,n])=>!Pe(o)||!we(n)||!Bt(n,["title","valueFrom"])||!Xe(n.title,128)||!os(n.valueFrom)))&&t.push("WORKFLOW_V2_ROUTING_DIMENSIONS_INVALID"),(!we(e.sources)||Object.keys(e.sources).length<1||Object.keys(e.sources).length>16||Object.entries(e.sources).some(([o,n])=>!Pe(o)||!we(n)||!Bt(n,["title","provider","roleCode","scope"])||!Xe(n.title,128)||!Pe(n.roleCode)||!["app_role","app_role_in_scope"].includes(n.provider)||(n.provider==="app_role_in_scope"?!cc(n.scope):n.scope!==void 0)))&&t.push("WORKFLOW_V2_ROUTING_SOURCES_INVALID"),t}function uc(e,t){if(Kt(e).length)return["WORKFLOW_V2_ROUTING_POLICY_INVALID"];if(!Array.isArray(t)||t.length>256||new TextEncoder().encode(JSON.stringify(t)).length>262144)return["WORKFLOW_V2_ROUTING_RULE_LIMIT_EXCEEDED"];let o=[],n=new Set;for(let i of t){if(!we(i)||!Bt(i,["ruleCode","title","enabled","workflowCode","nodeId","matches","sourceCode","effect","priority","validFrom","validTo"])||!Pe(i.ruleCode)||!Xe(i.title,128)||typeof i.enabled!="boolean"||!Pe(i.sourceCode)||!Object.hasOwn(e.sources,i.sourceCode)||!["append","replace"].includes(i.effect)||!Number.isSafeInteger(i.priority)||i.priority<-1e3||i.priority>1e3||i.workflowCode!==void 0&&!Pe(i.workflowCode)||i.nodeId!==void 0&&(!Pe(i.nodeId)||i.workflowCode===void 0)||i.validFrom!==void 0&&!ts(i.validFrom)||i.validTo!==void 0&&!ts(i.validTo)||i.validFrom&&i.validTo&&Date.parse(i.validFrom)>=Date.parse(i.validTo)){o.push("WORKFLOW_V2_ROUTING_RULE_INVALID");continue}n.has(i.ruleCode)&&o.push(`WORKFLOW_V2_ROUTING_RULE_DUPLICATE:${i.ruleCode}`),n.add(i.ruleCode),(!we(i.matches)||Object.entries(i.matches).some(([r,d])=>!Object.hasOwn(e.dimensions,r)||!Array.isArray(d)||d.length<1||d.length>64||new Set(d).size!==d.length||d.some(s=>!Xe(s,255))))&&o.push(`WORKFLOW_V2_ROUTING_MATCH_INVALID:${i.ruleCode}`)}return[...new Set(o)]}function is(e){return JSON.stringify({policyCode:e.policyCode,strategy:e.strategy,dimensions:Object.entries(e.dimensions).sort(([t],[o])=>t<o?-1:t>o?1:0).map(([t,o])=>[t,o.valueFrom]),sources:Object.entries(e.sources).sort(([t],[o])=>t<o?-1:t>o?1:0).map(([t,o])=>[t,o.provider,o.roleCode,o.scope?.dimension??null,o.scope?.valueFrom??null,o.scope?.value??null])})}function yi(e){let t=[],o=new Map;for(let n of e)for(let[i,r]of Object.entries(n.bindings||{})){if(!we(r)||r.routing===void 0)continue;let d=Kt(r.routing);if(d.length){t.push(...d.map(c=>`${c}:${i}`));continue}let s=is(r.routing),a=o.get(r.routing.policyCode);a&&a!==s&&t.push(`WORKFLOW_V2_ROUTING_POLICY_CONFLICT:${r.routing.policyCode}`),o.set(r.routing.policyCode,s)}return[...new Set(t)]}function fc(e,t){let o={};for(let[n,i]of Object.entries(e.dimensions)){let r=t;for(let d of i.valueFrom.split("."))r=we(r)&&Object.hasOwn(r,d)?r[d]:void 0;if(!(typeof r=="string"&&Xe(r,255)||typeof r=="number"&&Number.isFinite(r)||typeof r=="boolean"))throw new Error(`WORKFLOW_V2_ROUTING_FACT_REQUIRED:${n}`);o[n]=String(r)}return o}function pc(e,t,o){let n=t.filter(c=>c.enabled&&(!c.validFrom||Date.parse(c.validFrom)<=o.at)&&(!c.validTo||Date.parse(c.validTo)>o.at)&&(!c.workflowCode||c.workflowCode===o.workflowCode)&&(!c.nodeId||c.nodeId===o.nodeId)&&Object.entries(c.matches).every(([f,u])=>u.includes(o.facts[f])));if(n.length>64)throw new Error("WORKFLOW_V2_ROUTING_MATCH_LIMIT_EXCEEDED");let i=(c,f)=>f.priority-c.priority||+!!c.workflowCode-+!!f.workflowCode||+!!c.nodeId-+!!f.nodeId||(c.ruleCode<f.ruleCode?-1:c.ruleCode>f.ruleCode?1:0),r=n.filter(c=>c.effect==="replace").sort(i);if(r.length>1&&r[0].priority===r[1].priority)throw new Error("WORKFLOW_V2_ROUTING_REPLACE_CONFLICT");let d=r[0],s=d&&e.strategy==="replace_only"?[]:n.filter(c=>c.effect==="append").sort(i),a=[...d?[d]:[],...s];return{matched:n.sort(i),replacement:d,applied:a,ignored:n.filter(c=>!a.includes(c))}}var bi="^[A-Za-z][A-Za-z0-9_]{0,62}$",rs="^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$",mc={type:"object",additionalProperties:!1,required:["mode","resourceCode","subtables"],properties:{mode:{const:"create"},resourceCode:{type:"string",maxLength:64,pattern:rs},subtables:{type:"array",minItems:1,maxItems:16,items:{type:"object",additionalProperties:!1,required:["fieldCode","fieldCodes"],properties:{fieldCode:{type:"string",pattern:bi},fieldCodes:{type:"array",minItems:1,maxItems:200,uniqueItems:!0,items:{type:"string",pattern:bi}}}}}}};function Gt(e){let t=n=>!!(n&&typeof n=="object"&&!Array.isArray(n)),o=n=>typeof n=="string"&&new RegExp(bi).test(n)&&!["__proto__","prototype","constructor"].includes(n);if(!t(e)||Object.keys(e).some(n=>!["mode","resourceCode","subtables"].includes(n))||e.mode!=="create"||typeof e.resourceCode!="string"||e.resourceCode.length>64||!new RegExp(rs).test(e.resourceCode)||!Array.isArray(e.subtables)||e.subtables.length<1||e.subtables.length>16||e.subtables.some(n=>!t(n)||Object.keys(n).some(i=>!["fieldCode","fieldCodes"].includes(i))||!o(n.fieldCode)||!Array.isArray(n.fieldCodes)||n.fieldCodes.length<1||n.fieldCodes.length>200||new Set(n.fieldCodes).size!==n.fieldCodes.length||n.fieldCodes.some(i=>!o(i)))||new Set(e.subtables.map(n=>n.fieldCode)).size!==e.subtables.length)throw new Error("WORKFLOW_OWNED_SUBJECT_CREATE_INVALID")}function _c(e){return Gt(e),{mode:"create",resourceCode:e.resourceCode,subtables:e.subtables.map(t=>({fieldCode:t.fieldCode,fieldCodes:[...t.fieldCodes].sort()})).sort((t,o)=>t.fieldCode.localeCompare(o.fieldCode))}}function Oi(e,t,o){Gt(e);let n=s=>{throw new Error(`WORKFLOW_OWNED_SUBJECT_${s}`)},i=t.get(e.resourceCode);i||n("RESOURCE_MISSING");let r=new Set,d=0;for(let s of e.subtables){let a=i.get(s.fieldCode),c=a?.subtable,f=t.get(c?.resourceCode);(a?.type!=="subtable"||!f||c.resourceCode===e.resourceCode||r.has(c.resourceCode))&&n("RELATION_INVALID"),r.add(c.resourceCode);let u=c.maxRows??20;(!Number.isSafeInteger(u)||u<1||u>Le)&&n("BUDGET_EXCEEDED"),d+=u;for(let p of s.fieldCodes){let _=f.get(p);(!_||["serial-number","subtable"].includes(_.type)||[c.foreignKey,c.orderField].includes(p))&&n("FIELD_INVALID"),["file","image","signature","text.rich"].includes(_.type)&&!o.some(E=>E.resourceCode===c.resourceCode&&E.fieldCodes.includes(p)&&E.intents.includes("create"))&&n("FILE_ACCESS_REQUIRED")}}d>Be&&n("BUDGET_EXCEEDED")}var Yn=_a(require("crypto"),1);var ss="native-4",Ni="2.0.0-alpha.5",as={"application-native-2":"1.0.0","application.extended-declaration-capacity":"1.0.0","application.extended-artifact-capacity":"1.0.0","application.high-density-artifact-capacity":"1.0.0","application.extended-configuration-bytes":"1.0.0","application.development-configuration":"1.0.0","authz.native-batch-explain":"1.0.0","authz.native-management":"1.0.0","authz.native-membership-batch":"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.extended-owned-subtable-capacity":"1.0.0","data.aggregate-owned-subtable-capacity":"1.0.0","data.extended-field-capacity":"1.0.0","data.business-commands":"1.0.0","data.record-edit":"1.0.0","data.native-golden-crud":"1.0.0","data.audit-read-access":"1.0.0","data.managed-files":"1.1.0","data.decimal-reservations":"1.1.0","data.decimal-reservation-lifecycle":"1.0.0","data.unique-keys":"1.1.0","data.user-candidates":"1.0.0","data.user-candidate-launch-scope":"1.0.0","data.datetime-minute-precision":"1.0.0","data.subtable-minimum-rows":"1.0.0","data.managed-concurrency":"1.0.0","data.managed-concurrency.durable":"1.0.0","workflow.named-input-sources":"1.0.0","workflow.approved-delegation":"1.0.0","directory-v2":"1.0.0","directory.selected-user":"1.0.0","directory.current-initiator-phone":"1.0.0","events-v2":"1.0.0","events.durable-receipts":"1.0.0","events.capture-policy":"1.0.0","events.date-source-projection":"1.0.0","events.native-data-actions":"1.0.0","workflow-kernel-v2":"1.0.0","workflow.business-data-command":"1.0.0","workflow.approval-business-command":"1.0.0","workflow.native-stage-guard":"1.0.0","workflow.launch-preflight":"1.0.0","workflow.optional-rejection-comment":"1.0.0","workflow.optional-operation-reason":"1.0.0","workflow.optional-withdrawal-reason":"1.0.0","data.transaction-actor-authority":"1.0.0","data.authenticated-public-projection":"1.0.0","data.record-print":"1.0.0","data.workflow-record-deletion":"1.0.0","data.record-comments":"1.0.0","workflow.record-history-read":"1.0.0","workflow.rejection-notification":"1.0.0","workflow.instance-cancellation-policy":"1.0.0","workflow.node-administration":"1.0.0","workflow.assignment-routing":"1.0.0","workflow.role-union":"1.0.0","workflow.role-input-selection":"1.0.0","workflow.named-owned-create":"1.0.0","workflow.owned-initial-facts":"1.0.0","workflow.initiator-correction":"1.0.0","workflow.correction-business-command":"1.0.0","workflow.correction-derived-subject-facts":"1.0.0","workflow.role-references":"1.0.0","workflow.delegation-management":"1.0.0","workflow.automatic-cc":"1.0.0","workflow.approval-empty-policy":"1.0.0","workflow.initiator-approval-policy":"1.0.0","workflow.completion-deadline":"1.0.0","workflow.task-page-submit":"1.0.0","workflow.task-private-drafts":"1.0.0","workflow.task-managed-files":"1.0.0","workflow.task-rich-fields":"1.0.0","workflow.task-owned-subtables":"1.0.0","workflow.task-owned-files":"1.0.0","workflow.durable-business-step":"1.0.0","workflow.step-data-transaction":"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 hf=5,wf=20,Sf=50,Df=50,kf=100,Et=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.name="NativeDataPolicyExpressionV2Error"}code;pointer};function zt(e,t){let o=[],n=(i,r,d)=>{d>5&&qt("NATIVE_DATA_POLICY_EXPRESSION_DEPTH_EXCEEDED",r);let s=ds(i,r),a=["allOf","anyOf"].filter(u=>u in s);if(a.length===0){o.push({rule:s,pointer:r}),o.length>50&&qt("NATIVE_DATA_POLICY_EXPRESSION_LEAVES_EXCEEDED",r);return}let c=a[0],f=s[c];(a.length!==1||Object.keys(s).length!==1||!Array.isArray(f)||f.length<1||f.length>20)&&qt("NATIVE_DATA_POLICY_EXPRESSION_GROUP_INVALID",r),f.forEach((u,p)=>n(u,`${r}/${c}/${p}`,d+1))};return n(e,t,1),o}function Ri(e,t){zt(e,t);let o=(n,i)=>{let r=ds(n,i);if(Array.isArray(r.allOf))return Ti(r.allOf.flatMap((d,s)=>o(d,`${i}/allOf/${s}`)),i);if(Array.isArray(r.anyOf)){let d=[[]];return r.anyOf.forEach((s,a)=>{let c=o(s,`${i}/anyOf/${a}`);d=Ti(d.flatMap(f=>c.map(u=>[...f,...u])),i)}),d}return[[r]]};return Ti(o(e,t),t)}function Ti(e,t){let o=e.reduce((n,i)=>n+i.length,0);return(e.length>50||o>100)&&qt("NATIVE_DATA_POLICY_EXPRESSION_EXPANSION_EXCEEDED",t),e}function ds(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&qt("NATIVE_DATA_POLICY_EXPRESSION_NODE_INVALID",t),e}function qt(e,t){throw new Et(e,t)}var M=Object.freeze({perspectives:100,resources:512,dataPolicies:512,roles:256,subjectReadSurfaces:50,capabilities:4096,operations:500,eventConsumers:100,eventProducers:1e3,eventSchemas:100,eventTypes:500,workflows:512,routes:2048,adminPages:2048,adminNavigationGroups:100,adminNavigationItems:1024});function Ci(e){let t=(e.surface?.mutationOwner||"native")==="native";return["query","get","create","update","delete"].filter(o=>{let n=e.surface?.generated;return o==="query"?n?.list??!0:o==="get"?n?.detail??!0:n?.[o]??t})}function Un(e){let t=(e.data?.resources||[]).filter(o=>o.status!=="retired").reduce((o,n)=>o+Ci(n).length,0)+(e.backend?.operations||[]).filter(o=>o.ai).length;return(e.data?.resources?.length||0)>100||(e.authz?.dataPolicies?.length||0)>100||(e.authz?.roles?.length||0)>100||(e.authz?.capabilities?.length||0)>2e3||[e.workflows?.definitions,e.workflows?.bindings,e.workflows?.activations].some(o=>(o?.length||0)>100)||(e.frontend?.routes?.length||0)>500||t>500||(e.frontend?.admin?.navigation||[]).reduce((o,n)=>o+n.items.length,0)>500}var oe=Object.freeze({legacyConfigBytes:4194304,configBytes:8388608,contractBytes:8388608,depth:40,stringBytes:1048576,legacyNodes:1e5,extendedNodes:25e4}),Ze=Object.freeze({nodes:5e5});function Mn(e){return Buffer.byteLength(X(e),"utf8")>oe.legacyConfigBytes}function cs(e,t){let o=0,n=[[e][Symbol.iterator]()];for(;n.length;){let i=n[n.length-1].next();if(i.done){n.pop();continue}if(++o>t)return!0;if(Array.isArray(i.value))n.push(i.value.values());else if(i.value&&typeof i.value=="object"){let r=i.value;n.push((function*(){for(let d of Object.keys(r))r[d]!==void 0&&(yield r[d])})())}}return!1}function Jt(e){return cs(e,oe.legacyNodes)}function Ht(e){return cs(e,oe.extendedNodes)}var gc="openxiangda.config-bundle/v3",hs="openxiangda.contract-bundle/v3",ls="openxiangda.native-configuration-projection/v1",Xt=ss,Ac=/^[a-f0-9]{64}$/,Ec=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Ic=/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._*-]+$/,yc=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,bc=/^[a-z][a-z0-9]*(?:[-.][a-z0-9]+)*$/,Oc=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Nc=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,us=/^[A-Za-z][A-Za-z0-9_]{0,127}$/,Tc=/^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*$/,Rc=/^[A-Z][A-Z0-9_]*$/,Cc=/^[a-z][a-z0-9-]{2,63}$/,hc=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,wc=/^[A-Za-z][A-Za-z0-9_.]{0,127}$/,Sc=16,Dc=2*1024,kc=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"]),$c=new Set(["overview","database","operations","workflow","members","calendar","document","folder","settings"]),vc=new Set(["approve","reject","return","transfer","delegate","add_assignee","resubmit","withdraw","terminate","admin_reassign","admin_override","retry_resolution"]),Pc=oe.configBytes,Vc=oe.contractBytes,Lc=oe.depth,wi=oe.stringBytes,Fc="openxiangda.event-handler-manifest/v2",ws="openxiangda.application-route-manifest/v3",fs=64,Ss=new Set(["id","revision","created_by","updated_by","created_at","updated_at"]),Kn=["openxiangda.data.record.created.v2","openxiangda.data.record.updated.v2","openxiangda.data.record.deleted.v2"],Gn=["openxiangda.workflow.node.skipped.v2",pt,"openxiangda.workflow.step.result_received.v2","openxiangda.workflow.step.completed.v2","openxiangda.workflow.step.continuation_failed.v2","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"],xc=new Set(Gn),qn=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 jc(e){let t=S(e.appCode,"/appCode",128);Ec.test(t)||m("NATIVE_CONFIG_APP_CODE_INVALID","/appCode");let o=Di(e.expectedConfigDigest,"/expectedConfigDigest"),n=Di(e.expectedContractDigest,"/expectedContractDigest"),i=Ts(e.configBytes,Pc,"/configBytes","NATIVE_CONFIG_ARTIFACT_TOO_LARGE"),r=Ts(e.contractBytes,Vc,"/contractBytes","NATIVE_CONTRACT_ARTIFACT_TOO_LARGE");Rs(i,o,"/configBytes","NATIVE_CONFIG_DIGEST_MISMATCH"),Rs(r,n,"/contractBytes","NATIVE_CONTRACT_DIGEST_MISMATCH");let d=Ns(i,"/configBytes","NATIVE_CONFIG_JSON_INVALID","NATIVE_CONFIG_NOT_CANONICAL"),s=Ns(r,"/contractBytes","NATIVE_CONTRACT_JSON_INVALID","NATIVE_CONTRACT_NOT_CANONICAL");Bn(d,"/config",Ze.nodes),Bn(s,"/contracts",Ze.nodes),Ht(d)||Bn(s,"/contracts",oe.extendedNodes),Jt(d)||Bn(s,"/contracts",oe.legacyNodes);let a=d,c=s;Uc(a,t),Mc(c,t,o);let f=Bc(a,o,c.generatorVersion);Sl(f,c,a),X(f)!==X(c)&&m("NATIVE_CONTRACT_CLOSURE_MISMATCH",ki(f,c,"/contracts"));let u={authz:{appCode:t,...a.authz,perspectives:a.perspectives,capabilityCatalog:f.capabilities},data:{appCode:t,resources:a.data.resources,resourceContracts:f.resources,...f.concurrency?{concurrency:f.concurrency}:{},...f.subjectReadSurfaces?{subjectReadSurfaces:f.subjectReadSurfaces}:{}},events:{appCode:t,...a.events,consumers:f.eventConsumers,producers:f.eventProducers,handlerManifest:f.eventHandlerManifest,eventTypes:f.eventTypes,capturePlans:ks({resources:a.data.resources,dataPolicies:a.authz.dataPolicies,subscriptions:f.eventConsumers,capturePolicies:a.events.capturePolicies})},workflows:{appCode:t,...a.workflows,contracts:f.workflows},runtime:{appCode:t,requirements:a.runtime,backend:a.backend,frontend:a.frontend},contracts:f},p={authz:It(u.authz),data:It(u.data),events:It(u.events),workflows:It(u.workflows),runtime:It(u.runtime),contracts:It(u.contracts)},_={configDigest:o,contractDigest:n,generatorVersion:c.generatorVersion},E=Ds(a),A={schemaVersion:ls,compilerContractVersion:Xt,appCode:t,source:_,projections:p,requiredPlatformCapabilities:E,aggregateDigest:Z({schemaVersion:ls,compilerContractVersion:Xt,appCode:t,source:_,requiredPlatformCapabilities:E,projectionDigests:Object.fromEntries(Object.entries(p).map(([O,b])=>[O,b.digest]))})};return Bs(A)}function ps(e,t){let o=e.subject,n=t.find(r=>r.code===o?.resourceCode),i=new Set(Object.values(o?.factProjection||{}));return!!n?.schema?.fields?.some(r=>r.type==="subtable"&&i.has(r.code))}function Ds(e){let t=e.authz.roles,o=e.data.resources,n=e.backend.operations,i=n.filter(l=>l.platformAccess?.directory?.mode==="current-initiator"&&l.platformAccess.directory.fields.includes("phone")),r=(e.data.concurrency?.commands||[]).filter(l=>l.execution?.directory?.mode==="current-initiator"&&l.execution.directory.fields.includes("phone")),d=t.some(l=>l.capabilities.some(y=>y.endsWith(":directory:read")))||o.some(l=>l.schema.fields.some(y=>["user.single","user.multiple","department.single","department.multiple"].includes(y.type)))||n.some(l=>l.platformAccess?.directory),s=!!(e.events.subscriptions.length||e.events.timers.length||e.events.dateTriggers.length||e.events.schemas.length),a=n.some(l=>l.platformAccess?.managedFiles||l.platformAccess?.managedFileCopies)||e.events.subscriptions.some(l=>l.platformAccess?.managedFileCopies),c=e.workflows.definitions.some(l=>l.definition.rejectionNotification!==void 0)||n.some(l=>l.platformAccess?.notification)||e.events.subscriptions.some(l=>l.platformAccess?.notification),f=(l,y,R=!1)=>{let h=o.find($=>$.code===l.definition.subject?.resourceCode)?.schema.fields||[];return Object.values(l.definition.taskPages||{}).some($=>$.fields.some(w=>{if(w.readonly)return!1;let j=h.find(Q=>Q.code===w.code);if(!R&&j&&y.includes(j.type))return!0;if(!w.subtable||!j?.subtable)return!1;let L=o.find(Q=>Q.code===j.subtable.resourceCode)?.schema.fields||[];return w.subtable.fields.some(Q=>!Q.readonly&&L.some(ee=>ee.code===Q.code&&y.includes(ee.type)))}))},u=e.workflows.definitions.filter(l=>f(l,["file","image","signature","text.rich"])),p=e.workflows.definitions.filter(l=>f(l,["signature","text.rich"])),_=e.workflows.definitions.filter(l=>f(l,["file","image","signature","text.rich"],!0)),E=e.workflows.definitions.filter(l=>l.launch.mode==="standalone"||l.launch.mode==="hidden-handoff"),A=n.some(l=>l.platformAccess?.workflow)||E.length>0,O=E.filter(l=>{let y=l.launch.submission;if(!y)return!1;let R=o.find(h=>h.code===l.definition.subject.resourceCode);return[y.create,y.existing].some(h=>h&&Object.values(h.inputs).some($=>$.source==="field"&&R?.schema.fields.some(w=>w.code===$.fieldCode&&w.type.startsWith("resource-ref.")&&w.source)))}),b={resources:o},g={perspectives:e.perspectives,authz:e.authz},I={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(l=>({code:l.code,method:l.method,path:l.path,capability:l.capability,platformAccess:l.platformAccess||null,...l.browser?{browser:l.browser}:{},ai:l.ai||null}))}};return[...Mn(e)?[{code:"application.extended-configuration-bytes",declaration:{legacyConfigBytes:oe.legacyConfigBytes,configBytes:oe.configBytes}}]:[],...Jt(e)?[{code:"application.extended-artifact-capacity",declaration:oe}]:[],...Ht(e)?[{code:"application.high-density-artifact-capacity",declaration:Ze}]:[],...Un(e)?[{code:"application.extended-declaration-capacity",declaration:{resources:e.data.resources.length,policies:e.authz.dataPolicies.length,roles:e.authz.roles.length,capabilities:e.authz.capabilities.length,definitions:e.workflows.definitions.length,bindings:e.workflows.bindings.length,activations:e.workflows.activations.length,routes:e.frontend.routes.length,navigationItems:e.frontend.admin.navigation.reduce((l,y)=>l+y.items.length,0)}}]:[],...o.some(l=>l.uniqueKeys?.length)?[{code:"data.unique-keys",declaration:o.filter(l=>l.uniqueKeys?.length).map(l=>({code:l.code,uniqueKeys:l.uniqueKeys}))}]:[],...e.data.concurrency?[{code:"data.managed-concurrency",declaration:e.data.concurrency}]:[],...e.data.concurrency?.commands.some(l=>l.mode==="durable")?[{code:"data.managed-concurrency.durable",declaration:e.data.concurrency}]:[],...o.some(l=>l.decimalReservationLifecycle)?[{code:"data.decimal-reservation-lifecycle",declaration:o.filter(l=>l.decimalReservationLifecycle).map(l=>({code:l.code,decimalReservationLifecycle:l.decimalReservationLifecycle}))}]:[],...n.some(l=>l.platformAccess?.dataCommands)?[{code:"data.business-commands",declaration:n.filter(l=>l.platformAccess?.dataCommands)}]:[],...e.authz.dataPolicies.some(l=>l.publicRead)?[{code:"data.authenticated-public-projection",declaration:e.authz.dataPolicies.filter(l=>l.publicRead)}]:[],...n.some(l=>l.platformAccess?.roleAssertions?.actorAuthority)?[{code:"data.transaction-actor-authority",declaration:n.filter(l=>l.platformAccess?.roleAssertions?.actorAuthority)}]:[],...n.some(l=>l.platformAccess?.workflowStage)?[{code:"workflow.native-stage-guard",declaration:n.filter(l=>l.platformAccess?.workflowStage)}]:[],...n.some(l=>l.platformAccess?.recordEdit)?[{code:"data.record-edit",declaration:n.filter(l=>l.platformAccess?.recordEdit)}]:[],...n.some(l=>l.platformAccess?.decimalReservation)||e.events.subscriptions.some(l=>l.platformAccess?.decimalReservation)?[{code:"data.decimal-reservations",declaration:[...n.filter(l=>l.platformAccess?.decimalReservation).map(l=>({code:l.code,decimalReservation:l.platformAccess.decimalReservation})),...e.events.subscriptions.filter(l=>l.platformAccess?.decimalReservation).map(l=>({subscriptionCode:l.code,decimalReservation:l.platformAccess.decimalReservation}))]}]:[],{code:"application-native-2",declaration:I},{code:"authz.native-batch-explain",declaration:g},{code:"authz.native-management",declaration:g},{code:"deployment.durable-runs",declaration:I.backend},{code:"deployment.platform-executor",declaration:I.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:b},{code:"data.native-golden-crud",declaration:b}]:[],...o.some(l=>l.recordComments!==void 0)?[{code:"data.record-comments",declaration:b}]:[],...o.some(l=>l.recordDeletion!==void 0)?[{code:"data.workflow-record-deletion",declaration:b}]:[],...o.some(l=>l.recordPrint!==void 0)?[{code:"data.record-print",declaration:b}]:[],...o.some(l=>l.workflowHistory!==void 0)?[{code:"workflow.record-history-read",declaration:b}]:[],...o.some(Io)?[{code:"data.audit-read-access",declaration:b}]:[],...d?[{code:"directory-v2",declaration:{roles:t.map(l=>({code:l.code,capabilities:l.capabilities.filter(y=>y.endsWith(":directory:read"))})),resources:o.map(l=>({code:l.code,fields:l.schema.fields.filter(y=>["user.single","user.multiple","department.single","department.multiple"].includes(y.type))})),operations:n.filter(l=>l.platformAccess?.directory).map(l=>({code:l.code,directory:l.platformAccess.directory}))}}]:[],...n.some(l=>l.platformAccess?.directory?.mode==="selected-user")?[{code:"directory.selected-user",declaration:n.filter(l=>l.platformAccess?.directory?.mode==="selected-user").map(l=>({code:l.code,directory:l.platformAccess.directory}))}]:[],...i.length||r.length?[{code:"directory.current-initiator-phone",declaration:{operations:i.map(l=>({code:l.code,directory:l.platformAccess.directory})),commands:r.map(l=>({code:l.code,directory:l.execution.directory}))}}]:[],...a?[{code:"data.managed-files",declaration:{operations:n.filter(l=>l.platformAccess?.managedFiles||l.platformAccess?.managedFileCopies).map(l=>({code:l.code,...l.platformAccess?.managedFiles?{managedFiles:l.platformAccess.managedFiles}:{},...l.platformAccess?.managedFileCopies?{managedFileCopies:l.platformAccess.managedFileCopies}:{}})),subscriptions:e.events.subscriptions.filter(l=>l.platformAccess?.managedFileCopies).map(l=>({code:l.code,managedFileCopies:l.platformAccess.managedFileCopies}))}}]:[],...e.events.subscriptions.some(l=>l.execution)?[{code:"events.native-data-actions",declaration:e.events.subscriptions.filter(l=>l.execution)}]:[],...e.events.capturePolicies?.length?[{code:"events.capture-policy",declaration:e.events.capturePolicies}]:[],...e.events.dateTriggers.some(l=>mi(l.resourceCode,e.events.subscriptions.filter(y=>y.eventTypes.includes(l.eventType)),e.data.resources.find(y=>y.code===l.resourceCode)).length>0)?[{code:"events.date-source-projection",declaration:{triggers:e.events.dateTriggers,subscriptions:e.events.subscriptions}}]:[],...s?[{code:"events-v2",declaration:e.events},{code:"events.durable-receipts",declaration:e.events}]:[],...sn(e.data.resources)?[{code:"data.extended-owned-subtable-capacity",declaration:e.data.resources.filter(l=>sn([l]))}]:[],...on(e.data.resources,e.workflows?.definitions||[])?[{code:"data.extended-field-capacity",declaration:{resources:e.data.resources.filter(l=>l.schema.fields.length>100),workflows:(e.workflows?.definitions||[]).filter(l=>on([],[l]))}}]:[],...rn(e.data.resources)?[{code:"data.aggregate-owned-subtable-capacity",declaration:e.data.resources.filter(l=>rn([l]))}]:[],...e.data.resources.some(l=>l.schema.fields.some(y=>y.userCandidates!==void 0))?[{code:"data.user-candidates",declaration:e.data.resources.filter(l=>l.schema.fields.some(y=>y.userCandidates!==void 0))}]:[],...oi(e.workflows.bindings)?[{code:"workflow.role-input-selection",declaration:e.workflows.bindings.filter(l=>Object.values(l.binding.bindings).some(y=>y.selectedInputPath!==void 0))}]:[],...ti(e.workflows.bindings)?[{code:"workflow.role-union",declaration:e.workflows.bindings.filter(l=>Object.values(l.binding.bindings).some(y=>y.roleCodes!==void 0))}]:[],...e.backend.operations.some(l=>l.platformAccess?.ownedSubject)?[{code:"workflow.named-owned-create",declaration:e.backend.operations.filter(l=>l.platformAccess?.ownedSubject)}]:[],...tn(e.data.resources)?[{code:"data.user-candidate-launch-scope",declaration:e.data.resources.filter(l=>tn([l]))}]:[],...ln(e.data.resources)?[{code:"data.subtable-minimum-rows",declaration:e.data.resources.filter(l=>ln([l]))}]:[],...cn(e.data.resources)?[{code:"data.datetime-minute-precision",declaration:e.data.resources.filter(l=>cn([l]))}]:[],...e.workflows.activations.length?[{code:"workflow-kernel-v2",declaration:e.workflows},{code:"workflow.fresh-command-token",declaration:e.workflows}]:[],...e.workflows.definitions.some(l=>l.definition.instanceCommands!==void 0)?[{code:"workflow.instance-cancellation-policy",declaration:e.workflows.definitions.filter(l=>l.definition.instanceCommands!==void 0)}]:[],...e.workflows.definitions.some(l=>l.definition.instanceCommands?.withdraw?.reasonRequired===!1)?[{code:"workflow.optional-withdrawal-reason",declaration:e.workflows.definitions.filter(l=>l.definition.instanceCommands?.withdraw?.reasonRequired===!1)}]:[],...e.workflows.definitions.some(l=>l.definition.rejectionNotification!==void 0)?[{code:"workflow.rejection-notification",declaration:e.workflows.definitions.filter(l=>l.definition.rejectionNotification!==void 0)}]:[],...e.workflows.definitions.some(l=>l.definition.commandHandlers!==void 0)||n.some(l=>l.platformAccess?.workflow?.businessCommands)?[{code:"workflow.business-data-command",declaration:{definitions:e.workflows.definitions.filter(l=>l.definition.commandHandlers!==void 0),operations:n.filter(l=>l.platformAccess?.workflow?.businessCommands)}}]:[],...e.workflows.definitions.some(l=>l.definition.commandHandlers?.approve?.transitionPolicy==="workflow")?[{code:"workflow.approval-business-command",declaration:e.workflows.definitions.filter(l=>l.definition.commandHandlers?.approve?.transitionPolicy==="workflow")}]:[],...e.workflows.definitions.some(l=>l.definition.commandHandlers?.resubmit)||n.some(l=>l.platformAccess?.workflow?.businessCommands?.includes("resubmit"))?[{code:"workflow.correction-business-command",declaration:{definitions:e.workflows.definitions.filter(l=>l.definition.commandHandlers?.resubmit),operations:n.filter(l=>l.platformAccess?.workflow?.businessCommands?.includes("resubmit"))}}]:[],...e.workflows.definitions.some(l=>l.definition.launchPreflight!==void 0)?[{code:"workflow.launch-preflight",declaration:e.workflows.definitions.filter(l=>l.definition.launchPreflight!==void 0)}]:[],...e.workflows.definitions.some(l=>l.definition.commandHandlers?.resubmit?.derivedSubjectFields!==void 0)?[{code:"workflow.correction-derived-subject-facts",declaration:e.workflows.definitions.filter(l=>l.definition.commandHandlers?.resubmit?.derivedSubjectFields!==void 0)}]:[],...e.workflows.definitions.some(l=>l.definition.approvedDelegation!==void 0)?[{code:"workflow.approved-delegation",declaration:e.workflows.definitions.filter(l=>l.definition.approvedDelegation!==void 0)}]:[],...e.workflows.definitions.some(l=>ps(l.definition,e.data.resources))?[{code:"workflow.owned-initial-facts",declaration:e.workflows.definitions.filter(l=>ps(l.definition,e.data.resources))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.kind==="correction"))?[{code:"workflow.initiator-correction",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.kind==="correction"))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.operationPolicy?.reject?.commentRequired===!1))?[{code:"workflow.optional-rejection-comment",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.operationPolicy?.reject?.commentRequired===!1))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>Object.values(y.operationPolicy||{}).some(R=>R.reasonRequired===!1)))?[{code:"workflow.optional-operation-reason",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>Object.values(y.operationPolicy||{}).some(R=>R.reasonRequired===!1)))}]:[],...O.length?[{code:"workflow.named-input-sources",declaration:O}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.administration!==void 0||y.operationPolicy!==void 0))?[{code:"workflow.node-administration",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.administration!==void 0||y.operationPolicy!==void 0))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.kind==="approval"&&y.emptyPolicy!==void 0))?[{code:"workflow.approval-empty-policy",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.kind==="approval"&&y.emptyPolicy!==void 0))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.completionDeadline!==void 0))?[{code:"workflow.completion-deadline",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.completionDeadline!==void 0))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.initiatorApprovalPolicy!==void 0))?[{code:"workflow.initiator-approval-policy",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.initiatorApprovalPolicy!==void 0))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.kind==="cc"))?[{code:"workflow.automatic-cc",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.kind==="cc"))}]:[],...e.workflows.definitions.some(l=>l.definition.taskPages!==void 0)?["workflow.task-page-submit","workflow.task-private-drafts"].map(l=>({code:l,declaration:e.workflows.definitions.filter(y=>y.definition.taskPages!==void 0)})):[],...u.length?[{code:"workflow.task-managed-files",declaration:u}]:[],..._.length?[{code:"workflow.task-owned-files",declaration:_}]:[],...p.length?[{code:"workflow.task-rich-fields",declaration:p}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.taskPages||{}).some(y=>y.fields.some(R=>R.subtable)))?[{code:"workflow.task-owned-subtables",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.taskPages||{}).some(y=>y.fields.some(R=>R.subtable)))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.kind==="action"))?[{code:"workflow.durable-business-step",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.kind==="action"))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.kind==="action"&&y.handler.dataTransaction))?[{code:"workflow.step-data-transaction",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.kind==="action"&&y.handler.dataTransaction))}]:[],...e.workflows.bindings.some(l=>Object.values(l.binding.bindings).some(y=>y.routing!==void 0))?[{code:"workflow.assignment-routing",declaration:e.workflows.bindings.filter(l=>Object.values(l.binding.bindings).some(y=>y.routing!==void 0))}]:[],...A?[{code:"business-process.durable-command",declaration:{operations:n.filter(l=>l.platformAccess?.workflow).map(l=>({code:l.code,workflow:l.platformAccess.workflow})),definitions:E,activations:e.workflows.activations.filter(l=>E.some(y=>y.definition.code===l.workflowCode))}}]:[],...c?[{code:"notification-hub-v2",declaration:{...e.workflows.definitions.some(l=>l.definition.rejectionNotification!==void 0)?{rejectionNotifications:e.workflows.definitions.filter(l=>l.definition.rejectionNotification!==void 0)}:{},operations:n.filter(l=>l.platformAccess?.notification).map(l=>({code:l.code,notification:l.platformAccess.notification})),subscriptions:e.events.subscriptions.filter(l=>l.platformAccess?.notification).map(l=>({code:l.code,notification:l.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:l,declaration:y})=>({code:l,contractVersion:l==="data.unique-keys"?o.some(R=>Bo(R.schema.fields,R.uniqueKeys)==="1.1.0")?"1.1.0":"1.0.0":as[l],usageDigest:`sha256:${Z(y)}`})).sort((l,y)=>l.code===y.code?0:l.code<y.code?-1:1)}function ks(e){let t=new Map,o=new Set(e.resources.map(r=>String(r.code)));for(let[r,d]of D(e.capturePolicies===void 0?[]:e.capturePolicies,"/capturePlan/capturePolicies",100).entries()){let s=`/capturePlan/capturePolicies/${r}`,a=N(d,s);C(a,["resourceCode","mode"],s);let c=H(a.resourceCode,`${s}/resourceCode`);o.has(c)||m("NATIVE_EVENT_CAPTURE_RESOURCE_NOT_FOUND",s,{resourceCode:c}),t.has(c)&&m("NATIVE_EVENT_CAPTURE_POLICY_DUPLICATE",s,{resourceCode:c}),a.mode!=="all"&&a.mode!=="subscribed"&&m("NATIVE_EVENT_CAPTURE_MODE_INVALID",`${s}/mode`),t.set(c,a.mode)}let n=new Map(e.dataPolicies.map((r,d)=>{let s=N(r,`/capturePlan/dataPolicies/${d}`);return[String(s.code),s]})),i=e.subscriptions.map((r,d)=>N(r,`/capturePlan/subscriptions/${d}`));return e.resources.map((r,d)=>{let s=`/capturePlan/resources/${d}`,a=N(r,s),c=H(a.code,`${s}/code`),f=a.schema?N(a.schema,`${s}/schema`):a,u=new Set(D(f.fields||[],`${s}/schema/fields`,500).map((y,R)=>G(N(y,`${s}/schema/fields/${R}`).code,`${s}/schema/fields/${R}/code`))),p=a.dataPolicyCode?P(a.dataPolicyCode,`${s}/dataPolicyCode`):null,_=p?n.get(p):void 0;p&&!_&&m("NATIVE_EVENT_CAPTURE_AUTHZ_POLICY_NOT_FOUND",s,{resourceCode:c,dataPolicyCode:p});let E=new Set;for(let y of _?.rules||[])E.add(String(y.field));if(_?.readExpression)for(let y of zt(_.readExpression,`${s}/readExpression`))E.add(String(y.rule.field));let A=new Set,O=new Set,b=new Set;for(let[y,R]of i.entries()){let h=D(R.eventTypes,`/capturePlan/subscriptions/${y}/eventTypes`,20).map(String);if(!h.some(L=>L.startsWith("openxiangda.data.")))continue;let $=N(R.filter||{},`/capturePlan/subscriptions/${y}/filter`),w=Array.isArray($.resourceCodes)?$.resourceCodes.map(String):[];if(w.length&&!w.includes(c))continue;for(let L of h)Kn.includes(L)&&b.add(L);for(let L of Wc($,`/capturePlan/subscriptions/${y}/filter`))A.add(L);let j=N(R.payload||{},`/capturePlan/subscriptions/${y}/payload`);for(let L of D(j.fields||[],`/capturePlan/subscriptions/${y}/payload/fields`,32))O.add(G(L,`/capturePlan/subscriptions/${y}/payload/fields`))}let g=new Set([...A,...O]),I=new Set([...g,...E]);I.size>fs&&m("NATIVE_EVENT_CAPTURE_FIELDS_LIMIT",s,{resourceCode:c,maximum:fs});for(let y of I)!u.has(y)&&!(E.has(y)&&Ss.has(y))&&m("NATIVE_EVENT_CAPTURE_FIELD_NOT_FOUND",s,{resourceCode:c,field:y});let T=N(a.fieldPolicies||{},`${s}/fieldPolicies`);for(let y of g)T[y]?.mask==="omit"&&m("NATIVE_EVENT_CAPTURE_FIELD_SENSITIVE",s,{resourceCode:c,field:y});let l={resourceCode:c,...t.get(c)==="subscribed"?{capturedEventTypes:[...b].sort()}:{},filterFields:[...A].sort(),projectionFields:[...O].sort(),authorizationFields:[...E].sort(),captureFields:[...I].sort()};return{...l,digest:Z(l)}}).sort((r,d)=>r.resourceCode.localeCompare(d.resourceCode))}function Wc(e,t){let o=new Set;for(let[d,s]of D(e.changes||[],`${t}/changes`,16).entries()){let a=N(s,`${t}/changes/${d}`);o.add(G(a.field,`${t}/changes/${d}/field`))}let n=N(e.changedFields||{},`${t}/changedFields`);for(let d of["anyOf","allOf","noneOf"])for(let[s,a]of D(n[d]||[],`${t}/changedFields/${d}`,32).entries())o.add(G(a,`${t}/changedFields/${d}/${s}`));let i=0,r=(d,s,a)=>{a>3&&m("NATIVE_EVENT_FILTER_DEPTH_LIMIT",s);let c=N(d,s);if(c.change){let u=N(c.change,`${s}/change`);o.add(G(u.field,`${s}/change/field`)),i+=1;return}if(c.not){r(c.not,`${s}/not`,a+1);return}let f=c.all?"all":c.any?"any":null;f||m("NATIVE_EVENT_FILTER_CONDITION_INVALID",s);for(let[u,p]of D(c[f],`${s}/${f}`,16).entries())r(p,`${s}/${f}/${u}`,a+1)};return e.where&&r(e.where,`${t}/where`,1),i+=Array.isArray(e.changes)?e.changes.length:0,i>16&&m("NATIVE_EVENT_FILTER_ATOM_LIMIT",t),[...o].sort()}function Uc(e,t){C(e,["schemaVersion","compilerContractVersion","appCode","perspectives","authz","backend","data","events","workflows","frontend","runtime"],"/config"),F(e.schemaVersion,gc,"/config/schemaVersion"),F(e.compilerContractVersion,Xt,"/config/compilerContractVersion"),F(e.appCode,t,"/config/appCode"),D(e.perspectives,"/config/perspectives",100);let o=N(e.authz,"/config/authz");C(o,["capabilities","roles","scopeDimensions","scopeSources","roleMembershipSources","relationshipGrantSources","dataPolicies","authorizationTransitions"],"/config/authz",["authenticatedUserRoleCode"]),D(o.capabilities,"/config/authz/capabilities",M.capabilities),D(o.roles,"/config/authz/roles",M.roles),D(o.scopeDimensions,"/config/authz/scopeDimensions",100),D(o.scopeSources,"/config/authz/scopeSources",100),D(o.roleMembershipSources,"/config/authz/roleMembershipSources",100),D(o.relationshipGrantSources,"/config/authz/relationshipGrantSources",100),D(o.dataPolicies,"/config/authz/dataPolicies",M.dataPolicies),D(o.authorizationTransitions,"/config/authz/authorizationTransitions",100);let n=N(e.backend,"/config/backend");C(n,["secrets","operations"],"/config/backend"),D(n.secrets,"/config/backend/secrets",100),D(n.operations,"/config/backend/operations",500),Nl(n.secrets);let i=N(e.data,"/config/data");C(i,["resources"],"/config/data",["resourceDetailRoutes","subjectReadSurfaces","concurrency"]),D(i.resources,"/config/data/resources",M.resources),i.subjectReadSurfaces!==void 0&&D(i.subjectReadSurfaces,"/config/data/subjectReadSurfaces",M.subjectReadSurfaces),i.resourceDetailRoutes!==void 0&&D(i.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100);let r=N(e.events,"/config/events");C(r,["schemas","subscriptions","timers","dateTriggers"],"/config/events",["capturePolicies"]),D(r.schemas,"/config/events/schemas",100),D(r.subscriptions,"/config/events/subscriptions",100),D(r.timers,"/config/events/timers",100),D(r.dateTriggers,"/config/events/dateTriggers",100);let d=N(e.workflows,"/config/workflows");C(d,["definitions","bindings","activations","providers","editableParameters"],"/config/workflows"),D(d.definitions,"/config/workflows/definitions",M.workflows),D(d.bindings,"/config/workflows/bindings",M.workflows),D(d.activations,"/config/workflows/activations",M.workflows),D(d.providers,"/config/workflows/providers",100),D(d.editableParameters,"/config/workflows/editableParameters",100);let s=N(e.frontend,"/config/frontend");C(s,["routes","user","admin","devicePolicy"],"/config/frontend",["authentication","publicAccess"]),D(s.routes,"/config/frontend/routes",M.routes);let a=N(s.user,"/config/frontend/user");C(a,["applicationTodoCenter"],"/config/frontend/user"),bt(a.applicationTodoCenter,"/config/frontend/user/applicationTodoCenter"),$i(s.devicePolicy,"/config/frontend/devicePolicy"),Object.prototype.hasOwnProperty.call(s,"authentication")&&vs(s.authentication,s.routes,e,"/config/frontend/authentication"),Object.prototype.hasOwnProperty.call(s,"publicAccess")&&il(s.publicAccess,e,"/config/frontend/publicAccess");let c=N(s.admin,"/config/frontend/admin");C(c,["navigation"],"/config/frontend/admin",["access"]),c.access!==void 0&&Zn(c.access,"/config/frontend/admin/access",e.appCode),dl(c.navigation,"/config/frontend/admin/navigation");let f=N(e.runtime,"/config/runtime");C(f,["protocolCapabilities","health"],"/config/runtime"),V(f.protocolCapabilities,"/config/runtime/protocolCapabilities",100),C(N(f.health,"/config/runtime/health"),["livePath","readyPath","versionPath"],"/config/runtime/health"),F(f.health.livePath,"/__platform/health","/config/runtime/health/livePath"),F(f.health.readyPath,"/__platform/ready","/config/runtime/health/readyPath"),F(f.health.versionPath,"/__platform/version","/config/runtime/health/versionPath")}function Mc(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","subjectReadSurfaces","concurrency"]),F(e.schemaVersion,hs,"/contracts/schemaVersion"),F(e.compilerContractVersion,Xt,"/contracts/compilerContractVersion"),S(e.generatorVersion,"/contracts/generatorVersion",128),F(e.appCode,t,"/contracts/appCode"),F(e.configDigest,o,"/contracts/configDigest"),D(e.perspectives,"/contracts/perspectives",M.perspectives),D(e.resources,"/contracts/resources",M.resources),e.subjectReadSurfaces!==void 0&&D(e.subjectReadSurfaces,"/contracts/subjectReadSurfaces",M.subjectReadSurfaces),D(e.capabilities,"/contracts/capabilities",M.capabilities),D(e.operations,"/contracts/operations",M.operations),D(e.eventConsumers,"/contracts/eventConsumers",M.eventConsumers),D(e.eventProducers,"/contracts/eventProducers",M.eventProducers),D(e.eventSchemas,"/contracts/eventSchemas",M.eventSchemas),N(e.eventHandlerManifest,"/contracts/eventHandlerManifest"),V(e.eventTypes,"/contracts/eventTypes",M.eventTypes),D(e.workflows,"/contracts/workflows",M.workflows),D(e.routes,"/contracts/routes",M.routes),Object.prototype.hasOwnProperty.call(e,"authentication")&&tl(e.authentication,"/contracts/authentication"),Object.prototype.hasOwnProperty.call(e,"publicAccess")&&rl(e.publicAccess,"/contracts/publicAccess"),Object.prototype.hasOwnProperty.call(e,"adminAccess")&&Zn(e.adminAccess,"/contracts/adminAccess",t),ml(e.routeManifest,"/contracts/routeManifest",t),ul(e.adminPages,"/contracts/adminPages"),fl(e.adminNavigation,"/contracts/adminNavigation")}function Bc(e,t,o){let n=qc(e);Il(e,n),bl(e),yl(e),Tl(e);let i=e.events.schemas.map((g,I)=>{let T=`/config/events/schemas/${I}`,l=N(g,T),y=S(l.eventType,`${T}/eventType`,255);return y.startsWith("openxiangda.")&&m("NATIVE_EVENT_SCHEMA_RESERVED",`${T}/eventType`,{eventType:y}),F(l.schemaDigest,Z(N(l.jsonSchema,`${T}/jsonSchema`)),`${T}/schemaDigest`),l}),r=new Set([...Kn,...Gn,...i.map(g=>String(g.eventType))]),d=new Map(e.data.resources.map(g=>[String(g.code),new Map(g.schema.fields.map(I=>[String(I.code),String(I.type)]))])),s=te(e.events.subscriptions.map((g,I)=>{let T=`/config/events/subscriptions/${I}`,l=N(g,T),y=V(l.eventTypes,`${T}/eventTypes`,20);y.forEach((w,j)=>{r.has(w)||m("NATIVE_EVENT_TYPE_NOT_REGISTERED",`${T}/eventTypes/${j}`,{eventType:w})});let R=Ko(l,e.data.resources,T),h=Gc(l.delivery,y,`${T}/delivery`),$=Kc(l.platformAccess,`${T}/platformAccess`,d,e,l);return{code:P(l.code,`${T}/code`),endpointPath:Ne(l.endpointPath,`${T}/endpointPath`),eventTypes:y,filter:N(l.filter,`${T}/filter`),payload:R?.payload||N(l.payload,`${T}/payload`),...R?{execution:R.execution}:{},...$?{platformAccess:$}:{},delivery:h}}),g=>g.code),a=new Map(i.map(g=>[String(g.eventType),String(g.dataSchemaVersion)])),c=te([...e.data.resources.flatMap(g=>Kn.map(I=>({code:`data:${g.code}:${I}`,source:"data",eventType:I,dataSchemaVersion:"2.0.0",resourceCode:g.code}))),...i.map(g=>({code:`app:${g.eventType}`,source:"app",eventType:g.eventType,dataSchemaVersion:g.dataSchemaVersion})),...e.events.timers.map(g=>({code:g.code,source:"timer",eventType:g.eventType,dataSchemaVersion:a.get(String(g.eventType))||"2.0.0"})),...e.events.dateTriggers.map(g=>({code:g.code,source:"date",eventType:g.eventType,dataSchemaVersion:a.get(String(g.eventType))||"2.0.0",resourceCode:g.resourceCode,field:g.field})),...e.workflows.activations.length?Gn.filter(g=>!Ho.includes(g)||e.workflows.definitions.some(I=>Object.values(I.definition.nodes).some(T=>T.kind==="action"))).filter(g=>g!=="openxiangda.workflow.node.skipped.v2"||e.workflows.definitions.some(I=>Object.values(I.definition.nodes).some(T=>T.kind==="approval"&&T.emptyPolicy==="skip"))).map(g=>({code:`workflow:${g}`,source:"workflow",eventType:g,dataSchemaVersion:"2.0.0"})):[]],g=>`${g.source}:${g.code}:${g.eventType}`),f=B([...s.flatMap(g=>g.eventTypes),...c.map(g=>String(g.eventType))]);ll(e);let u=Ls(e),p;try{p=Do(e.data.concurrency,e.data.resources,n)}catch(g){throw g instanceof ct&&m(g.code,g.pointer,{reason:g.reason}),g}p?.commands.some(g=>g.mode==="durable")&&e.backend?.enabled===!1&&m("NATIVE_MANAGED_CONCURRENCY_INVALID","/data/concurrency",{reason:"durable commands require backend runtime"});let _=Jc(e,n),E=$s(e),A=e.workflows.definitions.map(g=>g.definition),O=Dn(A),b=Xo(A,s,!0);b.length&&m(b[0],"/config/events/subscriptions");try{Po(e.data.resources,E)}catch(g){throw g instanceof qe&&m(g.code,g.pointer,{reason:g.reason}),g}return{schemaVersion:hs,compilerContractVersion:Xt,generatorVersion:o,appCode:e.appCode,configDigest:t,perspectives:e.perspectives,resources:zc(e),..._.length?{subjectReadSurfaces:_}:{},...p?{concurrency:p}:{},capabilities:te(n,g=>g.code),operations:E,eventConsumers:s,eventProducers:c,eventSchemas:i,eventHandlerManifest:{schemaVersion:Fc,appCode:e.appCode,handlers:s.filter(g=>!g.execution).map(g=>({code:g.code,endpointPath:g.endpointPath,eventTypes:g.eventTypes,dataSchemaVersions:B(g.eventTypes.map(I=>I.startsWith("openxiangda.")?"2.0.0":a.get(I)||"2.0.0")),maxBodyBytes:65536,receiptProtocolVersion:2,...O[g.code]?{workflowStep:O[g.code]}:{}}))},eventTypes:f,workflows:js(e),routes:Xn(e),...Object.prototype.hasOwnProperty.call(e.frontend,"authentication")?{authentication:nl(e)}:{},...Object.prototype.hasOwnProperty.call(e.frontend,"publicAccess")?{publicAccess:sl(e)}:{},...e.frontend.admin.access?{adminAccess:e.frontend.admin.access}:{},routeManifest:Al(e),adminPages:u,adminNavigation:al(e)}}function Kc(e,t,o,n,i){if(e===void 0)return;let r=N(e,t);C(r,["notification","managedFileCopies","decimalReservation"],t,!0);let d={};if(r.decimalReservation!==void 0)try{d.decimalReservation=Rr(r.decimalReservation,Cr(n,i))}catch{m("NATIVE_EVENT_DECIMAL_RESERVATION_INVALID",`${t}/decimalReservation`)}if(r.notification!==void 0){let s=N(r.notification,`${t}/notification`);C(s,["mode"],`${t}/notification`),F(s.mode,"business-standard",`${t}/notification/mode`),d.notification={mode:"business-standard"}}if(r.managedFileCopies!==void 0){let s=D(r.managedFileCopies,`${t}/managedFileCopies`,16);s.length||m("NATIVE_EVENT_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let a=new Set;d.managedFileCopies=te(s.map((c,f)=>{let u=`${t}/managedFileCopies/${f}`,p=N(c,u);C(p,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],u),F(p.mode,"copy",`${u}/mode`);let _=H(p.sourceResourceCode,`${u}/sourceResourceCode`),E=H(p.targetResourceCode,`${u}/targetResourceCode`),A=o.get(_),O=o.get(E);(!A||!O)&&m("NATIVE_EVENT_MANAGED_FILE_COPY_RESOURCE_INVALID",u);let b=V(p.sourceFieldCodes,`${u}/sourceFieldCodes`,16),g=V(p.targetFieldCodes,`${u}/targetFieldCodes`,16);(!b.length||b.length!==g.length)&&m("NATIVE_EVENT_MANAGED_FILE_COPY_FIELDS_INVALID",u),b.forEach((T,l)=>{let y=A.get(T),R=O.get(g[l]);(!["file","image"].includes(String(y))||y!==R)&&m("NATIVE_EVENT_MANAGED_FILE_COPY_FIELD_INVALID",`${u}/sourceFieldCodes/${l}`)});let I=`${_}:${b.join(",")}=>${E}:${g.join(",")}`;return a.has(I)&&m("NATIVE_EVENT_MANAGED_FILE_COPY_DUPLICATE",u),a.add(I),{mode:"copy",sourceResourceCode:_,sourceFieldCodes:B(b),targetResourceCode:E,targetFieldCodes:B(g)}}),c=>`${c.sourceResourceCode}:${c.sourceFieldCodes.join(",")}=>${c.targetResourceCode}:${c.targetFieldCodes.join(",")}`)}return Object.keys(d).length||m("NATIVE_EVENT_PLATFORM_ACCESS_EMPTY",t),d}function Gc(e,t,o){let n=N(e,o);C(n,["timeoutMs","maxAttempts","initialBackoffMs","maxBackoffMs","ordering","concurrency"],o),se(n.timeoutMs,`${o}/timeoutMs`,1e3,3e4),se(n.maxAttempts,`${o}/maxAttempts`,1,12);let i=se(n.initialBackoffMs,`${o}/initialBackoffMs`,1e3,3e5);se(n.maxBackoffMs,`${o}/maxBackoffMs`,i,18e5),se(n.concurrency,`${o}/concurrency`,1,50);let r=S(n.ordering,`${o}/ordering`,32);return["none","record","workflow-instance"].includes(r)||m("NATIVE_EVENT_DELIVERY_ORDERING_INVALID",`${o}/ordering`),r==="workflow-instance"&&t.some(d=>!xc.has(d))&&m("NATIVE_EVENT_WORKFLOW_ORDERING_REQUIRES_WORKFLOW_FACTS",`${o}/ordering`),n}function qc(e){let t=new Map;for(let r of Ms(e.appCode))t.set(r.code,r);for(let[r,d]of e.authz.capabilities.entries()){let s=`/config/authz/capabilities/${r}`,a=N(d,s);C(a,["code","kind","name","description"],s,!0);let c=pe(a.code,`${s}/code`,e.appCode);t.has(c)&&m("NATIVE_CAPABILITY_DUPLICATE",`${s}/code`),["backend","ui"].includes(a.kind)||m("NATIVE_CAPABILITY_KIND_INVALID",`${s}/kind`);let f={code:c,kind:a.kind,name:S(a.name,`${s}/name`,255),source:"explicit",...a.description===void 0?{}:{description:Pi(a.description,`${s}/description`,2e3)}};t.set(c,f)}let o=e.data.resources.map((r,d)=>({pointer:`/config/data/resources/${d}`,resource:Qe(r,`/config/data/resources/${d}`,e.appCode)}));for(let{pointer:r,resource:d}of o){let s={read:`\u8BFB\u53D6${d.name}`,create:`\u65B0\u5EFA${d.name}`,update:`\u66F4\u65B0${d.name}`,delete:`\u5220\u9664${d.name}`};for(let a of["read","create","update","delete"]){let c=pe(d.capabilities[a],`${r}/capabilities/${a}`,e.appCode);t.has(c)&&m("NATIVE_CAPABILITY_DUPLICATE",`${r}/capabilities/${a}`),t.set(c,{code:c,kind:"data",name:s[a],source:"data"})}}let n=new Set(t.keys()),i=new Map;for(let{pointer:r,resource:d}of o)for(let[s,a]of Object.entries(d.fieldPolicies)){if(rt(s))continue;let c=N(a,`${r}/fieldPolicies/${s}`);for(let f of["read","create","update"])if(Array.isArray(c[f]))for(let u of V(c[f],`${r}/fieldPolicies/${s}/${f}`,2e3)){if(pe(u,`${r}/fieldPolicies/${s}/${f}`,e.appCode),n.has(u))continue;let p=i.get(u);p&&p!==d.code&&m("NATIVE_CAPABILITY_DUPLICATE",`${r}/fieldPolicies/${s}/${f}`),i.set(u,d.code),!t.has(u)&&t.set(u,{code:u,kind:"data",name:`${d.name}.${s}.${f}`,source:"data"})}}return[...t.values()]}function zc(e){let t=Hc(e);return te(e.data.resources.map((o,n)=>{let i=Qe(o,`/config/data/resources/${n}`,e.appCode),r=t.get(i.code);return{code:i.code,schemaDigest:Z(i.schema),fields:te(i.schema.fields.map(d=>({code:d.code,type:d.type})),d=>d.code),...r?{detailRouteCode:r}:{}}}),o=>o.code)}function Jc(e,t){if(e.data.subjectReadSurfaces===void 0)return[];let o=D(e.data.subjectReadSurfaces,"/config/data/subjectReadSurfaces",M.subjectReadSurfaces),n=new Set(t.map(d=>String(d.code))),i=new Map(e.data.resources.map((d,s)=>{let a=`/config/data/resources/${s}`,c=Qe(d,a,e.appCode);return[String(c.code),{resource:c,fields:new Map(D(N(c.schema,`${a}/schema`).fields,`${a}/schema/fields`,500).map(f=>{let u=N(f,`${a}/schema/fields`);return[String(u.code),u]}))}]})),r=new Set;return te(o.map((d,s)=>{let a=`/config/data/subjectReadSurfaces/${s}`,c=N(d,a);C(c,["code","name","capability","subject","relations"],a);let f=P(c.code,`${a}/code`);r.has(f)&&m("NATIVE_SUBJECT_READ_SURFACE_CODE_DUPLICATE",`${a}/code`),r.add(f);let u=pe(c.capability,`${a}/capability`,e.appCode);n.has(u)||m("NATIVE_SUBJECT_READ_SURFACE_CAPABILITY_NOT_DECLARED",`${a}/capability`);let p=N(c.subject,`${a}/subject`);C(p,["resourceCode","fields"],`${a}/subject`);let _=H(p.resourceCode,`${a}/subject/resourceCode`),E=i.get(_);E||m("NATIVE_SUBJECT_READ_SURFACE_RESOURCE_NOT_DECLARED",`${a}/subject/resourceCode`);let A=V(p.fields,`${a}/subject/fields`,100).map((T,l)=>G(T,`${a}/subject/fields/${l}`));A.length||m("NATIVE_SUBJECT_READ_SURFACE_FIELDS_REQUIRED",`${a}/subject/fields`);for(let[T,l]of A.entries()){let y=E.fields.get(l);(!y||y.type==="subtable")&&m("NATIVE_SUBJECT_READ_SURFACE_FIELD_INVALID",`${a}/subject/fields/${T}`)}let O=D(c.relations,`${a}/relations`,8);O.length||m("NATIVE_SUBJECT_READ_SURFACE_RELATIONS_REQUIRED",`${a}/relations`);let b=new Set,g=0,I=te(O.map((T,l)=>{let y=`${a}/relations/${l}`,R=N(T,y);C(R,["code","resourceCode","foreignKeyField","fields","limit"],y,["order"]);let h=P(R.code,`${y}/code`);b.has(h)&&m("NATIVE_SUBJECT_READ_SURFACE_RELATION_CODE_DUPLICATE",`${y}/code`),b.add(h);let $=H(R.resourceCode,`${y}/resourceCode`),w=i.get($);w||m("NATIVE_SUBJECT_READ_SURFACE_RESOURCE_NOT_DECLARED",`${y}/resourceCode`);let j=G(R.foreignKeyField,`${y}/foreignKeyField`),L=w.fields.get(j),Q=N(L?.source||{},`${y}/foreignKeyField/source`);(!L||!["uuid","resource-ref.single"].includes(String(L.type))||L.type==="resource-ref.single"&&(Q.kind!=="resource"||Q.resourceCode!==_))&&m("NATIVE_SUBJECT_READ_SURFACE_RELATION_INVALID",`${y}/foreignKeyField`);let ee=V(R.fields,`${y}/fields`,100).map((ie,v)=>G(ie,`${y}/fields/${v}`));ee.length||m("NATIVE_SUBJECT_READ_SURFACE_FIELDS_REQUIRED",`${y}/fields`);for(let[ie,v]of ee.entries()){let U=w.fields.get(v);(!U||U.type==="subtable")&&m("NATIVE_SUBJECT_READ_SURFACE_FIELD_INVALID",`${y}/fields/${ie}`)}let Y=D(R.order||[],`${y}/order`,10).map((ie,v)=>{let U=`${y}/order/${v}`,x=N(ie,U);C(x,["field","direction"],U);let q=G(x.field,`${U}/field`),z=w.fields.get(q);return(!Ss.has(q)&&!z||z?.type==="subtable"||z&&!at(z.type))&&m("NATIVE_SUBJECT_READ_SURFACE_ORDER_FIELD_INVALID",`${U}/field`),["asc","desc"].includes(String(x.direction))||m("NATIVE_SUBJECT_READ_SURFACE_ORDER_DIRECTION_INVALID",`${U}/direction`),{field:q,direction:x.direction}}),_e=se(R.limit,`${y}/limit`,1,100);return g+=_e,{code:h,resourceCode:$,foreignKeyField:j,fields:B(ee),...Y.length?{order:Y}:{},limit:_e}}),T=>T.code);return g>400&&m("NATIVE_SUBJECT_READ_SURFACE_ROW_LIMIT_EXCEEDED",`${a}/relations`),{code:f,name:S(c.name,`${a}/name`,255),capability:u,subject:{resourceCode:_,fields:B(A)},relations:I}}),d=>d.code)}function Hc(e){let t=e.data.resourceDetailRoutes===void 0?[]:D(e.data.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100),o=new Map(e.data.resources.map((r,d)=>{let s=`/config/data/resources/${d}`,a=Qe(r,s,e.appCode);return[a.code,a]})),n=new Map(Xn(e).map(r=>[String(r.code),r])),i=new Map;for(let[r,d]of t.entries()){let s=`/config/data/resourceDetailRoutes/${r}`,a=N(d,s);C(a,["resourceCode","desktop","mobile"],s);let c=H(a.resourceCode,`${s}/resourceCode`);i.has(c)&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_DUPLICATE",`${s}/resourceCode`);let f=o.get(c);f||m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_RESOURCE_MISSING",`${s}/resourceCode`);let u=P(a.desktop,`${s}/desktop`),p=P(a.mobile,`${s}/mobile`);u===p&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_INVALID",s);let _=String(f.capabilities.read);for(let[E,A]of[["desktop",u],["mobile",p]]){let O=`${s}/${E}`,b=n.get(A);b||m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_REFERENCE_MISSING",O),b.surface!=="user"&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_SURFACE_INVALID",O);let g=Ne(b.path,`${O}/path`),I=[...g.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)],T=E==="mobile"?!g.startsWith("/m/"):g==="/m"||g.startsWith("/m/");(g.includes("*")||g.includes("?")||g.includes("#")||g.split("/").includes("..")||I.length!==1||T)&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_PATH_INVALID",O);let l=Array.isArray(b.access?.allOf)?b.access.allOf:[];b.capability!==_&&!l.includes(_)&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_CAPABILITY_INVALID",O)}i.set(c,{desktop:u,mobile:p})}return i}function $s(e){let t=new Map(e.data.resources.map((d,s)=>{let a=`/config/data/resources/${s}`,c=Qe(d,a,e.appCode);return[c.code,new Map(c.schema.fields.map(f=>[String(f.code),f]))]})),o=new Map(e.data.resources.map((d,s)=>{let a=`/config/data/resources/${s}`,c=Qe(d,a,e.appCode);return[c.code,new Map(c.schema.fields.map(f=>[String(f.code),String(f.type)]))]})),n=new Set(o.keys()),i=new Set(e.workflows.activations.map((d,s)=>Qn(N(d,`/config/workflows/activations/${s}`).workflowCode,`/config/workflows/activations/${s}/workflowCode`))),r=new Map;return te(e.backend.operations.map((d,s)=>{let a=`/config/backend/operations/${s}`,c=N(d,a);C(c,["code","method","path","capability","requestSchema","responseSchema","description","platformAccess","browser","ai"],a,!0);let f=S(c.method,`${a}/method`,16);["GET","POST","PUT","PATCH","DELETE"].includes(f)||m("NATIVE_OPERATION_METHOD_INVALID",`${a}/method`);let u=P(c.code,`${a}/code`);Qc(c.ai,a,u,f,n);let p=Zc(c.platformAccess,`${a}/platformAccess`,o,t,i,new Set(e.authz.roles.map(E=>String(E.code))));if(p?.workflowStage){let E=p.workflowStage,A=e.workflows.definitions.find(O=>O.definition.code===E.workflowCode);(!A||A.definition.subject?.resourceCode!==E.resourceCode||E.runningNodeIds.some(O=>!A.definition.nodes[O]))&&m("NATIVE_WORKFLOW_STAGE_NODE_INVALID",`${a}/platformAccess/workflowStage/runningNodeIds`)}if(p?.recordEdit){let E=e.data.resources.find(A=>A.code===p.recordEdit.resourceCode);E?.surface?.mutationOwner!=="action"&&m("NATIVE_RECORD_EDIT_ACTION_OWNER_REQUIRED",`${a}/platformAccess/recordEdit`);for(let A of p.recordEdit.fieldCodes)(!E.fieldPolicies?.[A]?.update?.length||E.surface?.fields?.[A]?.system===!0)&&m("NATIVE_RECORD_EDIT_FIELD_INVALID",`${a}/platformAccess/recordEdit/fieldCodes`)}if(p?.decimalReservation){let E=p.decimalReservation,A=String(E.resourceCode),O=JSON.stringify([E.amountFieldCode,E.currencyFieldCode,E.relationFieldCode,E.parentFieldCode,E.rootFieldCode,E.statusFieldCode,E.parentRelationValue,E.childRelationValue]),b=r.get(A);b&&b!==O&&m("NATIVE_DECIMAL_RESERVATION_MAPPING_CONFLICT",`${a}/platformAccess/decimalReservation`),r.set(A,O)}let _=Yc(c.browser,`${a}/browser`,f,c.requestSchema,c.responseSchema,o,t,e.data.subjectReadSurfaces||[]);return{code:u,method:f,path:Ne(c.path,`${a}/path`),requiredCapability:pe(c.capability,`${a}/capability`,e.appCode),requestSchemaDigest:Z(N(c.requestSchema,`${a}/requestSchema`)),responseSchemaDigest:Z(N(c.responseSchema,`${a}/responseSchema`)),...c.description===void 0?{}:{description:Pi(c.description,`${a}/description`,2e3)},...p?{platformAccess:p}:{},..._?{browser:_}:{}}}),d=>d.code)}function Yc(e,t,o,n,i,r,d,s){if(e===void 0)return null;let a=N(e,t);C(a,["exposure","behavior","idempotency","subject"],t,["refreshTargets","fileIntent"]),F(a.exposure,"authenticated",`${t}/exposure`);let c=S(a.behavior,`${t}/behavior`,32);["read","controlled"].includes(c)||m("NATIVE_OPERATION_BROWSER_BEHAVIOR_INVALID",`${t}/behavior`);let f=S(a.idempotency,`${t}/idempotency`,32);(!["none","required"].includes(f)||c==="controlled"&&f!=="required"||c==="read"&&f!=="none")&&m("NATIVE_OPERATION_BROWSER_IDEMPOTENCY_INVALID",`${t}/idempotency`);let u=N(a.subject,`${t}/subject`);C(u,["resourceCode","inputField"],`${t}/subject`);let p=H(u.resourceCode,`${t}/subject/resourceCode`);r.has(p)||m("NATIVE_OPERATION_BROWSER_SUBJECT_RESOURCE_NOT_DECLARED",`${t}/subject/resourceCode`);let _=G(u.inputField,`${t}/subject/inputField`),E=N(n,`${t}/requestSchema`),A=N(i,`${t}/responseSchema`);(E.type!=="object"||E.additionalProperties!==!1||A.type!=="object"||A.additionalProperties!==!1)&&m("NATIVE_OPERATION_BROWSER_SCHEMA_ROOT_INVALID",`${t}/requestSchema`);let O=N(E.properties,`${t}/requestSchema/properties`),b=new Set(E.required===void 0?[]:V(E.required,`${t}/requestSchema/required`,200));(!(_ in O)||!b.has(_))&&m("NATIVE_OPERATION_BROWSER_SUBJECT_INPUT_INVALID",`${t}/subject/inputField`);let g=N(O[_],`${t}/requestSchema/properties/${_}`);(g.type!=="string"||g.format!=="uuid")&&m("NATIVE_OPERATION_BROWSER_SUBJECT_INPUT_INVALID",`${t}/subject/inputField`);let I=new Map((Array.isArray(s)?s:[]).map((h,$)=>{let w=N(h,`/config/data/subjectReadSurfaces/${$}`);return[String(w.code),String(N(w.subject,`/config/data/subjectReadSurfaces/${$}/subject`).resourceCode)]})),T=a.refreshTargets===void 0?[]:D(a.refreshTargets,`${t}/refreshTargets`,16),l=new Set,y=te(T.map((h,$)=>{let w=`${t}/refreshTargets/${$}`,j=N(h,w);C(j,["kind","code"],w),F(j.kind,"subject-surface",`${w}/kind`);let L=P(j.code,`${w}/code`);return(l.has(L)||!I.has(L)||I.get(L)!==p)&&m("NATIVE_OPERATION_BROWSER_REFRESH_TARGET_INVALID",`${w}/code`),l.add(L),{kind:"subject-surface",code:L}}),h=>`${h.kind}:${h.code}`),R=Xc(a.fileIntent,`${t}/fileIntent`,o,c,f,p,O,b,d);return{exposure:"authenticated",behavior:c,idempotency:f,subject:{resourceCode:p,inputField:_},...y.length?{refreshTargets:y}:{},...R?{fileIntent:R}:{}}}function Xc(e,t,o,n,i,r,d,s,a){if(e===void 0)return null;let c=N(e,t);C(c,["recordResourceCode","recordIdInputField","relationField","fileNameField","contentTypeField","sizeField","purposes","maxTtlSeconds","maxBytes"],t),(o!=="GET"||n!=="read"||i!=="none")&&m("NATIVE_OPERATION_FILE_INTENT_BEHAVIOR_INVALID",t);let f=H(c.recordResourceCode,`${t}/recordResourceCode`),u=a.get(f);u||m("NATIVE_OPERATION_FILE_INTENT_RESOURCE_NOT_DECLARED",`${t}/recordResourceCode`);let p=G(c.recordIdInputField,`${t}/recordIdInputField`),_=N(d[p],`${t}/recordIdInputField`);(!s.has(p)||_.type!=="string"||_.format!=="uuid")&&m("NATIVE_OPERATION_FILE_INTENT_RECORD_INPUT_INVALID",`${t}/recordIdInputField`);let E=G(c.relationField,`${t}/relationField`),A=u.get(E);(!A||!["uuid","resource-ref.single"].includes(String(A.type))||String(A.type)==="resource-ref.single"&&(String(N(A.source,`${t}/relationField`).kind||"")!=="resource"||String(N(A.source,`${t}/relationField`).resourceCode||"")!==r))&&m("NATIVE_OPERATION_FILE_INTENT_RELATION_INVALID",`${t}/relationField`);let O=[["fileNameField",["text.short","text.long"]],["contentTypeField",["text.short","text.long"]],["sizeField",["number.integer"]]],b={};for(let[l,y]of O){let R=G(c[l],`${t}/${l}`);y.includes(String(u.get(R)?.type))||m("NATIVE_OPERATION_FILE_INTENT_METADATA_INVALID",`${t}/${l}`),b[l]=R}let g=te(V(c.purposes,`${t}/purposes`,2),l=>l);(!g.length||g.some(l=>!["preview","download"].includes(l)))&&m("NATIVE_OPERATION_FILE_INTENT_PURPOSE_INVALID",`${t}/purposes`);let I=Number(c.maxTtlSeconds);(!Number.isSafeInteger(I)||I<1||I>300)&&m("NATIVE_OPERATION_FILE_INTENT_TTL_INVALID",`${t}/maxTtlSeconds`);let T=Number(c.maxBytes);return(!Number.isSafeInteger(T)||T<1||T>104857600)&&m("NATIVE_OPERATION_FILE_INTENT_SIZE_INVALID",`${t}/maxBytes`),{recordResourceCode:f,recordIdInputField:p,relationField:E,fileNameField:b.fileNameField,contentTypeField:b.contentTypeField,sizeField:b.sizeField,purposes:g,maxTtlSeconds:I,maxBytes:T}}function Zc(e,t,o,n,i,r){if(e===void 0)return null;let d=N(e,t);C(d,["directory","managedFiles","managedFileCopies","notification","workflow","roleAssertions","decimalReservation","dataCommands","recordEdit","ownedSubject","workflowStage"],t,!0),Object.keys(d).length===0&&m("NATIVE_OPERATION_PLATFORM_ACCESS_EMPTY",t);let s={};if(d.dataCommands!==void 0){let a=N(d.dataCommands,`${t}/dataCommands`);C(a,["mode"],`${t}/dataCommands`),F(a.mode,"recoverable-native",`${t}/dataCommands/mode`),s.dataCommands={mode:"recoverable-native"}}if(d.workflowStage!==void 0){try{xo(d.workflowStage)}catch{m("NATIVE_WORKFLOW_STAGE_DECLARATION_INVALID",`${t}/workflowStage`)}let a=d.workflowStage;(!s.dataCommands||d.decimalReservation!==void 0||!o.has(a.resourceCode)||!i.has(a.workflowCode)||!d.workflow?.codes?.includes(a.workflowCode))&&m("NATIVE_WORKFLOW_STAGE_DECLARATION_INVALID",`${t}/workflowStage`),s.workflowStage={...a,runningNodeIds:B([...a.runningNodeIds]),allowedStatuses:B([...a.allowedStatuses])}}if(d.recordEdit!==void 0){let a=`${t}/recordEdit`,c=N(d.recordEdit,a);C(c,["resourceCode","fieldCodes"],a);let f=H(c.resourceCode,`${a}/resourceCode`),u=n.get(f),p=V(c.fieldCodes,`${a}/fieldCodes`,200);(!u||!p.length||!s.dataCommands)&&m("NATIVE_RECORD_EDIT_DECLARATION_INVALID",a);for(let _ of p){let E=u.get(_);(!E||E.type==="serial-number"||E.type==="subtable")&&m("NATIVE_RECORD_EDIT_FIELD_INVALID",`${a}/fieldCodes`)}s.recordEdit={resourceCode:f,fieldCodes:B(p)}}if(d.roleAssertions!==void 0){let a=N(d.roleAssertions,`${t}/roleAssertions`);C(a,["roleCodes","actorAuthority"],`${t}/roleAssertions`,!0),a.actorAuthority!==void 0&&F(a.actorAuthority,!0,`${t}/roleAssertions/actorAuthority`);let c=V(a.roleCodes,`${t}/roleAssertions/roleCodes`,20);c.length||m("NATIVE_OPERATION_ROLE_ASSERTIONS_REQUIRED",`${t}/roleAssertions/roleCodes`),c.forEach((f,u)=>{r.has(f)||m("NATIVE_ROLE_REFERENCE_MISSING",`${t}/roleAssertions/roleCodes/${u}`)}),s.roleAssertions={roleCodes:B(c),...a.actorAuthority===!0?{actorAuthority:!0}:{}}}if(d.directory!==void 0){let a=N(d.directory,`${t}/directory`);C(a,["mode","fields"],`${t}/directory`),["current-initiator","selected-user"].includes(String(a.mode))||m("NATIVE_OPERATION_DIRECTORY_MODE_INVALID",`${t}/directory/mode`);let c=new Set(["displayName","employeeNumber","primaryDepartment","departments",...a.mode==="current-initiator"?["phone"]:[]]),f=V(a.fields,`${t}/directory/fields`,c.size);(!f.length||f.some(u=>!c.has(u)))&&m("NATIVE_OPERATION_DIRECTORY_FIELDS_INVALID",`${t}/directory/fields`),s.directory={mode:String(a.mode),fields:B(f)}}if(d.managedFiles!==void 0){let a=D(d.managedFiles,`${t}/managedFiles`,16);a.length||m("NATIVE_OPERATION_MANAGED_FILES_REQUIRED",`${t}/managedFiles`);let c=new Set;s.managedFiles=te(a.map((f,u)=>{let p=`${t}/managedFiles/${u}`,_=N(f,p);C(_,["resourceCode","fieldCodes","intents"],p);let E=H(_.resourceCode,`${p}/resourceCode`);(c.has(E)||!o.has(E))&&m("NATIVE_OPERATION_MANAGED_FILE_RESOURCE_INVALID",`${p}/resourceCode`),c.add(E);let A=V(_.fieldCodes,`${p}/fieldCodes`,16);(!A.length||A.some(b=>!["file","image","signature","text.rich"].includes(String(o.get(E)?.get(b)||""))))&&m("NATIVE_OPERATION_MANAGED_FILE_FIELD_INVALID",`${p}/fieldCodes`);let O=V(_.intents,`${p}/intents`,2);return(!O.length||O.some(b=>!["create","update"].includes(b)))&&m("NATIVE_OPERATION_MANAGED_FILE_INTENT_INVALID",`${p}/intents`),{resourceCode:E,fieldCodes:B(A),intents:B(O)}}),f=>f.resourceCode)}if(d.managedFileCopies!==void 0){let a=D(d.managedFileCopies,`${t}/managedFileCopies`,16);a.length||m("NATIVE_OPERATION_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let c=new Set;s.managedFileCopies=te(a.map((f,u)=>{let p=`${t}/managedFileCopies/${u}`,_=N(f,p);C(_,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],p),F(_.mode,"copy",`${p}/mode`);let E=H(_.sourceResourceCode,`${p}/sourceResourceCode`),A=H(_.targetResourceCode,`${p}/targetResourceCode`),O=o.get(E),b=o.get(A);(!O||!b)&&m("NATIVE_OPERATION_MANAGED_FILE_COPY_RESOURCE_INVALID",p);let g=V(_.sourceFieldCodes,`${p}/sourceFieldCodes`,16),I=V(_.targetFieldCodes,`${p}/targetFieldCodes`,16);(!g.length||g.length!==I.length)&&m("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELDS_INVALID",p),g.forEach((l,y)=>{let R=O.get(l),h=b.get(I[y]);(!["file","image"].includes(String(R))||R!==h)&&m("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELD_INVALID",`${p}/sourceFieldCodes/${y}`)});let T=`${E}:${g.join(",")}=>${A}:${I.join(",")}`;return c.has(T)&&m("NATIVE_OPERATION_MANAGED_FILE_COPY_DUPLICATE",p),c.add(T),{mode:"copy",sourceResourceCode:E,sourceFieldCodes:B(g),targetResourceCode:A,targetFieldCodes:B(I)}}),f=>`${f.sourceResourceCode}:${f.sourceFieldCodes.join(",")}=>${f.targetResourceCode}:${f.targetFieldCodes.join(",")}`)}if(d.notification!==void 0){let a=N(d.notification,`${t}/notification`);C(a,["mode"],`${t}/notification`),a.mode!=="business-standard"&&m("NATIVE_OPERATION_NOTIFICATION_MODE_INVALID",`${t}/notification/mode`),s.notification={mode:"business-standard"}}if(d.workflow!==void 0){let a=N(d.workflow,`${t}/workflow`);C(a,["codes"],`${t}/workflow`,["businessCommands"]);let c=V(a.codes,`${t}/workflow/codes`,16);(!c.length||c.some(u=>!i.has(u)))&&m("NATIVE_OPERATION_WORKFLOW_CODE_INVALID",`${t}/workflow/codes`);let f=a.businessCommands===void 0?void 0:V(a.businessCommands,`${t}/workflow/businessCommands`,4);f&&(!f.length||f.some(u=>!["approve","reject","withdraw","resubmit"].includes(u)))&&m("NATIVE_OPERATION_WORKFLOW_BUSINESS_COMMAND_INVALID",`${t}/workflow/businessCommands`),s.workflow={codes:B(c),...f?{businessCommands:B(f)}:{}}}if(d.ownedSubject!==void 0){let a=`${t}/ownedSubject`,c=d.ownedSubject;try{Gt(c)}catch{m("NATIVE_WORKFLOW_OWNED_SUBJECT_INVALID",a)}(!s.workflow||d.decimalReservation!==void 0)&&m("NATIVE_WORKFLOW_OWNED_SUBJECT_INVALID",a);try{Oi(c,n,s.managedFiles||[])}catch(f){m(`NATIVE_${f.message}`,a)}s.ownedSubject={mode:"create",resourceCode:c.resourceCode,subtables:te(c.subtables.map(f=>({fieldCode:f.fieldCode,fieldCodes:B([...f.fieldCodes])})),f=>f.fieldCode)}}if(d.decimalReservation!==void 0){let a=`${t}/decimalReservation`,c=N(d.decimalReservation,a);C(c,["mode","resourceCode","amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode","parentRelationValue","childRelationValue","eligibleParentStatuses","eligibleChildStatuses"],a);let f=S(c.mode,`${a}/mode`,16);["reserve","commit","release"].includes(f)||m("NATIVE_DECIMAL_RESERVATION_MODE_INVALID",`${a}/mode`);let u=H(c.resourceCode,`${a}/resourceCode`),p=n.get(u);p||m("NATIVE_DECIMAL_RESERVATION_RESOURCE_MISSING",`${a}/resourceCode`);let E=Object.fromEntries(["amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode"].map(l=>[l,G(c[l],`${a}/${l}`)])),A=l=>p.get(E[l]),O=l=>new Set((A(l)?.options||[]).map(y=>String(y.value))),b=P(c.parentRelationValue,`${a}/parentRelationValue`),g=P(c.childRelationValue,`${a}/childRelationValue`),I=V(c.eligibleParentStatuses,`${a}/eligibleParentStatuses`,16),T=V(c.eligibleChildStatuses,`${a}/eligibleChildStatuses`,16);(A("amountFieldCode")?.type!=="number.decimal"||A("amountFieldCode")?.exactDecimal!==!0||A("amountFieldCode")?.precision!==18||A("amountFieldCode")?.scale!==2||A("currencyFieldCode")?.type!=="option.single"||A("relationFieldCode")?.type!=="option.single"||A("parentFieldCode")?.type!=="resource-ref.single"||A("parentFieldCode")?.source?.resourceCode!==u||A("rootFieldCode")?.type!=="uuid"||A("statusFieldCode")?.type!=="option.single"||b===g||!O("relationFieldCode").has(b)||!O("relationFieldCode").has(g)||!I.length||!T.length||I.some(l=>!O("statusFieldCode").has(l))||T.some(l=>!O("statusFieldCode").has(l)))&&m("NATIVE_DECIMAL_RESERVATION_FIELD_INVALID",a),s.decimalReservation={mode:f,resourceCode:u,...E,parentRelationValue:b,childRelationValue:g,eligibleParentStatuses:B(I),eligibleChildStatuses:B(T)}}return s}function Qc(e,t,o,n,i){if(e===void 0)return;let r=`${t}/ai`,d=N(e,r);bc.test(o)||m("NATIVE_OPERATION_AI_CODE_INVALID",`${t}/code`),C(d,["name","description","risk","resources","sideEffects","concurrency","timeoutMs"],r,!0),S(d.name,`${r}/name`,wi),S(d.description,`${r}/description`,wi);let s=S(d.risk,`${r}/risk`,16);["read","write","destructive","external"].includes(s)||m("NATIVE_OPERATION_AI_RISK_INVALID",`${r}/risk`),s==="read"!=(n==="GET")&&m("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${r}/risk`),n==="DELETE"&&!["destructive","external"].includes(s)&&m("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${r}/risk`);let a=V(d.resources,`${r}/resources`,16);a.length===0&&m("NATIVE_OPERATION_AI_RESOURCE_REQUIRED",`${r}/resources`),a.forEach((f,u)=>{let p=H(f,`${r}/resources/${u}`);i.has(p)||m("NATIVE_OPERATION_AI_RESOURCE_MISSING",`${r}/resources/${u}`)});let c=V(d.sideEffects,`${r}/sideEffects`,20);(s==="read"&&c.length!==0||s!=="read"&&c.length===0)&&m("NATIVE_OPERATION_AI_SIDE_EFFECT_INVALID",`${r}/sideEffects`),d.concurrency!==void 0&&!["none","revision"].includes(S(d.concurrency,`${r}/concurrency`,16))&&m("NATIVE_OPERATION_AI_CONCURRENCY_INVALID",`${r}/concurrency`),d.timeoutMs!==void 0&&se(d.timeoutMs,`${r}/timeoutMs`,100,3e4)}function zn(e){return(e.replace(/\/{2,}/g,"/").replace(/\/$/,"")||"/").split("/").map(o=>o.startsWith(":")?":":o.includes("*")?"*":o).join("/")}function el(e,t){let o=N(e,t),n=S(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 d=P(o.code,`${t}/code`),s=S(o.label,`${t}/label`,255),a=S(o.presentation,`${t}/presentation`,16);["primary","secondary"].includes(a)||m("NATIVE_APPLICATION_AUTH_METHOD_PRESENTATION_INVALID",`${t}/presentation`);let c=bt(o.required,`${t}/required`);return["sso","password","dingtalk"].includes(n)||m("NATIVE_APPLICATION_AUTH_METHOD_TYPE_INVALID",`${t}/type`),n==="sso"&&o.provider!=="tenant-default"&&m("NATIVE_APPLICATION_AUTH_SSO_PROVIDER_INVALID",`${t}/provider`),n==="dingtalk"&&!["auto","jsapi","oauth"].includes(S(o.flow,`${t}/flow`,16))&&m("NATIVE_APPLICATION_AUTH_DINGTALK_FLOW_INVALID",`${t}/flow`),{code:d,type:n,label:s,presentation:a,required:c,...n==="sso"?{provider:"tenant-default"}:{},...n==="dingtalk"?{flow:o.flow}:{}}}function ms(e,t,o){let n=N(e,o);C(n,["routeCode","path","defaultRouteCode"],o);let i=P(n.routeCode,`${o}/routeCode`),r=Ne(n.path,`${o}/path`),d=t==="desktop"?"/login":"/m/login";return(r!==d||/[:*?#\\]/.test(r))&&m("NATIVE_APPLICATION_AUTH_SURFACE_PATH_INVALID",`${o}/path`,{device:t,expectedPath:d}),{routeCode:i,path:r,defaultRouteCode:P(n.defaultRouteCode,`${o}/defaultRouteCode`)}}function vs(e,t,o,n){if(e===null)return;let i=N(e,n);C(i,["accountMode","registration","methods","surfaces"],n),F(i.accountMode,"existing-platform-users-only",`${n}/accountMode`);let r=N(i.registration,`${n}/registration`);C(r,["mode"],`${n}/registration`),F(r.mode,"reject",`${n}/registration/mode`);let d=D(i.methods,`${n}/methods`,8);d.length===0&&m("NATIVE_APPLICATION_AUTH_METHOD_REQUIRED",`${n}/methods`);let s=d.map((b,g)=>el(b,`${n}/methods/${g}`)),a=new Set,c=new Set;for(let[b,g]of s.entries())a.has(g.code)&&m("NATIVE_APPLICATION_AUTH_METHOD_CODE_DUPLICATE",`${n}/methods/${b}/code`),c.has(g.type)&&m("NATIVE_APPLICATION_AUTH_METHOD_TYPE_DUPLICATE",`${n}/methods/${b}/type`),a.add(g.code),c.add(g.type);s.filter(b=>b.presentation==="primary").length!==1&&m("NATIVE_APPLICATION_AUTH_PRIMARY_METHOD_INVALID",`${n}/methods`);let f=N(i.surfaces,`${n}/surfaces`);C(f,["desktop","mobile"],`${n}/surfaces`);let u=ms(f.desktop,"desktop",`${n}/surfaces/desktop`),p=ms(f.mobile,"mobile",`${n}/surfaces/mobile`);u.routeCode===p.routeCode&&m("NATIVE_APPLICATION_AUTH_SURFACE_CODE_DUPLICATE",`${n}/surfaces/mobile/routeCode`);let _=D(t,"/config/frontend/routes",M.routes),E=new Map;for(let[b,g]of _.entries()){let I=N(g,`/config/frontend/routes/${b}`);E.set(String(I.code||""),I)}let A=new Set((Array.isArray(o.data?.resources)?o.data.resources:[]).map(b=>String(b.code||"")).filter(b=>/^[a-z][a-z0-9-]{0,62}$/.test(b)));for(let[b,g]of[["desktop",u],["mobile",p]]){E.has(g.routeCode)&&m("NATIVE_APPLICATION_AUTH_SURFACE_CODE_CONFLICT",`${n}/surfaces/${b}/routeCode`);let I=/^user\.([a-z][a-z0-9-]{0,62})\.(records|submit)$/.exec(String(g.defaultRouteCode||"")),T=E.get(g.defaultRouteCode),l=String(T?.path||"");if(I&&A.has(I[1])){let R=I[2]==="records"?`/my/${I[1]}`:`/my/${I[1]}/submit`;T={surface:"user",path:b==="mobile"?`/m${R}`:R},l=String(T.path)}let y=b==="desktop"?l==="/m"||l.startsWith("/m/"):!(l==="/m"||l.startsWith("/m/"));(!T||T.surface!=="user"||/[:*]/.test(l)||y)&&m("NATIVE_APPLICATION_AUTH_DEFAULT_ROUTE_INVALID",`${n}/surfaces/${b}/defaultRouteCode`)}let O=Ps(o).filter(b=>!b.owner.startsWith("authentication:"));for(let[b,g]of[["desktop",u],["mobile",p]]){let I=O.find(T=>zn(T.path)===zn(g.path));I&&m("NATIVE_APPLICATION_AUTH_SURFACE_PATH_CONFLICT",`${n}/surfaces/${b}/path`,{owner:I.owner})}}function tl(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=N(e,t),i=N(n.surfaces,`${t}/surfaces`),r={...n,surfaces:{...i,desktop:{...N(i.desktop,`${t}/surfaces/desktop`),defaultRouteCode:"auth-desktop-default"},mobile:{...N(i.mobile,`${t}/surfaces/mobile`),defaultRouteCode:"auth-mobile-default"}}};vs(r,o.frontend.routes,{...o,frontend:{...o.frontend,authentication:r}},t)}function nl(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 ol=new Set(["draft.read","draft.update","validate","create","own.list","own.read","public.list","public.read"]);function il(e,t,o){let n=N(e,o);C(n,["policies"],o);let i=D(n.policies,`${o}/policies`,16);i.length<1&&m("NATIVE_PUBLIC_POLICY_REQUIRED",o);let r=new Map(t.frontend.routes.map(c=>[c.code,c])),d=new Map(t.data.resources.map(c=>[c.code,c])),s=new Set,a=new Set(i.map(c=>String(c?.code||"")));i.forEach((c,f)=>{let u=`${o}/policies/${f}`,p=N(c,u);C(p,["code","routeCode","mode","resourceCode","operations","fields"],u,["requiredFields","ownRecordFields","publicRecordFields","publicFilters","serverGeneratedFields","schedule","publicSubtableFields","draft","validations"]);let _=P(p.code,`${u}/code`);s.has(_)&&m("NATIVE_PUBLIC_POLICY_DUPLICATE",`${u}/code`);let E=P(p.routeCode,`${u}/routeCode`),A=r.get(E);(!A||A.surface!=="user"||A.capability!==void 0||A.access!==void 0||/[:*]/.test(String(A.path)))&&m("NATIVE_PUBLIC_ROUTE_INVALID",`${u}/routeCode`),F(p.mode,"anonymous",`${u}/mode`);let O=H(p.resourceCode,`${u}/resourceCode`),b=d.get(O);b||m("NATIVE_PUBLIC_RESOURCE_MISSING",`${u}/resourceCode`);let g=new Map(b.schema.fields.map(v=>[String(v.code),String(v.type)])),I=V(p.operations,`${u}/operations`,8);(I.length<1||I.some(v=>!ol.has(v)))&&m("NATIVE_PUBLIC_OPERATION_INVALID",`${u}/operations`),I.includes("draft.read")!==I.includes("draft.update")&&m("NATIVE_PUBLIC_DRAFT_OPERATION_INCOMPLETE",`${u}/operations`);let T=V(p.fields,`${u}/fields`,64);(T.length<1||T.some(v=>!g.has(v)))&&m("NATIVE_PUBLIC_FIELD_INVALID",`${u}/fields`);for(let v of["requiredFields","ownRecordFields","publicRecordFields"]){if(!Object.prototype.hasOwnProperty.call(p,v))continue;V(p[v],`${u}/${v}`,64).some(x=>!T.includes(x))&&m("NATIVE_PUBLIC_FIELD_SCOPE_INVALID",`${u}/${v}`)}let l=Object.prototype.hasOwnProperty.call(p,"serverGeneratedFields")?D(p.serverGeneratedFields,`${u}/serverGeneratedFields`,16):[],y=new Set;l.forEach((v,U)=>{let x=`${u}/serverGeneratedFields/${U}`,q=N(v,x);C(q,["field","kind"],x);let z=G(q.field,`${x}/field`);(y.has(z)||!g.has(z)||T.includes(z)||g.get(z)!=="text.short"&&g.get(z)!=="text.long")&&m("NATIVE_PUBLIC_SERVER_GENERATED_FIELD_INVALID",`${x}/field`),F(q.kind,"random-token",`${x}/kind`),y.add(z)});let R=Object.prototype.hasOwnProperty.call(p,"schedule")?N(p.schedule,`${u}/schedule`):null;if(R){let v=["campusPolicyCode","rulePolicyCode","campusField","ruleCampusField","ruleWeekdaysField","ruleOpenAtField","ruleCloseAtField","ruleSlotMinutesField","ruleAdvanceHoursField","ruleAdvanceDaysField","campusEnabledField","ruleEnabledField","dateField","timeField"];C(R,v,`${u}/schedule`);for(let U of["campusPolicyCode","rulePolicyCode"])P(R[U],`${u}/schedule/${U}`);for(let U of v.filter(x=>!["campusPolicyCode","rulePolicyCode"].includes(x)))G(R[U],`${u}/schedule/${U}`);for(let U of[R.campusField,R.dateField,R.timeField])T.includes(String(U))||m("NATIVE_PUBLIC_SCHEDULE_FIELD_INVALID",`${u}/schedule`);(!a.has(String(R.campusPolicyCode))||!a.has(String(R.rulePolicyCode)))&&m("NATIVE_PUBLIC_SCHEDULE_POLICY_INVALID",`${u}/schedule`)}let h=Object.prototype.hasOwnProperty.call(p,"publicFilters")?D(p.publicFilters,`${u}/publicFilters`,16):[],$=new Set;h.forEach((v,U)=>{let x=`${u}/publicFilters/${U}`,q=N(v,x);C(q,["field","operator","value"],x);let z=G(q.field,`${x}/field`);$.has(z)&&m("NATIVE_PUBLIC_FILTER_DUPLICATE",`${x}/field`),T.includes(z)||m("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${x}/field`),F(q.operator,"eq",`${x}/operator`),["boolean","text.short","text.long","number.integer","number.decimal","date","time"].includes(g.get(z)||"")||m("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${x}/field`),q.value!==null&&typeof q.value!="string"&&typeof q.value!="number"&&typeof q.value!="boolean"&&m("NATIVE_PUBLIC_FILTER_VALUE_INVALID",`${x}/value`),$.add(z)});let w=Object.prototype.hasOwnProperty.call(p,"publicSubtableFields")?N(p.publicSubtableFields,`${u}/publicSubtableFields`):null;if(w){Object.keys(w).length>64&&m("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${u}/publicSubtableFields`);for(let[v,U]of Object.entries(w)){let x=b.schema.fields.find(J=>String(J.code)===v),q=String(x?.subtable?.resourceCode||""),z=d.get(q),ge=new Map((z?.schema?.fields||[]).map(J=>[String(J.code),String(J.type)])),Te=V(U,`${u}/publicSubtableFields/${v}`,64);(!T.includes(v)||g.get(v)!=="subtable"||!z||Te.length<1||Te.some(J=>!ge.has(J))||Te.some(J=>ge.get(J)==="subtable")||Te.some(J=>ge.get(J)==="signature"))&&m("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${u}/publicSubtableFields/${v}`)}}if(I.some(v=>v.startsWith("public."))){Object.prototype.hasOwnProperty.call(p,"publicRecordFields")||m("NATIVE_PUBLIC_RECORD_FIELDS_REQUIRED",`${u}/publicRecordFields`);let v=V(p.publicRecordFields,`${u}/publicRecordFields`,64);(v.length<1||v.some(U=>!T.includes(U))||v.some(U=>g.get(U)==="signature"||g.get(U)==="subtable"&&!w?.[U]))&&m("NATIVE_PUBLIC_RECORD_FIELDS_INVALID",`${u}/publicRecordFields`)}let j=Object.prototype.hasOwnProperty.call(p,"requiredFields")?V(p.requiredFields,`${u}/requiredFields`,64):[],L=b.surface||{},Q=L.fields||{},ee=String(L.mutationOwner||"native")==="native"&&L.generated?.create!==!1,Y=b.schema.fields.filter(v=>Ct(v,Q[v.code])).map(v=>String(v.code));if(I.includes("create")&&!ee&&m("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${u}/fields`),I.includes("create")&&!Object.prototype.hasOwnProperty.call(p,"draft")&&m("NATIVE_PUBLIC_DRAFT_REQUIRED",`${u}/draft`),I.includes("create"))for(let v of Y){let U=T.includes(v)?j.includes(v)?null:"requiredFields":"fields";U&&m("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${u}/${U}`,{resourceCode:H,fieldCode:v})}if(Object.prototype.hasOwnProperty.call(p,"draft")){let v=N(p.draft,`${u}/draft`);C(v,["enabled","inactivityTtlSeconds","maxBytes"],`${u}/draft`),F(v.enabled,!0,`${u}/draft/enabled`),se(v.inactivityTtlSeconds,`${u}/draft/inactivityTtlSeconds`,3600,7776e3),se(v.maxBytes,`${u}/draft/maxBytes`,4096,262144)}else I.includes("draft.read")&&m("NATIVE_PUBLIC_DRAFT_REQUIRED",`${u}/draft`);let _e=Object.prototype.hasOwnProperty.call(p,"validations")?D(p.validations,`${u}/validations`,16):[],ie=new Set;_e.forEach((v,U)=>{let x=`${u}/validations/${U}`,q=N(v,x);C(q,["code","kind","fields","result"],x);let z=P(q.code,`${x}/code`);ie.has(z)&&m("NATIVE_PUBLIC_VALIDATION_DUPLICATE",`${x}/code`),F(q.kind,"duplicate",`${x}/kind`),F(q.result,"availability",`${x}/result`);let ge=V(q.fields,`${x}/fields`,8);(ge.length<1||ge.some(Te=>!T.includes(Te))||ge.some(Te=>["file","subtable"].includes(g.get(Te)||"")))&&m("NATIVE_PUBLIC_VALIDATION_FIELD_INVALID",`${x}/fields`),ie.add(z)}),s.add(_)})}function rl(e,t){let o=N(e,t);C(o,["policies"],t),D(o.policies,`${t}/policies`,16).length<1&&m("NATIVE_PUBLIC_POLICY_REQUIRED",t)}function sl(e){return{policies:te(e.frontend.publicAccess.policies.map(t=>({code:t.code,routeCode:t.routeCode,mode:t.mode,resourceCode:t.resourceCode,operations:B(t.operations),fields:B(t.fields),...t.requiredFields?{requiredFields:B(t.requiredFields)}:{},...t.ownRecordFields?{ownRecordFields:B(t.ownRecordFields)}:{},...t.publicRecordFields?{publicRecordFields:B(t.publicRecordFields)}:{},...t.publicFilters?{publicFilters:t.publicFilters.map(o=>({field:o.field,operator:o.operator,value:o.value})).sort((o,n)=>Ee(o.field,n.field))}:{},...t.publicSubtableFields?{publicSubtableFields:Object.fromEntries(Object.entries(t.publicSubtableFields).sort(([o],[n])=>o.localeCompare(n)).map(([o,n])=>[o,B(Array.isArray(n)?n.map(String):[])]))}:{},...t.serverGeneratedFields?{serverGeneratedFields:t.serverGeneratedFields.map(o=>({field:o.field,kind:o.kind})).sort((o,n)=>Ee(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:te(t.validations.map(o=>({code:o.code,kind:o.kind,fields:B(o.fields),result:o.result})),o=>o.code)}:{}})),t=>t.code)}}function Ps(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=Vs(o),i=`/admin/resources/${o.code}`,r=[["list",i],["detail",`${i}/:id`],["create",`${i}/new`],["update",`${i}/:id/edit`]];for(let[d,s]of r)n[d]&&t.push({owner:`resource:${o.code}:${d}`,path:s},{owner:`resource:${o.code}:${d}: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 Xn(e){let t=new Map(Ps(e).map(o=>[zn(o.path),o]));return te(e.frontend.routes.map((o,n)=>{let i=`/config/frontend/routes/${n}`,r=N(o,i);C(r,["code","path","label","surface","parentCode","capability","access","pinned","tabPersistence","keepAlive"],i,!0),["admin","user"].includes(r.surface)||m("NATIVE_ROUTE_SURFACE_INVALID",`${i}/surface`);let d=Ne(r.path,`${i}/path`);r.surface==="admin"&&d!=="/admin"&&!d.startsWith("/admin/")&&m("NATIVE_ADMIN_ROUTE_PATH_INVALID",`${i}/path`),r.surface==="user"&&(d==="/admin"||d.startsWith("/admin/"))&&m("NATIVE_USER_ROUTE_PATH_RESERVED",`${i}/path`);let s=zn(d),a=t.get(s);a&&m("NATIVE_ROUTE_PATH_CONFLICT",`${i}/path`,{path:d,owner:a.owner}),t.set(s,{owner:`frontend:${String(r.code||n)}`,path:d});let c=/[:*]/.test(d),f=vi(r,i,e.appCode),u=r.pinned===void 0?void 0:bt(r.pinned,`${i}/pinned`),p=r.tabPersistence===void 0?c?"none":"session":S(r.tabPersistence,`${i}/tabPersistence`,16),_=r.keepAlive===void 0?"none":S(r.keepAlive,`${i}/keepAlive`,16);return["session","none"].includes(p)||m("NATIVE_ROUTE_TAB_PERSISTENCE_INVALID",`${i}/tabPersistence`),["none","memory"].includes(_)||m("NATIVE_ROUTE_KEEP_ALIVE_INVALID",`${i}/keepAlive`),c&&u===!0&&m("NATIVE_DYNAMIC_ROUTE_PINNED_FORBIDDEN",`${i}/pinned`),c&&p==="session"&&m("NATIVE_DYNAMIC_ROUTE_TAB_PERSISTENCE_FORBIDDEN",`${i}/tabPersistence`),c&&_==="memory"&&m("NATIVE_DYNAMIC_ROUTE_KEEP_ALIVE_FORBIDDEN",`${i}/keepAlive`),{code:P(r.code,`${i}/code`),path:d,label:S(r.label,`${i}/label`,255),surface:r.surface,...r.parentCode===void 0?{}:{parentCode:P(r.parentCode,`${i}/parentCode`)},...f,...u===void 0?{}:{pinned:u},tabPersistence:p,keepAlive:_}}),o=>o.code)}function Vs(e){let t=e.surface===void 0?{}:N(e.surface,"/surface"),o=t.mutationOwner||"native",n=t.generated===void 0?{}:N(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 Ls(e){let t=[];for(let o of te(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:En(n.surface,i.code)}}))])){let{resource:n,viewCode:i}=o,r=`/admin/resources/${n.code}${i?`/views/${i}`:""}`,d=Vs(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 a of s)d[a.operation]&&t.push({code:`resource:${n.code}${i?`:view:${i}`:""}:${a.operation}`,kind:a.kind,path:a.path,label:a.label,navigationEligible:a.navigationEligible,capability:a.capability,resourceCode:n.code,...i?{viewCode:i}:{}})}for(let o of Xn(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)=>Ee(o.code,n.code))}function Fs(e){return e.kind==="resource"?`resource:${e.resourceCode}${e.viewCode?`:view:${e.viewCode}`:""}:list`:`operation:${e.routeCode}`}function al(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:Fs(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||Ee(n.pageCode,i.pageCode))})).sort((t,o)=>t.order-o.order||Ee(t.code,o.code))}function dl(e,t){let o=D(e,t,M.adminNavigationGroups);o.reduce((i,r)=>i+(Array.isArray(r?.items)?r.items.length:0),0)>M.adminNavigationItems&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let n=0;o.forEach((i,r)=>{let d=`${t}/${r}`,s=N(i,d);C(s,["code","label","icon","order","items"],d,!0),P(s.code,`${d}/code`),S(s.label,`${d}/label`,255),Jn(s.icon,`${d}/icon`),Is(s.order,`${d}/order`);let a=D(s.items,`${d}/items`,500);a.length===0&&m("NATIVE_ADMIN_GROUP_ORPHANED",`${d}/items`),n+=a.length,n>M.adminNavigationItems&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t),a.forEach((c,f)=>{let u=`${d}/items/${f}`,p=N(c,u);C(p,["page","label","icon","order"],u,!0),cl(p.page,`${u}/page`),p.label!==void 0&&S(p.label,`${u}/label`,255),Jn(p.icon,`${u}/icon`),Is(p.order,`${u}/order`)})})}function cl(e,t){let o=N(e,t),n=S(o.kind,`${t}/kind`,64);if(n==="resource"){C(o,["kind","resourceCode"],t,["viewCode"]),o.viewCode!==void 0&&P(o.viewCode,`${t}/viewCode`),H(o.resourceCode,`${t}/resourceCode`);return}if(n==="operation"){C(o,["kind","routeCode"],t),P(o.routeCode,`${t}/routeCode`);return}m("NATIVE_ADMIN_PAGE_REFERENCE_KIND_INVALID",`${t}/kind`)}function ll(e){let t=new Map(Ls(e).map(i=>[String(i.code),i])),o=new Set,n=new Set;e.frontend.admin.navigation.forEach((i,r)=>{let d=`/config/frontend/admin/navigation/${r}`;o.has(i.code)&&m("NATIVE_ADMIN_GROUP_DUPLICATE",`${d}/code`),o.add(i.code),i.label===i.code&&m("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${d}/label`),i.items.forEach((s,a)=>{let c=`${d}/items/${a}`,f=Fs(s.page),u=t.get(f);(!u||u.navigationEligible!==!0)&&m("NATIVE_ADMIN_PAGE_NOT_FOUND",`${c}/page`),n.has(f)&&m("NATIVE_ADMIN_PAGE_DUPLICATE",`${c}/page`),n.add(f);let p=s.page.resourceCode||s.page.routeCode||s.page.workflowCode||f,_=s.label||u.label;(!_||_===p||_===f)&&m("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${c}/label`)})})}function ul(e,t){let o=D(e,t,M.adminPages),n=new Set;o.forEach((i,r)=>{let d=`${t}/${r}`,s=N(i,d);C(s,["code","kind","path","label","navigationEligible","capability","access","resourceCode","viewCode","routeCode"],d,!0);let a=S(s.code,`${d}/code`,255);n.has(a)&&m("NATIVE_ADMIN_PAGE_DUPLICATE",`${d}/code`),n.add(a);let c=S(s.kind,`${d}/kind`,64);if(["resource-list","resource-detail","resource-create","resource-update","operation"].includes(c)||m("NATIVE_ADMIN_PAGE_KIND_INVALID",`${d}/kind`),Ne(s.path,`${d}/path`),S(s.label,`${d}/label`,255),bt(s.navigationEligible,`${d}/navigationEligible`),s.capability!==void 0&&s.access!==void 0&&m("NATIVE_ROUTE_ACCESS_CONFLICT",`${d}/access`),s.capability!==void 0&&S(s.capability,`${d}/capability`,255),s.access!==void 0){let f=N(s.access,`${d}/access`);C(f,["allOf","anyOf"],`${d}/access`,!0);for(let u of["allOf","anyOf"])f[u]!==void 0&&V(f[u],`${d}/access/${u}`,50)}for(let f of["resourceCode","viewCode","routeCode"])s[f]!==void 0&&P(s[f],`${d}/${f}`)})}function fl(e,t){let o=D(e,t,M.adminNavigationGroups);o.reduce((i,r)=>i+(Array.isArray(r?.items)?r.items.length:0),0)>M.adminNavigationItems&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let n=0;o.forEach((i,r)=>{let d=`${t}/${r}`,s=N(i,d);C(s,["code","label","icon","order","items"],d,!0),P(s.code,`${d}/code`),S(s.label,`${d}/label`,255),Jn(s.icon,`${d}/icon`),se(s.order,`${d}/order`,-1e4,1e4);let a=D(s.items,`${d}/items`,500);a.length===0&&m("NATIVE_ADMIN_GROUP_ORPHANED",`${d}/items`),n+=a.length,n>M.adminNavigationItems&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t),a.forEach((c,f)=>{let u=`${d}/items/${f}`,p=N(c,u);C(p,["pageCode","label","icon","order"],u,!0),S(p.pageCode,`${u}/pageCode`,255),p.label!==void 0&&S(p.label,`${u}/label`,255),Jn(p.icon,`${u}/icon`),se(p.order,`${u}/order`,-1e4,1e4)})})}var pl=new Set(["application-todo-center","workflow-work-center","workflow-launch","workflow-task","workflow-instance","resource-records","resource-submit"]);function ml(e,t,o){let n=N(e,t);C(n,["schemaVersion","appCode","devicePolicy","rootEntry","authentication","routes","digest"],t),F(n.schemaVersion,ws,`${t}/schemaVersion`),F(n.appCode,o,`${t}/appCode`),$i(n.devicePolicy,`${t}/devicePolicy`),_l(n.rootEntry,`${t}/rootEntry`),gl(n.authentication,`${t}/authentication`),Di(n.digest,`${t}/digest`);let i=D(n.routes,`${t}/routes`,M.routes),r=new Set;i.forEach((d,s)=>{let a=`${t}/routes/${s}`,c=N(d,a),f=c.kind==="resource-records"||c.kind==="resource-submit";C(c,["code","kind","desktop","mobile"],a,["workflowCode",...f?["resourceCode"]:[]]);let u=S(c.code,`${a}/code`,255);r.has(u)&&m("NATIVE_ROUTE_MANIFEST_DUPLICATE",`${a}/code`),r.add(u);let p=S(c.kind,`${a}/kind`,64);if(pl.has(p)||m("NATIVE_ROUTE_MANIFEST_KIND_INVALID",`${a}/kind`),c.workflowCode!==void 0&&P(c.workflowCode,`${a}/workflowCode`),f){let A=H(c.resourceCode,`${a}/resourceCode`);F(u,`user.${A}.${c.kind==="resource-records"?"records":"submit"}`,`${a}/code`)}else c.resourceCode!==void 0&&m("NATIVE_PROPERTY_UNKNOWN",`${a}/resourceCode`);let _=gs(c.desktop,`${a}/desktop`,o),E=gs(c.mobile,`${a}/mobile`,o);_.surface!=="user"&&m("NATIVE_ROUTE_MANIFEST_DESKTOP_SURFACE_INVALID",`${a}/desktop/surface`),E.surface!=="user"&&m("NATIVE_ROUTE_MANIFEST_MOBILE_SURFACE_INVALID",`${a}/mobile/surface`),_.routeCode===E.routeCode&&m("NATIVE_ROUTE_MANIFEST_PAIR_DUPLICATE",a)}),F(n.digest,Z({schemaVersion:n.schemaVersion,appCode:n.appCode,devicePolicy:n.devicePolicy,rootEntry:n.rootEntry,authentication:n.authentication,routes:n.routes}),`${t}/digest`)}function $i(e,t){let o=N(e,t);C(o,["kind","mobileMaxWidthPx","desktopMinWidthPx"],t),F(o.kind,"viewport-family",`${t}/kind`);let n=se(o.mobileMaxWidthPx,`${t}/mobileMaxWidthPx`,320,1600),i=se(o.desktopMinWidthPx,`${t}/desktopMinWidthPx`,320,1600);return i!==n+1&&m("NATIVE_FRONTEND_DEVICE_POLICY_INVALID",t),{kind:"viewport-family",mobileMaxWidthPx:n,desktopMinWidthPx:i}}function _l(e,t){let o=N(e,t);C(o,["code","desktop","mobile"],t);let n=P(o.code,`${t}/code`),i=Si(o.desktop,`${t}/desktop`),r=Si(o.mobile,`${t}/mobile`);return(i===r||r==="/"||!r.startsWith("/m/"))&&m("NATIVE_ROUTE_MANIFEST_ROOT_ENTRY_INVALID",t),i.startsWith("/m/")&&m("NATIVE_ROUTE_MANIFEST_ROOT_ENTRY_INVALID",`${t}/desktop`),{code:n,desktop:i,mobile:r}}function gl(e,t){let o=N(e,t);C(o,["desktop","mobile"],t);let n=_s(o.desktop,`${t}/desktop`,!1),i=_s(o.mobile,`${t}/mobile`,!0);return(n.routeCode===i.routeCode||n.path===i.path)&&m("NATIVE_ROUTE_MANIFEST_AUTHENTICATION_DUPLICATE",t),{desktop:n,mobile:i}}function _s(e,t,o){let n=N(e,t);C(n,["routeCode","path"],t);let i=P(n.routeCode,`${t}/routeCode`),r=Si(n.path,`${t}/path`);return(o?!r.startsWith("/m/"):r.startsWith("/m/"))&&m("NATIVE_ROUTE_MANIFEST_AUTHENTICATION_PATH_INVALID",`${t}/path`),{routeCode:i,path:r}}function Si(e,t){let o=Ne(e,t);return/[:*?#\\\\]/.test(o)&&m("NATIVE_ROUTE_MANIFEST_STATIC_PATH_INVALID",t),o}function gs(e,t,o){let n=N(e,t);C(n,["routeCode","path","surface","pathParams","requiresAuthentication"],t,["capability","access"]),P(n.routeCode,`${t}/routeCode`);let i=Ne(n.path,`${t}/path`),r=S(n.surface,`${t}/surface`,16);["admin","user"].includes(r)||m("NATIVE_ROUTE_SURFACE_INVALID",`${t}/surface`);let d=V(n.pathParams,`${t}/pathParams`,8);return d.forEach((s,a)=>{(!/^[A-Za-z][A-Za-z0-9_]*$/.test(s)||s.length>64)&&m("NATIVE_ROUTE_PATH_PARAM_INVALID",`${t}/pathParams/${a}`)}),X(d)!==X(xs(i))&&m("NATIVE_ROUTE_PATH_PARAMS_MISMATCH",`${t}/pathParams`),vi(n,t,o),n.requiresAuthentication!==!0&&m("NATIVE_ROUTE_AUTHENTICATION_REQUIRED",`${t}/requiresAuthentication`),n}function xs(e){return B([...e.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(t=>t[1]))}function As(e,t,o,n){return{routeCode:e,path:t,surface:o,pathParams:xs(t),...n?.capability?{capability:n.capability}:{},...n?.access?{access:n.access}:{},requiresAuthentication:!0}}function Es(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 Al(e){let t=e.appCode,o=[],n=(_,E,A,O,b,g,I)=>{o.push({code:_,kind:E,...b?{workflowCode:b}:{},...I?{resourceCode:I}:{},desktop:As(Es(E,"desktop",b,I),A,"user",g),mobile:As(Es(E,"mobile",b,I),O,"user",g)})};e.frontend.user.applicationTodoCenter===!0&&n("application:todo-center","application-todo-center","/todos","/m/todos");let i=js(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 _ of i){if(!["standalone","hidden-handoff"].includes(_.launch.mode))continue;let E=B([_.launch.submission?.create?.requiredCapability,_.launch.submission?.existing?.requiredCapability].filter(A=>!!A));n(`workflow:${_.code}:launch`,"workflow-launch","/workflows/:workflowCode/start","/m/workflows/:workflowCode/start",_.code,E.length===1?{capability:E[0]}:E.length>1?{access:{anyOf:E}}:void 0)}let r=o.sort((_,E)=>Ee(String(_.code),String(E.code))),d=Xn(e),s=_=>{let E=_==="mobile"?"/m/":"/",A=d.filter(b=>b.surface==="user"&&!/[:*?#\\\\]/.test(b.path)&&b.path===E).sort((b,g)=>Ee(b.code,g.code))[0];if(A)return{code:A.code,path:A.path};let O=d.filter(b=>b.surface==="user"&&!/[:*?#\\\\]/.test(b.path)&&(_==="mobile"?b.path.startsWith("/m/"):!b.path.startsWith("/m/"))).sort((b,g)=>Ee(b.code,g.code))[0];return O?{code:O.code,path:O.path}:{code:_==="mobile"?"application-root-mobile":"application-root",path:E}},a=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"}},c=$i(e.frontend.devicePolicy,"/config/frontend/devicePolicy"),f=s("desktop"),u=s("mobile"),p={schemaVersion:ws,appCode:t,devicePolicy:c,rootEntry:{code:f.code,desktop:f.path,mobile:u.path},authentication:a,routes:r};return{...p,digest:Z(p)}}function Jn(e,t){if(e===void 0)return;let o=S(e,t,32);$c.has(o)||m("NATIVE_ADMIN_ICON_INVALID",t)}function Is(e,t){e!==void 0&&se(e,t,-1e4,1e4)}function vi(e,t,o){return e.capability!==void 0&&e.access!==void 0&&m("NATIVE_ROUTE_ACCESS_CONFLICT",`${t}/access`),e.capability!==void 0?{capability:pe(e.capability,`${t}/capability`,o)}:e.access===void 0?{}:{access:Zn(e.access,`${t}/access`,o)}}function Zn(e,t,o){let n=N(e,t);C(n,["allOf","anyOf"],t,!0);let i=n.allOf===void 0?void 0:B(V(n.allOf,`${t}/allOf`,50).map((d,s)=>pe(d,`${t}/allOf/${s}`,o))),r=n.anyOf===void 0?void 0:B(V(n.anyOf,`${t}/anyOf`,50).map((d,s)=>pe(d,`${t}/anyOf/${s}`,o)));return(i?.length||0)+(r?.length||0)===0&&m("NATIVE_ROUTE_ACCESS_EMPTY",t),{...i===void 0?{}:{allOf:i},...r===void 0?{}:{anyOf:r}}}function js(e){let t=new Map($s(e).map(i=>[String(i.code),i])),o=e.workflows.definitions.map((i,r)=>{let d=`/config/workflows/definitions/${r}`,s=N(i,d);C(s,["version","definition","launch"],d,["detailRouteCode"]);let a=N(s.definition,`${d}/definition`),c=s.detailRouteCode===void 0?void 0:Us(s.detailRouteCode,`${d}/detailRouteCode`);return{code:P(a.code,`${d}/definition/code`),title:S(a.title,`${d}/definition/title`,255),version:yt(s.version,`${d}/version`),launch:El(e,a,s.launch,`${d}/launch`,t),...c?{detailRouteCode:c}:{},definition:a}});return B(o.map(i=>i.code)).map(i=>{let r=o.filter(c=>c.code===i),d=e.workflows.activations.find(c=>c.workflowCode===i)?.definitionVersion,s=r.find(c=>c.version===d)||[...r].sort((c,f)=>f.version-c.version)[0],a=new Set;for(let c of r){let f=N(c.definition.nodes,"/config/workflows/definitions/nodes");for(let u of Object.values(f)){let p=N(u,"/config/workflows/definitions/nodes/*");if(p.kind==="approval")for(let _ of V(p.allowedOperations||[],"/config/workflows/definitions/nodes/*/allowedOperations",20))a.add(_)}}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:Cs(r.map(c=>c.version)),bindingVersions:Cs(e.workflows.bindings.map((c,f)=>{let u=`/config/workflows/bindings/${f}`,p=N(c,u),_=N(p.binding,`${u}/binding`);return{code:P(_.workflowCode,`${u}/binding/workflowCode`),version:yt(p.version,`${u}/version`)}}).filter(c=>c.code===i).map(c=>c.version)),providerCodes:B(e.workflows.providers.map((c,f)=>P(N(c,`/config/workflows/providers/${f}`).code,`/config/workflows/providers/${f}/code`))),allowedOperations:[...a].sort(Ee),editableParameterCodes:B(e.workflows.editableParameters.map((c,f)=>{let u=`/config/workflows/editableParameters/${f}`,p=N(c,u);return{code:P(p.code,`${u}/code`),workflowCode:P(p.workflowCode,`${u}/workflowCode`)}}).filter(c=>c.workflowCode===i).map(c=>c.code))}})}function Ws(e,t){let o=N(e,t);C(o,["mode"],t,["submission"]);let n=S(o.mode,`${t}/mode`,32);return["standalone","custom-page","hidden-handoff","work-center-only"].includes(n)||m("NATIVE_WORKFLOW_LAUNCH_MODE_INVALID",`${t}/mode`),{mode:n,...o.submission===void 0?{}:{submission:N(o.submission,`${t}/submission`)}}}function El(e,t,o,n,i){let r=Ws(o,n);if(!r.submission)return{mode:r.mode};["standalone","hidden-handoff"].includes(r.mode)||m("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${n}/submission`);let d=N(r.submission,`${n}/submission`);C(d,["kind"],`${n}/submission`,["create","existing","context"]),F(d.kind,"named-operation",`${n}/submission/kind`);let s=n.endsWith("/launch")?n.slice(0,-7):n,a=N(t.subject,`${s}/definition/subject`),c=H(a.resourceCode,`${s}/definition/subject/resourceCode`),f=e.data.resources.findIndex(y=>y.code===c),u=e.data.resources[f];(f<0||!u)&&m("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${s}/definition/subject/resourceCode`);let p=new Set(N(u.schema,`/config/data/resources/${f}/schema`).fields.map(y=>String(y.code))),_=new Map(e.backend.operations.map(y=>[String(y.code),y])),E=(y,R)=>{let h=`${n}/submission/${R}`,$=N(y,h);C($,["operationCode","inputs","output"],h);let w=P($.operationCode,`${h}/operationCode`),j=_.get(w),L=i.get(w),Q=L?.platformAccess?.workflow?.codes;(!j||!L||L.method!=="POST"||!Array.isArray(Q)||!Q.includes(t.code))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INVALID",h);let ee=N(j.requestSchema,`${h}/operation/requestSchema`),Y=N(ee.properties,`${h}/operation/requestSchema/properties`),_e=new Set(ee.required===void 0?[]:V(ee.required,`${h}/operation/requestSchema/required`,205)),ie=N($.inputs,`${h}/inputs`),v=Object.entries(ie);(!v.length||v.length>205)&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${h}/inputs`);let U=new Set,x=new Map,q={},z=L.platformAccess?.ownedSubject;z&&(R!=="create"||z.resourceCode!==c)&&m("NATIVE_WORKFLOW_OWNED_SUBJECT_LAUNCH_MISMATCH",h);for(let[J,tt]of v){(!us.test(J)||!Object.prototype.hasOwnProperty.call(Y,J))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${h}/inputs/${J}`);let Ue=`${h}/inputs/${J}`,io=N(tt,Ue),Me=S(io.source,`${Ue}/source`,32);if(["field","idempotency-key","current-user-reference","subject-id","subject-revision","requested-at"].includes(Me)||m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",Ue),C(io,["source"],Ue,Me==="field"?["fieldCode"]:!1),x.set(Me,(x.get(Me)||0)+1),Me==="field"){let nt=G(io.fieldCode,`${Ue}/fieldCode`);(U.has(nt)||!p.has(nt))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${Ue}/fieldCode`),U.add(nt),u.schema.fields.find(ro=>ro.code===nt)?.type==="subtable"&&(!z||!z.subtables.some(ro=>ro.fieldCode===nt))&&m("NATIVE_WORKFLOW_OWNED_SUBJECT_LAUNCH_REQUIRED",Ue),q[J]={source:Me,fieldCode:nt}}else q[J]={source:Me}}([..._e].some(J=>!(J in ie))||(x.get("idempotency-key")||0)!==1||!v.some(([J,tt])=>N(tt,`${h}/inputs/${J}`).source==="idempotency-key"&&_e.has(J))||R==="create"&&((x.get("subject-id")||0)>0||(x.get("subject-revision")||0)>0)||R==="existing"&&((x.get("subject-id")||0)!==1||(x.get("subject-revision")||0)!==1))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${h}/inputs`);let ge=N($.output,`${h}/output`);C(ge,["subjectId"],`${h}/output`,["subjectRevision","processCommand"]);let Te=N(N(j.responseSchema,`${h}/operation/responseSchema`).properties,`${h}/operation/responseSchema/properties`);for(let J of["subjectId","subjectRevision","processCommand"]){if(ge[J]===void 0)continue;let tt=S(ge[J],`${h}/output/${J}`,128);(!us.test(tt)||!Object.prototype.hasOwnProperty.call(Te,tt))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_OUTPUT_INVALID",`${h}/output/${J}`)}return{operationCode:w,method:"POST",path:L.path,requiredCapability:L.requiredCapability,requestSchemaDigest:L.requestSchemaDigest,responseSchemaDigest:L.responseSchemaDigest,inputs:q,output:{...ge},fieldCodes:U}},A=d.create===void 0?void 0:E(d.create,"create"),O=d.existing===void 0?void 0:E(d.existing,"existing");!A&&!O&&m("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${n}/submission`);let b=new Set([...A?.fieldCodes||[],...O?.fieldCodes||[]]),g=d.context===void 0?[]:D(d.context,`${n}/submission/context`,16),I=new Set,T=g.map((y,R)=>{let h=`${n}/submission/context/${R}`,$=N(y,h);C($,["queryParameter","fieldCode"],h);let w=S($.queryParameter,`${h}/queryParameter`,64),j=G($.fieldCode,`${h}/fieldCode`);return(!/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(w)||I.has(w)||!b.has(j))&&m("NATIVE_WORKFLOW_LAUNCH_CONTEXT_INVALID",h),I.add(w),{queryParameter:w,fieldCode:j}}),l=y=>{let{fieldCodes:R,...h}=y;return h};return{mode:r.mode,submission:{kind:"named-operation",...A?{create:l(A)}:{},...O?{existing:l(O)}:{},context:T}}}function Us(e,t){let o=N(e,t);C(o,["desktop","mobile"],t);let n=P(o.desktop,`${t}/desktop`),i=P(o.mobile,`${t}/mobile`);return n===i&&m("NATIVE_WORKFLOW_DETAIL_ROUTE_DUPLICATE",t),{desktop:n,mobile:i}}function Il(e,t){let o=new Set(t.map(f=>f.code)),n=new Map;e.data.resources.forEach((f,u)=>{let p=`/config/data/resources/${u}`,_=N(f,p);if(_.recordDeletion!==void 0){let O=`${p}/recordDeletion/delete`;for(let b of _.recordDeletion.delete)pe(b,O,e.appCode),o.has(b)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",O)}if(_.recordComments!==void 0)for(let O of["read","create"]){let b=`${p}/recordComments/${O}`;for(let g of _.recordComments[O])pe(g,b,e.appCode),o.has(g)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",b)}if(_.recordPrint!==void 0){let O=`${p}/recordPrint/read`;for(let b of _.recordPrint.read)pe(b,O,e.appCode),o.has(b)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",O)}if(_.workflowHistory!==void 0){let O=`${p}/workflowHistory/read`;for(let b of _.workflowHistory.read)pe(b,O,e.appCode),o.has(b)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",O)}for(let[O,b]of Object.entries(_.fieldPolicies||{})){if(!rt(O))continue;let g=`${p}/fieldPolicies/${O}/read`,I=N(b,`${p}/fieldPolicies/${O}`);for(let T of V(I.read||[],g,2e3))o.has(T)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",g)}let E=_.surface===void 0?{}:N(_.surface,`${p}/surface`);if(["native","queued-command"].includes(E.mutationOwner||"native"))return;let A=N(_.capabilities,`${p}/capabilities`);for(let O of["create","update","delete"])O==="delete"&&Array.isArray(_.recordDeletion?.delete)&&_.recordDeletion.delete.length>0||n.set(String(A[O]),O)});let i=new Set;for(let[f,u]of e.authz.roles.entries()){let p=`/config/authz/roles/${f}`,_=N(u,p);C(_,["code","name","description","capabilities"],p,!0);let E=P(_.code,`${p}/code`);i.has(E)&&m("NATIVE_ROLE_DUPLICATE",`${p}/code`),i.add(E),S(_.name,`${p}/name`,255);let A=V(_.capabilities,`${p}/capabilities`,2e3);for(let[O,b]of A.entries())n.has(b)&&m("NATIVE_DATA_SURFACE_MUTATION_GRANT_FORBIDDEN",`${p}/capabilities/${O}`,{operation:n.get(b)}),o.has(b)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",`${p}/capabilities`)}let r=e.authz.authenticatedUserRoleCode===void 0?"":P(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode");r&&!i.has(r)&&m("NATIVE_AUTHENTICATED_USER_ROLE_REFERENCE_MISSING","/config/authz/authenticatedUserRoleCode");let d=new Set,s=0;for(let[f,u]of e.perspectives.entries()){let p=`/config/perspectives/${f}`,_=N(u,p);C(_,["code","name","description","roleCodes","capabilityCodes","default"],p,!0);let E=P(_.code,`${p}/code`);d.has(E)&&m("NATIVE_PERSPECTIVE_DUPLICATE",`${p}/code`),d.add(E),S(_.name,`${p}/name`,255);let A=V(_.roleCodes,`${p}/roleCodes`,20);A.length<1&&m("NATIVE_PERSPECTIVE_ROLE_REQUIRED",`${p}/roleCodes`),A.forEach((g,I)=>{i.has(g)||m("NATIVE_PERSPECTIVE_ROLE_MISSING",`${p}/roleCodes/${I}`)});let O=B(e.authz.roles.filter(g=>A.includes(g.code)).flatMap(g=>g.capabilities)),b=V(_.capabilityCodes,`${p}/capabilityCodes`,2e3);X(O)!==X(b)&&m("NATIVE_PERSPECTIVE_CAPABILITY_PROJECTION_MISMATCH",`${p}/capabilityCodes`),_.default===!0?s+=1:_.default!==void 0&&m("NATIVE_PERSPECTIVE_DEFAULT_INVALID",`${p}/default`)}s>1&&m("NATIVE_PERSPECTIVE_DEFAULT_DUPLICATE","/config/perspectives");for(let[f,u]of e.backend.operations.entries()){let p=N(u,`/config/backend/operations/${f}`);o.has(p.capability)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/backend/operations/${f}/capability`)}let a=new Set,c=new Set;for(let[f,u]of e.frontend.routes.entries()){let p=`/config/frontend/routes/${f}`,_=N(u,p),E=P(_.code,`${p}/code`);a.has(E)&&m("NATIVE_ROUTE_DUPLICATE",`${p}/code`),a.add(E);let A=Ne(_.path,`${p}/path`);c.has(A)&&m("NATIVE_ROUTE_PATH_DUPLICATE",`${p}/path`),c.add(A);let O=vi(_,p,e.appCode);O.capability&&!o.has(O.capability)&&m("NATIVE_CAPABILITY_REFERENCE_MISSING",`${p}/capability`);let b=_.access===void 0?void 0:N(_.access,`${p}/access`);for(let g of["allOf","anyOf"]){let I=b?.[g]===void 0?[]:D(b[g],`${p}/access/${g}`,50);for(let[T,l]of I.entries()){let y=pe(l,`${p}/access/${g}/${T}`,e.appCode);o.has(y)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",`${p}/access/${g}/${T}`)}}}if(e.frontend.admin.access!==void 0){let f=Zn(e.frontend.admin.access,"/config/frontend/admin/access",e.appCode);for(let u of["allOf","anyOf"])for(let[p,_]of(f[u]||[]).entries())o.has(_)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/frontend/admin/access/${u}/${p}`)}for(let[f,u]of e.frontend.routes.entries()){let p=N(u,`/config/frontend/routes/${f}`);p.parentCode&&!a.has(p.parentCode)&&m("NATIVE_ROUTE_PARENT_MISSING",`/config/frontend/routes/${f}/parentCode`)}}function yl(e){let t=new Set(e.authz.roles.map(c=>String(c.code))),o=e.authz.authenticatedUserRoleCode===void 0?"":P(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode"),n=new Map(e.authz.scopeDimensions.map(c=>[String(c.code),{valueType:c.valueType==="uuid"?"uuid":"string",...c.valueSource?.resourceCode?{valueSourceResourceCode:String(c.valueSource.resourceCode)}:{}}])),i=new Set(n.keys()),r=new Map(e.data.resources.map((c,f)=>{let u=Qe(c,`/config/data/resources/${f}`,e.appCode);return[u.code,new Map(u.schema.fields.map(p=>[String(p.code),p]))]}));for(let[c,f]of e.authz.scopeDimensions.entries()){let u=`/config/authz/scopeDimensions/${c}`,p=N(f,u);if(C(p,["code","name","resourceCode","valueType","hierarchyMode","valueSource"],u,!0),p.valueSource===void 0)continue;let _=N(p.valueSource,`${u}/valueSource`);C(_,["kind","resourceCode","labelField","enabledField"],`${u}/valueSource`,!0),_.kind!=="native_resource"&&m("NATIVE_SCOPE_VALUE_SOURCE_KIND_INVALID",`${u}/valueSource/kind`),p.valueType!=="uuid"&&m("NATIVE_SCOPE_VALUE_SOURCE_TYPE_INVALID",`${u}/valueType`);let E=H(_.resourceCode,`${u}/valueSource/resourceCode`),A=r.get(E);A||m("NATIVE_SCOPE_VALUE_SOURCE_RESOURCE_MISSING",`${u}/valueSource/resourceCode`);let O=G(_.labelField,`${u}/valueSource/labelField`);if(["text.short","text.long"].includes(String(A.get(O)?.type||""))||m("NATIVE_SCOPE_VALUE_SOURCE_LABEL_FIELD_INVALID",`${u}/valueSource/labelField`),_.enabledField!==void 0){let b=G(_.enabledField,`${u}/valueSource/enabledField`);A.get(b)?.type!=="boolean"&&m("NATIVE_SCOPE_VALUE_SOURCE_ENABLED_FIELD_INVALID",`${u}/valueSource/enabledField`)}}let d=new Set,s=new Set;for(let[c,f]of e.authz.scopeSources.entries()){let u=`/config/authz/scopeSources/${c}`,p=N(f,u);C(p,["code","name","resourceCode","subject","grants","operationField","enabledField","effectiveFromField","effectiveToField","failureMode"],u,!0);let _=P(p.code,`${u}/code`);d.has(_)&&m("NATIVE_SCOPE_SOURCE_DUPLICATE",`${u}/code`),d.add(_),S(p.name,`${u}/name`,255);let E=H(p.resourceCode,`${u}/resourceCode`),A=r.get(E);A||m("NATIVE_SCOPE_SOURCE_RESOURCE_MISSING",`${u}/resourceCode`);let O=N(p.subject,`${u}/subject`),b=S(O.type,`${u}/subject/type`,32);C(O,b==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${u}/subject`),["user","role_membership"].includes(b)||m("NATIVE_SCOPE_SOURCE_SUBJECT_INVALID",`${u}/subject/type`);let g=lt(O.userIdField,A);Rn(g)||m("NATIVE_SCOPE_SOURCE_SUBJECT_PATH_INVALID",`${u}/subject/userIdField`),b==="role_membership"&&!t.has(String(O.roleCode))&&m("NATIVE_ROLE_REFERENCE_MISSING",`${u}/subject/roleCode`);let I=new Set;for(let[T,l]of D(p.grants,`${u}/grants`,100).entries()){let y=`${u}/grants/${T}`,R=N(l,y);C(R,["dimensionCode","valueField","parentValueField"],y,!0);let h=P(R.dimensionCode,`${y}/dimensionCode`);(!i.has(h)||I.has(h))&&m("NATIVE_SCOPE_SOURCE_DIMENSION_INVALID",`${y}/dimensionCode`),I.add(h),p.failureMode==="last_known_good"&&s.add(h);for(let $ of["valueField","parentValueField"]){if(R[$]===void 0)continue;let w=lt(R[$],A);Lo(w,n.get(h),r)||m("NATIVE_SCOPE_SOURCE_GRANT_PATH_INVALID",`${y}/${$}`)}}I.size===0&&m("NATIVE_SCOPE_SOURCE_GRANT_REQUIRED",`${u}/grants`),["strict","last_known_good"].includes(p.failureMode)||m("NATIVE_SCOPE_SOURCE_FAILURE_MODE_INVALID",`${u}/failureMode`);for(let T of["operationField","enabledField","effectiveFromField","effectiveToField"]){if(p[T]===void 0)continue;let l=G(p[T],`${u}/${T}`);A.has(l)||m("NATIVE_SCOPE_SOURCE_FIELD_MISSING",`${u}/${T}`)}}Ol(e,t,r,o);let a=new Set;for(let[c,f]of e.authz.dataPolicies.entries()){let u=`/config/authz/dataPolicies/${c}`,p=N(f,u);C(p,["code","name","resourceCode","unrestrictedRoleCodes","publicRead","operations","matchMode","rules","readExpression","writeBoundary"],u,!0);let _=P(p.code,`${u}/code`);a.has(_)&&m("NATIVE_DATA_POLICY_DUPLICATE",`${u}/code`),a.add(_);let E=p.readExpression!==void 0,A=V(p.operations||[],`${u}/operations`,4);p.operations!==void 0&&(A.length===0||A.some(l=>!["read","create","update","delete"].includes(l)))&&m("NATIVE_DATA_POLICY_OPERATIONS_INVALID",`${u}/operations`),["AND","OR"].includes(p.matchMode)||m("NATIVE_DATA_POLICY_MATCH_MODE_INVALID",`${u}/matchMode`),E&&p.operations!==void 0&&m("NATIVE_DATA_POLICY_READ_EXPRESSION_OPERATIONS_FORBIDDEN",`${u}/operations`);let O=e.data.resources.find(l=>l.dataPolicyCode===_),b=p.resourceCode||O?.code,g=b?r.get(H(b,`${u}/resourceCode`)):void 0;if(E&&!g&&m("NATIVE_DATA_POLICY_RESOURCE_MISSING",`${u}/resourceCode`),p.publicRead!==void 0){try{let l=e.authz.roles.find(y=>y.code===o);jo({policy:p,resource:e.data.resources.find(y=>y.code===b),baselineRoleCode:o,baselineCapabilities:l?.capabilities||[],baselineDeniedCapabilities:l?.deniedCapabilities||[],pointer:u})}catch(l){if(!(l instanceof ut))throw l;m(l.code,l.pointer)}(p.unrestrictedRoleCodes||[]).includes(o)||m("AUTHENTICATED_PUBLIC_READ_CANONICAL_BASELINE_MISSING",`${u}/unrestrictedRoleCodes`)}else o&&(p.unrestrictedRoleCodes||[]).includes(o)&&m("NATIVE_DATA_POLICY_BASELINE_UNRESTRICTED",`${u}/unrestrictedRoleCodes`);let I=V(p.unrestrictedRoleCodes||[],`${u}/unrestrictedRoleCodes`,100);p.unrestrictedRoleCodes!==void 0&&I.length===0&&m("NATIVE_DATA_POLICY_UNRESTRICTED_ROLES_INVALID",`${u}/unrestrictedRoleCodes`);for(let l of I)t.has(l)||m("NATIVE_ROLE_REFERENCE_MISSING",`${u}/unrestrictedRoleCodes`);let T;try{let l=D(p.rules,`${u}/rules`,100).map((y,R)=>({rule:N(y,`${u}/rules/${R}`),pointer:`${u}/rules/${R}`}));l.length===0?(!E||p.matchMode!=="AND"||p.writeBoundary!=="capability_only")&&m("NATIVE_DATA_POLICY_WRITE_BOUNDARY_REQUIRED",u):p.writeBoundary!==void 0&&m("NATIVE_DATA_POLICY_WRITE_BOUNDARY_INVALID",`${u}/writeBoundary`),T=[...l],E&&(T.push(...zt(p.readExpression,`${u}/readExpression`)),Ri(p.readExpression,`${u}/readExpression`))}catch(l){throw l instanceof Et&&m(l.code,l.pointer),l}for(let{rule:l,pointer:y}of T){C(l,["subject","dimensionCode","relationCode","resourceCode","field","roleCodes","operation","valuePath","emptyMatchesAll","operator","value","operand"],y,!0);let R=G(l.field,`${y}/field`),h=g?.get(R);E&&!h&&m("NATIVE_DATA_POLICY_FIELD_MISSING",`${y}/field`);for(let Y of V(l.roleCodes||[],`${y}/roleCodes`,100))t.has(Y)||m("NATIVE_ROLE_REFERENCE_MISSING",`${y}/roleCodes`);let $=String(l.operator||""),w=l.operand==="db_now",j=["is_null","is_not_null"].includes($),L=["eq","not_eq","in","not_in"].includes($),Q=!w&&(l.operator!==void 0||l.value!==void 0);if([l.subject==="current_user"?"current_user":"",typeof l.dimensionCode=="string"?"dimension":"",typeof l.relationCode=="string"?"relationship":"",Q?"constant":"",w?"db_now":""].filter(Boolean).length!==1&&m("NATIVE_DATA_POLICY_RULE_SOURCE_INVALID",y),l.subject!==void 0&&l.subject!=="current_user"&&m("NATIVE_DATA_POLICY_SUBJECT_INVALID",`${y}/subject`),Q){if(!L&&!j&&m("NATIVE_DATA_POLICY_OPERATOR_INVALID",`${y}/operator`),["in","not_in"].includes($)){let Y=D(l.value,`${y}/value`,100).map((_e,ie)=>S(_e,`${y}/value/${ie}`,2048));(Y.length===0||new Set(Y).size!==Y.length)&&m("NATIVE_DATA_POLICY_VALUE_INVALID",`${y}/value`)}else["eq","not_eq"].includes($)?S(l.value,`${y}/value`,2048):(l.value!==void 0||l.operand!==void 0)&&m("NATIVE_DATA_POLICY_VALUE_INVALID",`${y}/value`);for(let Y of["operation","valuePath","emptyMatchesAll","resourceCode","operand"])l[Y]!==void 0&&m("NATIVE_DATA_POLICY_CONSTANT_RULE_INVALID",`${y}/${Y}`)}if(w){(!["lt","lte","gt","gte"].includes($)||l.value!==void 0||h?.type!=="datetime")&&m("NATIVE_DATA_POLICY_DB_NOW_INVALID",y);for(let Y of["operation","valuePath","emptyMatchesAll","resourceCode","value"])l[Y]!==void 0&&m("NATIVE_DATA_POLICY_DB_NOW_INVALID",`${y}/${Y}`)}l.dimensionCode&&!i.has(l.dimensionCode)&&m("NATIVE_SCOPE_DIMENSION_MISSING",`${y}/dimensionCode`),s.has(String(l.dimensionCode||""))&&l.operation!=="read"&&m("NATIVE_SCOPE_SOURCE_LAST_KNOWN_GOOD_UNSAFE",`${y}/operation`)}}for(let[c,f]of e.data.resources.entries()){let u=N(f,`/config/data/resources/${c}`);u.dataPolicyCode&&!a.has(u.dataPolicyCode)&&m("NATIVE_DATA_POLICY_REFERENCE_MISSING",`/config/data/resources/${c}/dataPolicyCode`)}}function bl(e){try{Ao(e.data.resources,"/config/data/resources"),e.data.resources.forEach((t,o)=>lo(t.schema.fields,new Set(e.authz.roles.map(n=>n.code)),new Set(e.authz.scopeDimensions.map(n=>n.code)),`/config/data/resources/${o}/schema/fields`))}catch(t){throw(t instanceof ye||t instanceof Ve)&&m(t.code,t.pointer),t}}function Ol(e,t,o,n){let i=new Set;for(let[r,d]of e.authz.roleMembershipSources.entries()){let s=`/config/authz/roleMembershipSources/${r}`,a=N(d,s);C(a,["code","name","resourceCode","userIdField","roleCode","enabledField","effectiveFromField","effectiveToField","failureMode"],s,!0);let c=P(a.code,`${s}/code`);c.length>100&&m("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${s}/code`),i.has(c)&&m("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${s}/code`),i.add(c),S(a.name,`${s}/name`,255);let f=ys(a.resourceCode,`${s}/resourceCode`,o);bs(a.userIdField,`${s}/userIdField`,f),t.has(String(a.roleCode||""))||m("NATIVE_ROLE_REFERENCE_MISSING",`${s}/roleCode`),n&&a.roleCode===n&&m("NATIVE_AUTHENTICATED_USER_ROLE_SOURCE_CONFLICT",`${s}/roleCode`),Os(a,s,f)}for(let[r,d]of e.authz.relationshipGrantSources.entries()){let s=`/config/authz/relationshipGrantSources/${r}`,a=N(d,s);C(a,["code","name","resourceCode","subject","relationCode","targetResourceCode","resourceIdField","operations","enabledField","effectiveFromField","effectiveToField","failureMode"],s,!0);let c=P(a.code,`${s}/code`);c.length>100&&m("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${s}/code`),i.has(c)&&m("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${s}/code`),i.add(c),S(a.name,`${s}/name`,255);let f=ys(a.resourceCode,`${s}/resourceCode`,o),u=N(a.subject,`${s}/subject`),p=S(u.type,`${s}/subject/type`,32);C(u,p==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${s}/subject`),["user","role_membership"].includes(p)||m("NATIVE_AUTHORIZATION_PROJECTION_SUBJECT_INVALID",`${s}/subject/type`),bs(u.userIdField,`${s}/subject/userIdField`,f),p==="role_membership"&&!t.has(String(u.roleCode||""))&&m("NATIVE_ROLE_REFERENCE_MISSING",`${s}/subject/roleCode`),P(a.relationCode,`${s}/relationCode`);let _=H(a.targetResourceCode,`${s}/targetResourceCode`);o.has(_)||m("NATIVE_AUTHORIZATION_PROJECTION_TARGET_RESOURCE_MISSING",`${s}/targetResourceCode`);let E=lt(a.resourceIdField,f),A=E?.field.type==="resource-ref.single"&&E.valuePath==="value"&&E.field.source?.resourceCode===_;(a.resourceIdField==="id"?_!==String(a.resourceCode):!A)&&m("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_ID_FIELD_INVALID",`${s}/resourceIdField`);let O=V(a.operations,`${s}/operations`,20);(O.length===0||O.some(b=>b.length>64||!/^[A-Za-z0-9][A-Za-z0-9:._*-]{0,63}$/.test(b)))&&m("NATIVE_AUTHORIZATION_PROJECTION_OPERATIONS_INVALID",`${s}/operations`),Os(a,s,f)}}function ys(e,t,o){let n=H(e,t),i=o.get(n);return i||m("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_MISSING",t),i}function bs(e,t,o){let n=lt(e,o);Rn(n)||m("NATIVE_AUTHORIZATION_PROJECTION_USER_FIELD_INVALID",t)}function Os(e,t,o){if(e.failureMode!=="strict"&&m("NATIVE_AUTHORIZATION_PROJECTION_FAILURE_MODE_INVALID",`${t}/failureMode`),e.enabledField!==void 0){let n=G(e.enabledField,`${t}/enabledField`);o.get(n)?.type!=="boolean"&&m("NATIVE_AUTHORIZATION_PROJECTION_ENABLED_FIELD_INVALID",`${t}/enabledField`)}for(let n of["effectiveFromField","effectiveToField"]){if(e[n]===void 0)continue;let i=G(e[n],`${t}/${n}`);["date","datetime"].includes(String(o.get(i)?.type))||m("NATIVE_AUTHORIZATION_PROJECTION_EFFECTIVE_FIELD_INVALID",`${t}/${n}`)}}function Nl(e){let t=new Set,o=new Set;e.forEach((n,i)=>{let r=`/config/backend/secrets/${i}`,d=N(n,r);C(d,["name","env","description","required","exposure"],r,!0);let s=S(d.name,`${r}/name`,128),a=S(d.env,`${r}/env`,128);Tc.test(s)||m("NATIVE_SECRET_NAME_INVALID",`${r}/name`),(!Rc.test(a)||a.startsWith("OPENXIANGDA_")||["NODE_ENV","PORT"].includes(a))&&m("NATIVE_SECRET_ENV_INVALID",`${r}/env`),t.has(s)&&m("NATIVE_SECRET_NAME_DUPLICATE",`${r}/name`),o.has(a)&&m("NATIVE_SECRET_ENV_DUPLICATE",`${r}/env`),t.add(s),o.add(a),F(d.exposure,"active_only",`${r}/exposure`),d.required!==void 0&&bt(d.required,`${r}/required`),d.description!==void 0&&Pi(d.description,`${r}/description`,2e3)})}function Tl(e){let t=new Set,o=new Map,n=new Map(e.data.resources.map(_=>[String(_.code),_])),i=new Map(e.frontend.routes.map((_,E)=>{let A=N(_,`/config/frontend/routes/${E}`);return[P(A.code,`/config/frontend/routes/${E}/code`),A]}));for(let[_,E]of e.workflows.definitions.entries()){let A=`/config/workflows/definitions/${_}`,O=N(E,A);if(C(O,["version","definition","launch"],A,["detailRouteCode"]),Ws(O.launch,`${A}/launch`),O.detailRouteCode!==void 0){let w=Us(O.detailRouteCode,`${A}/detailRouteCode`);for(let[j,L,Q]of[["desktop",w.desktop,["admin","user"]],["mobile",w.mobile,["user"]]]){let ee=`${A}/detailRouteCode/${j}`,Y=i.get(L);Y||m("NATIVE_WORKFLOW_DETAIL_ROUTE_MISSING",ee),Q.some(v=>v===Y.surface)||m("NATIVE_WORKFLOW_DETAIL_ROUTE_SURFACE_INVALID",ee);let _e=Ne(Y.path,ee),ie=[..._e.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(v=>v[1]);(_e.includes("*")||ie.length!==1||ie[0]!=="instanceId")&&m("NATIVE_WORKFLOW_DETAIL_ROUTE_PATH_INVALID",ee)}}let b=N(O.definition,`${A}/definition`),g=`${b.code}:${yt(O.version,`${A}/version`)}`;t.has(g)&&m("NATIVE_WORKFLOW_DEFINITION_DUPLICATE",A),t.add(g),Cl(b,`${A}/definition`);let I=xn(b);I.length&&m(I[0],`${A}/definition/launchPreflight`);let T=fi(b);T.length&&m(T[0],`${A}/definition/approvedDelegation`);let l=li(b,e.backend.operations);l.length&&m(l[0],`${A}/definition/commandHandlers`),Rl(b.subject,n,`${A}/definition/subject`);let y=b.commandHandlers?.resubmit?.derivedSubjectFields||[],R=n.get(b.subject.resourceCode);for(let w of y){let j=R?.schema.fields.find(L=>L.code===w);(!j||j.system===!0||R?.surface?.fields?.[w]?.system===!0)&&m("WORKFLOW_CORRECTION_DERIVED_SUBJECT_FIELDS_INVALID",`${A}/definition/commandHandlers/resubmit/derivedSubjectFields`)}let h=Ut(b,new Map((n.get(b.subject.resourceCode)?.schema.fields||[]).map(w=>[w.code,{...n.get(b.subject.resourceCode)?.surface?.fields?.[w.code],...w,system:["id","revision","createdAt","updatedAt","createdBy","updatedBy"].includes(w.code)}])),new Map([...n].map(([w,j])=>[w,new Map(j.schema.fields.map(L=>[L.code,{...j.surface?.fields?.[L.code],...L,system:["id","revision","createdAt","updatedAt","createdBy","updatedBy"].includes(L.code)}]))])),Tt(n.get(b.subject.resourceCode)?.schema||{}));h.length&&m(h[0],`${A}/definition/taskPages`);let $=qo(b,{appCode:e.appCode,capabilities:e.authz.capabilities.map(w=>w.code),fields:new Map((n.get(b.subject.resourceCode)?.schema.fields||[]).map(w=>[w.code,w]))});$.length&&m("NATIVE_WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID",`${A}/definition/instanceCommands`,{errors:$}),b.title===b.code&&m("NATIVE_WORKFLOW_USER_TITLE_REQUIRED",`${A}/definition/title`),o.set(g,b)}let r=new Set,d=new Map;for(let[_,E]of e.workflows.bindings.entries()){let A=N(E,`/config/workflows/bindings/${_}`),O=N(A.binding,`/config/workflows/bindings/${_}/binding`),b=`${O.workflowCode}:${yt(A.version,`/config/workflows/bindings/${_}/version`)}`;r.has(b)&&m("NATIVE_WORKFLOW_BINDING_DUPLICATE",`/config/workflows/bindings/${_}`),r.add(b),hl(O,`/config/workflows/bindings/${_}/binding`),d.set(b,O)}let s=new Set,a=new Map;for(let[_,E]of e.workflows.activations.entries()){let A=`/config/workflows/activations/${_}`,O=N(E,A);C(O,["workflowCode","definitionVersion","bindingVersion","acceptedCommandDeactivationPolicy"],A,["environmentKey"]);let b=P(O.workflowCode,`${A}/workflowCode`);s.has(b)&&m("NATIVE_WORKFLOW_ACTIVATION_DUPLICATE",A),s.add(b);let g=`${b}:${yt(O.definitionVersion,`${A}/definitionVersion`)}`,I=`${b}:${yt(O.bindingVersion,`${A}/bindingVersion`)}`;t.has(g)||m("NATIVE_WORKFLOW_DEFINITION_REFERENCE_MISSING",`${A}/definitionVersion`),r.has(I)||m("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${A}/bindingVersion`);let T=o.get(g),l=d.get(I),y=xn(T,l);y.length&&m(y[0],A);let R=Ln(T,l);R.length&&m(R[0],A),(!["finish-pinned","cancel-on-deactivate"].includes(O.acceptedCommandDeactivationPolicy)||O.acceptedCommandDeactivationPolicy!==T.acceptedCommandDeactivationPolicy)&&m("NATIVE_WORKFLOW_COMMAND_DEACTIVATION_POLICY_MISMATCH",`${A}/acceptedCommandDeactivationPolicy`),wl(T,l,`/config/workflows/activations/${_}`);try{let h=n.get(T.subject.resourceCode)?.schema.fields||[];uo(T,l,new Map(h.map($=>[$.code,$])),`${A}/bindings`,new Map([...n].map(([$,w])=>[$,new Map(w.schema.fields.map(j=>[j.code,j]))])))}catch(h){throw h instanceof Ve&&m(h.code,h.pointer),h}a.set(b,l)}let c=yi([...a.values()]);c.length&&m(c[0],"/config/workflows/activations");let f=new Set;e.workflows.providers.forEach((_,E)=>{let A=`/config/workflows/providers/${E}`,O=N(_,A);C(O,["code","endpointPath","timeoutMs"],A,!0);let b=P(O.code,`${A}/code`);f.has(b)&&m("NATIVE_WORKFLOW_PROVIDER_DUPLICATE",`${A}/code`),f.add(b),Ne(O.endpointPath,`${A}/endpointPath`),O.timeoutMs!==void 0&&se(O.timeoutMs,`${A}/timeoutMs`,100,1e4)});for(let[_,E]of a.entries())for(let[A,O]of Object.entries(N(E.bindings,"/config/workflows/bindings/*/binding/bindings"))){let b=N(O,`/config/workflows/${_}/bindings/${A}`);b.provider==="application_provider"&&!f.has(b.providerCode)&&m("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`/config/workflows/${_}/bindings/${A}/providerCode`)}let u=new Set(e.authz.roles.map(_=>_.code)),p=new Set;e.workflows.editableParameters.forEach((_,E)=>{let A=`/config/workflows/editableParameters/${E}`,O=N(_,A);C(O,["code","workflowCode","bindingKey","label","valueType","required","allowedRoleCodes","allowedProviderCodes","maxItems"],A,!0);let b=P(O.code,`${A}/code`);p.has(b)&&m("NATIVE_WORKFLOW_EDITABLE_PARAMETER_DUPLICATE",`${A}/code`),p.add(b);let g=Qn(O.workflowCode,`${A}/workflowCode`),I=Hn(O.bindingKey,`${A}/bindingKey`),T=a.get(g);(!T||!N(T.bindings,`${A}/bindingKey`)[I])&&m("NATIVE_WORKFLOW_EDITABLE_BINDING_MISSING",`${A}/bindingKey`),S(O.label,`${A}/label`,255),["role_code","user_ids","provider_code"].includes(O.valueType)||m("NATIVE_WORKFLOW_EDITABLE_VALUE_TYPE_INVALID",`${A}/valueType`);for(let l of V(O.allowedRoleCodes||[],`${A}/allowedRoleCodes`,100))u.has(l)||m("NATIVE_ROLE_REFERENCE_MISSING",`${A}/allowedRoleCodes`);for(let l of V(O.allowedProviderCodes||[],`${A}/allowedProviderCodes`,100))f.has(l)||m("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`${A}/allowedProviderCodes`);O.required!==void 0&&bt(O.required,`${A}/required`),O.maxItems!==void 0&&se(O.maxItems,`${A}/maxItems`,1,200)})}function Rl(e,t,o){let n=N(e,o);C(n,["resourceCode","factProjection"],o,["summaryFields"]);let i=H(n.resourceCode,`${o}/resourceCode`),r=t.get(i);r||m("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${o}/resourceCode`);let d=new Set(D(N(r.schema,`${o}/resourceCode`).fields,`${o}/resourceCode`,500).map((c,f)=>G(N(c,`${o}/resourceCode/${f}`).code,`${o}/resourceCode/${f}`))),s=N(n.factProjection,`${o}/factProjection`),a=Object.entries(s);(a.length<1||a.length>64)&&m("NATIVE_WORKFLOW_SUBJECT_FACT_PROJECTION_INVALID",`${o}/factProjection`);for(let[c,f]of a){wc.test(c)||m("NATIVE_WORKFLOW_SUBJECT_FACT_KEY_INVALID",`${o}/factProjection/${c}`);let u=G(f,`${o}/factProjection/${c}`);d.has(u)||m("NATIVE_WORKFLOW_SUBJECT_FIELD_MISSING",`${o}/factProjection/${c}`)}if(n.summaryFields!==void 0){let c=V(n.summaryFields,`${o}/summaryFields`,Sc).map((E,A)=>G(E,`${o}/summaryFields/${A}`)),f=t.get(i),u=f.surface&&typeof f.surface=="object"&&!Array.isArray(f.surface)?f.surface:{},p=u.fields&&typeof u.fields=="object"&&!Array.isArray(u.fields)?u.fields:{},_=new Map(D(N(f.schema,`${o}/resourceCode`).fields,`${o}/resourceCode`,500).map((E,A)=>{let O=N(E,`${o}/resourceCode/${A}`);return[String(O.code),O]}));for(let[E,A]of c.entries()){let O=_.get(A),b=p[A],g=String(O?.type||""),I=O?.maxLength;(!O||O.system===!0||b&&typeof b=="object"&&!Array.isArray(b)&&b.system===!0||["id","revision","created_by","updated_by","created_at","updated_at"].includes(A)||!kc.has(g)||g==="text.long"&&typeof I=="number"&&Number.isFinite(I)&&I>Dc)&&m("NATIVE_WORKFLOW_SUBJECT_SUMMARY_FIELDS_INVALID",`${o}/summaryFields/${E}`)}}}function Cl(e,t){C(e,["schemaVersion","code","title","subject","acceptedCommandDeactivationPolicy","startAt","inputSchema","nodes"],t,["organizationContext","instanceCommands","readability","taskPages","rejectionNotification","commandHandlers","launchPreflight","approvedDelegation"]),F(e.schemaVersion,"openxiangda.workflow-definition/v2",`${t}/schemaVersion`),Qn(e.code,`${t}/code`),S(e.title,`${t}/title`,255),["finish-pinned","cancel-on-deactivate"].includes(e.acceptedCommandDeactivationPolicy)||m("NATIVE_WORKFLOW_COMMAND_DEACTIVATION_POLICY_REQUIRED",`${t}/acceptedCommandDeactivationPolicy`);let o=N(e.nodes,`${t}/nodes`),n=Object.keys(o);(n.length===0||n.length>200)&&m("NATIVE_WORKFLOW_NODE_COUNT_INVALID",`${t}/nodes`);let i=S(e.startAt,`${t}/startAt`,128),r=ei(e);r.length&&m(r[0],`${t}/readability`);let d=Ln(e);d.length&&m(d[0],`${t}/nodes`);let s=Fn(e);s.length&&m(s[0],`${t}/nodes`);let a=_t(e);a.length&&m(a[0],`${t}/nodes`);let c=ai(e);c.length&&m(c[0],`${t}/nodes`);let f=ci(e);f.length&&m(f[0],`${t}/rejectionNotification`);let u=$n(e);u.length&&m(u[0],`${t}/nodes`);let p=Ut(e);p.length&&m(p[0],`${t}/taskPages`);let _=Pt(e);_.length&&m(_[0],`${t}/nodes`),o[i]||m("NATIVE_WORKFLOW_START_NODE_MISSING",`${t}/startAt`);let E=new Map;for(let[g,I]of Object.entries(o)){let T=`${t}/nodes/${g}`,l=N(I,T);F(l.id,g,`${T}/id`),["approval","condition","end","cc","action","correction"].includes(l.kind)||m("NATIVE_WORKFLOW_NODE_KIND_INVALID",`${T}/kind`);let y=[];if(l.kind==="approval"){S(l.title,`${T}/title`,255),Hn(l.binding,`${T}/binding`),["single","any","all","sequence"].includes(l.mode)||m("NATIVE_WORKFLOW_APPROVAL_MODE_INVALID",`${T}/mode`),y.push(S(l.onApprove,`${T}/onApprove`,128),S(l.onReject,`${T}/onReject`,128));for(let R of V(l.returnTargets||[],`${T}/returnTargets`,200))o[R]||m("NATIVE_WORKFLOW_TARGET_MISSING",`${T}/returnTargets`);for(let R of V(l.allowedOperations||[],`${T}/allowedOperations`,20))vc.has(R)||m("NATIVE_WORKFLOW_OPERATION_INVALID",`${T}/allowedOperations`)}else if(l.kind==="correction"){let R=pi(e);R.length&&m(R[0],T)}else if(l.kind==="action")y.push(S(l.next,`${T}/next`,128));else if(l.kind==="cc")S(l.title,`${T}/title`,255),Hn(l.binding,`${T}/binding`),y.push(S(l.next,`${T}/next`,128));else if(l.kind==="condition"){let R=D(l.branches,`${T}/branches`,100);R.length===0&&m("NATIVE_WORKFLOW_BRANCH_REQUIRED",`${T}/branches`),R.forEach((h,$)=>{let w=N(h,`${T}/branches/${$}`);Yt(w.when,`${T}/branches/${$}/when`,0),y.push(S(w.target,`${T}/branches/${$}/target`,128))}),y.push(S(l.otherwise,`${T}/otherwise`,128))}else S(l.title,`${T}/title`,255),S(l.outcome,`${T}/outcome`,128);for(let R of y)o[R]||m("NATIVE_WORKFLOW_TARGET_MISSING",T);E.set(g,y)}let A=new Set,O=new Set,b=g=>{if(O.has(g)&&m("NATIVE_WORKFLOW_CYCLE_FORBIDDEN",`${t}/nodes/${g}`),!A.has(g)){A.add(g),O.add(g);for(let I of E.get(g)||[])b(I);O.delete(g)}};b(i);for(let g of[...A]){let I=o[g];if(I?.kind==="approval")for(let T of I.returnTargets||[])o[T]?.kind==="correction"&&A.add(T)}A.size!==n.length&&m("NATIVE_WORKFLOW_NODE_UNREACHABLE",`${t}/nodes`)}function Yt(e,t,o){o>20&&m("NATIVE_WORKFLOW_EXPRESSION_DEPTH_EXCEEDED",t);let n=N(e,t),i=S(n.op,`${t}/op`,16);if(i!=="literal"){if(i==="path"){let r=S(n.path,`${t}/path`,255);(!/^[A-Za-z][A-Za-z0-9_.-]{0,254}$/.test(r)||r.split(".").some(d=>["__proto__","constructor","prototype"].includes(d)))&&m("NATIVE_WORKFLOW_EXPRESSION_PATH_INVALID",`${t}/path`);return}if(["eq","neq","gt","gte","lt","lte","in","contains"].includes(i)){Yt(n.left,`${t}/left`,o+1),Yt(n.right,`${t}/right`,o+1);return}if(["and","or"].includes(i)){let r=D(n.values,`${t}/values`,100);r.length===0&&m("NATIVE_WORKFLOW_EXPRESSION_EMPTY",`${t}/values`),r.forEach((d,s)=>Yt(d,`${t}/values/${s}`,o+1));return}if(["not","exists"].includes(i)){Yt(n.value,`${t}/value`,o+1);return}m("NATIVE_WORKFLOW_EXPRESSION_OPERATOR_INVALID",`${t}/op`)}}function hl(e,t){F(e.schemaVersion,"openxiangda.workflow-binding/v2",`${t}/schemaVersion`),Qn(e.workflowCode,`${t}/workflowCode`);let o=N(e.bindings,`${t}/bindings`);Object.keys(o).length>200&&m("NATIVE_WORKFLOW_BINDING_LIMIT_EXCEEDED",`${t}/bindings`);for(let[n,i]of Object.entries(o)){Hn(n,`${t}/bindings/${n}`);let r=N(i,`${t}/bindings/${n}`),d=ni(r);d.length&&m(d[0],`${t}/bindings/${n}/selectedInputPath`);let s=Lt(r);s.length&&m(s[0],`${t}/bindings/${n}/roleCodes`);let a=S(r.provider,`${t}/bindings/${n}/provider`,64);if(["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)||m("NATIVE_WORKFLOW_BINDING_PROVIDER_INVALID",`${t}/bindings/${n}/provider`),a==="fixed_users"&&(Array.isArray(r.users)||m("NATIVE_WORKFLOW_BINDING_USERS_REQUIRED",`${t}/bindings/${n}/users`),D(r.users,`${t}/bindings/${n}/users`,200)),["input_users","form_field_users"].includes(a)&&S(r.inputPath,`${t}/bindings/${n}/inputPath`,255),["app_role","app_role_in_scope","initiator_select"].includes(a)&&r.roleCodes===void 0&&P(r.roleCode,`${t}/bindings/${n}/roleCode`),a==="department_supervisor"&&S(r.departmentIdFrom,`${t}/bindings/${n}/departmentIdFrom`,255),a==="application_provider"&&P(r.providerCode,`${t}/bindings/${n}/providerCode`),r.routing!==void 0){let c=Kt(r.routing);c.length&&m(c[0],`${t}/bindings/${n}/routing`)}}}function wl(e,t,o){F(t.workflowCode,e.code,`${o}/workflowCode`);let n=N(t.bindings,`${o}/bindings`);for(let[s,a]of Object.entries(n))a.provider==="fixed_users"&&!a.users.length&&!si(e,s)&&m("NATIVE_WORKFLOW_BINDING_USERS_REQUIRED",`${o}/bindings/${s}/users`);let i=Fn(e,t);i.length&&m(i[0],o);let r=$n(e,t);r.length&&m(r[0],o);let d=Pt(e,t);d.length&&m(d[0],o);for(let[s,a]of Object.entries(N(e.nodes,`${o}/nodes`))){let c=N(a,`${o}/nodes/${s}`);["approval","cc"].includes(c.kind)&&!n[c.binding]&&m("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${o}/nodes/${s}/binding`)}}function Sl(e,t,o){let n=N(t.routeManifest,"/contracts/routeManifest"),i=N(e.routeManifest,"/contracts/routeManifest"),r=new Map;for(let f of D(o.data?.resources,"/config/data/resources",M.resources)){let u=N(f,"/config/data/resources");r.set(String(u.code||""),u)}let d=new Set(D(i.routes,"/contracts/routeManifest/routes",M.routes).map(f=>String(N(f,"/contracts/routeManifest/routes").code||""))),s=[];for(let f of D(n.routes,"/contracts/routeManifest/routes",M.routes)){let u=N(f,"/contracts/routeManifest/routes"),p=String(u.kind||"");if(p!=="resource-records"&&p!=="resource-submit")continue;let _=String(u.resourceCode||""),E=r.get(_);E||m("NATIVE_ROUTE_MANIFEST_RESOURCE_UNKNOWN","/contracts/routeManifest/routes");let O=`user.${_}.${p==="resource-records"?"records":"submit"}`;F(String(u.code||""),O,"/contracts/routeManifest/routes/code");let b=p==="resource-records"?"read":"create",g=String(N(E.capabilities,"/config/data/resources/capabilities")[b]||"");for(let I of["desktop","mobile"]){let T=N(u[I],`/contracts/routeManifest/routes/${I}`),l=I==="mobile"?"/m/my/":"/my/",y=p==="resource-records"?`${l}${_}`:`${l}${_}/submit`;F(String(T.path||""),y,`/contracts/routeManifest/routes/${I}/path`),F(String(T.capability||""),g,`/contracts/routeManifest/routes/${I}/capability`),F(String(T.routeCode||""),`${O}.${I}`,`/contracts/routeManifest/routes/${I}/routeCode`)}(d.has(O)||s.some(I=>String(I.code)===O))&&m("NATIVE_ROUTE_MANIFEST_DUPLICATE","/contracts/routeManifest/routes/code"),s.push(u)}if(!s.length)return;i.routes=D([...i.routes,...s],"/contracts/routeManifest/routes",1e3).sort((f,u)=>Ee(String(N(f,"x").code||""),String(N(u,"x").code||"")));let a=String(N(n.rootEntry,"x").code||"");if(s.find(f=>String(f.code)===a&&f.kind==="resource-records")){let f=N(n.rootEntry,"x");i.rootEntry={code:a,desktop:String(f.desktop||""),mobile:String(f.mobile||"")}}i.digest=Z({schemaVersion:i.schemaVersion,appCode:i.appCode,devicePolicy:i.devicePolicy,rootEntry:i.rootEntry,authentication:i.authentication,routes:i.routes})}function Qe(e,t,o){let n=N(e,t);C(n,["schemaVersion","appCode","code","name","schema","surface","invariants","decimalReservationLifecycle","uniqueKeys","workflowHistory","recordPrint","recordComments","recordDeletion","capabilities","dataPolicyCode","fieldPolicies"],t,!0),F(n.schemaVersion,"openxiangda.data-resource/v2",`${t}/schemaVersion`),F(n.appCode,o,`${t}/appCode`);let i=H(n.code,`${t}/code`),r=S(n.name,`${t}/name`,255),d=N(n.schema,`${t}/schema`);C(d,["fields","ownedRowLimit"],`${t}/schema`,!0),d.ownedRowLimit!==void 0&&!it(d.ownedRowLimit)&&m("NATIVE_DATA_OWNED_ROW_LIMIT_INVALID",`${t}/schema/ownedRowLimit`);let s,a,c,f;try{c=bn(n.decimalReservationLifecycle,`${t}/decimalReservationLifecycle`),s=fn(d.fields,`${t}/schema/fields`),f=Mo(n.uniqueKeys,s,`${t}/uniqueKeys`),a=Eo(n.invariants,s,`${t}/invariants`),An(n.surface,s,`${t}/surface`)}catch(E){throw(E instanceof ye||E instanceof Ve||E instanceof qe||E instanceof ft)&&m(E.code,E.pointer),E}if(n.recordComments!==void 0){let E=N(n.recordComments,`${t}/recordComments`);C(E,["read","create"],`${t}/recordComments`);for(let A of["read","create"]){let O=E[A];(!Array.isArray(O)||O.length>20||O.some(b=>typeof b!="string"||!b.trim())||new Set(O).size!==O.length)&&m("NATIVE_RECORD_COMMENTS_POLICY_INVALID",`${t}/recordComments/${A}`)}}if(n.recordDeletion!==void 0){let E=N(n.recordDeletion,`${t}/recordDeletion`);C(E,["delete"],`${t}/recordDeletion`);let A=E.delete;(!Array.isArray(A)||A.length>20||A.some(O=>typeof O!="string"||!O.trim())||new Set(A).size!==A.length)&&m("NATIVE_RECORD_DELETION_DELETE_INVALID",`${t}/recordDeletion/delete`)}if(n.recordPrint!==void 0){let E=N(n.recordPrint,`${t}/recordPrint`);C(E,["read"],`${t}/recordPrint`);let A=E.read;(!Array.isArray(A)||A.length>20||A.some(O=>typeof O!="string"||!O.trim())||new Set(A).size!==A.length)&&m("NATIVE_RECORD_PRINT_READ_INVALID",`${t}/recordPrint/read`)}if(n.workflowHistory!==void 0){let E=N(n.workflowHistory,`${t}/workflowHistory`);C(E,["read"],`${t}/workflowHistory`);let A=E.read;(!Array.isArray(A)||A.length>20||A.some(O=>typeof O!="string"||!O.trim())||new Set(A).size!==A.length)&&m("NATIVE_WORKFLOW_HISTORY_READ_INVALID",`${t}/workflowHistory/read`)}let u=new Set(s.map(E=>E.code)),p=N(n.capabilities,`${t}/capabilities`);C(p,["read","create","update","delete"],`${t}/capabilities`);let _=N(n.fieldPolicies,`${t}/fieldPolicies`);for(let[E,A]of Object.entries(_)){!u.has(E)&&!rt(E)&&m("NATIVE_DATA_FIELD_POLICY_FIELD_MISSING",`${t}/fieldPolicies/${E}`);let O=`${t}/fieldPolicies/${E}`,b=N(A,O);rt(E)&&(C(b,["read"],O,!0),(!Array.isArray(b.read)||b.read.length>20||b.read.some(g=>typeof g!="string"||!g.trim())||new Set(b.read).size!==b.read.length)&&m("NATIVE_DATA_AUDIT_READ_POLICY_INVALID",`${O}/read`)),C(b,["read","create","update","mask"],O,!0),b.mask!==void 0&&!["omit","null"].includes(b.mask)&&m("NATIVE_DATA_FIELD_POLICY_MASK_INVALID",`${O}/mask`)}return{...n,code:i,name:r,schema:{fields:s,...d.ownedRowLimit!==void 0?{ownedRowLimit:d.ownedRowLimit}:{}},...n.invariants===void 0?{}:{invariants:a},...c?{decimalReservationLifecycle:c}:{},...f!==void 0?{uniqueKeys:f}:{},capabilities:p,fieldPolicies:_}}function Ms(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 Ns(e,t,o,n){let i=e.toString("utf8"),r;try{r=JSON.parse(i)}catch{m(o,t)}let d=N(r,t);return X(d)!==i&&m(n,t),d}function Bn(e,t,o){let n=0,i=(r,d,s)=>{if(n+=1,n>o&&m("NATIVE_ARTIFACT_NODE_LIMIT_EXCEEDED",d),s>Lc&&m("NATIVE_ARTIFACT_DEPTH_LIMIT_EXCEEDED",d),typeof r=="string"){Buffer.byteLength(r)>wi&&m("NATIVE_ARTIFACT_STRING_LIMIT_EXCEEDED",d);return}if(Array.isArray(r)){r.forEach((a,c)=>i(a,`${d}/${c}`,s+1));return}if(!(!r||typeof r!="object"))for(let[a,c]of Object.entries(r))["__proto__","prototype","constructor"].includes(a)&&m("NATIVE_ARTIFACT_DANGEROUS_KEY",`${d}/${a}`),Dl(a)&&m("NATIVE_ARTIFACT_RUNTIME_FIELD_FORBIDDEN",`${d}/${a}`),i(c,`${d}/${a}`,s+1)};i(e,t,0)}function Dl(e){return["environmentKey","environmentId","secretValue","ciphertext","oauthClient","oauthClientId","oauthClientSecret","signingSecret","kubernetesNamespace","nodePort","productionUrl"].includes(e)}function It(e){return{value:e,digest:Z(e)}}function Ts(e,t,o,n){typeof e!="string"&&!Buffer.isBuffer(e)&&!(e instanceof Uint8Array)&&m("NATIVE_ARTIFACT_BYTES_REQUIRED",o);let i=Buffer.isBuffer(e)?e:Buffer.from(e);return i.byteLength===0&&m("NATIVE_ARTIFACT_EMPTY",o),i.byteLength>t&&m(n,o),i}function Rs(e,t,o,n){let i=Yn.createHash("sha256").update(e).digest("hex");Yn.timingSafeEqual(Buffer.from(i),Buffer.from(t))||m(n,o)}function N(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&m("NATIVE_OBJECT_REQUIRED",t),e}function D(e,t,o){return Array.isArray(e)||m("NATIVE_ARRAY_REQUIRED",t),e.length>o&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t),e}function V(e,t,o){let n=D(e,t,o).map((i,r)=>S(i,`${t}/${r}`,255));return new Set(n).size!==n.length&&m("NATIVE_ARRAY_DUPLICATE",t),n}function S(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&m("NATIVE_STRING_INVALID",t),e}function Pi(e,t,o){return(typeof e!="string"||e.length>o)&&m("NATIVE_STRING_INVALID",t),e}function P(e,t){let o=S(e,t,128);return yc.test(o)||m("NATIVE_CODE_INVALID",t),o}function H(e,t){let o=S(e,t,64);return Oc.test(o)||m("NATIVE_RESOURCE_CODE_INVALID",t),o}function G(e,t){let o=S(e,t,63);return Nc.test(o)||m("NATIVE_FIELD_CODE_INVALID",t),o}function Qn(e,t){let o=S(e,t,128);return Cc.test(o)||m("NATIVE_WORKFLOW_CODE_INVALID",t),o}function Hn(e,t){let o=S(e,t,128);return hc.test(o)||m("NATIVE_WORKFLOW_BINDING_CODE_INVALID",t),o}function pe(e,t,o){let n=S(e,t,255);return Ic.test(n)||m("NATIVE_CAPABILITY_CODE_INVALID",t),!n.startsWith(`app:${o}:`)&&!Ms(o).some(i=>i.code===n)&&m("NATIVE_CAPABILITY_APP_MISMATCH",t),n}function Ne(e,t){let o=S(e,t,2048);return(!o.startsWith("/")||o.startsWith("//")||o.includes("..")||o.includes("?")||o.includes("#"))&&m("NATIVE_ABSOLUTE_PATH_INVALID",t),o}function yt(e,t){return(!Number.isInteger(e)||Number(e)<1)&&m("NATIVE_POSITIVE_INTEGER_REQUIRED",t),Number(e)}function se(e,t,o,n){return(!Number.isInteger(e)||Number(e)<o||Number(e)>n)&&m("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function bt(e,t){return typeof e!="boolean"&&m("NATIVE_BOOLEAN_REQUIRED",t),e}function Di(e,t){let o=S(e,t,64).toLowerCase();return Ac.test(o)||m("NATIVE_DIGEST_INVALID",t),o}function F(e,t,o){e!==t&&m("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)||m("NATIVE_PROPERTY_UNKNOWN",`${o}/${r}`);if(n!==!0)for(let r of t)Object.prototype.hasOwnProperty.call(e,r)||m("NATIVE_PROPERTY_REQUIRED",`${o}/${r}`)}function te(e,t){return[...e].sort((o,n)=>Ee(t(o),t(n)))}function B(e){return[...new Set(e)].sort(Ee)}function Cs(e){return[...new Set(e)].sort((t,o)=>t-o)}function Ee(e,t){return e===t?0:e<t?-1:1}function Bs(e){return!e||typeof e!="object"||Object.isFrozen(e)||(Object.freeze(e),Object.values(e).forEach(t=>Bs(t))),e}function ki(e,t,o){if(hi(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(!hi(e[i],t[i]))return ki(e[i],t[i],`${o}/${i}`)}if(e&&t&&typeof e=="object"&&typeof t=="object"&&!Array.isArray(e)&&!Array.isArray(t)){let n=B([...Object.keys(e),...Object.keys(t)]);for(let i of n){let r=e[i],d=t[i];if(!hi(r,d))return ki(r,d,`${o}/${i}`)}}return o}function hi(e,t){return e===void 0||t===void 0?e===t:X(e)===X(t)}function m(e,t,o={}){throw new qn(e,t,o)}var kl="openxiangda.workflow-step-data-command/v1",Ks="openxiangda.workflow-step-data-resolution/v1";function $l(e,t,o=!1){let n=s=>!!s&&typeof s=="object"&&!Array.isArray(s),i=s=>typeof s=="string"&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(s),r=()=>{throw new Error("WORKFLOW_STEP_DATA_RESPONSE_INVALID")};if(!n(e)||e.schemaVersion!==Ks||e.executionId!==t||Object.keys(e).some(s=>!["schemaVersion","executionId","outcome","transaction"].includes(s)))return r();if(e.outcome==="not_observed"&&!Object.hasOwn(e,"transaction")&&!o)return e;let d=e.transaction;if(e.outcome!=="committed"||!n(d)||d.schemaVersion!=="openxiangda.data-transaction-result/v2"||d.idempotencyKey!==`workflow-step:${t}`||typeof d.replayed!="boolean"||!Array.isArray(d.items)||d.items.length<1||d.items.length>po||d.evaluatedAt!==void 0&&(typeof d.evaluatedAt!="string"||!Number.isFinite(Date.parse(d.evaluatedAt))))return r();for(let[s,a]of d.items.entries()){if(!n(a)||a.index!==s)return r();if(a.operation==="emitEvent"){if(typeof a.eventType!="string"||!a.eventType||!i(a.eventId))return r()}else if(!["create","update","delete","increment"].includes(a.operation)||typeof a.resourceCode!="string"||!a.resourceCode||!i(a.id)||!Number.isSafeInteger(a.revision)||a.revision<1)return r()}return e}var kp=50,$p=131072,eo=class extends Error{constructor(o){super("OPENXIANGDA_NATIVE_AUTHZ_BATCH_INPUT_INVALID");this.pointer=o}pointer;code="OPENXIANGDA_NATIVE_AUTHZ_BATCH_INPUT_INVALID";status=400};function vl(e){let t=u=>{throw new eo(u)},o=(u,p)=>((!u||typeof u!="object"||Array.isArray(u))&&t(p),u),n=(u,p,_)=>{for(let E of Object.keys(u))p.includes(E)||t(`${_}/${E}`)},i=(u,p,_)=>((typeof u!="string"||!u.trim()||u.length>p)&&t(_),u),r=(u,p)=>{let _=i(u,36,p);return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(_)||t(p),_.toLowerCase()},d=o(e,""),s;try{s=new TextEncoder().encode(JSON.stringify(d)).byteLength}catch{t("")}s>131072&&t(""),n(d,["schemaVersion","environmentKey","items"],""),d.schemaVersion!=="openxiangda.native-role-membership-batch-request/v2"&&t("/schemaVersion"),d.environmentKey!==void 0&&!["preproduction","production"].includes(String(d.environmentKey))&&t("/environmentKey"),(!Array.isArray(d.items)||d.items.length<1||d.items.length>50)&&t("/items");let a=new Set,c=new Set,f;for(let[u,p]of d.items.entries()){let _=`/items/${u}`,E=o(p,_);["create","update","revoke"].includes(String(E.operation))||t(`${_}/operation`),f??=E.operation,f!==E.operation&&t(`${_}/operation`),n(E,["operation","operationId","reason",...f==="create"?["userId","roleCode"]:["membershipId","expectedRevision"],...f!=="revoke"?["scopeGrants","validFrom","validTo"]:[]],_);let A=r(E.operationId,`${_}/operationId`);a.has(A)&&t(`${_}/operationId`),a.add(A),i(E.reason,1e3,`${_}/reason`);let O;if(f==="create"){let b=i(E.userId,255,`${_}/userId`),g=i(E.roleCode,128,`${_}/roleCode`);/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(g)||t(`${_}/roleCode`),O=JSON.stringify([b,g])}else O=r(E.membershipId,`${_}/membershipId`),(!Number.isSafeInteger(E.expectedRevision)||Number(E.expectedRevision)<1)&&t(`${_}/expectedRevision`);c.has(O)&&t(_),c.add(O),E.scopeGrants!==void 0&&(!Array.isArray(E.scopeGrants)||E.scopeGrants.length>100)&&t(`${_}/scopeGrants`);for(let b of["validFrom","validTo"])E[b]!==void 0&&E[b]!==null&&i(E[b],64,`${_}/${b}`)}}var Js="openxiangda.workflow-delegation-administration/v2",Hs="openxiangda.workflow-delegation-mutation/v2",Gs="openxiangda.workflow-delegation-preview/v2";var Zt={type:"string",format:"uuid",pattern:"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$"},me={type:"string",minLength:1,maxLength:255},et={type:"string",format:"date-time"},Ot={type:"integer",minimum:1},Pl={anyOf:[et,{type:"null"}]},Vi={anyOf:[me,{type:"null"}]},Ys={anyOf:[{type:"string",pattern:"^[A-Za-z0-9._:-]{1,128}$"},{type:"null"}]},to={type:"string",pattern:"^membership:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},Xs={const:"future-assignments-only"},Li={schemaVersion:{const:Js},id:Zt,appCode:me,environmentKey:me,workflowCode:Vi,nodeId:Ys,delegatorUserId:me,delegateUserId:me,delegatorRoleSubjectKey:to,delegateRoleSubjectKey:to,validFrom:et,validTo:et,status:{enum:["active","revoked","expired"]},reason:{type:"string",minLength:1,maxLength:4e3},createdBy:me,createdAt:et,revokedAt:Pl,revision:Ot,roleCode:me,roleName:me,delegatorDisplayName:me,delegateDisplayName:me,delegatorRoleSubjectRevision:Ot,delegateRoleSubjectRevision:Ot,effectiveState:{enum:["active","scheduled","expired","revoked","ineligible"]},evaluatedAt:et,issues:{type:"array",maxItems:20,uniqueItems:!0,items:me},canRevoke:{type:"boolean"},revokedBy:Vi,revokeReason:{type:["string","null"],maxLength:4e3},taskPolicy:Xs},Fi={type:"object",additionalProperties:!1,required:Object.keys(Li).filter(e=>e!=="nodeId"),properties:Li},Pp={$id:Js,...Fi},Zs={schemaVersion:{const:Hs},operationId:Zt,environmentKey:{enum:["preproduction","production"]},reason:{type:"string",minLength:1,maxLength:2e3,pattern:"\\S"}},qs={...Zs,operation:{const:"create"},workflowCode:Vi,nodeId:Ys,delegatorRoleSubjectKey:to,expectedDelegatorRevision:Ot,delegateUserId:me,delegateRoleSubjectKey:to,expectedDelegateRevision:Ot,validFrom:et,validTo:et},zs={...Zs,operation:{const:"revoke"},delegationId:Zt,expectedRevision:Ot},Qs={$id:Hs,type:"object",oneOf:[{type:"object",additionalProperties:!1,required:Object.keys(qs).filter(e=>e!=="nodeId"),properties:qs,if:{required:["nodeId"],properties:{nodeId:{type:"string"}}},then:{properties:{workflowCode:me}}},{type:"object",additionalProperties:!1,required:Object.keys(zs),properties:zs}]},Vl={type:"string",pattern:"^[0-9a-f]{64}$"},Vp={$id:Gs,type:"object",additionalProperties:!1,required:["schemaVersion","operationId","operation","requestDigest","before","after","taskPolicy"],properties:{schemaVersion:{const:Gs},operationId:Zt,operation:{enum:["create","revoke"]},requestDigest:Vl,before:{anyOf:[Fi,{type:"null"}]},after:{...Fi,properties:{...Li,id:{anyOf:[Zt,{type:"null"}]}}},taskPolicy:Xs}};function Ll(e){return e===void 0?"":`
9
- ${Z(e)}`}function Fl(e,t){let o=e.handlers.find(n=>n.code===t);return Z(o?.workflowStep?o:e)}var xl="openxiangda.data-business-command/v1",ea="openxiangda.data-business-command-resolution/v1",jp=65536;function jl(e){let t=0,o=0,n=new Set,i=new TextEncoder,r=()=>{throw new Error("OPENXIANGDA_DATA_COMMAND_INTENT_INVALID")},d=a=>(o+=i.encode(a).byteLength,o>65536&&r(),a),s=(a,c)=>{if(++t>1e4||c>32)return r();if(a===null||typeof a=="string"||typeof a=="boolean")return d(JSON.stringify(a));if(typeof a=="number")return Number.isFinite(a)?d(JSON.stringify(a)):r();if(!a||typeof a!="object"||n.has(a)||Object.getOwnPropertySymbols(a).length)return r();n.add(a);let f;if(Array.isArray(a))return Object.keys(a).length!==a.length?r():(f=d("[")+a.map((p,_)=>(_?d(","):"")+s(p,c+1)).join("")+d("]"),n.delete(a),f);let u=Object.getPrototypeOf(a);return u!==Object.prototype&&u!==null?r():(f=d("{")+Object.keys(a).sort().map((p,_)=>(_?d(","):"")+d(JSON.stringify(p))+d(":")+s(a[p],c+1)).join("")+d("}"),n.delete(a),f)};return!e||typeof e!="object"||Array.isArray(e)?r():s(e,0)}function Wl(e,t,o=!1){let n=e,i=()=>{throw new Error("OPENXIANGDA_DATA_COMMAND_RESPONSE_INVALID")};if(!n||typeof n!="object"||n.schemaVersion!==ea)return i();for(let a of["appCode","environmentKey","operationCode","idempotencyKey","intentDigest"])if(n[a]!==t[a])return i();if(typeof n.observedAt!="string"||!Number.isFinite(Date.parse(n.observedAt)))return i();if(n.outcome==="not_observed"&&n.receipt===null&&!o)return n;if(n.outcome!=="committed"||!n.receipt)return i();let r=n.receipt,d=a=>typeof a=="string"&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(a);if(!d(r.id)||!d(r.appVersionId)||!Number.isSafeInteger(r.environmentHeadRevision)||r.environmentHeadRevision<1||typeof r.completedAt!="string"||!Number.isFinite(Date.parse(r.completedAt)))return i();let s=r.transaction;if(!s||s.schemaVersion!=="openxiangda.data-transaction-result/v2"||s.idempotencyKey!==t.idempotencyKey||typeof s.replayed!="boolean"||!Array.isArray(s.items)||!s.items.length||s.items.length>1e3)return i();for(let[a,c]of s.items.entries()){if(!c||c.index!==a)return i();if(c.operation==="emitEvent"){if(!d(c.eventId)||typeof c.eventType!="string"||!c.eventType)return i()}else if(!["create","update","delete","increment"].includes(c.operation)||!d(c.id)||typeof c.resourceCode!="string"||!c.resourceCode||!Number.isSafeInteger(c.revision)||c.revision<1)return i()}return n}var ta=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,no=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Qt=(e,t)=>typeof e=="string"&&e.length<=t&&e.trim().length>0&&e===e.trim(),xi=(e,t,o=[])=>t.every(n=>Object.hasOwn(e,n))&&Object.keys(e).every(n=>[...t,...o].includes(n));function Ul(e){if(!no(e)||!xi(e,["kind","errorCode","anyOf"],["allowAppSuperAdmin"])||e.kind!=="actor-authority"||!Qt(e.errorCode,110)||!/^OPENXIANGDA_[A-Z0-9_]{1,96}$/.test(e.errorCode)||Object.hasOwn(e,"allowAppSuperAdmin")&&typeof e.allowAppSuperAdmin!="boolean"||!Array.isArray(e.anyOf)||e.anyOf.length<1||e.anyOf.length>20)return!1;let t=new Set;return e.anyOf.every(o=>{if(!no(o)||!xi(o,["roleCode"],["scope"])||!Qt(o.roleCode,100)||!ta.test(o.roleCode))return!1;if(Object.hasOwn(o,"scope")){let r=o.scope;if(!no(r)||!xi(r,["dimensionCode","value","operation"])||!Qt(r.dimensionCode,100)||!ta.test(r.dimensionCode)||!Qt(r.value,255)||!Qt(r.operation,64)||!/^[A-Za-z0-9*][A-Za-z0-9*._:-]*$/.test(r.operation))return!1}let n=o.scope,i=JSON.stringify([o.roleCode,n?.dimensionCode,n?.value,n?.operation]);return t.has(i)?!1:(t.add(i),!0)})}function Ml(e,t,o){if(t.roleSource!=="package"||t.roleCode!==e.roleCode||!o||!t.capabilityCodes.includes(o))return!1;if(!e.scope)return!0;let n;try{n=JSON.parse(t.scopeGrantsJson)}catch{return!1}if(!Array.isArray(n))return!1;let i=e.scope;return n.some(r=>no(r)&&r.dimensionCode===i.dimensionCode&&Array.isArray(r.values)&&r.values.includes(i.value)&&(r.operations===void 0||r.operations===null||Array.isArray(r.operations)&&(!r.operations.length||r.operations.includes("*")||r.operations.includes(i.operation))))}var Mp=500,Bl=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,ji=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function Kl(e){if(!ji(e)||e.kind!=="record-set-match"||Object.keys(e).some(o=>!["kind","resourceCode","errorCode","records","where"].includes(o))||typeof e.resourceCode!="string"||e.resourceCode.length>64||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(e.resourceCode)||typeof e.errorCode!="string"||!/^OPENXIANGDA_[A-Z0-9_]{1,96}$/.test(e.errorCode)||!Array.isArray(e.records)||!e.records.length||e.records.length>500||Object.hasOwn(e,"where")&&!ji(e.where))return!1;let t=new Set;return e.records.every(o=>{if(!ji(o)||Object.keys(o).length!==2||typeof o.id!="string"||!Bl.test(o.id)||!Number.isSafeInteger(o.expectedRevision)||Number(o.expectedRevision)<1)return!1;let n=o.id.toLowerCase();return t.has(n)?!1:(t.add(n),!0)})}function na(e,t){if(t===void 0)return e;let o=e.views?.find(d=>d.code===t);if(!o)throw new Error(`DATA_RESOURCE_VIEW_NOT_FOUND: ${t}`);let n=new Map(o.sections?.flatMap(d=>d.fields.map(s=>[s,d.title]))),{views:i,...r}=e;return{...r,generated:o.generated,list:o.list,form:o.form,detail:o.detail,mobile:o.mobile,fields:Object.fromEntries(Object.entries(e.fields).map(([d,s])=>{let{section:a,...c}=s,f=n.get(d);return[d,{...c,...f?{section:f}:{},list:o.list.fieldOrder?.includes(d)??!1}]}))}}var oa="openxiangda.development-configuration/v1",Wi="openxiangda.development-configuration-manifest/v1",Gl="application.development-configuration",ql="/openxiangda-api/v2/applications/{appCode}/dev-sessions/configuration",oo=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.data={pointer:n}}code;pointer;status=400;data};function We(e){throw new oo("OPENXIANGDA_CONNECTED_DEV_CONFIGURATION_INVALID",e)}function ia(e){(!e||typeof e!="object"||Array.isArray(e))&&We("/packageManifest");let t=e,o=["schemaVersion","appCode","version","configDigest","contractDigest","source","toolchain","artifacts"];(Object.keys(t).some(i=>!o.includes(i))||t.schemaVersion!==Wi||typeof t.appCode!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(t.appCode)||!/^[a-f0-9]{64}$/.test(t.configDigest)||!/^[a-f0-9]{64}$/.test(t.contractDigest)||t.version!==`development-${t.configDigest}`)&&We("/packageManifest"),(!t.source||typeof t.source!="object"||Array.isArray(t.source)||Object.keys(t.source).some(i=>!["repository","commit","dirty"].includes(i))||![null,"string"].includes(t.source.repository===null?null:typeof t.source.repository)||t.source.repository!==null&&(t.source.repository.length>1024||/[\r\n\0]/.test(t.source.repository))||t.source.commit!==null&&(typeof t.source.commit!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(t.source.commit))||typeof t.source.dirty!="boolean")&&We("/packageManifest/source"),(!t.toolchain||Object.keys(t.toolchain).some(i=>!["version","contractVersion"].includes(i))||typeof t.toolchain.version!="string"||!/^[A-Za-z0-9][A-Za-z0-9.+_-]{0,127}$/.test(t.toolchain.version)||t.toolchain.contractVersion!==Ni)&&We("/packageManifest/toolchain");let n=[{kind:"config",digest:t.configDigest,mediaType:"application/json"},{kind:"contracts",digest:t.contractDigest,mediaType:"application/json"}];return X(t.artifacts)!==X(n)&&We("/packageManifest/artifacts"),t}function zl(e,t){return ia({schemaVersion:Wi,appCode:e,version:`development-${t.configDigest}`,configDigest:t.configDigest,contractDigest:t.contractDigest,source:{...t.source},toolchain:{version:t.toolchainVersion,contractVersion:Ni},artifacts:[{kind:"config",digest:t.configDigest,mediaType:"application/json"},{kind:"contracts",digest:t.contractDigest,mediaType:"application/json"}]})}function Jl(e,t){return(!Number.isSafeInteger(t)||t<1)&&We("/expectedHeadRevision"),`development:${Z({manifest:e,expectedHeadRevision:t})}`}function Hl(e,t,o){(!e||typeof e!="object"||Array.isArray(e))&&We("/result");let n=e,i=["schemaVersion","appCode","environmentKey","environmentId","appVersionId","configurationRunId","headRevision","configDigest","contractDigest","reused","runtimeArtifactsDeployed","backendEventsAvailable"],r=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i;return(Object.keys(n).some(d=>!i.includes(d))||n.schemaVersion!==oa||n.appCode!==t||n.environmentKey!=="preproduction"||n.configDigest!==o.configDigest||n.contractDigest!==o.contractDigest||!r.test(n.environmentId)||!r.test(n.appVersionId)||!r.test(n.configurationRunId)||typeof n.reused!="boolean"||!Number.isSafeInteger(n.headRevision)||n.headRevision<1||!n.reused&&n.headRevision!==o.expectedHeadRevision+1||n.runtimeArtifactsDeployed!==!1||n.backendEventsAvailable!==!1)&&We("/result"),n}var Yl="application.development-backend-events",Xl="openxiangda.development-backend/v1",Zl="application.development-backend-invocations",ra="openxiangda.development-backend-invocation/v1",Jp=262144,Hp=1048576,Yp=131072,Xp=131072,Zp=8,Qp=45,Ql=/^\/__platform\/events\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function eu(e){return(e.backend?.operations?.length||0)>0||(e.workflows?.providers?.length||0)>0||(e.events?.subscriptions||[]).some(t=>t.execution?.kind!=="native-data")}function tu(e){return`connected-development:${e}`}function sa(e){if(typeof e!="string"||e.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(e))return null;let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=e.endsWith("==")?2:e.endsWith("=")?1:0;return o&&t.indexOf(e[e.length-o-1])%(o===2?16:4)!==0?null:e.length/4*3-o}function aa(e,t,o){if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)||o.method!==e||typeof t!="string"||t.length>2048||!t.startsWith("/")||t.startsWith("//")||t.startsWith("/__platform")||/[\\?#\s\u0000-\u001f\u007f]/.test(t))return!1;let n=t.split("/"),i=String(o.path||"").split("/");return n.length!==i.length?!1:n.every((r,d)=>{if(d===0)return i[d]==="";let s;try{s=decodeURIComponent(r)}catch{return!1}return!s||[".",".."].includes(s)||/[\/\\\s\u0000-\u001f\u007f]/.test(s)?!1:/^:[A-Za-z][A-Za-z0-9_]*$/.test(i[d]||"")||r===i[d]})}var nu=/^(?:authorization|content-type|content-length|accept|if-match|idempotency-key|x-request-id|x-openxiangda-(?:gateway-assertion|forwarded-by|perspective|csrf-token|mcp-bus-token))$/i,ou=/^(?:content-type|content-disposition|cache-control|etag|last-modified|retry-after)$/i;function da(e,t=!1){if(!e||typeof e!="object"||Array.isArray(e))return!1;let o=Object.entries(e),n=o.map(([i])=>i.toLowerCase());return o.length<=24&&new Set(n).size===n.length&&o.every(([i,r])=>(t?ou:nu).test(i)&&typeof r=="string"&&r.length<=8192&&!/[\r\n\u0000]/.test(r))}function iu(e){let t=sa(e.body);return e.schemaVersion===ra&&!!e.operation&&typeof e.operation.code=="string"&&e.operation.code.length<=128&&e.operation.code.length>0&&aa(e.method,e.endpointPath,e.operation)&&typeof e.canonicalQuery=="string"&&e.canonicalQuery.length<=8192&&!/[\s#\u0000-\u001f\u007f]/.test(e.canonicalQuery)&&t!==null&&t<=262144&&da(e.headers)&&Object.entries(e.headers).some(([o,n])=>o.toLowerCase()==="authorization"&&/^Bearer \S+$/.test(n))&&Object.entries(e.headers).some(([o,n])=>o.toLowerCase()==="x-openxiangda-gateway-assertion"&&!!n)}var ru="4211d39e543f8dacbb978ef7e243a15b4668a484d144c5b4bf89c10ee9443518";0&&(module.exports={AuthenticatedPublicReadContractError,DATA_AUDIT_METADATA_FIELDS,DATA_BUSINESS_COMMAND_INTENT_MAX_BYTES,DATA_BUSINESS_COMMAND_RESOLUTION_SCHEMA,DATA_BUSINESS_COMMAND_SCHEMA,DATA_EVENT_TYPES_V2,DATA_FORM_DRAFT_MAX_BYTES,DATA_RESOURCE_MAX_FIELDS,DATA_SUBTABLE_DEFAULT_TOTAL_ROWS,DATA_SUBTABLE_MAX_ROWS,DATA_SUBTABLE_MAX_TOTAL_ROWS,DATA_SYSTEM_SORT_FIELD_CODES,DATA_TRANSACTION_MAX_BYTES,DATA_TRANSACTION_MAX_OPERATIONS,DATA_TRANSACTION_RECORD_SET_MAX_RECORDS,DATE_EVENT_RESERVED_DATA_FIELDS_V2,DEVELOPMENT_BACKEND_CONNECTION_TTL_SECONDS,DEVELOPMENT_BACKEND_ENDPOINT_PATTERN,DEVELOPMENT_BACKEND_FEATURE,DEVELOPMENT_BACKEND_INVOCATION_FEATURE,DEVELOPMENT_BACKEND_INVOCATION_MAX_REQUEST_BYTES,DEVELOPMENT_BACKEND_INVOCATION_MAX_RESPONSE_BYTES,DEVELOPMENT_BACKEND_INVOCATION_SCHEMA,DEVELOPMENT_BACKEND_MAX_INFLIGHT,DEVELOPMENT_BACKEND_MAX_REQUEST_BYTES,DEVELOPMENT_BACKEND_MAX_RESPONSE_BYTES,DEVELOPMENT_BACKEND_SCHEMA,DEVELOPMENT_CONFIGURATION_ENDPOINT,DEVELOPMENT_CONFIGURATION_FEATURE,DEVELOPMENT_CONFIGURATION_MANIFEST_SCHEMA,DEVELOPMENT_CONFIGURATION_SCHEMA,DateEventProjectionV2Error,DevelopmentConfigurationContractError,ManagedConcurrencyContractError,NATIVE_ARTIFACT_CAPACITY_V2,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,NATIVE_HIGH_DENSITY_ARTIFACT_CAPACITY_V2,NATIVE_ROLE_MEMBERSHIP_BATCH_MAX_BYTES,NATIVE_ROLE_MEMBERSHIP_BATCH_MAX_ITEMS,NATIVE_UNIQUE_KEY_MAX_BYTES,NATIVE_UNIQUE_KEY_NORMALIZERS,NativeConfigurationCompilerError,NativeDataFieldContractV2Error,NativeDataPolicyExpressionV2Error,NativeDecimalLifecycleContractError,NativeEventActionContractError,NativeRoleMembershipBatchInputError,NativeScopeSourceFieldPathV2Error,NativeUniqueKeyContractError,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,USER_CANDIDATE_MAX_SELECTIONS,USER_CANDIDATE_SCOPE_FIELD_TYPES,UserCandidateContractError,WORKFLOW_APPROVAL_EMPTY_PROVIDERS,WORKFLOW_APPROVED_DELEGATION_MAX_BYTES,WORKFLOW_APPROVED_DELEGATION_MAX_REQUESTS,WORKFLOW_AUTOMATIC_CC_DEFAULT_RECIPIENTS,WORKFLOW_AUTOMATIC_CC_MAX_RECIPIENTS,WORKFLOW_AUTOMATIC_CC_PROVIDERS,WORKFLOW_BUSINESS_STEP_EVENT,WORKFLOW_BUSINESS_STEP_EVENTS,WORKFLOW_BUSINESS_STEP_FACTS_KEY,WORKFLOW_BUSINESS_STEP_MAX_BYTES,WORKFLOW_BUSINESS_STEP_MAX_RECEIPT_BYTES,WORKFLOW_CONFIGURABLE_OPERATIONS,WORKFLOW_CONFIGURABLE_PROVIDERS,WORKFLOW_EVENT_TYPES_V2,WORKFLOW_LAUNCH_MAX_INPUTS,WORKFLOW_LAUNCH_PREFLIGHT_PROVIDERS,WORKFLOW_REJECTION_NOTIFICATION_MAX_BYTES,WORKFLOW_REJECTION_NOTIFICATION_SCHEMA,WORKFLOW_ROLE_UNION_MAX_ROLES,WORKFLOW_ROUTING_MAX_BYTES,WORKFLOW_ROUTING_MAX_MATCHED_RULES,WORKFLOW_ROUTING_MAX_RULES,WORKFLOW_STEP_DATA_COMMAND_SCHEMA,WORKFLOW_STEP_DATA_RESOLUTION_SCHEMA,WORKFLOW_TASK_PAGE_DEFINITION_MAX_BYTES,WORKFLOW_TASK_PAGE_MAX_BYTES,WORKFLOW_TASK_PAGE_MAX_FIELDS,WORKFLOW_TASK_SUBTABLE_MAX_ROWS,WORKFLOW_TASK_SUBTABLE_MAX_TOTAL_ROWS,WorkflowTaskPageError,applyWorkflowTaskPageValues,applyWorkflowTaskSubtableRows,assertDevelopmentConfigurationManifest,assertDevelopmentConfigurationResult,assertNativeRoleMembershipBatchInput,assertWorkflowNativeStageGuard,assertWorkflowNativeStagePolicy,assertWorkflowNativeStageSourceGuard,assertWorkflowOwnedSubjectCreate,assertWorkflowOwnedSubjectCreateResources,canonicalDataBusinessIntent,compileNativeApplicationConfiguration,compileNativeEventAction,compileNativeEventCapturePlansV2,compileRequiredPlatformCapabilitiesV3,compileWorkflowBusinessStepHandlers,createDevelopmentConfigurationManifest,dataOwnedRowLimit,dateEventProjectionEnvelopeSchemaV2,dateEventProjectionFieldsV2,developmentBackendBase64Bytes,developmentBackendInvocationHeadersValid,developmentBackendInvocationRequestValid,developmentBackendInvocationRevision,developmentBackendOperationMatches,developmentConfigurationKey,evaluateWorkflowTaskPageExpression,formatWorkflowCompletionDeadline,formatWorkflowExpression,generatedCrudCapabilityOperations,hasDataAuditReadPolicy,isDataAuditMetadataField,isDataOwnedRowLimit,isDataSystemSortField,isDataTransactionActorAuthorityGuard,isDataTransactionRecordSetMatchGuard,isNativeDataQueryOperatorV2,isNativeMultiValueFieldV2,isWorkflowRejectionNotificationSnapshot,matchesDataActorAuthorityMembership,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,nativeUniqueKeysContractVersion,nativeUniqueKeysJsonSchema,normalizeWorkflowOwnedSubjectCreate,parseDataBusinessCommandResolution,parseDataFieldUserCandidates,parseDecimalReservationLifecycle,parseNativeDataFieldsV2,parseNativeDataResourceInvariantsV2,parseNativeUniqueKeys,parseWorkflowStepDataResolution,projectDataResourceView,projectNativeDataResourceViewV2,projectWorkflowGraph,projectWorkflowNodePolicy,quoteNativeIdentifierV2,refreshWorkflowTaskPageFacts,requiresAggregateOwnedSubtableCapacity,requiresDateTimeMinutePrecision,requiresDevelopmentBackendCredential,requiresExtendedArtifactCapacity,requiresExtendedConfigurationBytes,requiresExtendedDeclarationCapacity,requiresExtendedFieldCapacity,requiresExtendedOwnedSubtableCapacity,requiresHighDensityArtifactCapacity,requiresOwnedSubtableMinimumRows,requiresUserCandidateLaunchScope,requiresWorkflowRoleInputSelection,requiresWorkflowRoleUnion,resolveNativeScopeSourceFieldPathV2,resolveWorkflowUserCandidates,selectWorkflowAssignmentRoutingRules,serializedDataBytes,userCandidateScopeValue,validateAuthenticatedPublicRead,validateDecimalReservationLifecycles,validateManagedConcurrency,validateNativeDataDraftStateV2,validateNativeDataResourceReferencesV2,validateNativeDataResourceSurfaceV2,validateUserCandidateReferences,validateWorkflowAdministration,validateWorkflowApprovalEmptyPolicy,validateWorkflowApprovedDelegation,validateWorkflowAssignmentRoutingBindings,validateWorkflowAssignmentRoutingPolicy,validateWorkflowAssignmentRoutingRules,validateWorkflowAutomaticCc,validateWorkflowBusinessStepHandlerContract,validateWorkflowBusinessStepRequest,validateWorkflowBusinessStepResult,validateWorkflowBusinessStepSchema,validateWorkflowBusinessStepSubscriptions,validateWorkflowBusinessSteps,validateWorkflowCommandHandlers,validateWorkflowCompletionDeadlines,validateWorkflowCorrections,validateWorkflowInitiatorApprovalPolicy,validateWorkflowInstanceCommandPolicies,validateWorkflowLaunchPreflight,validateWorkflowNodeConfigurationPatch,validateWorkflowReadability,validateWorkflowRejectionNotification,validateWorkflowRoleInputSelection,validateWorkflowRoleUnion,validateWorkflowTaskPages,validateWorkflowUserCandidateBindings,workflowApprovalCanSkip,workflowApprovedDelegationRequests,workflowAssignmentRoutingFacts,workflowAssignmentRoutingPolicySchema,workflowAssignmentRoutingSemantic,workflowBindingAllowsEmptyUsers,workflowBindingRoleCodes,workflowBusinessCommandInvocationSchema,workflowBusinessStepFactSchema,workflowBusinessStepHandlerDigest,workflowBusinessStepInput,workflowBusinessStepPath,workflowBusinessStepReceiptSignatureSuffix,workflowBusinessStepValueMatches,workflowDelegationMutationRequestSchema,workflowExpressionPaths,workflowInitiatorApprovalCanComplete,workflowInstanceCommandDeadlineError,workflowInstanceTerminateCapabilityAllowed,workflowInstanceWithdrawalReasonRequired,workflowNativeStagePolicySchema,workflowNodeAllowedOperations,workflowOperationCommentRequired,workflowOperationReasonRequired,workflowOwnedSubjectCreateSchema,workflowPolicyTimestamp,workflowRoleCodesSchema,workflowTaskPageFieldState,workflowTaskPageReplayCoversInvalidation,workflowTaskSubtableRows,workflowVariableLabel});
8
+ END $native_subtable$`]}function $e(e,...t){return`${e}_${(0,gi.createHash)("sha256").update(t.join(":")).digest("hex").slice(0,32)}`}function de(e){if(!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(e))throw new Error("OPENXIANGDA_NATIVE_IDENTIFIER_INVALID");return`"${e}"`}function Ed(e,t){return e.type==="subtable"?"none":t?"gin-trigram":e.indexed?["date-range","datetime-range"].includes(e.type)?"gist-range":xo.has(e.type)?"btree-snapshot-expressions":id.has(e.type)?"gin-jsonb-path":"btree":"none"}function Id(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 ad.has(e.type),"jsonb"}}function Ii(e,t){if(ht(t.type)&&t.type!=="subtable")return"'[]'::jsonb";if(t.type!=="serial-number")return"";let o=_i(t.serial?.prefix||""),n=t.serial?.digits??6;return`(${o} || lpad(nextval(${_i(Rn(e,t.code))})::text, ${n}, '0'))`}function yd(e,t){return Ai.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'array')`:sd.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'object')`:""}function Tn(e){return`"app_data".${de(e)}`}function Rn(e,t){let o=$e("seq",e,t);return`"app_data".${de(o)}`}function _i(e){return`'${e.replace(/'/g,"''")}'`}var yi=new Set(["option.single","option.multiple","user.single","user.multiple","department.single","department.multiple","resource-ref.single","resource-ref.multiple"]),bd=new Set([...yi,"cascade.single","cascade.multiple","file","image","signature","address","location","json"]),bi=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Od=new Set(["__proto__","prototype","constructor"]),Cn=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 ft(e,t){let o=Oi(e);if(!o)return null;let n=t.get(o[0]);if(!n)return null;let r=o.slice(1).join(".")||void 0;return{field:n,...r?{valuePath:r}:{}}}function hn(e){return!!(e&&e.field.type==="user.single"&&e.valuePath==="value")}function jo(e,t,o){if(!e||!t||!Td(e))return!1;let{field:n,valuePath:r}=e;if(!r)return t.valueType==="uuid"?n.type==="uuid":["text.short","text.long","serial-number"].includes(n.type);if(r==="value")return!(t.valueSourceResourceCode&&n.type.startsWith("resource-ref.")&&n.source?.resourceCode!==t.valueSourceResourceCode);let i=r.slice(9),s=o.get(n.source?.resourceCode||"")?.get(i)?.type;return t.valueType==="uuid"?s==="uuid":["text.short","text.long","serial-number"].includes(s||"")}function Nd(e,t){let o=Oi(t);if(!o)throw new Cn(String(t||""));let n=e;for(let r of o){if(!n||typeof n!="object"||!Object.prototype.hasOwnProperty.call(n,r))return;n=n[r]}return n}function Td(e){let{field:t,valuePath:o}=e;if(!o)return!bd.has(t.type);if(o==="value")return yi.has(t.type);if(!o.startsWith("snapshot."))return!1;let n=o.slice(9);return bi.test(n)&&t.type.startsWith("resource-ref.")&&!!t.source?.snapshotFields?.includes(n)}function Oi(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=>!bi.test(o)||Od.has(o))||t.length===2&&t[1]!=="value"||t.length===3&&t[1]!=="snapshot"?null:t}var Rd=new Set(["option.single","user.single","department.single","resource-ref.single"]),Cd=new Set(["text.short","text.long","text.rich","number.integer","number.decimal","boolean","date","time","datetime","uuid","serial-number"]),hd=new Set(["value","label","description","color"]),wd=new Set(["avatarUrl","employeeNo","title","mobile","email"]),Sd=new Set(["fullPath","parent.value","parent.label"]),Dd=new Set(["country.value","country.label","province.value","province.label","city.value","city.label","district.value","district.label","street.value","street.label","detail","fullAddress"]),kd=new Set(["longitude","latitude","accuracy"]),$d=new Set(["address","name","province","city","district","source"]);function Pd(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 r=Vd(n,t);if(!Object.keys(r).length)return n;let i={...n};return Object.defineProperty(i,"queryPathTypes",{configurable:!1,enumerable:!1,writable:!1,value:Object.freeze(r)}),i})}}))}function vd(e,t){if(Rd.has(e.type)&&hd.has(t)||e.type==="user.single"&&wd.has(t)||e.type==="department.single"&&Sd.has(t))return kt(t);if(e.type==="resource-ref.single"){let o=e.queryPathTypes?.[t];return o?{parts:t.split("."),type:o}:null}if(e.type==="address"&&Dd.has(t))return kt(t);if(e.type==="location"){if(kd.has(t))return{parts:[t],type:"number.decimal"};if($d.has(t))return kt(t);if(t==="capturedAt")return{parts:[t],type:"datetime"}}return null}function Vd(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 r=o.get(n);return r?[[`snapshot.${n}`,Cd.has(r.type)?r.type:"json"]]:[]})):{}}function kt(e){return{parts:e.split("."),type:"text.short"}}var qu=5,zu=20,Ju=50,Hu=50,Yu=100,pt=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.name="NativeDataPolicyExpressionV2Error"}code;pointer};function Je(e,t){let o=[],n=(r,i,d)=>{d>5&&$t("NATIVE_DATA_POLICY_EXPRESSION_DEPTH_EXCEEDED",i);let s=Ni(r,i),a=["allOf","anyOf"].filter(u=>u in s);if(a.length===0){o.push({rule:s,pointer:i}),o.length>50&&$t("NATIVE_DATA_POLICY_EXPRESSION_LEAVES_EXCEEDED",i);return}let c=a[0],f=s[c];(a.length!==1||Object.keys(s).length!==1||!Array.isArray(f)||f.length<1||f.length>20)&&$t("NATIVE_DATA_POLICY_EXPRESSION_GROUP_INVALID",i),f.forEach((u,p)=>n(u,`${i}/${c}/${p}`,d+1))};return n(e,t,1),o}function Uo(e,t){Je(e,t);let o=(n,r)=>{let i=Ni(n,r);if(Array.isArray(i.allOf))return Wo(i.allOf.flatMap((d,s)=>o(d,`${r}/allOf/${s}`)),r);if(Array.isArray(i.anyOf)){let d=[[]];return i.anyOf.forEach((s,a)=>{let c=o(s,`${r}/anyOf/${a}`);d=Wo(d.flatMap(f=>c.map(u=>[...f,...u])),r)}),d}return[[i]]};return Wo(o(e,t),t)}function Wo(e,t){let o=e.reduce((n,r)=>n+r.length,0);return(e.length>50||o>100)&&$t("NATIVE_DATA_POLICY_EXPRESSION_EXPANSION_EXCEEDED",t),e}function Ni(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&$t("NATIVE_DATA_POLICY_EXPRESSION_NODE_INVALID",t),e}function $t(e,t){throw new pt(e,t)}var ce=class extends Error{constructor(o,n){super(`${o}: ${n}`);this.code=o;this.pointer=n}code;pointer},Ld=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Ti=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/;function Ri(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new ce("NATIVE_PARENT_READ_INVALID",t);let o=e;if(Object.keys(o).some(n=>!["resourceCode","subtableFieldCode"].includes(n))||typeof o.resourceCode!="string"||o.resourceCode.length>64||!Ld.test(o.resourceCode)||typeof o.subtableFieldCode!="string"||!Ti.test(o.subtableFieldCode))throw new ce("NATIVE_PARENT_READ_INVALID",t);return{resourceCode:o.resourceCode,subtableFieldCode:o.subtableFieldCode}}function Ci(e,t){return[...(Array.isArray(e.rules)?e.rules:[]).map((o,n)=>({rule:o,pointer:`${t}/rules/${n}`,base:!0})),...e.readExpression===void 0?[]:Je(e.readExpression,`${t}/readExpression`).map(o=>({...o,base:!1}))]}function Pt(e,t,o,n){let r=Ri(o,n),i=e.find(_=>_.code===r.resourceCode),d=e.find(_=>_.code===t),a=(Array.isArray(i?.schema?.fields)?i.schema.fields:[]).find(_=>_.code===r.subtableFieldCode);if(!i||!d||i.code===d.code||a?.type!=="subtable"||a.subtable?.resourceCode!==t)throw new ce("NATIVE_PARENT_READ_BINDING_INVALID",n);if(e.flatMap(_=>(Array.isArray(_.schema?.fields)?_.schema.fields:[]).filter(E=>E.type==="subtable"&&E.subtable?.resourceCode===t).map(E=>({resource:_,field:E}))).length!==1)throw new ce("NATIVE_PARENT_READ_PARENT_AMBIGUOUS",n);let f=a.subtable.foreignKey,p=(Array.isArray(d.schema?.fields)?d.schema.fields:[]).find(_=>_.code===f);if(typeof f!="string"||!Ti.test(f)||p?.type!=="uuid")throw new ce("NATIVE_PARENT_READ_FOREIGN_KEY_INVALID",n);return{...r,childResourceCode:t,foreignKey:f,...a.subtable.orderField?{orderField:a.subtable.orderField}:{}}}function Mo(e,t,o="/config/authz/dataPolicies"){let n=new Map;for(let[r,i]of t.entries())for(let d of Ci(i,`${o}/${r}`)){if(d.rule.parentRead===void 0)continue;if(Object.keys(d.rule).some(f=>!["parentRead","roleCodes"].includes(f)))throw new ce("NATIVE_PARENT_READ_RULE_KEYS_INVALID",d.pointer);if(d.base&&(i.operations?.length!==1||i.operations[0]!=="read"))throw new ce("NATIVE_PARENT_READ_READ_ONLY",d.pointer);if(e.find(f=>f.code===i.resourceCode)?.dataPolicyCode!==i.code)throw new ce("NATIVE_PARENT_READ_POLICY_BINDING_INVALID",d.pointer);let a=Pt(e,i.resourceCode,d.rule.parentRead,`${d.pointer}/parentRead`),c=n.get(i.resourceCode);if(c&&c!==a.resourceCode)throw new ce("NATIVE_PARENT_READ_PARENT_AMBIGUOUS",d.pointer);n.set(i.resourceCode,a.resourceCode)}for(let[r,i]of n)if(n.has(i))throw new ce("NATIVE_PARENT_READ_MULTI_HOP_FORBIDDEN",`${o}/${t.findIndex(d=>d.resourceCode===r)}`)}function wn(e){return Ci(e,"/dataPolicy").some(t=>t.rule.parentRead!==void 0)}var Si=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Di=(e,t)=>Object.keys(e).length===t.length&&Object.keys(e).every(o=>t.includes(o)),hi=e=>typeof e=="string"&&/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(e)&&e.length<=100,wi=e=>typeof e=="string"&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(e);function Bo(e){throw new Error(`OPENXIANGDA_WORKFLOW_STAGE_${e}`)}function Ko(e){(!Si(e)||!Di(e,["workflowCode","resourceCode","actor","runningNodeIds","allowedStatuses"])||!hi(e.workflowCode)||!hi(e.resourceCode)||!["initiator","reader"].includes(String(e.actor))||!Array.isArray(e.runningNodeIds)||e.runningNodeIds.length>32||new Set(e.runningNodeIds).size!==e.runningNodeIds.length||e.runningNodeIds.some(t=>typeof t!="string"||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(t))||!Array.isArray(e.allowedStatuses)||e.allowedStatuses.length>5||new Set(e.allowedStatuses).size!==e.allowedStatuses.length||e.allowedStatuses.some(t=>!["approved","rejected","cancelled","terminated","returned"].includes(t))||e.runningNodeIds.length+e.allowedStatuses.length===0)&&Bo("POLICY_INVALID")}function Fd(e){(!Si(e)||!Di(e,["instanceId","subjectRecordId","expectedInstanceSequence"])||!wi(e.instanceId)||!wi(e.subjectRecordId)||!Number.isSafeInteger(e.expectedInstanceSequence)||e.expectedInstanceSequence<0)&&Bo("GUARD_INVALID")}function xd(e,t,o){o?.some(n=>(n.kind==="record-match"||n.kind==="record-assert")&&n.resourceCode===e.resourceCode&&n.id.toLowerCase()===t.subjectRecordId.toLowerCase()&&n.assertions.some(r=>r.kind==="value"&&r.field==="revision"&&r.operator==="eq"&&Number.isSafeInteger(r.value)&&Number(r.value)>0))||Bo("SOURCE_GUARD_REQUIRED")}var jd={type:"object",additionalProperties:!1,required:["workflowCode","resourceCode","actor","runningNodeIds","allowedStatuses"],properties:{workflowCode:{type:"string",pattern:"^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$",maxLength:100},resourceCode:{type:"string",pattern:"^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$",maxLength:100},actor:{enum:["initiator","reader"]},runningNodeIds:{type:"array",maxItems:32,uniqueItems:!0,items:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$"}},allowedStatuses:{type:"array",maxItems:5,uniqueItems:!0,items:{enum:["approved","rejected","cancelled","terminated","returned"]}}},anyOf:[{properties:{runningNodeIds:{minItems:1}}},{properties:{allowedStatuses:{minItems:1}}}]};var mt=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n}code;pointer},fe=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},ki=(e,t)=>e===t||e==="*"||e.endsWith(":*")&&t.startsWith(e.slice(0,-1));function Go(e){let{policy:t,resource:o,baselineRoleCode:n,baselineCapabilities:r,pointer:i}=e,d=A=>A===void 0||A===!0||Array.isArray(A)&&A.length>0&&A.every(O=>typeof O=="string"&&O.length>0&&!e.baselineDeniedCapabilities?.some(b=>ki(b,O))&&r.some(b=>ki(b,O))),s=(A,O="")=>{throw new mt(A,`${i}/publicRead${O}`)},a=fe(t.publicRead);(!t.publicRead||Object.keys(a).length!==1||!Object.hasOwn(a,"fields")||!Array.isArray(a.fields)||a.fields.length<1||a.fields.length>1e3||a.fields.some(A=>typeof A!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(A))||new Set(a.fields).size!==a.fields.length)&&s("AUTHENTICATED_PUBLIC_READ_FIELDS_INVALID","/fields"),(!Array.isArray(t.operations)||t.operations.length!==1||t.operations[0]!=="read"||t.readExpression!==void 0||t.writeBoundary!==void 0)&&s("AUTHENTICATED_PUBLIC_READ_POLICY_NOT_READ_ONLY"),(!n||!o||o.code!==t.resourceCode||o.dataPolicyCode!==t.code||!d([fe(o.capabilities).read]))&&s("AUTHENTICATED_PUBLIC_READ_BASELINE_OR_RESOURCE_INVALID");let c=fe(o),f=fe(c.schema).fields;(!Array.isArray(f)||!f.length)&&s("AUTHENTICATED_PUBLIC_READ_RESOURCE_FIELDS_MISSING");let u=new Map(f.map(A=>[String(fe(A).code),fe(A)])),p=new Set(a.fields),_=fe(c.fieldPolicies);for(let A of p){let O=fe(u.get(A));(!u.has(A)||O.system===!0||fe(fe(c.surface).fields)[A]?.system===!0||qe.has(A))&&s("AUTHENTICATED_PUBLIC_READ_FIELD_NOT_DECLARED",`/fields/${A}`),(O.type==="subtable"||O.subtable!==void 0)&&s("AUTHENTICATED_PUBLIC_READ_SUBTABLE_UNSUPPORTED",`/fields/${A}`),d(fe(_[A]).read)||s("AUTHENTICATED_PUBLIC_READ_FIELD_NOT_BASELINE_READABLE",`/fields/${A}`)}let E=[...u.keys()].filter(A=>!p.has(A));for(let A of E)d(fe(_[A]).read)&&s("AUTHENTICATED_PUBLIC_READ_PRIVATE_FIELD_ACCESSIBLE",`/fields/${A}`);E.length&&St.some(A=>d(fe(_[A]).read))&&s("AUTHENTICATED_PUBLIC_READ_PRIVATE_HISTORY_ACCESSIBLE")}var zo=["exact-v1","nfkc-space-v1","nfkc-upper-ascii-v1"],rf=256,_t=class extends Error{constructor(o,n){super(`\u6761\u4EF6\u552F\u4E00\u952E\u58F0\u660E\u65E0\u6548\uFF1A${n}\uFF08${o}\uFF09`);this.pointer=o;this.reason=n}pointer;reason;code="NATIVE_UNIQUE_KEY_INVALID"},qo=e=>!!(e&&typeof e=="object"&&!Array.isArray(e)),ie=(e,t)=>{throw new _t(e,t)},Sn=(e,t)=>e<t?-1:e>t?1:0,vt=(e,t,o)=>{Object.keys(e).some(n=>!t.includes(n))&&ie(o,"\u4E0D\u652F\u6301\u672A\u77E5\u5C5E\u6027")};function Jo(e,t,o="/uniqueKeys"){if(e===void 0)return;if(!Array.isArray(e)||e.length>8)return ie(o,"\u6BCF\u8D44\u6E90\u6700\u591A 8 \u6761\u89C4\u5219");let n=new Map(t.map(i=>[i.code,i])),r=new Set;return e.map((i,d)=>{let s=`${o}/${d}`;if(!qo(i))return ie(s,"\u89C4\u5219\u5FC5\u987B\u662F\u5BF9\u8C61");if(vt(i,["code","fields","when"],s),typeof i.code!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(i.code)||i.code.length>20||r.has(i.code))return ie(`${s}/code`,"\u9700\u8981\u4E0D\u91CD\u590D\u4E14\u4E0D\u8D85\u8FC7 20 \u5B57\u7B26\u7684 lower-kebab-case \u6807\u8BC6");if(r.add(i.code),!Array.isArray(i.fields)||i.fields.length<1||i.fields.length>4)return ie(`${s}/fields`,"\u5FC5\u987B\u9009\u62E9 1 \u5230 4 \u4E2A\u5B57\u6BB5");let a=new Set,c=i.fields.map((_,E)=>{let A=`${s}/fields/${E}`;if(!qo(_))return ie(A,"\u5B57\u6BB5\u5FC5\u987B\u662F\u5BF9\u8C61");vt(_,["fieldCode","normalizer"],A);let O=n.get(_.fieldCode);if(!O||!["text.short","uuid","option.single","resource-ref.single","user.single"].includes(O.type)||a.has(_.fieldCode))return ie(`${A}/fieldCode`,"\u9700\u8981\u4E0D\u91CD\u590D\u7684\u77ED\u6587\u672C\u3001UUID\u3001\u5355\u9009\u3001\u5355\u8BB0\u5F55\u5F15\u7528\u6216\u5355\u4EBA\u5B57\u6BB5");a.add(_.fieldCode);let b=_.normalizer===void 0?"exact-v1":_.normalizer;return!zo.includes(b)||O.type!=="text.short"&&b!=="exact-v1"?ie(`${A}/normalizer`,"\u5F52\u4E00\u5316\u65B9\u5F0F\u4E0D\u652F\u6301\u6216\u4E0E\u5B57\u6BB5\u7C7B\u578B\u4E0D\u7B26"):{fieldCode:O.code,normalizer:b}}).sort((_,E)=>Sn(_.fieldCode,E.fieldCode)),f=i.when===void 0?[]:i.when;if(!Array.isArray(f)||f.length>4)return ie(`${s}/when`,"\u6700\u591A 4 \u4E2A\u5408\u53D6\u6761\u4EF6");let u=new Set,p=f.map((_,E)=>{let A=`${s}/when/${E}`;if(!qo(_))return ie(A,"\u6761\u4EF6\u5FC5\u987B\u662F\u5BF9\u8C61");let O=n.get(_.fieldCode);if(!O)return ie(`${A}/fieldCode`,"\u5B57\u6BB5\u4E0D\u5B58\u5728");let b;if(_.operator==="empty"||_.operator==="nonempty"){if(vt(_,["fieldCode","operator"],A),O.type!=="text.short")return ie(A,"\u7A7A\u503C\u6761\u4EF6\u4EC5\u652F\u6301\u77ED\u6587\u672C");b={fieldCode:O.code,operator:_.operator}}else if(_.operator==="in"||_.operator==="notIn"){vt(_,["fieldCode","operator","values"],A);let I=new Set((O.options??[]).map(T=>T.value));if(O.type!=="option.single"||!Array.isArray(_.values)||_.values.length<1||_.values.length>16||_.values.some(T=>typeof T!="string"||T.length<1||T.length>128||!I.has(T))||new Set(_.values).size!==_.values.length)return ie(A,"\u96C6\u5408\u6761\u4EF6\u9700\u8981 1 \u5230 16 \u4E2A\u4E0D\u91CD\u590D\u7684\u5DF2\u58F0\u660E\u5355\u9009\u503C");b={fieldCode:O.code,operator:_.operator,values:[..._.values].sort(Sn)}}else if(_.operator==="eq"||_.operator==="ne"){if(vt(_,["fieldCode","operator","value"],A),O.type!=="boolean"||typeof _.value!="boolean")return ie(A,"\u7B49\u503C\u6761\u4EF6\u4EC5\u652F\u6301\u5E03\u5C14\u5B57\u6BB5\u548C\u5E03\u5C14\u503C");b={fieldCode:O.code,operator:_.operator,value:_.value}}else return ie(`${A}/operator`,"\u53EA\u652F\u6301 empty\u3001nonempty\u3001in\u3001notIn \u548C\u5E03\u5C14 eq\u3001ne");let g=JSON.stringify(b);return u.has(g)?ie(A,"\u6761\u4EF6\u4E0D\u80FD\u91CD\u590D"):(u.add(g),b)}).sort((_,E)=>Sn(JSON.stringify(_),JSON.stringify(E)));return{code:i.code,fields:c,when:p}}).sort((i,d)=>Sn(i.code,d.code))}function Ho(e,t){let o=new Set(e.filter(n=>n.type==="user.single").map(n=>n.code));return t?.some(n=>n.fields.some(r=>o.has(r.fieldCode))||n.when?.some(r=>r.operator==="eq"||r.operator==="ne"))?"1.1.0":"1.0.0"}var Dn={type:"string",pattern:"^[A-Za-z_][A-Za-z0-9_]{0,62}$"},Wd={type:"array",maxItems:8,items:{type:"object",additionalProperties:!1,required:["code","fields"],properties:{code:{type:"string",maxLength:20,pattern:"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"},fields:{type:"array",minItems:1,maxItems:4,uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["fieldCode"],properties:{fieldCode:Dn,normalizer:{enum:[...zo]}}}},when:{type:"array",maxItems:4,uniqueItems:!0,items:{oneOf:[{type:"object",additionalProperties:!1,required:["fieldCode","operator"],properties:{fieldCode:Dn,operator:{enum:["empty","nonempty"]}}},{type:"object",additionalProperties:!1,required:["fieldCode","operator","values"],properties:{fieldCode:Dn,operator:{enum:["in","notIn"]},values:{type:"array",minItems:1,maxItems:16,uniqueItems:!0,items:{type:"string",minLength:1,maxLength:128}}}},{type:"object",additionalProperties:!1,required:["fieldCode","operator","value"],properties:{fieldCode:Dn,operator:{enum:["eq","ne"]},value:{type:"boolean"}}}]}}}}};var $i={"openxiangda.workflow.instance.completed.v2":"commit","openxiangda.workflow.instance.rejected.v2":"release","openxiangda.workflow.instance.withdrawn.v2":"release"};function Pi(e,t){let o=()=>{throw new Error("NATIVE_EVENT_DECIMAL_RESERVATION_INVALID")},n=p=>!p||typeof p!="object"||Array.isArray(p)?o():p,r=n(e);if(Object.keys(r).some(p=>!["resourceCode","workflowCode","outcomes"].includes(p))||typeof r.resourceCode!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(r.resourceCode)||typeof r.workflowCode!="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(r.workflowCode)||t.execution!==void 0||!Array.isArray(r.outcomes)||!r.outcomes.length||r.outcomes.length>3)return o();let i=t.resources.find(p=>p.code===r.resourceCode),d=t.reservations.find(p=>p.mode==="reserve"&&p.resourceCode===r.resourceCode),s=t.workflows.find(p=>p.code===r.workflowCode);if(!i||!d||!s||s.resourceCode!==i.code)return o();let a=i.fields.find(p=>p.code===d.statusFieldCode);if(a?.type!=="option.single")return o();let c=new Set(a.options?.map(p=>p.value)),f=new Set,u=r.outcomes.map(p=>{let _=n(p),E=_.eventType;return Object.keys(_).some(A=>!["eventType","mode","eligibleChildStatuses"].includes(A))||typeof E!="string"||!Object.prototype.hasOwnProperty.call($i,E)||!t.eventTypes.includes(E)||f.has(E)||_.mode!==$i[E]||!Array.isArray(_.eligibleChildStatuses)||!_.eligibleChildStatuses.length||_.eligibleChildStatuses.length>16||new Set(_.eligibleChildStatuses).size!==_.eligibleChildStatuses.length||_.eligibleChildStatuses.some(A=>typeof A!="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(A)||!c.has(A))?o():(f.add(E),{eventType:E,mode:_.mode,eligibleChildStatuses:[..._.eligibleChildStatuses].sort()})}).sort((p,_)=>p.eventType.localeCompare(_.eventType));return{resourceCode:r.resourceCode,workflowCode:r.workflowCode,outcomes:u}}function vi(e,t){let o=n=>Array.isArray(n)?n.filter(r=>r&&typeof r=="object"&&!Array.isArray(r)):[];return{eventTypes:Array.isArray(t.eventTypes)?t.eventTypes:[],execution:t.execution,resources:o(e.data?.resources).map(n=>({code:n.code,fields:o(n.schema?.fields).map(r=>({code:r.code,type:r.type,options:o(r.options).map(i=>({value:i.value}))}))})),reservations:o(e.backend?.operations).flatMap(n=>n.platformAccess?.decimalReservation?[n.platformAccess.decimalReservation]:[]),workflows:o(e.workflows?.definitions).map(n=>({code:n.definition?.code,resourceCode:n.definition?.subject?.resourceCode}))}}var kn=class extends Error{constructor(o,n){super(n);this.pointer=o}pointer;code="NATIVE_EVENT_ACTION_INVALID"};function Yo(e,t,o="/events/subscriptions"){if(e.execution===void 0)return;let n=(A,O)=>{throw new kn(`${o}${A}`,O)},r=(A,O,b)=>((!A||typeof A!="object"||Array.isArray(A)||Object.keys(A).some(g=>!b.includes(g)))&&n(O,"Invalid action object or unsupported property"),A),i=r(e.execution,"/execution",["kind","version","operations"]);(i.kind!=="native-data"||i.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(A=>!/^openxiangda\.data\.record\.(created|updated|deleted)\.v2$/.test(A)))&&n("/eventTypes","Native data actions require declared data events");let d=e.filter?.resourceCodes;(!Array.isArray(d)||!d.length||d.length>20)&&n("/filter/resourceCodes","Native actions require explicit source resources");let s=new Map(t.map(A=>[A.code,A])),a=d.map(A=>{let O=s.get(A);return O||n("/filter/resourceCodes","Unknown source resource"),new Set((O.schema?.fields||[]).map(b=>b.code))}),c=new Set(e.payload?.fields||[]),f=e.payload?.includeChanges===!0,u=(A,O)=>{let b=r(A,O,["source","path","value"]);if(b.source==="literal"){(!Object.hasOwn(b,"value")||Object.hasOwn(b,"path"))&&n(O,"Literal binding requires only value");let l;try{l=JSON.stringify(b.value)}catch{n(O,"Literal must be JSON")}return(l===void 0||Buffer.byteLength(l)>65536)&&n(O,"Literal is too large or not JSON"),{source:"literal",value:JSON.parse(l)}}(b.source!=="event"||typeof b.path!="string"||Object.hasOwn(b,"value"))&&n(O,"Expected a literal or event binding");let g=b.path.split(".");(g.length>8||g.some(l=>!/^[A-Za-z0-9_-]+$/.test(l)||["__proto__","prototype","constructor"].includes(l)))&&n(O,"Invalid event path");let I=/^data\.projection\.([A-Za-z][A-Za-z0-9_]{0,62})$/.exec(b.path),T=/^data\.changes\.([A-Za-z][A-Za-z0-9_]{0,62})\.(before|after)$/.exec(b.path);if(I||T){let l=(I||T)[1];a.some(y=>!y.has(l))&&n(O,"Source field must exist on every filtered resource"),c.add(l),T&&(f=!0)}else["id","time","type","subject","data.recordId","data.revision","data.operation","data.resourceCode"].includes(b.path)||n(O,"Event path is not part of the data event contract");return{source:"event",path:b.path}};(!Array.isArray(i.operations)||i.operations.length<1||i.operations.length>16)&&n("/execution/operations","Expected 1 to 16 operations");let p={},_=i.operations.map((A,O)=>{let b=`/execution/operations/${O}`,g=r(A,b,["operation","resourceCode","data","id","expectedRevision"]);["create","update","delete"].includes(g.operation)||n(b,"Unsupported Native operation");let I=s.get(g.resourceCode);I||n(b,"Unknown action target resource");let T=new Map((I.schema?.fields||[]).map(y=>[y.code,y])),l=g.data===void 0?{}:r(g.data,`${b}/data`,[...T.keys()]);return Object.keys(l).length>32&&n(b,"Maximum 32 mapped fields per operation"),g.operation==="create"&&(g.id!==void 0||g.expectedRevision!==void 0)&&n(b,"Create does not accept id or expectedRevision"),g.operation==="delete"&&g.data!==void 0&&n(b,"Delete does not accept data"),Object.keys(l).some(y=>T.get(y)?.type==="serial-number")&&n(b,"Generated fields cannot be assigned"),p[g.resourceCode]=Z(I),{operation:g.operation,resourceCode:g.resourceCode,...g.operation==="create"?{}:{id:u(g.id,`${b}/id`),expectedRevision:u(g.expectedRevision,`${b}/expectedRevision`)},...g.operation==="delete"?{}:{data:Object.fromEntries(Object.entries(l).map(([y,R])=>[y,u(R,`${b}/data/${y}`)]))}}});(c.size>32||[...c].some(A=>a.some(O=>!O.has(A))))&&n("/payload/fields","Payload must contain at most 32 declared source fields");let E={kind:"native-data",version:1,operations:_,resourceDigests:p};return Buffer.byteLength(JSON.stringify(E))>65536&&n("/execution","Action plan exceeds 64 KiB"),{execution:{...E,digest:Z(E)},payload:{includeChanges:f,fields:[...c].sort()}}}function xe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Zo(e,t){if(e?.instanceCommands===void 0)return[];let o=xe(e.instanceCommands);if(!o||!Object.keys(o).length||Object.keys(o).some(r=>!["withdraw","terminate"].includes(r)))return["WORKFLOW_INSTANCE_COMMAND_POLICIES_INVALID"];let n=[];for(let[r,i]of Object.entries(o)){let d=xe(i),s=r==="withdraw"?["beforeFact","reasonRequired"]:["beforeFact","capability"];if(!d||!Object.keys(d).length||Object.keys(d).some(a=>!s.includes(a))||Object.hasOwn(d,"reasonRequired")&&typeof d.reasonRequired!="boolean"){n.push(`WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID:${r}`);continue}if(r==="terminate"){let a=d.capability;(typeof a!="string"||a.length>255||!/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._-]+$/.test(a)||t&&(!a.startsWith(`app:${t.appCode}:`)||!t.capabilities.includes(a)))&&n.push("WORKFLOW_INSTANCE_TERMINATE_CAPABILITY_INVALID")}if(Object.hasOwn(d,"beforeFact")){let a=d.beforeFact,c=xe(e.inputSchema),f=xe(xe(c?.properties)?.[a]),u=xe(xe(e.subject)?.factProjection)?.[a],p=t?.fields.get(u);(typeof a!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(a)||!Array.isArray(c?.required)||!c.required.includes(a)||f?.type!=="string"||f?.format!=="date-time"||typeof u!="string"||t&&(p?.type!=="datetime"||p.nullable===!0))&&n.push(`WORKFLOW_INSTANCE_COMMAND_DEADLINE_FACT_INVALID:${r}`)}}return n}function Ud(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 Md(e){return e?.withdraw?.reasonRequired!==!1}function Xo(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,r,i,d,s]=t,a=t[8],c=new Date(Date.UTC(Number(o),Number(n),0)).getUTCDate();if(Number(n)<1||Number(n)>12||Number(r)<1||Number(r)>c||Number(i)>23||Number(d)>59||Number(s)>59||a!=="Z"&&(Number(a.slice(1,3))>23||Number(a.slice(4))>59))return null;let f=Date.parse(e);return Number.isFinite(f)?f:null}function Bd(e,t,o,n){let r=e?.[t];if(!r||r.beforeFact===void 0)return null;let i=r.beforeFact,d=xe(o),s=i&&d&&Object.hasOwn(d,i)?Xo(d[i]):null,a=n instanceof Date?n.getTime():Xo(n);return s===null||a===null||!Number.isFinite(a)?"WORKFLOW_V2_CANCELLATION_DEADLINE_INVALID":a<s?null:"WORKFLOW_V2_CANCELLATION_DEADLINE_PASSED"}var gt="openxiangda.workflow.step.requested.v2",tr=[gt,"openxiangda.workflow.step.result_received.v2","openxiangda.workflow.step.completed.v2","openxiangda.workflow.step.continuation_failed.v2"],$n=16384,Fi=2048,Kd="steps",nr=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,xi=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,He=new Set(["__proto__","prototype","constructor"]),K=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[Object.prototype,null].includes(Object.getPrototypeOf(e)),ji=e=>{try{let t=JSON.stringify(e);return t===void 0?1/0:new TextEncoder().encode(t).length}catch{return 1/0}},At=(e,t,o=0)=>{if(o>32)return!1;if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((i,d)=>At(i,t[d],o+1));if(!K(e)||!K(t))return!1;let n=Object.keys(e).filter(i=>e[i]!==void 0),r=Object.keys(t).filter(i=>t[i]!==void 0);return n.length===r.length&&n.every(i=>Object.hasOwn(t,i)&&At(e[i],t[i],o+1))};function Qo(e,t){let o=0,n=(r,i)=>++o>1e4||i>8?!1:r===null||typeof r=="boolean"||typeof r=="string"?!0:typeof r=="number"?Number.isFinite(r):Array.isArray(r)?r.length<=200&&r.every(d=>n(d,i+1)):K(r)&&Object.keys(r).length<=32&&Object.keys(r).every(d=>!He.has(d))&&Object.values(r).every(d=>n(d,i+1));return ji(e)<=t&&n(e,0)}function Wi(e){return!K(e)||Object.keys(e).some(t=>!["executionId","handlerVersion","inputDigest","expectedFactRevision","output","receipt"].includes(t))?!1:/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i.test(e.executionId||"")&&Number.isSafeInteger(e.handlerVersion)&&e.handlerVersion>=1&&e.handlerVersion<=1e6&&/^[a-f0-9]{64}$/.test(e.inputDigest||"")&&Number.isSafeInteger(e.expectedFactRevision)&&e.expectedFactRevision>=0&&K(e.output)&&Qo(e.output,$n)&&(e.receipt===void 0||K(e.receipt)&&Qo(e.receipt,Fi))}function Gd(e){return K(e)&&Object.keys(e).every(t=>["executionId","nodeId","handlerCode","handlerVersion","mode","dataTransaction","input","inputDigest","expectedFactRevision"].includes(t))&&typeof e.nodeId=="string"&&nr.test(e.nodeId)&&!He.has(e.nodeId)&&typeof e.handlerCode=="string"&&/^[a-z][a-z0-9-]{0,100}$/.test(e.handlerCode)&&e.handlerCode.endsWith(`-v${e.handlerVersion}`)&&["pure","reconciled-effect"].includes(e.mode)&&(e.dataTransaction===void 0||e.dataTransaction===!0&&e.mode==="reconciled-effect")&&Wi({executionId:e.executionId,handlerVersion:e.handlerVersion,inputDigest:e.inputDigest,expectedFactRevision:e.expectedFactRevision,output:e.input})}function Vt(e,t,o=$n){if(!Qo(t,o))return!1;let n=1e4,r=(i,d,s)=>{if(--n<0||s>8||!K(i))return!1;let a=d===null?"null":Array.isArray(d)?"array":typeof d=="number"&&Number.isSafeInteger(d)?"integer":typeof d,c=Array.isArray(i.type)?i.type:[i.type];if(!c.includes(a)&&!(a==="integer"&&c.includes("number"))||i.enum!==void 0&&(!Array.isArray(i.enum)||!i.enum.some(f=>At(f,d)))||Object.hasOwn(i,"const")&&!At(i.const,d))return!1;if(typeof d=="number")return Number.isFinite(d)&&(i.minimum===void 0||d>=i.minimum)&&(i.maximum===void 0||d<=i.maximum);if(typeof d=="string"){let f=Array.from(d).length;return(i.minLength===void 0||f>=i.minLength)&&(i.maxLength===void 0||f<=i.maxLength)}return Array.isArray(d)?d.length<=i.maxItems&&(i.minItems===void 0||d.length>=i.minItems)&&d.every(f=>r(i.items,f,s+1)):K(d)?!K(i.properties)||Object.keys(d).some(f=>He.has(f)||!Object.hasOwn(i.properties,f))||(Array.isArray(i.required)?i.required:[]).some(f=>!Object.hasOwn(d,f))||i.minProperties!==void 0&&Object.keys(d).length<i.minProperties||i.maxProperties!==void 0&&Object.keys(d).length>i.maxProperties?!1:Object.entries(d).every(([f,u])=>r(i.properties[f],u,s+1)):d===null||typeof d=="boolean"};return r(e,t,0)}function Ui(e){return typeof e=="string"&&e.length<=256&&e.split(".").length<=8&&e.split(".").every(t=>nr.test(t)&&!He.has(t))}function Lt(e){let t=0,o=(n,r)=>{if(!K(n)||r>6||++t>256||Object.keys(n).some(s=>!["type","title","description","properties","required","additionalProperties","items","maxItems","minItems","maxLength","minLength","minimum","maximum","enum","const","maxProperties","minProperties"].includes(s)))return!1;let i=Array.isArray(n.type)?n.type:[n.type];if(!i.length||i.length>2||i.some(s=>!["object","array","string","integer","number","boolean","null"].includes(s))||i.length>1&&(!i.includes("null")||new Set(i).size!==i.length))return!1;for(let s of["title","description"])if(n[s]!==void 0&&(typeof n[s]!="string"||n[s].length>2e3))return!1;for(let s of["minimum","maximum"])if(n[s]!==void 0&&(typeof n[s]!="number"||!Number.isFinite(n[s])))return!1;for(let[s,a]of[["maxItems",200],["minItems",200],["maxLength",16384],["minLength",16384],["maxProperties",32],["minProperties",32]])if(n[s]!==void 0&&(!Number.isSafeInteger(n[s])||n[s]<0||n[s]>a))return!1;for(let[s,a]of[["minimum","maximum"],["minItems","maxItems"],["minLength","maxLength"],["minProperties","maxProperties"]])if(n[s]!==void 0&&n[a]!==void 0&&n[s]>n[a])return!1;if(["properties","required","additionalProperties","maxProperties","minProperties"].some(s=>n[s]!==void 0)&&!i.includes("object")||["items","maxItems","minItems"].some(s=>n[s]!==void 0)&&!i.includes("array")||["maxLength","minLength"].some(s=>n[s]!==void 0)&&!i.includes("string")||["minimum","maximum"].some(s=>n[s]!==void 0)&&!i.some(s=>s==="integer"||s==="number")||n.enum!==void 0&&(!Array.isArray(n.enum)||!n.enum.length||n.enum.length>100)||i.includes("object")&&(!K(n.properties)||n.additionalProperties!==!1||Object.keys(n.properties).length>32||Object.keys(n.properties).some(s=>!xi.test(s)||He.has(s))||n.required!==void 0&&(!Array.isArray(n.required)||new Set(n.required).size!==n.required.length||n.required.some(s=>typeof s!="string"||!Object.hasOwn(n.properties,s)))||n.minProperties!==void 0&&n.minProperties>Object.keys(n.properties).length||n.maxProperties!==void 0&&n.maxProperties<(n.required?.length||0)||!Object.values(n.properties).every(s=>o(s,r+1)))||i.includes("array")&&(!Number.isSafeInteger(n.maxItems)||!o(n.items,r+1)))return!1;let d={...n};return delete d.enum,delete d.const,!(n.enum!==void 0&&(!n.enum.every(s=>Vt(d,s))||n.enum.some((s,a)=>n.enum.slice(0,a).some(c=>At(s,c))))||Object.hasOwn(n,"const")&&!Vt(d,n.const))};return K(e)&&e.type==="object"&&ji(e)<=$n&&o(e,0)}function Ft(e){let t=Object.fromEntries(Object.values(e.nodes||{}).filter(o=>o?.kind==="action").map(o=>[o.id,o.outputSchema]));return Object.keys(t).length?{...e.inputSchema,properties:{...e.inputSchema?.properties,steps:{type:"object",additionalProperties:!1,properties:t}}}:e.inputSchema||{}}function Mi(e,t){let o=e;for(let n of t.split(".")){if(!K(o?.properties)||!Object.hasOwn(o.properties,n))return;o=o.properties[n]}return K(o)?o:void 0}var Vi=(e,t)=>!!Mi(e,t);function qd(e){return K(e)&&Object.keys(e).every(t=>["version","mode","dataTransaction","inputSchema","outputSchema"].includes(t))&&Number.isSafeInteger(e.version)&&e.version>=1&&e.version<=1e6&&["pure","reconciled-effect"].includes(e.mode)&&(e.dataTransaction===void 0||e.dataTransaction===!0&&e.mode==="reconciled-effect")&&Lt(e.inputSchema)&&Lt(e.outputSchema)}function Li(e){return e.kind==="approval"?[e.onApprove,e.onReject]:e.kind==="condition"?[...Array.isArray(e.branches)?e.branches.map(t=>t.target):[],e.otherwise]:e.kind==="cc"||e.kind==="action"?[e.next]:[]}function er(e,t=0){return!K(e)||t>16?[]:e.op==="path"?typeof e.path=="string"?[e.path]:[]:["left","right","value"].flatMap(o=>er(e[o],t+1)).concat(Array.isArray(e.values)?e.values.flatMap(o=>er(o,t+1)):[])}function xt(e,t){if(!K(e)||!K(e.nodes))return["WORKFLOW_STEP_DEFINITION_INVALID"];let o=e.nodes,n=Object.entries(o).filter(([,s])=>s?.kind==="action");if(!n.length)return[];let r=[];Object.hasOwn(e.inputSchema?.properties||{},"steps")&&r.push("WORKFLOW_STEP_FACT_NAMESPACE_RESERVED");let i=Ft(e);for(let[s,a]of n){(Object.keys(a).some(u=>!["id","kind","title","next","handler","inputSchema","outputSchema","inputs"].includes(u))||a.id!==s||!nr.test(s)||He.has(s)||typeof a.title!="string"||!a.title.trim()||a.title.length>255||typeof a.next!="string"||!Object.hasOwn(o,a.next))&&r.push(`WORKFLOW_STEP_NODE_INVALID:${s}`);let c=a.handler;(!K(c)||Object.keys(c).some(u=>!["code","version","mode","dataTransaction"].includes(u))||!Number.isSafeInteger(c.version)||c.version<1||c.version>1e6||!/^[a-z][a-z0-9-]{0,100}$/.test(c.code||"")||!String(c.code).endsWith(`-v${c.version}`)||!["pure","reconciled-effect"].includes(c.mode)||c.dataTransaction!==void 0&&(c.dataTransaction!==!0||c.mode!=="reconciled-effect"))&&r.push(`WORKFLOW_STEP_HANDLER_INVALID:${s}`);let f=Lt(a.inputSchema);if((!f||!Lt(a.outputSchema))&&r.push(`WORKFLOW_STEP_SCHEMA_INVALID:${s}`),!K(a.inputs)||Object.keys(a.inputs).length>32){r.push(`WORKFLOW_STEP_INPUTS_INVALID:${s}`);continue}for(let u of Array.isArray(a.inputSchema?.required)?a.inputSchema.required:[])Object.hasOwn(a.inputs,u)||r.push(`WORKFLOW_STEP_INPUT_REQUIRED:${s}:${u}`);for(let[u,p]of Object.entries(a.inputs)){if(!xi.test(u)||He.has(u)||!Object.hasOwn(a.inputSchema?.properties||{},u)||!K(p)){r.push(`WORKFLOW_STEP_INPUT_INVALID:${s}:${u}`);continue}if(p.source==="literal")(!f||Object.keys(p).some(_=>!["source","value"].includes(_))||!Object.hasOwn(p,"value")||!Vt(a.inputSchema.properties[u],p.value))&&r.push(`WORKFLOW_STEP_LITERAL_INVALID:${s}:${u}`);else if(p.source!=="fact"||Object.keys(p).some(_=>!["source","path"].includes(_))||!Ui(p.path)||!Vi(i,p.path))r.push(`WORKFLOW_STEP_FACT_PATH_INVALID:${s}:${u}`);else if(f){let _=Mi(i,p.path),E=a.inputSchema.properties[u],A=Array.isArray(_.type)?_.type:[_.type],O=Array.isArray(E.type)?E.type:[E.type];A.some(b=>!O.includes(b)&&!(b==="integer"&&O.includes("number")))&&r.push(`WORKFLOW_STEP_FACT_TYPE_MISMATCH:${s}:${u}`)}}}let d=(s,a)=>{let c=new Set,f=[e.startAt||""];for(;f.length&&c.size<=200;){let u=f.shift();if(!(u===a||c.has(u)||!o[u])){if(u===s)return!0;c.add(u),f.push(...Li(o[u]))}}return!1};for(let[s,a]of Object.entries(o)){if(!K(a))continue;let c=a.kind==="action"?Object.values(a.inputs||{}).flatMap(u=>u?.source==="fact"?[u.path]:[]):(Array.isArray(a.branches)?a.branches:[]).flatMap(u=>er(u?.when)),f=t?.bindings?.[a.binding];f&&c.push(...[f.inputPath,f.departmentIdFrom,f.resourceIdFrom,f.scope?.valueFrom].filter(u=>typeof u=="string"));for(let u of c.filter(p=>typeof p=="string"&&p.startsWith("steps."))){let p=u.split(".")[1];(o[p]?.kind!=="action"||p===s||!Vi(i,u)||d(s,p))&&r.push(`WORKFLOW_STEP_OUTPUT_NOT_AVAILABLE:${s}:${u}`)}}if(t)for(let[,s]of n){let a=new Set,c=[s.next];for(;c.length&&a.size<=200;){let f=c.shift();if(a.has(f)||!K(o[f]))continue;a.add(f);let u=o[f];if(!(u.kind==="action"||u.kind==="end")){if(u.kind==="approval"){let p=t.bindings?.[u.binding];p&&["application_provider","initiator_select"].includes(p.provider)&&r.push(`WORKFLOW_STEP_NEXT_PROVIDER_REQUIRES_PREPARED_RESULT:${f}`);continue}c.push(...Li(u))}}}return[...new Set(r)]}function zd(e,t){let o={};for(let[n,r]of Object.entries(e.inputs)){let i=r.source==="literal"?r.value:r.path.split(".").reduce((d,s)=>K(d)&&Object.hasOwn(d,s)?d[s]:void 0,t);i!==void 0&&(o[n]=i)}if(!Vt(e.inputSchema,o))throw new Error("WORKFLOW_STEP_INPUT_SCHEMA_INVALID");return o}function or(e,t,o){let n=Pn(e),r=[];Object.keys(n).length&&!o&&r.push("WORKFLOW_STEP_BACKEND_REQUIRED");for(let i of Object.keys(n)){let d=t.find(s=>s.code===i);(!d||d.execution||d.action||!Array.isArray(d.eventTypes)||d.eventTypes.length!==1||d.eventTypes[0]!==gt||!K(d.filter)||Object.keys(d.filter).length!==1||!K(d.filter.workflowStep)||Object.keys(d.filter.workflowStep).length!==1||d.filter.workflowStep.handlerCode!==i||!K(d.payload)||d.payload.includeChanges!==!1||!Array.isArray(d.payload.fields)||d.payload.fields.length)&&r.push(`WORKFLOW_STEP_SUBSCRIPTION_INVALID:${i}`)}for(let i of t)(i.eventTypes?.includes(gt)&&!n[i.code]||i.filter?.workflowStep&&!n[i.code])&&r.push(`WORKFLOW_STEP_HANDLER_NOT_DECLARED:${i.code}`);return r}function Pn(e){let t={};for(let o of e){let n=xt(o);if(n.length)throw new Error(n.join("; "));for(let r of Object.values(o.nodes||{})){if(r.kind!=="action")continue;let i={version:r.handler.version,mode:r.handler.mode,...r.handler.dataTransaction?{dataTransaction:!0}:{},inputSchema:r.inputSchema,outputSchema:r.outputSchema},d=t[r.handler.code];if(d&&!At(d,i))throw new Error(`WORKFLOW_STEP_HANDLER_CONTRACT_CONFLICT:${r.handler.code}`);t[r.handler.code]=i}}return t}var pe=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Ye=(e,t)=>typeof e=="string"&&!!e.trim()&&e.length<=t,Jd=/^[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z][A-Za-z0-9_-]*){0,15}$/,rr=e=>typeof e=="string"&&e.length<=256&&Jd.test(e)&&!e.split(".").some(t=>["__proto__","prototype","constructor"].includes(t));function vn(e,t){let o=pe(e),n=!0;for(let r of t.split(".")){n&&=Array.isArray(o.required)&&o.required.includes(r);let i=pe(o.properties)[r];if(!i||typeof i!="object")return null;o=pe(i)}return{schema:o,required:n}}function ir(e){let t=new Set,o=[],n=2048,r=(i,d)=>{if(--n<0||d>20){o.push("WORKFLOW_EXPRESSION_BUDGET_EXCEEDED");return}let s=pe(i);if(s.op==="path")rr(s.path)?t.add(s.path):o.push("WORKFLOW_EXPRESSION_PATH_INVALID");else{if(s.op==="literal")return;if(s.op==="and"||s.op==="or")if(!Array.isArray(s.values)||!s.values.length||s.values.length>128)o.push("WORKFLOW_EXPRESSION_GROUP_INVALID");else for(let a of s.values){if(n<0)break;r(a,d+1)}else s.op==="not"||s.op==="exists"?r(s.value,d+1):["eq","neq","gt","gte","lt","lte","in","contains"].includes(String(s.op))?(r(s.left,d+1),r(s.right,d+1)):o.push("WORKFLOW_EXPRESSION_OPERATOR_INVALID")}};return r(e,0),{paths:[...t],errors:[...new Set(o)]}}function sr(e){if(e?.readability===void 0)return[];let t=[],o=Ft(e),n=pe(e.readability);(Object.keys(n).some(s=>!["variables","logic"].includes(s))||!Object.keys(n).length)&&t.push("WORKFLOW_READABILITY_INVALID");let r=pe(n.variables);n.variables!==void 0&&(typeof n.variables!="object"||Array.isArray(n.variables)||n.variables===null)&&t.push("WORKFLOW_VARIABLES_INVALID"),Object.keys(r).length>128&&t.push("WORKFLOW_VARIABLE_LIMIT_EXCEEDED");for(let[s,a]of Object.entries(r)){let c=pe(a);(!rr(s)||!vn(o,s))&&t.push(`WORKFLOW_VARIABLE_SOURCE_UNKNOWN:${s}`),(!Ye(c.label,160)||Object.keys(c).some(f=>!["label","unit","description"].includes(f))||c.unit!==void 0&&!Ye(c.unit,32)||c.description!==void 0&&!Ye(c.description,2e3))&&t.push(`WORKFLOW_VARIABLE_METADATA_INVALID:${s}`)}let i=n.logic===void 0?[]:n.logic;(!Array.isArray(i)||i.length>32)&&t.push("WORKFLOW_LOGIC_LIMIT_INVALID");let d=new Set;for(let s of Array.isArray(i)?i.slice(0,32):[]){let a=pe(s),c=String(a.code||"");e.approvedDelegation&&c==="kernel-approved-delegation"&&t.push("WORKFLOW_LOGIC_PLATFORM_CODE_RESERVED"),(!/^[a-z][a-z0-9-]{2,63}$/.test(c)||d.has(c)||!Ye(a.title,160)||!Ye(a.description,4e3)||Object.keys(a).some(f=>!["code","title","description","phase","nodeId","inputPaths","outputPaths","source"].includes(f)))&&t.push(`WORKFLOW_LOGIC_METADATA_INVALID:${c}`),d.add(c),(!["submission","node_input","completion"].includes(String(a.phase))||a.phase==="node_input"&&!pe(e.nodes)[String(a.nodeId)]||a.phase!=="node_input"&&a.nodeId!==void 0)&&t.push(`WORKFLOW_LOGIC_ANCHOR_INVALID:${c}`);for(let f of["inputPaths","outputPaths"]){let u=a[f];if(!(f==="outputPaths"&&u===void 0))if(!Array.isArray(u)||u.length>32||new Set(u).size!==u.length)t.push(`WORKFLOW_LOGIC_PATHS_INVALID:${c}:${f}`);else for(let p of u)(!rr(p)||!vn(o,p))&&t.push(`WORKFLOW_LOGIC_SOURCE_UNKNOWN:${c}:${String(p)}`)}if(a.source!==void 0){let f=pe(a.source);(!Ye(f.path,256)||String(f.path).startsWith("/")||String(f.path).includes("..")||String(f.path).includes("://")||!/^sha256:[a-f0-9]{64}$/.test(String(f.digest))||f.symbol!==void 0&&!Ye(f.symbol,160)||Object.keys(f).some(u=>!["path","symbol","digest"].includes(u)))&&t.push(`WORKFLOW_LOGIC_SOURCE_REFERENCE_INVALID:${c}`)}}for(let s of Object.values(pe(e.nodes))){let a=pe(s),c=Array.isArray(a.branches)?a.branches:[];for(let f of c){let u=ir(f.when);t.push(...u.errors.map(p=>`${p}:${a.id}`));for(let p of u.paths)vn(o,p)||t.push(`WORKFLOW_VARIABLE_SOURCE_UNKNOWN:${a.id}:${p}`)}}return[...new Set(t)]}function Hd(e,t){let o=Ft(e),n=[],r=new Map,i=[];for(let c of Object.values(e.nodes)){if(c.kind==="approval")for(let[f,u,p]of[["approve",c.onApprove,"\u540C\u610F"],["reject",c.onReject,"\u62D2\u7EDD"]])u&&n.push({id:`${c.id}:${f}`,from:c.id,to:u,kind:f,label:p,variablePaths:[]});if(c.kind==="approval")for(let f of new Set(c.returnTargets||[]))e.nodes[f]?.kind==="correction"&&n.push({id:`${c.id}:return:${f}`,from:c.id,to:f,kind:"return",label:"\u9000\u56DE\u53D1\u8D77\u4EBA\u8865\u6B63",variablePaths:[]});if(c.kind==="correction"&&c.next&&n.push({id:`${c.id}:resubmit`,from:c.id,to:c.next,kind:"resubmit",label:"\u91CD\u65B0\u63D0\u4EA4\uFF0C\u4ECE\u8D77\u70B9\u91CD\u7B97",variablePaths:[]}),c.kind==="cc"&&c.next&&n.push({id:`${c.id}:next`,from:c.id,to:c.next,kind:"next",label:"\u6284\u9001\u540E\u7EE7\u7EED",variablePaths:[]}),c.kind==="action"&&c.next){let f=Object.values(c.inputs||{}).flatMap(u=>u.source==="fact"?[u.path]:[]);for(let u of f)r.has(u)||r.set(u,new Set),r.get(u).add(c.id);n.push({id:`${c.id}:next`,from:c.id,to:c.next,kind:"next",label:"\u6210\u529F\u56DE\u6267\u540E\u7EE7\u7EED",variablePaths:f})}if(c.kind==="condition"){for(let[f,u]of(c.branches||[]).entries()){let p=ir(u.when);for(let _ of p.paths)r.has(_)||r.set(_,new Set),r.get(_).add(c.id);n.push({id:`${c.id}:branch:${f}`,from:c.id,to:u.target,kind:"branch",label:u.label||`\u6761\u4EF6 ${f+1}`,priority:f+1,expression:u.when,variablePaths:p.paths}),i.push(...p.errors.map(_=>({code:_,path:c.id})))}c.otherwise&&n.push({id:`${c.id}:default`,from:c.id,to:c.otherwise,kind:"default",label:"\u5747\u4E0D\u6EE1\u8DB3\u65F6",variablePaths:[]})}}let d=[...e.readability?.logic||[]];if(e.approvedDelegation){let c=e.approvedDelegation,f=c.confirmer==="initiator"?"\u7533\u8BF7\u4EBA\u672C\u4EBA":"\u6240\u9009\u4EE3\u7406\u4EBA";d.push({code:"kernel-approved-delegation",title:"\u6279\u51C6\u540E\u6574\u6279\u6388\u6743\u4EE3\u7406",phase:"completion",inputPaths:[c.requestsField],description:`\u6279\u51C6\u65F6\u6838\u9A8C${f}\u5728\u5F53\u524D\u9000\u56DE\u5468\u671F\u5B8C\u6210\u201C${e.nodes[c.confirmationNodeId]?.title||c.confirmationNodeId}\u201D\u7684\u4EBA\u5DE5\u786E\u8BA4\uFF1B\u968F\u540E\u91CD\u65B0\u6838\u9A8C\u53CC\u65B9\u5F53\u524D\u8D26\u53F7\u3001\u804C\u8D23\u3001\u4FEE\u8BA2\u3001\u8303\u56F4\u4E0E\u5B8C\u6574\u6709\u6548\u671F\uFF0C\u6574\u6279\u6388\u6743\uFF08\u6700\u591A${c.maxRequests}\u884C\uFF09\u3002\u4EFB\u4E00\u884C\u5931\u8D25\uFF0C\u6279\u51C6\u4E0E\u5168\u90E8\u6388\u6743\u4E00\u8D77\u56DE\u6EDA\uFF1B\u539F\u547D\u4EE4\u6062\u590D\u4E0D\u91CD\u65B0\u6FC0\u6D3B\u5DF2\u64A4\u9500\u6388\u6743\u3002`})}let a=[...new Set([...r.keys(),...Object.keys(e.readability?.variables||{}),...d.flatMap(c=>[...c.inputPaths,...c.outputPaths||[]])])].slice(0,128).map(c=>{let f=vn(o,c),u=e.readability?.variables?.[c],p=c.split("."),_=e.subject?.factProjection[p[0]],E=p[0]==="steps"?e.nodes[p[1]]:void 0;return f||i.push({code:"WORKFLOW_VARIABLE_SOURCE_UNKNOWN",path:c}),{path:c,label:u?.label||String(f?.schema.title||c),type:String(f?.schema.type||"unknown"),...u,required:f?.required||!1,usedBy:[...r.get(c)||[]],source:f&&E?.handler?{kind:"step_output",nodeId:E.id,handlerCode:E.handler.code,handlerVersion:E.handler.version}:f&&_&&e.subject?{kind:"subject_field",resourceCode:e.subject.resourceCode,fieldPath:[_,...p.slice(1)].join(".")}:{kind:f?"input":"unknown"}}});return{schemaVersion:"openxiangda.workflow-graph/v2",workflowCode:e.code,definitionDigest:t,startAt:e.startAt,fixedTopology:!0,branchStrategy:"first_match",nodes:Object.values(e.nodes).map(c=>({id:c.id,kind:c.kind,title:c.title||c.id,...c.binding?{binding:c.binding}:{},...c.mode?{mode:c.mode}:{},...c.outcome?{outcome:c.outcome}:{},...c.kind==="cc"?{emptyPolicy:c.emptyPolicy,notify:c.notify!==!1}:{},...c.kind==="approval"?{emptyPolicy:c.emptyPolicy||"block",initiatorApprovalPolicy:c.initiatorApprovalPolicy||"manual",...c.completionDeadline?{completionDeadline:{...c.completionDeadline}}:{}}:{},...c.kind==="action"&&c.handler?{businessStep:{handler:c.handler,inputs:c.inputs||{},outputPaths:Object.keys(pe(c.outputSchema).properties||{}).map(f=>`steps.${c.id}.${f}`)}}:{}})),edges:n,variables:a,logic:d,diagnostics:i}}function Bi(e,t=[]){let o=r=>{let i=t.find(d=>d.path===r)?.label;return i&&i!==r?i:void 0},n=o(e);if(n)return n;for(let r=e.lastIndexOf(".");r>0;r=e.lastIndexOf(".",r-1)){let i=o(e.slice(0,r));if(!i)continue;let d=e.slice(r+1);return d==="value"?`${i}\uFF08\u503C\uFF09`:d==="label"?`${i}\uFF08\u663E\u793A\u540D\u79F0\uFF09`:`${i}.${d}`}return e}function jt(e,t=[],o=0){if(!e||o>20)return"\u65E0\u6CD5\u8BC6\u522B\u7684\u6761\u4EF6";if(e.op==="path")return Bi(e.path,t);if(e.op==="literal")return JSON.stringify(e.value)??"\u7F3A\u503C";if(e.op==="and"||e.op==="or")return e.values.slice(0,128).map(d=>`\uFF08${jt(d,t,o+1)}\uFF09`).join(e.op==="and"?" \u4E14 ":" \u6216 ");if(e.op==="not"||e.op==="exists")return`${e.op==="not"?"\u4E0D\u6EE1\u8DB3":"\u5B58\u5728"}\uFF08${jt(e.value,t,o+1)}\uFF09`;if(!("left"in e))return"\u65E0\u6CD5\u8BC6\u522B\u7684\u6761\u4EF6";let n={eq:"=",neq:"\u2260",gt:">",gte:"\u2265",lt:"<",lte:"\u2264",in:"\u5C5E\u4E8E",contains:"\u5305\u542B"},r=e.left.op==="path"?e.left.path:void 0,i=r&&e.right.op==="literal"&&typeof e.right.value=="number"?t.find(d=>d.path===r)?.unit:void 0;return`${jt(e.left,t,o+1)} ${n[e.op]} ${jt(e.right,t,o+1)}${i?` ${i}`:""}`}function Ki(e,t=0){return!Array.isArray(e)||e.length>64||t>1?!1:e.every(o=>{if(!o||typeof o!="object"||Array.isArray(o)||o.readonlyWhen!==void 0)return!1;if(o.subtable!==void 0){let n=o.subtable;return n&&n.create===!1&&n.delete===!1&&n.reorder===!1&&Ki(n.fields,t+1)}return o.readonly===!0})}function Et(e){let t=[];for(let[o,n]of Object.entries(e?.nodes||{}))if(n.initiatorApprovalPolicy!==void 0){if(n.kind!=="approval"||!["manual","auto_approve"].includes(n.initiatorApprovalPolicy)){t.push(`WORKFLOW_INITIATOR_APPROVAL_POLICY_INVALID:${o}`);continue}n.initiatorApprovalPolicy==="auto_approve"&&((n.taskPageCode!==void 0&&(typeof n.taskPageCode!="string"||!Ki(e.taskPages?.[n.taskPageCode]?.fields))||[n.fieldPolicy?.default,...Object.values(n.fieldPolicy?.fields||{})].some(r=>r==="edit"||r==="edit_required"))&&t.push(`WORKFLOW_INITIATOR_APPROVAL_INPUT_REQUIRED:${o}`),n.operationPolicy?.approve?.commentRequired===!0&&t.push(`WORKFLOW_INITIATOR_APPROVAL_COMMENT_REQUIRED:${o}`))}return t}function Yd(e,t,o,n,r){return e.kind==="approval"&&e.initiatorApprovalPolicy==="auto_approve"&&Et({nodes:{node:e},...r?{taskPages:r}:{}}).length===0&&t!=="return_review"&&!!o&&n.user_id===o&&n.status==="active"&&n.participant_kind==="primary"&&["resolution","resolution_retry"].includes(n.source||"")&&!n.source_participant_id&&!n.delegate_authorization_id}var _f=8,Xd={type:"array",minItems:2,maxItems:8,uniqueItems:!0,items:{type:"string",maxLength:128,pattern:"^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$"}};function Wt(e){if(e.roleCodes===void 0)return[];let t=e.roleCodes;if(!["app_role","app_role_in_scope"].includes(e.provider||"")||e.roleCode!==void 0||e.candidateField!==void 0||!Array.isArray(t)||t.length<2||t.length>8||new Set(t).size!==t.length||t.some(o=>typeof o!="string"||o.length>128||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(o)))return["WORKFLOW_V2_BINDING_ROLE_UNION_INVALID"];if(e.provider==="app_role_in_scope"){let o=e.scope,n=typeof o?.value=="string"&&o.value.length>0&&o.value.length<=255&&o.valueFrom===void 0,r=typeof o?.valueFrom=="string"&&o.valueFrom.length<=255&&/^[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z][A-Za-z0-9_-]*)*$/.test(o.valueFrom)&&!o.valueFrom.split(".").some(i=>["__proto__","prototype","constructor"].includes(i))&&o.value===void 0;if(!o||typeof o!="object"||Array.isArray(o)||Object.keys(o).some(i=>!["dimension","value","valueFrom"].includes(i))||typeof o.dimension!="string"||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(o.dimension)||!n&&!r)return["WORKFLOW_V2_BINDING_ROLE_UNION_SCOPE_INVALID"]}else if(e.scope!==void 0)return["WORKFLOW_V2_BINDING_ROLE_UNION_SCOPE_INVALID"];return[]}function Zd(e){return e.roleCodes?[...e.roleCodes]:e.roleCode?[e.roleCode]:[]}function ar(e){return e.some(t=>Object.values(t.binding.bindings).some(o=>o.roleCodes!==void 0))}function dr(e){if(e.selectedInputPath===void 0)return[];let t=e.selectedInputPath;return!["app_role","app_role_in_scope"].includes(e.provider||"")||e.candidateField!==void 0||e.inputPath!==void 0||e.routing!==void 0||e.roleCode===void 0&&e.roleCodes===void 0||typeof t!="string"||t.length>255||!/^[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z][A-Za-z0-9_-]*)*$/.test(t)||t.split(".").some(o=>["__proto__","constructor","prototype"].includes(o))?["WORKFLOW_V2_ROLE_INPUT_SELECTION_INVALID"]:[]}function cr(e){return e.some(t=>Object.values(t.binding.bindings).some(o=>o.selectedInputPath!==void 0))}var Gi=20,qi=200,zi=["fixed_users","initiator","input_users","form_field_users","app_role","app_role_in_scope","previous_node_actor"];function Vn(e,t){let o=[];for(let[n,r]of Object.entries(e?.nodes||{})){if(r?.kind!=="cc"||((Object.keys(r).some(a=>!["id","kind","title","binding","next","emptyPolicy","notify","administration"].includes(a))||typeof r.title!="string"||!r.title.trim()||r.title.length>255||typeof r.binding!="string"||!r.binding.trim()||r.binding.length>255||typeof r.next!="string"||!r.next.trim()||!e.nodes?.[r.next]||!["block","skip"].includes(r.emptyPolicy)||r.notify!==void 0&&typeof r.notify!="boolean")&&o.push(`WORKFLOW_CC_NODE_INVALID:${n}`),!t))continue;let i=t.bindings?.[r.binding];if(!i){o.push(`WORKFLOW_CC_BINDING_NOT_FOUND:${n}`);continue}zi.includes(i.provider)||o.push(`WORKFLOW_CC_PROVIDER_INVALID:${n}`);let d=i.min??1,s=i.max??20;(!Number.isSafeInteger(d)||!Number.isSafeInteger(s)||d<1||s<d||s>200||i.provider==="fixed_users"&&(!Array.isArray(i.users)||!i.users.length||i.users.length>s))&&o.push(`WORKFLOW_CC_RECIPIENT_LIMIT_INVALID:${n}`)}return[...new Set(o)]}var Fn=["approve","reject","return","transfer","delegate","add_assignee"],xn=["fixed_users","app_role","app_role_in_scope"],Qd=["single","any","all","sequence"],je=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Xe=(e,t)=>Object.keys(e).every(o=>t.includes(o)),Ln=(e,t,o)=>Array.isArray(e)&&e.length>0&&e.length<=o&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n));function It(e){return e.allowedOperations||[...Fn]}function Ji(e,t){return t?.commentRequired??e==="reject"}function Hi(e,t){return!["transfer","delegate","add_assignee","return"].includes(e)||t?.reasonRequired!==!1}function Yi(e,t,o={},n=!1){return!(!je(e)||!Object.keys(e).length||!Xe(e,n?["enabled","label","commentRequired","reasonRequired"]:["label","commentRequired","reasonRequired"])||e.label!==void 0&&(typeof e.label!="string"||!e.label.trim()||e.label.length>40||/[\u0000-\u001f\u007f]/.test(e.label))||e.enabled!==void 0&&(typeof e.enabled!="boolean"||["approve","reject"].includes(t)&&!e.enabled)||e.commentRequired!==void 0&&(typeof e.commentRequired!="boolean"||!["approve","reject"].includes(t)||n&&Ji(t,o)&&!e.commentRequired)||e.reasonRequired!==void 0&&(typeof e.reasonRequired!="boolean"||!["transfer","delegate","add_assignee","return"].includes(t)||n&&Hi(t,o)&&!e.reasonRequired))}function jn(e,t){let o=[];for(let[n,r]of Object.entries(e?.nodes||{})){if(!je(r))continue;let i=r.administration,d=r.operationPolicy;if(r.kind==="cc"){(d!==void 0||i!==void 0&&(!je(i)||!Xe(i,["assigneeProviders"])))&&o.push(`WORKFLOW_NODE_ADMINISTRATION_INVALID:${n}`),i?.assigneeProviders!==void 0&&!Ln(i.assigneeProviders,xn,3)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_PROVIDERS_INVALID:${n}`),i?.assigneeProviders?.includes("app_role_in_scope")&&t&&!t.bindings[r.binding||""]?.scope&&o.push(`WORKFLOW_NODE_ADMINISTRATION_SCOPE_REQUIRED:${n}`);continue}if(r.kind!=="approval"){(i!==void 0||d!==void 0)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_APPROVAL_REQUIRED:${n}`);continue}if(d!==void 0&&(!je(d)||Object.keys(d).length>8||Object.entries(d).some(([a,c])=>!Fn.includes(a)||!It(r).includes(a)||!Yi(c,a)))&&o.push(`WORKFLOW_NODE_OPERATION_POLICY_INVALID:${n}`),i===void 0)continue;if(!je(i)||!Xe(i,["modes","assigneeProviders","operations"])){o.push(`WORKFLOW_NODE_ADMINISTRATION_INVALID:${n}`);continue}i.modes!==void 0&&(!Ln(i.modes,Qd,4)||!i.modes.includes(r.mode))&&o.push(`WORKFLOW_NODE_ADMINISTRATION_MODES_INVALID:${n}`),i.assigneeProviders!==void 0&&!Ln(i.assigneeProviders,xn,3)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_PROVIDERS_INVALID:${n}`);let s=t?.bindings[r.binding||""];s&&Array.isArray(i.assigneeProviders)&&i.assigneeProviders.includes("app_role_in_scope")&&!s.scope&&o.push(`WORKFLOW_NODE_ADMINISTRATION_SCOPE_REQUIRED:${n}`),i.operations!==void 0&&(!Ln(i.operations,Fn,8)||i.operations.some(a=>!It(r).includes(a)))&&o.push(`WORKFLOW_NODE_ADMINISTRATION_OPERATIONS_INVALID:${n}`)}return o}function ec(e,t,o,n){let r=[];if(!e||!je(o)||!Object.keys(o).length||!Xe(o,["title","description","assignee","mode","operations"]))return["WORKFLOW_V2_NODE_CONFIGURATION_PATCH_INVALID"];let i=o;for(let s of["title","description"])i[s]!==void 0&&(typeof i[s]!="string"||i[s].length>(s==="title"?255:1e3)||s==="title"&&!i[s].trim())&&r.push("WORKFLOW_V2_NODE_CONFIGURATION_PATCH_INVALID");let d=e.administration;if(i.mode!==void 0&&(e.kind!=="approval"||!d?.modes?.includes(i.mode))&&r.push("WORKFLOW_V2_NODE_CONFIGURATION_MODE_READONLY"),i.operations!==void 0&&(e.kind!=="approval"||!je(i.operations)||!Object.keys(i.operations).length||Object.keys(i.operations).length>8||Object.entries(i.operations).some(([s,a])=>!d?.operations?.includes(s)||!It(e).includes(s)||!Yi(a,s,e.operationPolicy?.[s],!0)))&&r.push("WORKFLOW_V2_NODE_CONFIGURATION_OPERATION_INVALID"),i.assignee!==void 0){let s=i.assignee,a=d?.assigneeProviders||(e.kind==="approval"&&t&&xn.includes(t.provider)?[t.provider]:[]);if(t?.selectedInputPath&&!["app_role","app_role_in_scope"].includes(s?.provider||"")&&r.push("WORKFLOW_V2_NODE_CONFIGURATION_PROVIDER_READONLY"),!je(s)||!["approval","cc"].includes(e.kind)||!a.includes(s.provider)||s.provider==="app_role_in_scope"&&!t?.scope)r.push("WORKFLOW_V2_NODE_CONFIGURATION_PROVIDER_READONLY");else if(s.provider==="fixed_users"){let c=e.kind==="cc"?t?.min??1:e.emptyPolicy==="skip"?0:1,f=e.kind==="cc"?Math.min(t?.max??20,200):200;(!Xe(s,["provider","users"])||!Array.isArray(s.users)||s.users.length<c||s.users.length>f||new Set(s.users).size!==s.users.length||s.users.some(u=>typeof u!="string"||!u.trim()||u.length>255))&&r.push("WORKFLOW_V2_NODE_CONFIGURATION_USERS_INVALID")}else s.roleCodes!==void 0?(!Xe(s,["provider","roleCodes"])||Wt({...s,...s.provider==="app_role_in_scope"?{scope:t?.scope}:{}}).length)&&r.push("WORKFLOW_V2_NODE_CONFIGURATION_ROLE_INVALID"):(!Xe(s,["provider","roleCode"])||typeof s.roleCode!="string"||!/^[a-z][a-z0-9_-]{0,127}$/.test(s.roleCode))&&r.push("WORKFLOW_V2_NODE_CONFIGURATION_ROLE_INVALID")}return r.push(...Et({nodes:{node:{...e,operationPolicy:lr(e,i).operationPolicy}},...n?{taskPages:n}:{}})),e.completionDeadline&&lr(e,i).operationPolicy.approve?.commentRequired===!0&&r.push("WORKFLOW_COMPLETION_DEADLINE_INPUT_REQUIRED:node"),r}function lr(e,t){let o=Object.fromEntries(It(e).flatMap(n=>{let r=n,i=t?.operations?.[r],d={...e.operationPolicy?.[r],...i?.label!==void 0?{label:i.label}:{},...i?.commentRequired!==void 0?{commentRequired:i.commentRequired}:{},...i?.reasonRequired!==void 0?{reasonRequired:i.reasonRequired}:{}};return Object.keys(d).length?[[r,d]]:[]}));return{mode:t?.mode||e.mode,initiatorApprovalPolicy:e.initiatorApprovalPolicy||"manual",allowedOperations:It(e).filter(n=>t?.operations?.[n]?.enabled!==!1),operationPolicy:o,fieldPolicy:{default:e.fieldPolicy?.default||"readonly",fields:{...e.fieldPolicy?.fields}}}}var ur=["fixed_users","input_users","form_field_users","app_role","app_role_in_scope"];function Wn(e,t){let o=[];for(let[n,r]of Object.entries(e?.nodes||{}))r.kind==="cc"||r.emptyPolicy===void 0||(r.kind!=="approval"||!["block","skip"].includes(r.emptyPolicy)?o.push(`WORKFLOW_APPROVAL_EMPTY_POLICY_INVALID:${n}`):r.emptyPolicy==="skip"&&t&&!ur.includes(t.bindings?.[r.binding||""]?.provider)&&o.push(`WORKFLOW_APPROVAL_EMPTY_PROVIDER_UNSUPPORTED:${n}`));return o}function tc(e,t){return e.kind==="approval"&&e.emptyPolicy==="skip"&&t?.emptyResult==="no_candidates"&&ur.includes(t.provider)&&Array.isArray(t.candidates)&&t.candidates.length===0&&Array.isArray(t.selected)&&t.selected.length===0&&Array.isArray(t.warnings)&&t.warnings.length===0}function fr(e,t){let o=Object.values(e.nodes||{}).filter(n=>n.binding===t);return o.length>0&&o.every(n=>n.kind==="approval"&&n.emptyPolicy==="skip")}function Xi(e,t=0){return!Array.isArray(e)||e.length>64||t>1?!0:e.some(o=>!o||typeof o!="object"||Array.isArray(o)||o.required===!0||o.requiredWhen!==void 0||o.subtable!==void 0&&(!o.subtable||Xi(o.subtable.fields,t+1)))}function nc(e){let t=e.afterSeconds;return`\u8FDB\u5165\u540E ${t%86400===0?`${t/86400} \u5929`:t%3600===0?`${t/3600} \u5C0F\u65F6`:t%60===0?`${t/60} \u5206\u949F`:`${t} \u79D2`}\u672A\u5B8C\u6210\uFF0C\u81EA\u52A8\u540C\u610F`}function pr(e){let t=[];for(let[o,n]of Object.entries(e?.nodes||{})){if(!n||typeof n!="object"||n.completionDeadline===void 0)continue;let r=n.completionDeadline;if(n.kind!=="approval"||!r||typeof r!="object"||Array.isArray(r)||Object.keys(r).length!==2||Object.keys(r).some(d=>!["afterSeconds","action"].includes(d))||r.action!=="approve"||!Number.isInteger(r.afterSeconds)||r.afterSeconds<1||r.afterSeconds>2592e3){t.push(`WORKFLOW_COMPLETION_DEADLINE_INVALID:${o}`);continue}n.allowedOperations&&!n.allowedOperations.includes("approve")&&t.push(`WORKFLOW_COMPLETION_DEADLINE_APPROVE_UNAVAILABLE:${o}`);let i=n.taskPageCode?e.taskPages?.[n.taskPageCode]:void 0;(n.taskPageCode&&(!i||Xi(i.fields))||[n.fieldPolicy?.default,...Object.values(n.fieldPolicy?.fields||{})].includes("edit_required")||n.operationPolicy?.approve?.commentRequired===!0||e.commandHandlers?.approve!==void 0)&&t.push(`WORKFLOW_COMPLETION_DEADLINE_INPUT_REQUIRED:${o}`)}return t}var Zi="openxiangda.workflow-rejection-notification/v1",Tf=4096;function Qi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function yt(e,t){return typeof e=="string"&&e.trim().length>0&&e.length<=t}function mr(e,t){return Object.keys(e).sort().join(",")===t.sort().join(",")}function _r(e){let t=e?.rejectionNotification;return t===void 0?[]:!Qi(t)||!mr(t,["recipient","title","summary"])||t.recipient!=="record_last_modifier"||!yt(t.title,160)||!yt(t.summary,500)?["WORKFLOW_REJECTION_NOTIFICATION_INVALID"]:yt(e.subject?.resourceCode,63)?[]:["WORKFLOW_REJECTION_NOTIFICATION_SUBJECT_REQUIRED"]}function oc(e){if(!Qi(e)||e.schemaVersion!==Zi||e.recipient!=="record_last_modifier"||!yt(e.title,160)||!yt(e.summary,500))return!1;let t=["schemaVersion","recipient","title","summary","status","sourceRevision"];if(e.status==="ready"){if(!mr(e,[...t,"userId"])||!yt(e.userId,255)||!Number.isSafeInteger(e.sourceRevision)||Number(e.sourceRevision)<1)return!1}else if(e.status==="skipped"){if(!mr(e,[...t,"reason"])||!["record_missing","modifier_missing","modifier_ineligible"].includes(String(e.reason))||(e.reason==="record_missing"?e.sourceRevision!==null:!Number.isSafeInteger(e.sourceRevision)||Number(e.sourceRevision)<1))return!1}else return!1;return new TextEncoder().encode(JSON.stringify(e)).byteLength<=4096}function gr(e,t){let o=e.commandHandlers;if(o===void 0)return[];if(!o||typeof o!="object"||Array.isArray(o)||!Object.keys(o).length||Object.keys(o).some(r=>!["approve","reject","withdraw","resubmit"].includes(r)))return["WORKFLOW_BUSINESS_COMMAND_HANDLERS_INVALID"];let n=[];o.resubmit&&!Object.values(e.nodes||{}).some(r=>r.kind==="correction")&&n.push("WORKFLOW_BUSINESS_CORRECTION_REQUIRED");for(let[r,i]of Object.entries(o)){if(!i||typeof i!="object"||Array.isArray(i)||Object.keys(i).some(s=>!["operationCode","transitionPolicy","derivedSubjectFields"].includes(s))||i.transitionPolicy!==void 0&&(r!=="approve"||i.transitionPolicy!=="workflow")||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(i.operationCode||"")){n.push("WORKFLOW_BUSINESS_COMMAND_HANDLER_INVALID");continue}if(i.derivedSubjectFields!==void 0){let s=i.derivedSubjectFields,a=new Set(Object.values(e.subject?.factProjection||{}));(r!=="resubmit"||!Array.isArray(s)||s.length<1||s.length>32||new Set(s).size!==s.length||s.some(c=>typeof c!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(c)||!a.has(c)||qe.has(c)||["createdBy","updatedBy","createdAt","updatedAt"].includes(c)||Object.values(e.taskPages||{}).some(f=>f.fields?.some(u=>u.code===c&&u.readonly!==!0))))&&n.push("WORKFLOW_CORRECTION_DERIVED_SUBJECT_FIELDS_INVALID")}if(!t)continue;let d=t.find(s=>s.code===i.operationCode);if(!d){n.push("WORKFLOW_BUSINESS_COMMAND_OPERATION_MISSING");continue}(d.method!=="POST"||d.browser?.exposure!=="authenticated"||d.browser.behavior!=="controlled"||d.browser.idempotency!=="required"||d.browser.fileIntent||d.browser.subject?.resourceCode!==e.subject?.resourceCode||d.browser.subject?.inputField!=="recordId"||!d.platformAccess?.workflow?.codes?.includes(e.code)||!d.platformAccess.workflow.businessCommands?.includes(r))&&n.push("WORKFLOW_BUSINESS_COMMAND_OPERATION_INVALID")}return["approve","reject","withdraw"].some(r=>Object.hasOwn(o,r))&&Object.values(e.nodes||{}).some(r=>r.kind==="approval"&&(r.emptyPolicy==="skip"||r.initiatorApprovalPolicy==="auto_approve"))&&n.push("WORKFLOW_BUSINESS_COMMAND_AUTOMATIC_DECISION_FORBIDDEN"),[...new Set(n)]}var rc={type:"object",additionalProperties:!1,required:["workflowCode","target","recordId","expectedRevision","commandToken","idempotencyKey","input"],properties:{workflowCode:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_-]{0,127}$"},target:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","id","command"],properties:{kind:{const:"task"},id:{type:"string",format:"uuid"},command:{enum:["approve","reject","resubmit"]}}},{type:"object",additionalProperties:!1,required:["kind","id","command"],properties:{kind:{const:"instance"},id:{type:"string",format:"uuid"},command:{const:"withdraw"}}}]},recordId:{type:"string",format:"uuid"},expectedRevision:{type:"integer",minimum:1},commandToken:{type:"string",pattern:"^[A-Za-z0-9_-]{43}$"},idempotencyKey:{type:"string",minLength:1,maxLength:128},input:{type:"object",maxProperties:64}}};var es=["fixed_users","initiator","app_role","app_role_in_scope"],ic=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function Un(e,t){let o=e?.launchPreflight;if(o===void 0)return[];if(!ic(o)||Object.keys(o).join(",")!=="requiredApprovalNodes"||!Array.isArray(o.requiredApprovalNodes)||o.requiredApprovalNodes.length<1||o.requiredApprovalNodes.length>20||new Set(o.requiredApprovalNodes).size!==o.requiredApprovalNodes.length||o.requiredApprovalNodes.some(r=>typeof r!="string"||!/^[A-Za-z][A-Za-z0-9_-]{0,127}$/.test(r)))return["WORKFLOW_LAUNCH_PREFLIGHT_INVALID"];let n=[];for(let r of o.requiredApprovalNodes){let i=e.nodes?.[r];if(!i||i.kind!=="approval"){n.push(`WORKFLOW_LAUNCH_PREFLIGHT_NODE_INVALID:${r}`);continue}if(!t)continue;let d=t.bindings?.[i.binding||""];(!d||!es.includes(d.provider)||d.candidateField!==void 0)&&n.push(`WORKFLOW_LAUNCH_PREFLIGHT_PROVIDER_UNSUPPORTED:${r}`)}return n}var Ar=e=>!!e&&typeof e=="object"&&!Array.isArray(e),sc=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,ns=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,ts=/^membership:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Sf=500,Df=262144;function Er(e){if(e?.approvedDelegation===void 0)return[];let t=e.approvedDelegation;if(!Ar(t)||Object.keys(t).some(a=>!["confirmationNodeId","confirmer","requestsField","maxRequests"].includes(a))||!ns.test(t.confirmationNodeId||"")||!["initiator","delegate"].includes(t.confirmer)||!sc.test(t.requestsField||"")||!Number.isSafeInteger(t.maxRequests)||t.maxRequests<1||t.maxRequests>500)return["WORKFLOW_APPROVED_DELEGATION_POLICY_INVALID"];let o=[],n=e.nodes?.[t.confirmationNodeId];(!n||n.kind!=="approval"||n.mode!=="single"||n.emptyPolicy==="skip"||n.initiatorApprovalPolicy==="auto_approve"||n.completionDeadline||n.administration?.assigneeProviders?.length||n.administration?.modes?.some(a=>a!=="single")||n.allowedOperations?.some(a=>["transfer","delegate","add_assignee","admin_override"].includes(a)))&&o.push("WORKFLOW_APPROVED_DELEGATION_CONFIRMATION_INVALID");let r=e.inputSchema?.properties?.[t.requestsField];(!r||r.type!=="array"||!Number.isSafeInteger(r.maxItems)||r.maxItems<1||r.maxItems>t.maxRequests||!r.items||r.items.type!=="object"||r.items.additionalProperties!==!1||!e.subject?.factProjection?.[t.requestsField])&&o.push("WORKFLOW_APPROVED_DELEGATION_REQUEST_SCHEMA_INVALID"),Object.values(e.nodes||{}).some(a=>a.kind==="end"&&a.outcome==="approved")||o.push("WORKFLOW_APPROVED_DELEGATION_APPROVED_END_REQUIRED");let d=[e.startAt],s=new Set;for(;d.length;){let a=d.pop();if(a===t.confirmationNodeId||s.has(a))continue;s.add(a);let c=e.nodes?.[a];c&&(c.kind==="end"&&c.outcome==="approved"&&o.push("WORKFLOW_APPROVED_DELEGATION_CONFIRMATION_BYPASS"),c.kind==="approval"&&d.push(c.onApprove,c.onReject),c.kind==="condition"&&d.push(c.otherwise,...(c.branches||[]).map(f=>f.target)),(c.kind==="cc"||c.kind==="action")&&d.push(c.next))}return[...new Set(o)]}function ac(e,t){let o=t?.data?.[e.requestsField],n=()=>{throw new Error("WORKFLOW_APPROVED_DELEGATION_REQUEST_INVALID")};(!Array.isArray(o)||!o.length||o.length>e.maxRequests||o.length>500||new TextEncoder().encode(JSON.stringify(o)).byteLength>262144)&&n();let r=["key","delegatorRoleSubjectKey","delegatorRoleSubjectRevision","delegate","delegateRoleSubjectKey","expectedDelegateRevision","workflowCode","nodeId","validFrom","validTo","reason"],i=(a,c)=>typeof a=="string"&&a.trim().length>0&&a.length<=c,d=a=>{if(typeof a!="string")return!1;let c=/^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)(?:\.\d{1,3})?(?:Z|[+-](\d\d):(\d\d))$/.exec(a);if(!c)return!1;let[,f,u,p,_,E,A,O,b]=c,g=Number(f),I=Number(u),T=Number(p),y=[31,g%4===0&&(g%100!==0||g%400===0)?29:28,31,30,31,30,31,31,30,31,30,31];return I>=1&&I<=12&&T>=1&&T<=y[I-1]&&Number(_)<=23&&Number(E)<=59&&Number(A)<=59&&(O===void 0||Number(O)<=23&&Number(b)<=59)&&Number.isFinite(Date.parse(a))},s=o.map(a=>Ar(a)?((Object.keys(a).some(c=>!r.includes(c))||!i(a.delegatorRoleSubjectKey,255)||!ts.test(a.delegatorRoleSubjectKey)||!i(a.delegateRoleSubjectKey,255)||!ts.test(a.delegateRoleSubjectKey)||!Number.isSafeInteger(a.delegatorRoleSubjectRevision)||a.delegatorRoleSubjectRevision<1||!Number.isSafeInteger(a.expectedDelegateRevision)||a.expectedDelegateRevision<1||!Ar(a.delegate)||Object.keys(a.delegate).some(c=>!["value","label"].includes(c))||!i(a.delegate.value,255)||!i(a.delegate.label,200)||!(a.workflowCode===null||i(a.workflowCode,128)&&ns.test(a.workflowCode))||!(a.nodeId===null||i(a.nodeId,128)&&/^[A-Za-z0-9._:-]{1,128}$/.test(a.nodeId)&&a.workflowCode)||!d(a.validFrom)||!d(a.validTo)||Date.parse(a.validFrom)>=Date.parse(a.validTo)||!i(a.reason,4e3)||a.key!==void 0&&!i(a.key,128))&&n(),{...a,delegate:{value:a.delegate.value,label:a.delegate.label},validFrom:new Date(a.validFrom).toISOString(),validTo:new Date(a.validTo).toISOString()}):n());return e.confirmer==="delegate"&&new Set(s.map(a=>a.delegate.value)).size!==1&&n(),s}var dc=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[null,Object.prototype].includes(Object.getPrototypeOf(e));function Ir(e){let t=e?.nodes||{},o=Object.values(t).filter(s=>s?.kind==="correction");if(!o.length)return[];let n=[],r=s=>s?.kind==="approval"?[s.onApprove,s.onReject]:s?.kind==="condition"?[...(Array.isArray(s.branches)?s.branches:[]).map(a=>a.target),s.otherwise]:s?.kind==="action"||s?.kind==="cc"?[s.next]:[],i=new Set,d=[e.startAt];for(;d.length;){let s=d.pop();i.has(s)||(i.add(s),d.push(...r(t[s])))}for(let s of o){(!dc(s)||Object.keys(s).some(c=>!["id","kind","title","taskPageCode","next"].includes(c))||typeof s.id!="string"||!/^[A-Za-z][A-Za-z0-9_-]{0,127}$/.test(s.id)||["__proto__","prototype","constructor"].includes(s.id)||t[s.id]!==s||typeof s.title!="string"||!s.title.trim()||s.title.length>255||typeof s.taskPageCode!="string"||!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(s.taskPageCode))&&n.push("WORKFLOW_CORRECTION_NODE_INVALID"),(s.next!==e.startAt||t[s.next]?.kind==="correction")&&n.push("WORKFLOW_CORRECTION_REPLAY_TARGET_INVALID"),(i.has(s.id)||Object.values(t).some(c=>r(c).includes(s.id)))&&n.push("WORKFLOW_CORRECTION_FORWARD_ENTRY_FORBIDDEN"),Object.values(t).some(c=>c?.kind==="approval"&&i.has(c.id)&&Array.isArray(c.returnTargets)&&c.returnTargets.includes(s.id))||n.push("WORKFLOW_CORRECTION_RETURN_SOURCE_REQUIRED");let a=e.taskPages?.[s.taskPageCode];!a||!Array.isArray(a.fields)?n.push("WORKFLOW_CORRECTION_PAGE_REQUIRED"):a.fields.some(c=>c?.subtable&&Object.values(e.subject?.factProjection||{}).some(f=>f===c.code||f.startsWith(`${c.code}.`)))&&n.push("WORKFLOW_CORRECTION_OWNED_FACTS_UNSUPPORTED")}return[...new Set(n)]}var Ut=class extends Error{constructor(o){super(o);this.code=o}code},cc=["projection","triggerCode","resourceCode","recordId","recordRevision","field","dueAt"];function yr(e,t,o){let n=i=>{throw new Ut(i)};t.length>100&&n("DATE_TRIGGER_PROJECTION_LIMIT");let r=new Set;for(let i of t){let d=i.filter?.resourceCodes||[];if(Array.isArray(d)||n("DATE_TRIGGER_PROJECTION_INVALID"),d.length&&!d.includes(e))continue;let s=i.payload?.fields||[];(!Array.isArray(s)||s.length>32)&&n("DATE_TRIGGER_PROJECTION_LIMIT");for(let a of s)(typeof a!="string"||!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(a)||["__proto__","constructor","prototype"].includes(a))&&n("DATE_TRIGGER_PROJECTION_FIELD_INVALID"),r.add(a)}if(r.size>64&&n("DATE_TRIGGER_PROJECTION_LIMIT"),o!==void 0){let i=o?.schema?.fields??o?.fields;Array.isArray(i)||n("DATE_TRIGGER_PROJECTION_RESOURCE_INVALID");let d=new Map(i.map(s=>[s.code,s]));for(let s of r){let a=d.get(s);a||n("DATE_TRIGGER_PROJECTION_FIELD_UNKNOWN"),a.type==="subtable"&&n("DATE_TRIGGER_PROJECTION_SUBTABLE_FORBIDDEN"),o.fieldPolicies?.[s]?.mask==="omit"&&n("DATE_TRIGGER_PROJECTION_FIELD_SENSITIVE")}}return[...r].sort()}function lc(e,t){if(!t.length)return e;let o=e?.properties?.projection;if(o?.type!=="object"||!o.properties||typeof o.properties!="object"||Array.isArray(o.properties)||o.additionalProperties!==!1||o.required!==void 0&&!Array.isArray(o.required)||t.some(n=>!Object.hasOwn(o.properties,n))||(o.required||[]).some(n=>!t.includes(n)))throw new Ut("DATE_TRIGGER_PROJECTION_SCHEMA_INVALID");return{...e,properties:{...e.properties,projection:{}}}}var rs=200,Mn=1024*1024,is=65536,Nr=Fe,br=Ke,Ze=new Set(["__proto__","prototype","constructor"]),ss=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,Bt=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,os=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,le=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[null,Object.prototype].includes(Object.getPrototypeOf(e)),ve=(e,t)=>le(e)&&Object.keys(e).every(o=>t.includes(o)&&!Ze.has(o)),Bn=e=>{try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 1/0}},as=e=>e==null||typeof e=="string"&&!e.trim()||Array.isArray(e)&&e.length===0;function We(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((n,r)=>We(n,t[r]));if(!le(e)||!le(t))return!1;let o=Object.keys(e);return o.length===Object.keys(t).length&&o.every(n=>Object.hasOwn(t,n)&&We(e[n],t[n]))}function Or(e,t){let o=t.split(".");if(!(o.some(n=>!ss.test(n)||Ze.has(n))||o.length>12))return o.reduce((n,r)=>le(n)&&Object.hasOwn(n,r)?n[r]:void 0,e)}function Pe(e,t){switch(e.op){case"literal":return e.value;case"path":return Or({values:t},e.path);case"and":return e.values.every(o=>!!Pe(o,t));case"or":return e.values.some(o=>!!Pe(o,t));case"not":return!Pe(e.value,t);case"exists":return!as(Pe(e.value,t));default:{let o=Pe(e.left,t),n=Pe(e.right,t);return e.op==="eq"?We(o,n):e.op==="neq"?!We(o,n):e.op==="in"?Array.isArray(n)&&n.some(r=>We(r,o)):e.op==="contains"?Array.isArray(o)?o.some(r=>We(r,n)):typeof o=="string"&&typeof n=="string"&&o.includes(n):typeof o!="number"||typeof n!="number"||!Number.isFinite(o)||!Number.isFinite(n)?!1:e.op==="gt"?o>n:e.op==="gte"?o>=n:e.op==="lt"?o<n:o<=n}}}function Mt(e,t,o=0,n={nodes:0}){if(o>8||++n.nodes>64||!le(e))return!1;if(e.op==="literal")return ve(e,["op","value"])&&Object.hasOwn(e,"value")&&Bn(e.value)<=4096&&Kt(e.value);if(e.op==="path"){if(!ve(e,["op","path"])||typeof e.path!="string")return!1;let r=e.path.split(".");return r[0]==="values"&&r.length>=2&&r.length<=8&&t.has(r[1])&&r.every(i=>Bt.test(i)&&!Ze.has(i))}return["not","exists"].includes(e.op)?ve(e,["op","value"])&&Mt(e.value,t,o+1,n):["and","or"].includes(e.op)?ve(e,["op","values"])&&Array.isArray(e.values)&&e.values.length>0&&e.values.length<=16&&e.values.every(r=>Mt(r,t,o+1,n)):["eq","neq","gt","gte","lt","lte","in","contains"].includes(e.op)&&ve(e,["op","left","right"])&&Mt(e.left,t,o+1,n)&&Mt(e.right,t,o+1,n)}function Gt(e,t,o,n=br){let r=[],i=e.taskPages;if(i!==void 0&&(!le(i)||Object.keys(i).length===0||Object.keys(i).length>16||Bn(i)>is))return["WORKFLOW_TASK_PAGES_INVALID"];for(let[d,s]of Object.entries(i||{})){let a=`taskPages.${d}`;if(!ss.test(d)||Ze.has(d)||!ve(s,["title","fields"])||typeof s.title!="string"||!s.title.trim()||s.title.length>160||!Array.isArray(s.fields)||!s.fields.length||s.fields.length>rs){r.push(`WORKFLOW_TASK_PAGE_INVALID:${a}`);continue}let c=new Set(s.fields.map(p=>p?.code));c.size!==s.fields.length&&r.push(`WORKFLOW_TASK_PAGE_DUPLICATE_FIELD:${a}`);let f=0,u=new Set;for(let p of s.fields){if(!ve(p,["code","readonly","required","visibleWhen","requiredWhen","subtable"])||!Bt.test(p.code)||Ze.has(p.code)||["readonly","required"].some(_=>p[_]!==void 0&&typeof p[_]!="boolean")||p.readonly&&(p.required||p.requiredWhen)){r.push(`WORKFLOW_TASK_PAGE_FIELD_INVALID:${a}`);continue}for(let _ of["visibleWhen","requiredWhen"])p[_]!==void 0&&!Mt(p[_],c)&&r.push(`WORKFLOW_TASK_PAGE_EXPRESSION_INVALID:${a}.${p.code}.${_}`);if(t){let _=t.get(p.code);if((!_||_.system||_.hidden||_.type==="serial-number"||!p.readonly&&_.widget==="readonly"||!p.readonly&&_.type==="subtable"&&!p.subtable||p.subtable&&_.type!=="subtable")&&r.push(`WORKFLOW_TASK_PAGE_RESOURCE_FIELD_INVALID:${a}.${p.code}`),p.subtable&&_?.subtable){let E=_.subtable;f+=E.maxRows??20,(u.has(E.resourceCode)||!Number.isSafeInteger(E.maxRows??20)||(E.maxRows??20)<1||(E.maxRows??20)>Nr||!Bt.test(E.foreignKey)||!Bt.test(E.orderField)||E.foreignKey===E.orderField)&&r.push(`WORKFLOW_TASK_SUBTABLE_RELATION_INVALID:${a}.${p.code}`),u.add(E.resourceCode);let A=o?.get(E.resourceCode);o&&(!A||!["uuid","resource-ref.single"].includes(A.get(E.foreignKey)?.type||"")||A.get(E.orderField)?.type!=="number.integer")&&r.push(`WORKFLOW_TASK_SUBTABLE_RELATION_INVALID:${a}.${p.code}`);for(let O of Array.isArray(p.subtable.fields)?p.subtable.fields:[]){if(!O||typeof O.code!="string")continue;let b=A?.get(O.code);(O.code===E.foreignKey||O.code===E.orderField||A&&(!b||b.system||b.hidden||b.type==="subtable"||!O.readonly&&(b.widget==="readonly"||b.type==="serial-number")))&&r.push(`WORKFLOW_TASK_SUBTABLE_FIELD_UNSUPPORTED:${a}.${p.code}.${O.code}`)}}else p.subtable&&t&&r.push(`WORKFLOW_TASK_SUBTABLE_RELATION_INVALID:${a}.${p.code}`)}p.subtable&&(p.readonly||!ve(p.subtable,["fields","create","delete","reorder"])||["create","delete","reorder"].some(_=>p.subtable?.[_]!==void 0&&typeof p.subtable[_]!="boolean")||!Array.isArray(p.subtable.fields)||p.subtable.fields.some(_=>_?.subtable)?r.push(`WORKFLOW_TASK_SUBTABLE_PAGE_INVALID:${a}.${p.code}`):r.push(...Gt({taskPages:{child:{title:"\u5B50\u884C",fields:p.subtable.fields}}},o?.get(t?.get(p.code)?.subtable?.resourceCode||"")).map(_=>`${_}:${a}.${p.code}`)))}(f>Math.min(n,br)||f<0||!Number.isSafeInteger(f)||!Number.isSafeInteger(n)||n<1)&&r.push(`WORKFLOW_TASK_SUBTABLE_BUDGET_EXCEEDED:${a}`)}for(let[d,s]of Object.entries(e.nodes||{}))le(s)&&s.taskPageCode!==void 0&&(!["approval","correction"].includes(s.kind)||typeof s.taskPageCode!="string"||!le(i)||!Object.hasOwn(i,s.taskPageCode)?r.push(`WORKFLOW_TASK_PAGE_NOT_FOUND:${d}`):Array.isArray(i[s.taskPageCode]?.fields)&&i[s.taskPageCode].fields.some(a=>a&&(s.fieldPolicy?.fields?.[a.code]||s.fieldPolicy?.default)==="hidden")&&r.push(`WORKFLOW_TASK_PAGE_FIELD_HIDDEN:${d}`));return r}function Tr(e,t){return e.fields.map(o=>({code:o.code,visible:o.visibleWhen===void 0||!!Pe(o.visibleWhen,t),readonly:o.readonly===!0,required:o.required===!0||o.requiredWhen!==void 0&&!!Pe(o.requiredWhen,t)}))}var Ne=class extends Error{constructor(o,n){super(o);this.code=o;this.field=n}code;field;rowIndex;childField};function uc(e,t){return t.map(o=>({key:String(o.id),id:String(o.id),revision:Number(o.revision),state:"persisted",values:Object.fromEntries(Tr({title:"\u5B50\u884C",fields:e.fields},o).filter(n=>n.visible&&!n.readonly).map(n=>[n.code,o[n.code]??null]))}))}function fc(e,t,o,n,r,i=!0,d=0){let s=e.subtable,a=_=>{throw new Ne(_,e.code)};if(!s||!Number.isSafeInteger(t)||t<1||t>Nr||!Number.isSafeInteger(d)||d<0||d>t||!Array.isArray(n)||n.length>2*t||Bn(n)>Mn||!Kt(n))return a("WORKFLOW_TASK_SUBTABLE_VALUES_INVALID");let c=new Map(o.map(_=>[String(_.id),_])),f=new Set,u=new Set,p=[];for(let _ of n){if(!ve(_,["key","state","id","revision","values"])||typeof _.key!="string"||!os.test(_.key)||f.has(_.key)||!["created","persisted","deleted"].includes(_.state)||!le(_.values))return a("WORKFLOW_TASK_SUBTABLE_ROW_INVALID");if(f.add(_.key),_.state==="created"){if(!s.create||_.id!==void 0||_.revision!==void 0||c.has(_.key))return a("WORKFLOW_TASK_SUBTABLE_CREATE_FORBIDDEN")}else{if(typeof _.id!="string"||_.id!==_.key||!os.test(_.id)||u.has(_.id)||!Number.isSafeInteger(_.revision)||_.revision<1||!c.has(_.id))return a("WORKFLOW_TASK_SUBTABLE_SCOPE_CONFLICT");if(u.add(_.id),i&&Number(c.get(_.id).revision)!==_.revision)return a("WORKFLOW_TASK_SUBTABLE_REVISION_CONFLICT")}if(_.state==="deleted"){if(!s.delete||Object.keys(_.values).length)return a("WORKFLOW_TASK_SUBTABLE_DELETE_FORBIDDEN");continue}try{ds({title:e.code,fields:s.fields},_.id?c.get(_.id):{},_.values,r)}catch(E){if(!(E instanceof Ne))throw E;let A=new Ne(E.code,e.code);throw A.rowIndex=p.length,E.field!==void 0&&(A.childField=E.field),A}p.push(_)}if(u.size!==c.size)return a("WORKFLOW_TASK_SUBTABLE_SCOPE_CONFLICT");if(p.length>t)return a("WORKFLOW_TASK_SUBTABLE_MAX_ROWS_EXCEEDED");if(r&&p.length<d)return a("WORKFLOW_TASK_SUBTABLE_MIN_ROWS_NOT_MET");if(!s.reorder){let _=o.filter(A=>p.some(O=>O.id===String(A.id))).map(A=>String(A.id)),E=p.filter(A=>A.state==="persisted").map(A=>A.id);if(!We(_,E)||p.some((A,O)=>A.state==="created"&&p.slice(O+1).some(b=>b.state==="persisted")))return a("WORKFLOW_TASK_SUBTABLE_REORDER_FORBIDDEN")}return n}function Kt(e,t={members:0},o=0){return++t.members>5e4||o>12?!1:e===null||typeof e=="boolean"?!0:typeof e=="string"?e.length<=Mn:typeof e=="number"?Number.isFinite(e):Array.isArray(e)?e.length<=1e3&&e.every(n=>Kt(n,t,o+1)):le(e)&&Object.entries(e).every(([n,r])=>!Ze.has(n)&&Kt(r,t,o+1))}function ds(e,t,o,n){if(!le(o)||Bn(o)>Mn||!Kt(o))throw new Ne("WORKFLOW_TASK_FORM_VALUES_INVALID");let r={...t,...o},i=new Map(Tr(e,r).map(d=>[d.code,d]));for(let d of Object.keys(o)){let s=i.get(d);if(!s||s.readonly||!s.visible)throw new Ne("WORKFLOW_TASK_FORM_FIELD_NOT_EDITABLE",d)}if(n)for(let d of i.values()){let s=r[d.code],a=e.fields.find(c=>c.code===d.code)?.subtable&&Array.isArray(s)?s.every(c=>le(c)&&c.state==="deleted"):as(s);if(d.visible&&!d.readonly&&d.required&&a)throw new Ne("WORKFLOW_TASK_FORM_REQUIRED",d.code)}return r}function pc(e,t,o){let n=JSON.parse(JSON.stringify(t));for(let[d,s]of Object.entries(e.subject?.factProjection||{})){let a=d.split(".");if(!a.length||a.length>12||d.length>128||a[0]==="steps"||a.some(f=>!Bt.test(f)||Ze.has(f)))throw new Ne("WORKFLOW_TASK_FORM_FACT_PROJECTION_INVALID");if(!Object.hasOwn(o,s))throw new Ne("WORKFLOW_TASK_FORM_FACT_FIELD_MISSING",s);let c=n;for(let f of a.slice(0,-1))c=c[f]=le(c[f])?c[f]:{};c[a.at(-1)]=o[s]===void 0?void 0:JSON.parse(JSON.stringify(o[s]))}let r=new Set,i=Object.values(e.nodes||{}).filter(d=>d.kind==="action");for(let d=0;d<=i.length;d++){let s=!1;for(let a of i)le(n.steps)&&Object.hasOwn(n.steps,a.id)&&Object.values(a.inputs||{}).some(c=>c.source==="fact"&&!We(Or(t,c.path),Or(n,c.path)))&&(delete n.steps[a.id],r.add(a.id),s=!0);if(!s)break}return{facts:n,invalidatedNodeIds:[...r].sort()}}function mc(e,t,o){let n=e.nodes||{};for(let r of o){let i=new Set,d=new Map,s=a=>{if(a===r)return!0;if(d.has(a))return d.get(a);if(i.has(a)||i.size>200)return!1;let c=n[a];if(!le(c)||c.kind==="end")return!1;i.add(a);let f=c.kind==="approval"?[c.onApprove]:c.kind==="condition"?[...(c.branches||[]).map(p=>p.target),c.otherwise]:[c.next],u=f.length>0&&f.every(p=>typeof p=="string"&&s(p));return i.delete(a),d.set(a,u),u};if(!s(t))return!1}return!0}var Lf=256,Ff=64,xf=262144,_c=/^[a-z][a-z0-9_-]{0,127}$/,gc=/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*$/,ls=new Set(["__proto__","prototype","constructor"]),Se=e=>!!e&&typeof e=="object"&&!Array.isArray(e),zt=(e,t)=>Object.keys(e).every(o=>t.includes(o)),Qe=(e,t)=>typeof e=="string"&&e.trim().length>0&&e.length<=t&&!/[\u0000-\u001f\u007f]/.test(e),Ve=e=>typeof e=="string"&&_c.test(e)&&!ls.has(e),us=e=>typeof e=="string"&&e.length<=255&&gc.test(e)&&!e.split(".").some(t=>ls.has(t)),Ac=e=>Se(e)&&zt(e,["dimension","valueFrom","value"])&&Ve(e.dimension)&&(Qe(e.value,255)&&e.valueFrom===void 0||us(e.valueFrom)&&e.value===void 0),cs=e=>typeof e=="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/.test(e)&&Number.isFinite(Date.parse(e)),qt={type:"string",pattern:"^[a-z][a-z0-9_-]{0,127}$"},Rr={type:"string",minLength:1,maxLength:128},Ec={type:"object",additionalProperties:!1,required:["policyCode","title","strategy","dimensions","sources"],properties:{policyCode:qt,title:Rr,strategy:{enum:["replace_then_append","replace_only"]},dimensions:{type:"object",maxProperties:8,propertyNames:qt,additionalProperties:{type:"object",additionalProperties:!1,required:["title","valueFrom"],properties:{title:Rr,valueFrom:{type:"string",minLength:1,maxLength:255}}}},sources:{type:"object",minProperties:1,maxProperties:16,propertyNames:qt,additionalProperties:{type:"object",additionalProperties:!1,required:["title","provider","roleCode"],properties:{title:Rr,provider:{enum:["app_role","app_role_in_scope"]},roleCode:qt,scope:{type:"object",additionalProperties:!1,required:["dimension"],properties:{dimension:qt,value:{type:"string",minLength:1,maxLength:255},valueFrom:{type:"string",minLength:1,maxLength:255}}}}}}}};function Jt(e){if(!Se(e)||!zt(e,["policyCode","title","strategy","dimensions","sources"])||!Ve(e.policyCode)||!Qe(e.title,128)||!["replace_then_append","replace_only"].includes(e.strategy))return["WORKFLOW_V2_ROUTING_POLICY_INVALID"];let t=[];return(!Se(e.dimensions)||Object.keys(e.dimensions).length>8||Object.entries(e.dimensions).some(([o,n])=>!Ve(o)||!Se(n)||!zt(n,["title","valueFrom"])||!Qe(n.title,128)||!us(n.valueFrom)))&&t.push("WORKFLOW_V2_ROUTING_DIMENSIONS_INVALID"),(!Se(e.sources)||Object.keys(e.sources).length<1||Object.keys(e.sources).length>16||Object.entries(e.sources).some(([o,n])=>!Ve(o)||!Se(n)||!zt(n,["title","provider","roleCode","scope"])||!Qe(n.title,128)||!Ve(n.roleCode)||!["app_role","app_role_in_scope"].includes(n.provider)||(n.provider==="app_role_in_scope"?!Ac(n.scope):n.scope!==void 0)))&&t.push("WORKFLOW_V2_ROUTING_SOURCES_INVALID"),t}function Ic(e,t){if(Jt(e).length)return["WORKFLOW_V2_ROUTING_POLICY_INVALID"];if(!Array.isArray(t)||t.length>256||new TextEncoder().encode(JSON.stringify(t)).length>262144)return["WORKFLOW_V2_ROUTING_RULE_LIMIT_EXCEEDED"];let o=[],n=new Set;for(let r of t){if(!Se(r)||!zt(r,["ruleCode","title","enabled","workflowCode","nodeId","matches","sourceCode","effect","priority","validFrom","validTo"])||!Ve(r.ruleCode)||!Qe(r.title,128)||typeof r.enabled!="boolean"||!Ve(r.sourceCode)||!Object.hasOwn(e.sources,r.sourceCode)||!["append","replace"].includes(r.effect)||!Number.isSafeInteger(r.priority)||r.priority<-1e3||r.priority>1e3||r.workflowCode!==void 0&&!Ve(r.workflowCode)||r.nodeId!==void 0&&(!Ve(r.nodeId)||r.workflowCode===void 0)||r.validFrom!==void 0&&!cs(r.validFrom)||r.validTo!==void 0&&!cs(r.validTo)||r.validFrom&&r.validTo&&Date.parse(r.validFrom)>=Date.parse(r.validTo)){o.push("WORKFLOW_V2_ROUTING_RULE_INVALID");continue}n.has(r.ruleCode)&&o.push(`WORKFLOW_V2_ROUTING_RULE_DUPLICATE:${r.ruleCode}`),n.add(r.ruleCode),(!Se(r.matches)||Object.entries(r.matches).some(([i,d])=>!Object.hasOwn(e.dimensions,i)||!Array.isArray(d)||d.length<1||d.length>64||new Set(d).size!==d.length||d.some(s=>!Qe(s,255))))&&o.push(`WORKFLOW_V2_ROUTING_MATCH_INVALID:${r.ruleCode}`)}return[...new Set(o)]}function fs(e){return JSON.stringify({policyCode:e.policyCode,strategy:e.strategy,dimensions:Object.entries(e.dimensions).sort(([t],[o])=>t<o?-1:t>o?1:0).map(([t,o])=>[t,o.valueFrom]),sources:Object.entries(e.sources).sort(([t],[o])=>t<o?-1:t>o?1:0).map(([t,o])=>[t,o.provider,o.roleCode,o.scope?.dimension??null,o.scope?.valueFrom??null,o.scope?.value??null])})}function Cr(e){let t=[],o=new Map;for(let n of e)for(let[r,i]of Object.entries(n.bindings||{})){if(!Se(i)||i.routing===void 0)continue;let d=Jt(i.routing);if(d.length){t.push(...d.map(c=>`${c}:${r}`));continue}let s=fs(i.routing),a=o.get(i.routing.policyCode);a&&a!==s&&t.push(`WORKFLOW_V2_ROUTING_POLICY_CONFLICT:${i.routing.policyCode}`),o.set(i.routing.policyCode,s)}return[...new Set(t)]}function yc(e,t){let o={};for(let[n,r]of Object.entries(e.dimensions)){let i=t;for(let d of r.valueFrom.split("."))i=Se(i)&&Object.hasOwn(i,d)?i[d]:void 0;if(!(typeof i=="string"&&Qe(i,255)||typeof i=="number"&&Number.isFinite(i)||typeof i=="boolean"))throw new Error(`WORKFLOW_V2_ROUTING_FACT_REQUIRED:${n}`);o[n]=String(i)}return o}function bc(e,t,o){let n=t.filter(c=>c.enabled&&(!c.validFrom||Date.parse(c.validFrom)<=o.at)&&(!c.validTo||Date.parse(c.validTo)>o.at)&&(!c.workflowCode||c.workflowCode===o.workflowCode)&&(!c.nodeId||c.nodeId===o.nodeId)&&Object.entries(c.matches).every(([f,u])=>u.includes(o.facts[f])));if(n.length>64)throw new Error("WORKFLOW_V2_ROUTING_MATCH_LIMIT_EXCEEDED");let r=(c,f)=>f.priority-c.priority||+!!c.workflowCode-+!!f.workflowCode||+!!c.nodeId-+!!f.nodeId||(c.ruleCode<f.ruleCode?-1:c.ruleCode>f.ruleCode?1:0),i=n.filter(c=>c.effect==="replace").sort(r);if(i.length>1&&i[0].priority===i[1].priority)throw new Error("WORKFLOW_V2_ROUTING_REPLACE_CONFLICT");let d=i[0],s=d&&e.strategy==="replace_only"?[]:n.filter(c=>c.effect==="append").sort(r),a=[...d?[d]:[],...s];return{matched:n.sort(r),replacement:d,applied:a,ignored:n.filter(c=>!a.includes(c))}}var hr="^[A-Za-z][A-Za-z0-9_]{0,62}$",ps="^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$",Oc={type:"object",additionalProperties:!1,required:["mode","resourceCode","subtables"],properties:{mode:{const:"create"},resourceCode:{type:"string",maxLength:64,pattern:ps},subtables:{type:"array",minItems:1,maxItems:16,items:{type:"object",additionalProperties:!1,required:["fieldCode","fieldCodes"],properties:{fieldCode:{type:"string",pattern:hr},fieldCodes:{type:"array",minItems:1,maxItems:200,uniqueItems:!0,items:{type:"string",pattern:hr}}}}}}};function Ht(e){let t=n=>!!(n&&typeof n=="object"&&!Array.isArray(n)),o=n=>typeof n=="string"&&new RegExp(hr).test(n)&&!["__proto__","prototype","constructor"].includes(n);if(!t(e)||Object.keys(e).some(n=>!["mode","resourceCode","subtables"].includes(n))||e.mode!=="create"||typeof e.resourceCode!="string"||e.resourceCode.length>64||!new RegExp(ps).test(e.resourceCode)||!Array.isArray(e.subtables)||e.subtables.length<1||e.subtables.length>16||e.subtables.some(n=>!t(n)||Object.keys(n).some(r=>!["fieldCode","fieldCodes"].includes(r))||!o(n.fieldCode)||!Array.isArray(n.fieldCodes)||n.fieldCodes.length<1||n.fieldCodes.length>200||new Set(n.fieldCodes).size!==n.fieldCodes.length||n.fieldCodes.some(r=>!o(r)))||new Set(e.subtables.map(n=>n.fieldCode)).size!==e.subtables.length)throw new Error("WORKFLOW_OWNED_SUBJECT_CREATE_INVALID")}function Nc(e){return Ht(e),{mode:"create",resourceCode:e.resourceCode,subtables:e.subtables.map(t=>({fieldCode:t.fieldCode,fieldCodes:[...t.fieldCodes].sort()})).sort((t,o)=>t.fieldCode.localeCompare(o.fieldCode))}}function wr(e,t,o){Ht(e);let n=s=>{throw new Error(`WORKFLOW_OWNED_SUBJECT_${s}`)},r=t.get(e.resourceCode);r||n("RESOURCE_MISSING");let i=new Set,d=0;for(let s of e.subtables){let a=r.get(s.fieldCode),c=a?.subtable,f=t.get(c?.resourceCode);(a?.type!=="subtable"||!f||c.resourceCode===e.resourceCode||i.has(c.resourceCode))&&n("RELATION_INVALID"),i.add(c.resourceCode);let u=c.maxRows??20;(!Number.isSafeInteger(u)||u<1||u>Fe)&&n("BUDGET_EXCEEDED"),d+=u;for(let p of s.fieldCodes){let _=f.get(p);(!_||["serial-number","subtable"].includes(_.type)||[c.foreignKey,c.orderField].includes(p))&&n("FIELD_INVALID"),["file","image","signature","text.rich"].includes(_.type)&&!o.some(E=>E.resourceCode===c.resourceCode&&E.fieldCodes.includes(p)&&E.intents.includes("create"))&&n("FILE_ACCESS_REQUIRED")}}d>Ke&&n("BUDGET_EXCEEDED")}var Qn=Oa(require("crypto"),1);var ms="native-4",Sr="2.0.0-alpha.5",_s={"application-native-2":"1.0.0","application.extended-declaration-capacity":"1.0.0","application.extended-artifact-capacity":"1.0.0","application.high-density-artifact-capacity":"1.0.0","application.extended-configuration-bytes":"1.0.0","application.development-configuration":"1.0.0","authz.native-batch-explain":"1.0.0","authz.native-management":"1.0.0","authz.native-membership-batch":"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.extended-owned-subtable-capacity":"1.0.0","data.aggregate-owned-subtable-capacity":"1.0.0","data.extended-field-capacity":"1.0.0","data.business-commands":"1.0.0","data.record-edit":"1.0.0","data.native-golden-crud":"1.0.0","data.audit-read-access":"1.0.0","data.managed-files":"1.1.0","data.decimal-reservations":"1.1.0","data.decimal-reservation-lifecycle":"1.0.0","data.unique-keys":"1.1.0","data.user-candidates":"1.0.0","data.user-candidate-launch-scope":"1.0.0","data.datetime-minute-precision":"1.0.0","data.subtable-minimum-rows":"1.0.0","data.managed-concurrency":"1.0.0","data.managed-concurrency.durable":"1.0.0","workflow.named-input-sources":"1.0.0","workflow.approved-delegation":"1.0.0","directory-v2":"1.0.0","directory.selected-user":"1.0.0","directory.current-initiator-phone":"1.0.0","events-v2":"1.0.0","events.durable-receipts":"1.0.0","events.capture-policy":"1.0.0","events.date-source-projection":"1.0.0","events.native-data-actions":"1.0.0","workflow-kernel-v2":"1.0.0","workflow.business-data-command":"1.0.0","workflow.approval-business-command":"1.0.0","workflow.native-stage-guard":"1.0.0","workflow.launch-preflight":"1.0.0","workflow.optional-rejection-comment":"1.0.0","workflow.optional-operation-reason":"1.0.0","workflow.optional-withdrawal-reason":"1.0.0","data.transaction-actor-authority":"1.0.0","data.authenticated-public-projection":"1.0.0","data.parent-read-policy":"1.0.0","data.record-print":"1.0.0","data.workflow-record-deletion":"1.0.0","data.record-comments":"1.0.0","workflow.record-history-read":"1.0.0","workflow.rejection-notification":"1.0.0","workflow.instance-cancellation-policy":"1.0.0","workflow.node-administration":"1.0.0","workflow.assignment-routing":"1.0.0","workflow.role-union":"1.0.0","workflow.role-input-selection":"1.0.0","workflow.named-owned-create":"1.0.0","workflow.owned-initial-facts":"1.0.0","workflow.initiator-correction":"1.0.0","workflow.correction-business-command":"1.0.0","workflow.correction-derived-subject-facts":"1.0.0","workflow.role-references":"1.0.0","workflow.delegation-management":"1.0.0","workflow.automatic-cc":"1.0.0","workflow.approval-empty-policy":"1.0.0","workflow.initiator-approval-policy":"1.0.0","workflow.completion-deadline":"1.0.0","workflow.task-page-submit":"1.0.0","workflow.task-private-drafts":"1.0.0","workflow.task-managed-files":"1.0.0","workflow.task-rich-fields":"1.0.0","workflow.task-owned-subtables":"1.0.0","workflow.task-owned-files":"1.0.0","workflow.durable-business-step":"1.0.0","workflow.step-data-transaction":"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 M=Object.freeze({perspectives:100,resources:512,dataPolicies:512,roles:256,subjectReadSurfaces:50,capabilities:4096,operations:500,eventConsumers:100,eventProducers:1e3,eventSchemas:100,eventTypes:500,workflows:512,routes:2048,adminPages:2048,adminNavigationGroups:100,adminNavigationItems:1024});function Dr(e){let t=(e.surface?.mutationOwner||"native")==="native";return["query","get","create","update","delete"].filter(o=>{let n=e.surface?.generated;return o==="query"?n?.list??!0:o==="get"?n?.detail??!0:n?.[o]??t})}function Kn(e){let t=(e.data?.resources||[]).filter(o=>o.status!=="retired").reduce((o,n)=>o+Dr(n).length,0)+(e.backend?.operations||[]).filter(o=>o.ai).length;return(e.data?.resources?.length||0)>100||(e.authz?.dataPolicies?.length||0)>100||(e.authz?.roles?.length||0)>100||(e.authz?.capabilities?.length||0)>2e3||[e.workflows?.definitions,e.workflows?.bindings,e.workflows?.activations].some(o=>(o?.length||0)>100)||(e.frontend?.routes?.length||0)>500||t>500||(e.frontend?.admin?.navigation||[]).reduce((o,n)=>o+n.items.length,0)>500}var oe=Object.freeze({legacyConfigBytes:4194304,configBytes:8388608,contractBytes:8388608,depth:40,stringBytes:1048576,legacyNodes:1e5,extendedNodes:25e4}),et=Object.freeze({nodes:5e5});function Gn(e){return Buffer.byteLength(X(e),"utf8")>oe.legacyConfigBytes}function gs(e,t){let o=0,n=[[e][Symbol.iterator]()];for(;n.length;){let r=n[n.length-1].next();if(r.done){n.pop();continue}if(++o>t)return!0;if(Array.isArray(r.value))n.push(r.value.values());else if(r.value&&typeof r.value=="object"){let i=r.value;n.push((function*(){for(let d of Object.keys(i))i[d]!==void 0&&(yield i[d])})())}}return!1}function Yt(e){return gs(e,oe.legacyNodes)}function Xt(e){return gs(e,oe.extendedNodes)}var Tc="openxiangda.config-bundle/v3",vs="openxiangda.contract-bundle/v3",As="openxiangda.native-configuration-projection/v1",Qt=ms,Rc=/^[a-f0-9]{64}$/,Cc=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,hc=/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._*-]+$/,wc=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,Sc=/^[a-z][a-z0-9]*(?:[-.][a-z0-9]+)*$/,Dc=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,kc=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Es=/^[A-Za-z][A-Za-z0-9_]{0,127}$/,$c=/^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*$/,Pc=/^[A-Z][A-Z0-9_]*$/,vc=/^[a-z][a-z0-9-]{2,63}$/,Vc=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,Lc=/^[A-Za-z][A-Za-z0-9_.]{0,127}$/,Fc=16,xc=2*1024,jc=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"]),Wc=new Set(["overview","database","operations","workflow","members","calendar","document","folder","settings"]),Uc=new Set(["approve","reject","return","transfer","delegate","add_assignee","resubmit","withdraw","terminate","admin_reassign","admin_override","retry_resolution"]),Mc=oe.configBytes,Bc=oe.contractBytes,Kc=oe.depth,$r=oe.stringBytes,Gc="openxiangda.event-handler-manifest/v2",Vs="openxiangda.application-route-manifest/v3",Is=64,Ls=new Set(["id","revision","created_by","updated_by","created_at","updated_at"]),zn=["openxiangda.data.record.created.v2","openxiangda.data.record.updated.v2","openxiangda.data.record.deleted.v2"],Jn=["openxiangda.workflow.node.skipped.v2",gt,"openxiangda.workflow.step.result_received.v2","openxiangda.workflow.step.completed.v2","openxiangda.workflow.step.continuation_failed.v2","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"],qc=new Set(Jn),Hn=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(([r,i])=>[r,String(i).slice(0,128)]))}};function zc(e){let t=S(e.appCode,"/appCode",128);Cc.test(t)||m("NATIVE_CONFIG_APP_CODE_INVALID","/appCode");let o=vr(e.expectedConfigDigest,"/expectedConfigDigest"),n=vr(e.expectedContractDigest,"/expectedContractDigest"),r=ks(e.configBytes,Mc,"/configBytes","NATIVE_CONFIG_ARTIFACT_TOO_LARGE"),i=ks(e.contractBytes,Bc,"/contractBytes","NATIVE_CONTRACT_ARTIFACT_TOO_LARGE");$s(r,o,"/configBytes","NATIVE_CONFIG_DIGEST_MISMATCH"),$s(i,n,"/contractBytes","NATIVE_CONTRACT_DIGEST_MISMATCH");let d=Ds(r,"/configBytes","NATIVE_CONFIG_JSON_INVALID","NATIVE_CONFIG_NOT_CANONICAL"),s=Ds(i,"/contractBytes","NATIVE_CONTRACT_JSON_INVALID","NATIVE_CONTRACT_NOT_CANONICAL");qn(d,"/config",et.nodes),qn(s,"/contracts",et.nodes),Xt(d)||qn(s,"/contracts",oe.extendedNodes),Yt(d)||qn(s,"/contracts",oe.legacyNodes);let a=d,c=s;Hc(a,t),Yc(c,t,o);let f=Xc(a,o,c.generatorVersion);Fl(f,c,a),X(f)!==X(c)&&m("NATIVE_CONTRACT_CLOSURE_MISMATCH",Vr(f,c,"/contracts"));let u={authz:{appCode:t,...a.authz,perspectives:a.perspectives,capabilityCatalog:f.capabilities},data:{appCode:t,resources:a.data.resources,resourceContracts:f.resources,...f.concurrency?{concurrency:f.concurrency}:{},...f.subjectReadSurfaces?{subjectReadSurfaces:f.subjectReadSurfaces}:{}},events:{appCode:t,...a.events,consumers:f.eventConsumers,producers:f.eventProducers,handlerManifest:f.eventHandlerManifest,eventTypes:f.eventTypes,capturePlans:xs({resources:a.data.resources,dataPolicies:a.authz.dataPolicies,subscriptions:f.eventConsumers,capturePolicies:a.events.capturePolicies})},workflows:{appCode:t,...a.workflows,contracts:f.workflows},runtime:{appCode:t,requirements:a.runtime,backend:a.backend,frontend:a.frontend},contracts:f},p={authz:bt(u.authz),data:bt(u.data),events:bt(u.events),workflows:bt(u.workflows),runtime:bt(u.runtime),contracts:bt(u.contracts)},_={configDigest:o,contractDigest:n,generatorVersion:c.generatorVersion},E=Fs(a),A={schemaVersion:As,compilerContractVersion:Qt,appCode:t,source:_,projections:p,requiredPlatformCapabilities:E,aggregateDigest:Z({schemaVersion:As,compilerContractVersion:Qt,appCode:t,source:_,requiredPlatformCapabilities:E,projectionDigests:Object.fromEntries(Object.entries(p).map(([O,b])=>[O,b.digest]))})};return Ys(A)}function ys(e,t){let o=e.subject,n=t.find(i=>i.code===o?.resourceCode),r=new Set(Object.values(o?.factProjection||{}));return!!n?.schema?.fields?.some(i=>i.type==="subtable"&&r.has(i.code))}function Fs(e){let t=e.authz.roles,o=e.data.resources,n=e.backend.operations,r=n.filter(l=>l.platformAccess?.directory?.mode==="current-initiator"&&l.platformAccess.directory.fields.includes("phone")),i=(e.data.concurrency?.commands||[]).filter(l=>l.execution?.directory?.mode==="current-initiator"&&l.execution.directory.fields.includes("phone")),d=t.some(l=>l.capabilities.some(y=>y.endsWith(":directory:read")))||o.some(l=>l.schema.fields.some(y=>["user.single","user.multiple","department.single","department.multiple"].includes(y.type)))||n.some(l=>l.platformAccess?.directory),s=!!(e.events.subscriptions.length||e.events.timers.length||e.events.dateTriggers.length||e.events.schemas.length),a=n.some(l=>l.platformAccess?.managedFiles||l.platformAccess?.managedFileCopies)||e.events.subscriptions.some(l=>l.platformAccess?.managedFileCopies),c=e.workflows.definitions.some(l=>l.definition.rejectionNotification!==void 0)||n.some(l=>l.platformAccess?.notification)||e.events.subscriptions.some(l=>l.platformAccess?.notification),f=(l,y,R=!1)=>{let h=o.find($=>$.code===l.definition.subject?.resourceCode)?.schema.fields||[];return Object.values(l.definition.taskPages||{}).some($=>$.fields.some(w=>{if(w.readonly)return!1;let j=h.find(Q=>Q.code===w.code);if(!R&&j&&y.includes(j.type))return!0;if(!w.subtable||!j?.subtable)return!1;let L=o.find(Q=>Q.code===j.subtable.resourceCode)?.schema.fields||[];return w.subtable.fields.some(Q=>!Q.readonly&&L.some(ee=>ee.code===Q.code&&y.includes(ee.type)))}))},u=e.workflows.definitions.filter(l=>f(l,["file","image","signature","text.rich"])),p=e.workflows.definitions.filter(l=>f(l,["signature","text.rich"])),_=e.workflows.definitions.filter(l=>f(l,["file","image","signature","text.rich"],!0)),E=e.workflows.definitions.filter(l=>l.launch.mode==="standalone"||l.launch.mode==="hidden-handoff"),A=n.some(l=>l.platformAccess?.workflow)||E.length>0,O=E.filter(l=>{let y=l.launch.submission;if(!y)return!1;let R=o.find(h=>h.code===l.definition.subject.resourceCode);return[y.create,y.existing].some(h=>h&&Object.values(h.inputs).some($=>$.source==="field"&&R?.schema.fields.some(w=>w.code===$.fieldCode&&w.type.startsWith("resource-ref.")&&w.source)))}),b={resources:o},g={perspectives:e.perspectives,authz:e.authz},I={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(l=>({code:l.code,method:l.method,path:l.path,capability:l.capability,platformAccess:l.platformAccess||null,...l.browser?{browser:l.browser}:{},ai:l.ai||null}))}};return[...Gn(e)?[{code:"application.extended-configuration-bytes",declaration:{legacyConfigBytes:oe.legacyConfigBytes,configBytes:oe.configBytes}}]:[],...Yt(e)?[{code:"application.extended-artifact-capacity",declaration:oe}]:[],...Xt(e)?[{code:"application.high-density-artifact-capacity",declaration:et}]:[],...Kn(e)?[{code:"application.extended-declaration-capacity",declaration:{resources:e.data.resources.length,policies:e.authz.dataPolicies.length,roles:e.authz.roles.length,capabilities:e.authz.capabilities.length,definitions:e.workflows.definitions.length,bindings:e.workflows.bindings.length,activations:e.workflows.activations.length,routes:e.frontend.routes.length,navigationItems:e.frontend.admin.navigation.reduce((l,y)=>l+y.items.length,0)}}]:[],...o.some(l=>l.uniqueKeys?.length)?[{code:"data.unique-keys",declaration:o.filter(l=>l.uniqueKeys?.length).map(l=>({code:l.code,uniqueKeys:l.uniqueKeys}))}]:[],...e.data.concurrency?[{code:"data.managed-concurrency",declaration:e.data.concurrency}]:[],...e.data.concurrency?.commands.some(l=>l.mode==="durable")?[{code:"data.managed-concurrency.durable",declaration:e.data.concurrency}]:[],...o.some(l=>l.decimalReservationLifecycle)?[{code:"data.decimal-reservation-lifecycle",declaration:o.filter(l=>l.decimalReservationLifecycle).map(l=>({code:l.code,decimalReservationLifecycle:l.decimalReservationLifecycle}))}]:[],...n.some(l=>l.platformAccess?.dataCommands)?[{code:"data.business-commands",declaration:n.filter(l=>l.platformAccess?.dataCommands)}]:[],...e.authz.dataPolicies.some(wn)?[{code:"data.parent-read-policy",declaration:e.authz.dataPolicies.filter(wn)}]:[],...e.authz.dataPolicies.some(l=>l.publicRead)?[{code:"data.authenticated-public-projection",declaration:e.authz.dataPolicies.filter(l=>l.publicRead)}]:[],...n.some(l=>l.platformAccess?.roleAssertions?.actorAuthority)?[{code:"data.transaction-actor-authority",declaration:n.filter(l=>l.platformAccess?.roleAssertions?.actorAuthority)}]:[],...n.some(l=>l.platformAccess?.workflowStage)?[{code:"workflow.native-stage-guard",declaration:n.filter(l=>l.platformAccess?.workflowStage)}]:[],...n.some(l=>l.platformAccess?.recordEdit)?[{code:"data.record-edit",declaration:n.filter(l=>l.platformAccess?.recordEdit)}]:[],...n.some(l=>l.platformAccess?.decimalReservation)||e.events.subscriptions.some(l=>l.platformAccess?.decimalReservation)?[{code:"data.decimal-reservations",declaration:[...n.filter(l=>l.platformAccess?.decimalReservation).map(l=>({code:l.code,decimalReservation:l.platformAccess.decimalReservation})),...e.events.subscriptions.filter(l=>l.platformAccess?.decimalReservation).map(l=>({subscriptionCode:l.code,decimalReservation:l.platformAccess.decimalReservation}))]}]:[],{code:"application-native-2",declaration:I},{code:"authz.native-batch-explain",declaration:g},{code:"authz.native-management",declaration:g},{code:"deployment.durable-runs",declaration:I.backend},{code:"deployment.platform-executor",declaration:I.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:b},{code:"data.native-golden-crud",declaration:b}]:[],...o.some(l=>l.recordComments!==void 0)?[{code:"data.record-comments",declaration:b}]:[],...o.some(l=>l.recordDeletion!==void 0)?[{code:"data.workflow-record-deletion",declaration:b}]:[],...o.some(l=>l.recordPrint!==void 0)?[{code:"data.record-print",declaration:b}]:[],...o.some(l=>l.workflowHistory!==void 0)?[{code:"workflow.record-history-read",declaration:b}]:[],...o.some(Oo)?[{code:"data.audit-read-access",declaration:b}]:[],...d?[{code:"directory-v2",declaration:{roles:t.map(l=>({code:l.code,capabilities:l.capabilities.filter(y=>y.endsWith(":directory:read"))})),resources:o.map(l=>({code:l.code,fields:l.schema.fields.filter(y=>["user.single","user.multiple","department.single","department.multiple"].includes(y.type))})),operations:n.filter(l=>l.platformAccess?.directory).map(l=>({code:l.code,directory:l.platformAccess.directory}))}}]:[],...n.some(l=>l.platformAccess?.directory?.mode==="selected-user")?[{code:"directory.selected-user",declaration:n.filter(l=>l.platformAccess?.directory?.mode==="selected-user").map(l=>({code:l.code,directory:l.platformAccess.directory}))}]:[],...r.length||i.length?[{code:"directory.current-initiator-phone",declaration:{operations:r.map(l=>({code:l.code,directory:l.platformAccess.directory})),commands:i.map(l=>({code:l.code,directory:l.execution.directory}))}}]:[],...a?[{code:"data.managed-files",declaration:{operations:n.filter(l=>l.platformAccess?.managedFiles||l.platformAccess?.managedFileCopies).map(l=>({code:l.code,...l.platformAccess?.managedFiles?{managedFiles:l.platformAccess.managedFiles}:{},...l.platformAccess?.managedFileCopies?{managedFileCopies:l.platformAccess.managedFileCopies}:{}})),subscriptions:e.events.subscriptions.filter(l=>l.platformAccess?.managedFileCopies).map(l=>({code:l.code,managedFileCopies:l.platformAccess.managedFileCopies}))}}]:[],...e.events.subscriptions.some(l=>l.execution)?[{code:"events.native-data-actions",declaration:e.events.subscriptions.filter(l=>l.execution)}]:[],...e.events.capturePolicies?.length?[{code:"events.capture-policy",declaration:e.events.capturePolicies}]:[],...e.events.dateTriggers.some(l=>yr(l.resourceCode,e.events.subscriptions.filter(y=>y.eventTypes.includes(l.eventType)),e.data.resources.find(y=>y.code===l.resourceCode)).length>0)?[{code:"events.date-source-projection",declaration:{triggers:e.events.dateTriggers,subscriptions:e.events.subscriptions}}]:[],...s?[{code:"events-v2",declaration:e.events},{code:"events.durable-receipts",declaration:e.events}]:[],...dn(e.data.resources)?[{code:"data.extended-owned-subtable-capacity",declaration:e.data.resources.filter(l=>dn([l]))}]:[],...sn(e.data.resources,e.workflows?.definitions||[])?[{code:"data.extended-field-capacity",declaration:{resources:e.data.resources.filter(l=>l.schema.fields.length>100),workflows:(e.workflows?.definitions||[]).filter(l=>sn([],[l]))}}]:[],...an(e.data.resources)?[{code:"data.aggregate-owned-subtable-capacity",declaration:e.data.resources.filter(l=>an([l]))}]:[],...e.data.resources.some(l=>l.schema.fields.some(y=>y.userCandidates!==void 0))?[{code:"data.user-candidates",declaration:e.data.resources.filter(l=>l.schema.fields.some(y=>y.userCandidates!==void 0))}]:[],...cr(e.workflows.bindings)?[{code:"workflow.role-input-selection",declaration:e.workflows.bindings.filter(l=>Object.values(l.binding.bindings).some(y=>y.selectedInputPath!==void 0))}]:[],...ar(e.workflows.bindings)?[{code:"workflow.role-union",declaration:e.workflows.bindings.filter(l=>Object.values(l.binding.bindings).some(y=>y.roleCodes!==void 0))}]:[],...e.backend.operations.some(l=>l.platformAccess?.ownedSubject)?[{code:"workflow.named-owned-create",declaration:e.backend.operations.filter(l=>l.platformAccess?.ownedSubject)}]:[],...on(e.data.resources)?[{code:"data.user-candidate-launch-scope",declaration:e.data.resources.filter(l=>on([l]))}]:[],...fn(e.data.resources)?[{code:"data.subtable-minimum-rows",declaration:e.data.resources.filter(l=>fn([l]))}]:[],...un(e.data.resources)?[{code:"data.datetime-minute-precision",declaration:e.data.resources.filter(l=>un([l]))}]:[],...e.workflows.activations.length?[{code:"workflow-kernel-v2",declaration:e.workflows},{code:"workflow.fresh-command-token",declaration:e.workflows}]:[],...e.workflows.definitions.some(l=>l.definition.instanceCommands!==void 0)?[{code:"workflow.instance-cancellation-policy",declaration:e.workflows.definitions.filter(l=>l.definition.instanceCommands!==void 0)}]:[],...e.workflows.definitions.some(l=>l.definition.instanceCommands?.withdraw?.reasonRequired===!1)?[{code:"workflow.optional-withdrawal-reason",declaration:e.workflows.definitions.filter(l=>l.definition.instanceCommands?.withdraw?.reasonRequired===!1)}]:[],...e.workflows.definitions.some(l=>l.definition.rejectionNotification!==void 0)?[{code:"workflow.rejection-notification",declaration:e.workflows.definitions.filter(l=>l.definition.rejectionNotification!==void 0)}]:[],...e.workflows.definitions.some(l=>l.definition.commandHandlers!==void 0)||n.some(l=>l.platformAccess?.workflow?.businessCommands)?[{code:"workflow.business-data-command",declaration:{definitions:e.workflows.definitions.filter(l=>l.definition.commandHandlers!==void 0),operations:n.filter(l=>l.platformAccess?.workflow?.businessCommands)}}]:[],...e.workflows.definitions.some(l=>l.definition.commandHandlers?.approve?.transitionPolicy==="workflow")?[{code:"workflow.approval-business-command",declaration:e.workflows.definitions.filter(l=>l.definition.commandHandlers?.approve?.transitionPolicy==="workflow")}]:[],...e.workflows.definitions.some(l=>l.definition.commandHandlers?.resubmit)||n.some(l=>l.platformAccess?.workflow?.businessCommands?.includes("resubmit"))?[{code:"workflow.correction-business-command",declaration:{definitions:e.workflows.definitions.filter(l=>l.definition.commandHandlers?.resubmit),operations:n.filter(l=>l.platformAccess?.workflow?.businessCommands?.includes("resubmit"))}}]:[],...e.workflows.definitions.some(l=>l.definition.launchPreflight!==void 0)?[{code:"workflow.launch-preflight",declaration:e.workflows.definitions.filter(l=>l.definition.launchPreflight!==void 0)}]:[],...e.workflows.definitions.some(l=>l.definition.commandHandlers?.resubmit?.derivedSubjectFields!==void 0)?[{code:"workflow.correction-derived-subject-facts",declaration:e.workflows.definitions.filter(l=>l.definition.commandHandlers?.resubmit?.derivedSubjectFields!==void 0)}]:[],...e.workflows.definitions.some(l=>l.definition.approvedDelegation!==void 0)?[{code:"workflow.approved-delegation",declaration:e.workflows.definitions.filter(l=>l.definition.approvedDelegation!==void 0)}]:[],...e.workflows.definitions.some(l=>ys(l.definition,e.data.resources))?[{code:"workflow.owned-initial-facts",declaration:e.workflows.definitions.filter(l=>ys(l.definition,e.data.resources))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.kind==="correction"))?[{code:"workflow.initiator-correction",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.kind==="correction"))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.operationPolicy?.reject?.commentRequired===!1))?[{code:"workflow.optional-rejection-comment",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.operationPolicy?.reject?.commentRequired===!1))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>Object.values(y.operationPolicy||{}).some(R=>R.reasonRequired===!1)))?[{code:"workflow.optional-operation-reason",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>Object.values(y.operationPolicy||{}).some(R=>R.reasonRequired===!1)))}]:[],...O.length?[{code:"workflow.named-input-sources",declaration:O}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.administration!==void 0||y.operationPolicy!==void 0))?[{code:"workflow.node-administration",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.administration!==void 0||y.operationPolicy!==void 0))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.kind==="approval"&&y.emptyPolicy!==void 0))?[{code:"workflow.approval-empty-policy",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.kind==="approval"&&y.emptyPolicy!==void 0))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.completionDeadline!==void 0))?[{code:"workflow.completion-deadline",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.completionDeadline!==void 0))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.initiatorApprovalPolicy!==void 0))?[{code:"workflow.initiator-approval-policy",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.initiatorApprovalPolicy!==void 0))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.kind==="cc"))?[{code:"workflow.automatic-cc",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.kind==="cc"))}]:[],...e.workflows.definitions.some(l=>l.definition.taskPages!==void 0)?["workflow.task-page-submit","workflow.task-private-drafts"].map(l=>({code:l,declaration:e.workflows.definitions.filter(y=>y.definition.taskPages!==void 0)})):[],...u.length?[{code:"workflow.task-managed-files",declaration:u}]:[],..._.length?[{code:"workflow.task-owned-files",declaration:_}]:[],...p.length?[{code:"workflow.task-rich-fields",declaration:p}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.taskPages||{}).some(y=>y.fields.some(R=>R.subtable)))?[{code:"workflow.task-owned-subtables",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.taskPages||{}).some(y=>y.fields.some(R=>R.subtable)))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.kind==="action"))?[{code:"workflow.durable-business-step",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.kind==="action"))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.kind==="action"&&y.handler.dataTransaction))?[{code:"workflow.step-data-transaction",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.kind==="action"&&y.handler.dataTransaction))}]:[],...e.workflows.bindings.some(l=>Object.values(l.binding.bindings).some(y=>y.routing!==void 0))?[{code:"workflow.assignment-routing",declaration:e.workflows.bindings.filter(l=>Object.values(l.binding.bindings).some(y=>y.routing!==void 0))}]:[],...A?[{code:"business-process.durable-command",declaration:{operations:n.filter(l=>l.platformAccess?.workflow).map(l=>({code:l.code,workflow:l.platformAccess.workflow})),definitions:E,activations:e.workflows.activations.filter(l=>E.some(y=>y.definition.code===l.workflowCode))}}]:[],...c?[{code:"notification-hub-v2",declaration:{...e.workflows.definitions.some(l=>l.definition.rejectionNotification!==void 0)?{rejectionNotifications:e.workflows.definitions.filter(l=>l.definition.rejectionNotification!==void 0)}:{},operations:n.filter(l=>l.platformAccess?.notification).map(l=>({code:l.code,notification:l.platformAccess.notification})),subscriptions:e.events.subscriptions.filter(l=>l.platformAccess?.notification).map(l=>({code:l.code,notification:l.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:l,declaration:y})=>({code:l,contractVersion:l==="data.unique-keys"?o.some(R=>Ho(R.schema.fields,R.uniqueKeys)==="1.1.0")?"1.1.0":"1.0.0":_s[l],usageDigest:`sha256:${Z(y)}`})).sort((l,y)=>l.code===y.code?0:l.code<y.code?-1:1)}function xs(e){let t=new Map,o=new Set(e.resources.map(i=>String(i.code)));for(let[i,d]of D(e.capturePolicies===void 0?[]:e.capturePolicies,"/capturePlan/capturePolicies",100).entries()){let s=`/capturePlan/capturePolicies/${i}`,a=N(d,s);C(a,["resourceCode","mode"],s);let c=H(a.resourceCode,`${s}/resourceCode`);o.has(c)||m("NATIVE_EVENT_CAPTURE_RESOURCE_NOT_FOUND",s,{resourceCode:c}),t.has(c)&&m("NATIVE_EVENT_CAPTURE_POLICY_DUPLICATE",s,{resourceCode:c}),a.mode!=="all"&&a.mode!=="subscribed"&&m("NATIVE_EVENT_CAPTURE_MODE_INVALID",`${s}/mode`),t.set(c,a.mode)}let n=new Map(e.dataPolicies.map((i,d)=>{let s=N(i,`/capturePlan/dataPolicies/${d}`);return[String(s.code),s]})),r=e.subscriptions.map((i,d)=>N(i,`/capturePlan/subscriptions/${d}`));return e.resources.map((i,d)=>{let s=`/capturePlan/resources/${d}`,a=N(i,s),c=H(a.code,`${s}/code`),f=a.schema?N(a.schema,`${s}/schema`):a,u=new Set(D(f.fields||[],`${s}/schema/fields`,500).map((y,R)=>G(N(y,`${s}/schema/fields/${R}`).code,`${s}/schema/fields/${R}/code`))),p=a.dataPolicyCode?v(a.dataPolicyCode,`${s}/dataPolicyCode`):null,_=p?n.get(p):void 0;p&&!_&&m("NATIVE_EVENT_CAPTURE_AUTHZ_POLICY_NOT_FOUND",s,{resourceCode:c,dataPolicyCode:p});let E=new Set;for(let y of _?.rules||[])E.add(y.parentRead?Pt(e.resources,c,y.parentRead,`${s}/parentRead`).foreignKey:String(y.field));if(_?.readExpression)for(let y of Je(_.readExpression,`${s}/readExpression`))E.add(y.rule.parentRead?Pt(e.resources,c,y.rule.parentRead,`${s}/parentRead`).foreignKey:String(y.rule.field));let A=new Set,O=new Set,b=new Set;for(let[y,R]of r.entries()){let h=D(R.eventTypes,`/capturePlan/subscriptions/${y}/eventTypes`,20).map(String);if(!h.some(L=>L.startsWith("openxiangda.data.")))continue;let $=N(R.filter||{},`/capturePlan/subscriptions/${y}/filter`),w=Array.isArray($.resourceCodes)?$.resourceCodes.map(String):[];if(w.length&&!w.includes(c))continue;for(let L of h)zn.includes(L)&&b.add(L);for(let L of Jc($,`/capturePlan/subscriptions/${y}/filter`))A.add(L);let j=N(R.payload||{},`/capturePlan/subscriptions/${y}/payload`);for(let L of D(j.fields||[],`/capturePlan/subscriptions/${y}/payload/fields`,32))O.add(G(L,`/capturePlan/subscriptions/${y}/payload/fields`))}let g=new Set([...A,...O]),I=new Set([...g,...E]);I.size>Is&&m("NATIVE_EVENT_CAPTURE_FIELDS_LIMIT",s,{resourceCode:c,maximum:Is});for(let y of I)!u.has(y)&&!(E.has(y)&&Ls.has(y))&&m("NATIVE_EVENT_CAPTURE_FIELD_NOT_FOUND",s,{resourceCode:c,field:y});let T=N(a.fieldPolicies||{},`${s}/fieldPolicies`);for(let y of g)T[y]?.mask==="omit"&&m("NATIVE_EVENT_CAPTURE_FIELD_SENSITIVE",s,{resourceCode:c,field:y});let l={resourceCode:c,...t.get(c)==="subscribed"?{capturedEventTypes:[...b].sort()}:{},filterFields:[...A].sort(),projectionFields:[...O].sort(),authorizationFields:[...E].sort(),captureFields:[...I].sort()};return{...l,digest:Z(l)}}).sort((i,d)=>i.resourceCode.localeCompare(d.resourceCode))}function Jc(e,t){let o=new Set;for(let[d,s]of D(e.changes||[],`${t}/changes`,16).entries()){let a=N(s,`${t}/changes/${d}`);o.add(G(a.field,`${t}/changes/${d}/field`))}let n=N(e.changedFields||{},`${t}/changedFields`);for(let d of["anyOf","allOf","noneOf"])for(let[s,a]of D(n[d]||[],`${t}/changedFields/${d}`,32).entries())o.add(G(a,`${t}/changedFields/${d}/${s}`));let r=0,i=(d,s,a)=>{a>3&&m("NATIVE_EVENT_FILTER_DEPTH_LIMIT",s);let c=N(d,s);if(c.change){let u=N(c.change,`${s}/change`);o.add(G(u.field,`${s}/change/field`)),r+=1;return}if(c.not){i(c.not,`${s}/not`,a+1);return}let f=c.all?"all":c.any?"any":null;f||m("NATIVE_EVENT_FILTER_CONDITION_INVALID",s);for(let[u,p]of D(c[f],`${s}/${f}`,16).entries())i(p,`${s}/${f}/${u}`,a+1)};return e.where&&i(e.where,`${t}/where`,1),r+=Array.isArray(e.changes)?e.changes.length:0,r>16&&m("NATIVE_EVENT_FILTER_ATOM_LIMIT",t),[...o].sort()}function Hc(e,t){C(e,["schemaVersion","compilerContractVersion","appCode","perspectives","authz","backend","data","events","workflows","frontend","runtime"],"/config"),F(e.schemaVersion,Tc,"/config/schemaVersion"),F(e.compilerContractVersion,Qt,"/config/compilerContractVersion"),F(e.appCode,t,"/config/appCode"),D(e.perspectives,"/config/perspectives",100);let o=N(e.authz,"/config/authz");C(o,["capabilities","roles","scopeDimensions","scopeSources","roleMembershipSources","relationshipGrantSources","dataPolicies","authorizationTransitions"],"/config/authz",["authenticatedUserRoleCode"]),D(o.capabilities,"/config/authz/capabilities",M.capabilities),D(o.roles,"/config/authz/roles",M.roles),D(o.scopeDimensions,"/config/authz/scopeDimensions",100),D(o.scopeSources,"/config/authz/scopeSources",100),D(o.roleMembershipSources,"/config/authz/roleMembershipSources",100),D(o.relationshipGrantSources,"/config/authz/relationshipGrantSources",100),D(o.dataPolicies,"/config/authz/dataPolicies",M.dataPolicies),D(o.authorizationTransitions,"/config/authz/authorizationTransitions",100);let n=N(e.backend,"/config/backend");C(n,["secrets","operations"],"/config/backend"),D(n.secrets,"/config/backend/secrets",100),D(n.operations,"/config/backend/operations",500),kl(n.secrets);let r=N(e.data,"/config/data");C(r,["resources"],"/config/data",["resourceDetailRoutes","subjectReadSurfaces","concurrency"]),D(r.resources,"/config/data/resources",M.resources),r.subjectReadSurfaces!==void 0&&D(r.subjectReadSurfaces,"/config/data/subjectReadSurfaces",M.subjectReadSurfaces),r.resourceDetailRoutes!==void 0&&D(r.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100);let i=N(e.events,"/config/events");C(i,["schemas","subscriptions","timers","dateTriggers"],"/config/events",["capturePolicies"]),D(i.schemas,"/config/events/schemas",100),D(i.subscriptions,"/config/events/subscriptions",100),D(i.timers,"/config/events/timers",100),D(i.dateTriggers,"/config/events/dateTriggers",100);let d=N(e.workflows,"/config/workflows");C(d,["definitions","bindings","activations","providers","editableParameters"],"/config/workflows"),D(d.definitions,"/config/workflows/definitions",M.workflows),D(d.bindings,"/config/workflows/bindings",M.workflows),D(d.activations,"/config/workflows/activations",M.workflows),D(d.providers,"/config/workflows/providers",100),D(d.editableParameters,"/config/workflows/editableParameters",100);let s=N(e.frontend,"/config/frontend");C(s,["routes","user","admin","devicePolicy"],"/config/frontend",["authentication","publicAccess"]),D(s.routes,"/config/frontend/routes",M.routes);let a=N(s.user,"/config/frontend/user");C(a,["applicationTodoCenter"],"/config/frontend/user"),Nt(a.applicationTodoCenter,"/config/frontend/user/applicationTodoCenter"),Lr(s.devicePolicy,"/config/frontend/devicePolicy"),Object.prototype.hasOwnProperty.call(s,"authentication")&&Ws(s.authentication,s.routes,e,"/config/frontend/authentication"),Object.prototype.hasOwnProperty.call(s,"publicAccess")&&fl(s.publicAccess,e,"/config/frontend/publicAccess");let c=N(s.admin,"/config/frontend/admin");C(c,["navigation"],"/config/frontend/admin",["access"]),c.access!==void 0&&to(c.access,"/config/frontend/admin/access",e.appCode),gl(c.navigation,"/config/frontend/admin/navigation");let f=N(e.runtime,"/config/runtime");C(f,["protocolCapabilities","health"],"/config/runtime"),V(f.protocolCapabilities,"/config/runtime/protocolCapabilities",100),C(N(f.health,"/config/runtime/health"),["livePath","readyPath","versionPath"],"/config/runtime/health"),F(f.health.livePath,"/__platform/health","/config/runtime/health/livePath"),F(f.health.readyPath,"/__platform/ready","/config/runtime/health/readyPath"),F(f.health.versionPath,"/__platform/version","/config/runtime/health/versionPath")}function Yc(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","subjectReadSurfaces","concurrency"]),F(e.schemaVersion,vs,"/contracts/schemaVersion"),F(e.compilerContractVersion,Qt,"/contracts/compilerContractVersion"),S(e.generatorVersion,"/contracts/generatorVersion",128),F(e.appCode,t,"/contracts/appCode"),F(e.configDigest,o,"/contracts/configDigest"),D(e.perspectives,"/contracts/perspectives",M.perspectives),D(e.resources,"/contracts/resources",M.resources),e.subjectReadSurfaces!==void 0&&D(e.subjectReadSurfaces,"/contracts/subjectReadSurfaces",M.subjectReadSurfaces),D(e.capabilities,"/contracts/capabilities",M.capabilities),D(e.operations,"/contracts/operations",M.operations),D(e.eventConsumers,"/contracts/eventConsumers",M.eventConsumers),D(e.eventProducers,"/contracts/eventProducers",M.eventProducers),D(e.eventSchemas,"/contracts/eventSchemas",M.eventSchemas),N(e.eventHandlerManifest,"/contracts/eventHandlerManifest"),V(e.eventTypes,"/contracts/eventTypes",M.eventTypes),D(e.workflows,"/contracts/workflows",M.workflows),D(e.routes,"/contracts/routes",M.routes),Object.prototype.hasOwnProperty.call(e,"authentication")&&cl(e.authentication,"/contracts/authentication"),Object.prototype.hasOwnProperty.call(e,"publicAccess")&&pl(e.publicAccess,"/contracts/publicAccess"),Object.prototype.hasOwnProperty.call(e,"adminAccess")&&to(e.adminAccess,"/contracts/adminAccess",t),Ol(e.routeManifest,"/contracts/routeManifest",t),Il(e.adminPages,"/contracts/adminPages"),yl(e.adminNavigation,"/contracts/adminNavigation")}function Xc(e,t,o){let n=el(e);hl(e,n),Sl(e),wl(e),$l(e);let r=e.events.schemas.map((g,I)=>{let T=`/config/events/schemas/${I}`,l=N(g,T),y=S(l.eventType,`${T}/eventType`,255);return y.startsWith("openxiangda.")&&m("NATIVE_EVENT_SCHEMA_RESERVED",`${T}/eventType`,{eventType:y}),F(l.schemaDigest,Z(N(l.jsonSchema,`${T}/jsonSchema`)),`${T}/schemaDigest`),l}),i=new Set([...zn,...Jn,...r.map(g=>String(g.eventType))]),d=new Map(e.data.resources.map(g=>[String(g.code),new Map(g.schema.fields.map(I=>[String(I.code),String(I.type)]))])),s=te(e.events.subscriptions.map((g,I)=>{let T=`/config/events/subscriptions/${I}`,l=N(g,T),y=V(l.eventTypes,`${T}/eventTypes`,20);y.forEach((w,j)=>{i.has(w)||m("NATIVE_EVENT_TYPE_NOT_REGISTERED",`${T}/eventTypes/${j}`,{eventType:w})});let R=Yo(l,e.data.resources,T),h=Qc(l.delivery,y,`${T}/delivery`),$=Zc(l.platformAccess,`${T}/platformAccess`,d,e,l);return{code:v(l.code,`${T}/code`),endpointPath:Te(l.endpointPath,`${T}/endpointPath`),eventTypes:y,filter:N(l.filter,`${T}/filter`),payload:R?.payload||N(l.payload,`${T}/payload`),...R?{execution:R.execution}:{},...$?{platformAccess:$}:{},delivery:h}}),g=>g.code),a=new Map(r.map(g=>[String(g.eventType),String(g.dataSchemaVersion)])),c=te([...e.data.resources.flatMap(g=>zn.map(I=>({code:`data:${g.code}:${I}`,source:"data",eventType:I,dataSchemaVersion:"2.0.0",resourceCode:g.code}))),...r.map(g=>({code:`app:${g.eventType}`,source:"app",eventType:g.eventType,dataSchemaVersion:g.dataSchemaVersion})),...e.events.timers.map(g=>({code:g.code,source:"timer",eventType:g.eventType,dataSchemaVersion:a.get(String(g.eventType))||"2.0.0"})),...e.events.dateTriggers.map(g=>({code:g.code,source:"date",eventType:g.eventType,dataSchemaVersion:a.get(String(g.eventType))||"2.0.0",resourceCode:g.resourceCode,field:g.field})),...e.workflows.activations.length?Jn.filter(g=>!tr.includes(g)||e.workflows.definitions.some(I=>Object.values(I.definition.nodes).some(T=>T.kind==="action"))).filter(g=>g!=="openxiangda.workflow.node.skipped.v2"||e.workflows.definitions.some(I=>Object.values(I.definition.nodes).some(T=>T.kind==="approval"&&T.emptyPolicy==="skip"))).map(g=>({code:`workflow:${g}`,source:"workflow",eventType:g,dataSchemaVersion:"2.0.0"})):[]],g=>`${g.source}:${g.code}:${g.eventType}`),f=B([...s.flatMap(g=>g.eventTypes),...c.map(g=>String(g.eventType))]);El(e);let u=Bs(e),p;try{p=Po(e.data.concurrency,e.data.resources,n)}catch(g){throw g instanceof ut&&m(g.code,g.pointer,{reason:g.reason}),g}p?.commands.some(g=>g.mode==="durable")&&e.backend?.enabled===!1&&m("NATIVE_MANAGED_CONCURRENCY_INVALID","/data/concurrency",{reason:"durable commands require backend runtime"});let _=nl(e,n),E=js(e),A=e.workflows.definitions.map(g=>g.definition),O=Pn(A),b=or(A,s,!0);b.length&&m(b[0],"/config/events/subscriptions");try{Fo(e.data.resources,E)}catch(g){throw g instanceof ze&&m(g.code,g.pointer,{reason:g.reason}),g}return{schemaVersion:vs,compilerContractVersion:Qt,generatorVersion:o,appCode:e.appCode,configDigest:t,perspectives:e.perspectives,resources:tl(e),..._.length?{subjectReadSurfaces:_}:{},...p?{concurrency:p}:{},capabilities:te(n,g=>g.code),operations:E,eventConsumers:s,eventProducers:c,eventSchemas:r,eventHandlerManifest:{schemaVersion:Gc,appCode:e.appCode,handlers:s.filter(g=>!g.execution).map(g=>({code:g.code,endpointPath:g.endpointPath,eventTypes:g.eventTypes,dataSchemaVersions:B(g.eventTypes.map(I=>I.startsWith("openxiangda.")?"2.0.0":a.get(I)||"2.0.0")),maxBodyBytes:65536,receiptProtocolVersion:2,...O[g.code]?{workflowStep:O[g.code]}:{}}))},eventTypes:f,workflows:qs(e),routes:eo(e),...Object.prototype.hasOwnProperty.call(e.frontend,"authentication")?{authentication:ll(e)}:{},...Object.prototype.hasOwnProperty.call(e.frontend,"publicAccess")?{publicAccess:ml(e)}:{},...e.frontend.admin.access?{adminAccess:e.frontend.admin.access}:{},routeManifest:Rl(e),adminPages:u,adminNavigation:_l(e)}}function Zc(e,t,o,n,r){if(e===void 0)return;let i=N(e,t);C(i,["notification","managedFileCopies","decimalReservation"],t,!0);let d={};if(i.decimalReservation!==void 0)try{d.decimalReservation=Pi(i.decimalReservation,vi(n,r))}catch{m("NATIVE_EVENT_DECIMAL_RESERVATION_INVALID",`${t}/decimalReservation`)}if(i.notification!==void 0){let s=N(i.notification,`${t}/notification`);C(s,["mode"],`${t}/notification`),F(s.mode,"business-standard",`${t}/notification/mode`),d.notification={mode:"business-standard"}}if(i.managedFileCopies!==void 0){let s=D(i.managedFileCopies,`${t}/managedFileCopies`,16);s.length||m("NATIVE_EVENT_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let a=new Set;d.managedFileCopies=te(s.map((c,f)=>{let u=`${t}/managedFileCopies/${f}`,p=N(c,u);C(p,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],u),F(p.mode,"copy",`${u}/mode`);let _=H(p.sourceResourceCode,`${u}/sourceResourceCode`),E=H(p.targetResourceCode,`${u}/targetResourceCode`),A=o.get(_),O=o.get(E);(!A||!O)&&m("NATIVE_EVENT_MANAGED_FILE_COPY_RESOURCE_INVALID",u);let b=V(p.sourceFieldCodes,`${u}/sourceFieldCodes`,16),g=V(p.targetFieldCodes,`${u}/targetFieldCodes`,16);(!b.length||b.length!==g.length)&&m("NATIVE_EVENT_MANAGED_FILE_COPY_FIELDS_INVALID",u),b.forEach((T,l)=>{let y=A.get(T),R=O.get(g[l]);(!["file","image"].includes(String(y))||y!==R)&&m("NATIVE_EVENT_MANAGED_FILE_COPY_FIELD_INVALID",`${u}/sourceFieldCodes/${l}`)});let I=`${_}:${b.join(",")}=>${E}:${g.join(",")}`;return a.has(I)&&m("NATIVE_EVENT_MANAGED_FILE_COPY_DUPLICATE",u),a.add(I),{mode:"copy",sourceResourceCode:_,sourceFieldCodes:B(b),targetResourceCode:E,targetFieldCodes:B(g)}}),c=>`${c.sourceResourceCode}:${c.sourceFieldCodes.join(",")}=>${c.targetResourceCode}:${c.targetFieldCodes.join(",")}`)}return Object.keys(d).length||m("NATIVE_EVENT_PLATFORM_ACCESS_EMPTY",t),d}function Qc(e,t,o){let n=N(e,o);C(n,["timeoutMs","maxAttempts","initialBackoffMs","maxBackoffMs","ordering","concurrency"],o),se(n.timeoutMs,`${o}/timeoutMs`,1e3,3e4),se(n.maxAttempts,`${o}/maxAttempts`,1,12);let r=se(n.initialBackoffMs,`${o}/initialBackoffMs`,1e3,3e5);se(n.maxBackoffMs,`${o}/maxBackoffMs`,r,18e5),se(n.concurrency,`${o}/concurrency`,1,50);let i=S(n.ordering,`${o}/ordering`,32);return["none","record","workflow-instance"].includes(i)||m("NATIVE_EVENT_DELIVERY_ORDERING_INVALID",`${o}/ordering`),i==="workflow-instance"&&t.some(d=>!qc.has(d))&&m("NATIVE_EVENT_WORKFLOW_ORDERING_REQUIRES_WORKFLOW_FACTS",`${o}/ordering`),n}function el(e){let t=new Map;for(let i of Hs(e.appCode))t.set(i.code,i);for(let[i,d]of e.authz.capabilities.entries()){let s=`/config/authz/capabilities/${i}`,a=N(d,s);C(a,["code","kind","name","description"],s,!0);let c=me(a.code,`${s}/code`,e.appCode);t.has(c)&&m("NATIVE_CAPABILITY_DUPLICATE",`${s}/code`),["backend","ui"].includes(a.kind)||m("NATIVE_CAPABILITY_KIND_INVALID",`${s}/kind`);let f={code:c,kind:a.kind,name:S(a.name,`${s}/name`,255),source:"explicit",...a.description===void 0?{}:{description:xr(a.description,`${s}/description`,2e3)}};t.set(c,f)}let o=e.data.resources.map((i,d)=>({pointer:`/config/data/resources/${d}`,resource:tt(i,`/config/data/resources/${d}`,e.appCode)}));for(let{pointer:i,resource:d}of o){let s={read:`\u8BFB\u53D6${d.name}`,create:`\u65B0\u5EFA${d.name}`,update:`\u66F4\u65B0${d.name}`,delete:`\u5220\u9664${d.name}`};for(let a of["read","create","update","delete"]){let c=me(d.capabilities[a],`${i}/capabilities/${a}`,e.appCode);t.has(c)&&m("NATIVE_CAPABILITY_DUPLICATE",`${i}/capabilities/${a}`),t.set(c,{code:c,kind:"data",name:s[a],source:"data"})}}let n=new Set(t.keys()),r=new Map;for(let{pointer:i,resource:d}of o)for(let[s,a]of Object.entries(d.fieldPolicies)){if(at(s))continue;let c=N(a,`${i}/fieldPolicies/${s}`);for(let f of["read","create","update"])if(Array.isArray(c[f]))for(let u of V(c[f],`${i}/fieldPolicies/${s}/${f}`,2e3)){if(me(u,`${i}/fieldPolicies/${s}/${f}`,e.appCode),n.has(u))continue;let p=r.get(u);p&&p!==d.code&&m("NATIVE_CAPABILITY_DUPLICATE",`${i}/fieldPolicies/${s}/${f}`),r.set(u,d.code),!t.has(u)&&t.set(u,{code:u,kind:"data",name:`${d.name}.${s}.${f}`,source:"data"})}}return[...t.values()]}function tl(e){let t=ol(e);return te(e.data.resources.map((o,n)=>{let r=tt(o,`/config/data/resources/${n}`,e.appCode),i=t.get(r.code);return{code:r.code,schemaDigest:Z(r.schema),fields:te(r.schema.fields.map(d=>({code:d.code,type:d.type})),d=>d.code),...i?{detailRouteCode:i}:{}}}),o=>o.code)}function nl(e,t){if(e.data.subjectReadSurfaces===void 0)return[];let o=D(e.data.subjectReadSurfaces,"/config/data/subjectReadSurfaces",M.subjectReadSurfaces),n=new Set(t.map(d=>String(d.code))),r=new Map(e.data.resources.map((d,s)=>{let a=`/config/data/resources/${s}`,c=tt(d,a,e.appCode);return[String(c.code),{resource:c,fields:new Map(D(N(c.schema,`${a}/schema`).fields,`${a}/schema/fields`,500).map(f=>{let u=N(f,`${a}/schema/fields`);return[String(u.code),u]}))}]})),i=new Set;return te(o.map((d,s)=>{let a=`/config/data/subjectReadSurfaces/${s}`,c=N(d,a);C(c,["code","name","capability","subject","relations"],a);let f=v(c.code,`${a}/code`);i.has(f)&&m("NATIVE_SUBJECT_READ_SURFACE_CODE_DUPLICATE",`${a}/code`),i.add(f);let u=me(c.capability,`${a}/capability`,e.appCode);n.has(u)||m("NATIVE_SUBJECT_READ_SURFACE_CAPABILITY_NOT_DECLARED",`${a}/capability`);let p=N(c.subject,`${a}/subject`);C(p,["resourceCode","fields"],`${a}/subject`);let _=H(p.resourceCode,`${a}/subject/resourceCode`),E=r.get(_);E||m("NATIVE_SUBJECT_READ_SURFACE_RESOURCE_NOT_DECLARED",`${a}/subject/resourceCode`);let A=V(p.fields,`${a}/subject/fields`,100).map((T,l)=>G(T,`${a}/subject/fields/${l}`));A.length||m("NATIVE_SUBJECT_READ_SURFACE_FIELDS_REQUIRED",`${a}/subject/fields`);for(let[T,l]of A.entries()){let y=E.fields.get(l);(!y||y.type==="subtable")&&m("NATIVE_SUBJECT_READ_SURFACE_FIELD_INVALID",`${a}/subject/fields/${T}`)}let O=D(c.relations,`${a}/relations`,8);O.length||m("NATIVE_SUBJECT_READ_SURFACE_RELATIONS_REQUIRED",`${a}/relations`);let b=new Set,g=0,I=te(O.map((T,l)=>{let y=`${a}/relations/${l}`,R=N(T,y);C(R,["code","resourceCode","foreignKeyField","fields","limit"],y,["order"]);let h=v(R.code,`${y}/code`);b.has(h)&&m("NATIVE_SUBJECT_READ_SURFACE_RELATION_CODE_DUPLICATE",`${y}/code`),b.add(h);let $=H(R.resourceCode,`${y}/resourceCode`),w=r.get($);w||m("NATIVE_SUBJECT_READ_SURFACE_RESOURCE_NOT_DECLARED",`${y}/resourceCode`);let j=G(R.foreignKeyField,`${y}/foreignKeyField`),L=w.fields.get(j),Q=N(L?.source||{},`${y}/foreignKeyField/source`);(!L||!["uuid","resource-ref.single"].includes(String(L.type))||L.type==="resource-ref.single"&&(Q.kind!=="resource"||Q.resourceCode!==_))&&m("NATIVE_SUBJECT_READ_SURFACE_RELATION_INVALID",`${y}/foreignKeyField`);let ee=V(R.fields,`${y}/fields`,100).map((re,P)=>G(re,`${y}/fields/${P}`));ee.length||m("NATIVE_SUBJECT_READ_SURFACE_FIELDS_REQUIRED",`${y}/fields`);for(let[re,P]of ee.entries()){let U=w.fields.get(P);(!U||U.type==="subtable")&&m("NATIVE_SUBJECT_READ_SURFACE_FIELD_INVALID",`${y}/fields/${re}`)}let Y=D(R.order||[],`${y}/order`,10).map((re,P)=>{let U=`${y}/order/${P}`,x=N(re,U);C(x,["field","direction"],U);let q=G(x.field,`${U}/field`),z=w.fields.get(q);return(!Ls.has(q)&&!z||z?.type==="subtable"||z&&!ct(z.type))&&m("NATIVE_SUBJECT_READ_SURFACE_ORDER_FIELD_INVALID",`${U}/field`),["asc","desc"].includes(String(x.direction))||m("NATIVE_SUBJECT_READ_SURFACE_ORDER_DIRECTION_INVALID",`${U}/direction`),{field:q,direction:x.direction}}),ge=se(R.limit,`${y}/limit`,1,100);return g+=ge,{code:h,resourceCode:$,foreignKeyField:j,fields:B(ee),...Y.length?{order:Y}:{},limit:ge}}),T=>T.code);return g>400&&m("NATIVE_SUBJECT_READ_SURFACE_ROW_LIMIT_EXCEEDED",`${a}/relations`),{code:f,name:S(c.name,`${a}/name`,255),capability:u,subject:{resourceCode:_,fields:B(A)},relations:I}}),d=>d.code)}function ol(e){let t=e.data.resourceDetailRoutes===void 0?[]:D(e.data.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100),o=new Map(e.data.resources.map((i,d)=>{let s=`/config/data/resources/${d}`,a=tt(i,s,e.appCode);return[a.code,a]})),n=new Map(eo(e).map(i=>[String(i.code),i])),r=new Map;for(let[i,d]of t.entries()){let s=`/config/data/resourceDetailRoutes/${i}`,a=N(d,s);C(a,["resourceCode","desktop","mobile"],s);let c=H(a.resourceCode,`${s}/resourceCode`);r.has(c)&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_DUPLICATE",`${s}/resourceCode`);let f=o.get(c);f||m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_RESOURCE_MISSING",`${s}/resourceCode`);let u=v(a.desktop,`${s}/desktop`),p=v(a.mobile,`${s}/mobile`);u===p&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_INVALID",s);let _=String(f.capabilities.read);for(let[E,A]of[["desktop",u],["mobile",p]]){let O=`${s}/${E}`,b=n.get(A);b||m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_REFERENCE_MISSING",O),b.surface!=="user"&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_SURFACE_INVALID",O);let g=Te(b.path,`${O}/path`),I=[...g.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)],T=E==="mobile"?!g.startsWith("/m/"):g==="/m"||g.startsWith("/m/");(g.includes("*")||g.includes("?")||g.includes("#")||g.split("/").includes("..")||I.length!==1||T)&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_PATH_INVALID",O);let l=Array.isArray(b.access?.allOf)?b.access.allOf:[];b.capability!==_&&!l.includes(_)&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_CAPABILITY_INVALID",O)}r.set(c,{desktop:u,mobile:p})}return r}function js(e){let t=new Map(e.data.resources.map((d,s)=>{let a=`/config/data/resources/${s}`,c=tt(d,a,e.appCode);return[c.code,new Map(c.schema.fields.map(f=>[String(f.code),f]))]})),o=new Map(e.data.resources.map((d,s)=>{let a=`/config/data/resources/${s}`,c=tt(d,a,e.appCode);return[c.code,new Map(c.schema.fields.map(f=>[String(f.code),String(f.type)]))]})),n=new Set(o.keys()),r=new Set(e.workflows.activations.map((d,s)=>no(N(d,`/config/workflows/activations/${s}`).workflowCode,`/config/workflows/activations/${s}/workflowCode`))),i=new Map;return te(e.backend.operations.map((d,s)=>{let a=`/config/backend/operations/${s}`,c=N(d,a);C(c,["code","method","path","capability","requestSchema","responseSchema","description","platformAccess","browser","ai"],a,!0);let f=S(c.method,`${a}/method`,16);["GET","POST","PUT","PATCH","DELETE"].includes(f)||m("NATIVE_OPERATION_METHOD_INVALID",`${a}/method`);let u=v(c.code,`${a}/code`);al(c.ai,a,u,f,n);let p=sl(c.platformAccess,`${a}/platformAccess`,o,t,r,new Set(e.authz.roles.map(E=>String(E.code))));if(p?.workflowStage){let E=p.workflowStage,A=e.workflows.definitions.find(O=>O.definition.code===E.workflowCode);(!A||A.definition.subject?.resourceCode!==E.resourceCode||E.runningNodeIds.some(O=>!A.definition.nodes[O]))&&m("NATIVE_WORKFLOW_STAGE_NODE_INVALID",`${a}/platformAccess/workflowStage/runningNodeIds`)}if(p?.recordEdit){let E=e.data.resources.find(A=>A.code===p.recordEdit.resourceCode);E?.surface?.mutationOwner!=="action"&&m("NATIVE_RECORD_EDIT_ACTION_OWNER_REQUIRED",`${a}/platformAccess/recordEdit`);for(let A of p.recordEdit.fieldCodes)(!E.fieldPolicies?.[A]?.update?.length||E.surface?.fields?.[A]?.system===!0)&&m("NATIVE_RECORD_EDIT_FIELD_INVALID",`${a}/platformAccess/recordEdit/fieldCodes`)}if(p?.decimalReservation){let E=p.decimalReservation,A=String(E.resourceCode),O=JSON.stringify([E.amountFieldCode,E.currencyFieldCode,E.relationFieldCode,E.parentFieldCode,E.rootFieldCode,E.statusFieldCode,E.parentRelationValue,E.childRelationValue]),b=i.get(A);b&&b!==O&&m("NATIVE_DECIMAL_RESERVATION_MAPPING_CONFLICT",`${a}/platformAccess/decimalReservation`),i.set(A,O)}let _=rl(c.browser,`${a}/browser`,f,c.requestSchema,c.responseSchema,o,t,e.data.subjectReadSurfaces||[]);return{code:u,method:f,path:Te(c.path,`${a}/path`),requiredCapability:me(c.capability,`${a}/capability`,e.appCode),requestSchemaDigest:Z(N(c.requestSchema,`${a}/requestSchema`)),responseSchemaDigest:Z(N(c.responseSchema,`${a}/responseSchema`)),...c.description===void 0?{}:{description:xr(c.description,`${a}/description`,2e3)},...p?{platformAccess:p}:{},..._?{browser:_}:{}}}),d=>d.code)}function rl(e,t,o,n,r,i,d,s){if(e===void 0)return null;let a=N(e,t);C(a,["exposure","behavior","idempotency","subject"],t,["refreshTargets","fileIntent"]),F(a.exposure,"authenticated",`${t}/exposure`);let c=S(a.behavior,`${t}/behavior`,32);["read","controlled"].includes(c)||m("NATIVE_OPERATION_BROWSER_BEHAVIOR_INVALID",`${t}/behavior`);let f=S(a.idempotency,`${t}/idempotency`,32);(!["none","required"].includes(f)||c==="controlled"&&f!=="required"||c==="read"&&f!=="none")&&m("NATIVE_OPERATION_BROWSER_IDEMPOTENCY_INVALID",`${t}/idempotency`);let u=N(a.subject,`${t}/subject`);C(u,["resourceCode","inputField"],`${t}/subject`);let p=H(u.resourceCode,`${t}/subject/resourceCode`);i.has(p)||m("NATIVE_OPERATION_BROWSER_SUBJECT_RESOURCE_NOT_DECLARED",`${t}/subject/resourceCode`);let _=G(u.inputField,`${t}/subject/inputField`),E=N(n,`${t}/requestSchema`),A=N(r,`${t}/responseSchema`);(E.type!=="object"||E.additionalProperties!==!1||A.type!=="object"||A.additionalProperties!==!1)&&m("NATIVE_OPERATION_BROWSER_SCHEMA_ROOT_INVALID",`${t}/requestSchema`);let O=N(E.properties,`${t}/requestSchema/properties`),b=new Set(E.required===void 0?[]:V(E.required,`${t}/requestSchema/required`,200));(!(_ in O)||!b.has(_))&&m("NATIVE_OPERATION_BROWSER_SUBJECT_INPUT_INVALID",`${t}/subject/inputField`);let g=N(O[_],`${t}/requestSchema/properties/${_}`);(g.type!=="string"||g.format!=="uuid")&&m("NATIVE_OPERATION_BROWSER_SUBJECT_INPUT_INVALID",`${t}/subject/inputField`);let I=new Map((Array.isArray(s)?s:[]).map((h,$)=>{let w=N(h,`/config/data/subjectReadSurfaces/${$}`);return[String(w.code),String(N(w.subject,`/config/data/subjectReadSurfaces/${$}/subject`).resourceCode)]})),T=a.refreshTargets===void 0?[]:D(a.refreshTargets,`${t}/refreshTargets`,16),l=new Set,y=te(T.map((h,$)=>{let w=`${t}/refreshTargets/${$}`,j=N(h,w);C(j,["kind","code"],w),F(j.kind,"subject-surface",`${w}/kind`);let L=v(j.code,`${w}/code`);return(l.has(L)||!I.has(L)||I.get(L)!==p)&&m("NATIVE_OPERATION_BROWSER_REFRESH_TARGET_INVALID",`${w}/code`),l.add(L),{kind:"subject-surface",code:L}}),h=>`${h.kind}:${h.code}`),R=il(a.fileIntent,`${t}/fileIntent`,o,c,f,p,O,b,d);return{exposure:"authenticated",behavior:c,idempotency:f,subject:{resourceCode:p,inputField:_},...y.length?{refreshTargets:y}:{},...R?{fileIntent:R}:{}}}function il(e,t,o,n,r,i,d,s,a){if(e===void 0)return null;let c=N(e,t);C(c,["recordResourceCode","recordIdInputField","relationField","fileNameField","contentTypeField","sizeField","purposes","maxTtlSeconds","maxBytes"],t),(o!=="GET"||n!=="read"||r!=="none")&&m("NATIVE_OPERATION_FILE_INTENT_BEHAVIOR_INVALID",t);let f=H(c.recordResourceCode,`${t}/recordResourceCode`),u=a.get(f);u||m("NATIVE_OPERATION_FILE_INTENT_RESOURCE_NOT_DECLARED",`${t}/recordResourceCode`);let p=G(c.recordIdInputField,`${t}/recordIdInputField`),_=N(d[p],`${t}/recordIdInputField`);(!s.has(p)||_.type!=="string"||_.format!=="uuid")&&m("NATIVE_OPERATION_FILE_INTENT_RECORD_INPUT_INVALID",`${t}/recordIdInputField`);let E=G(c.relationField,`${t}/relationField`),A=u.get(E);(!A||!["uuid","resource-ref.single"].includes(String(A.type))||String(A.type)==="resource-ref.single"&&(String(N(A.source,`${t}/relationField`).kind||"")!=="resource"||String(N(A.source,`${t}/relationField`).resourceCode||"")!==i))&&m("NATIVE_OPERATION_FILE_INTENT_RELATION_INVALID",`${t}/relationField`);let O=[["fileNameField",["text.short","text.long"]],["contentTypeField",["text.short","text.long"]],["sizeField",["number.integer"]]],b={};for(let[l,y]of O){let R=G(c[l],`${t}/${l}`);y.includes(String(u.get(R)?.type))||m("NATIVE_OPERATION_FILE_INTENT_METADATA_INVALID",`${t}/${l}`),b[l]=R}let g=te(V(c.purposes,`${t}/purposes`,2),l=>l);(!g.length||g.some(l=>!["preview","download"].includes(l)))&&m("NATIVE_OPERATION_FILE_INTENT_PURPOSE_INVALID",`${t}/purposes`);let I=Number(c.maxTtlSeconds);(!Number.isSafeInteger(I)||I<1||I>300)&&m("NATIVE_OPERATION_FILE_INTENT_TTL_INVALID",`${t}/maxTtlSeconds`);let T=Number(c.maxBytes);return(!Number.isSafeInteger(T)||T<1||T>104857600)&&m("NATIVE_OPERATION_FILE_INTENT_SIZE_INVALID",`${t}/maxBytes`),{recordResourceCode:f,recordIdInputField:p,relationField:E,fileNameField:b.fileNameField,contentTypeField:b.contentTypeField,sizeField:b.sizeField,purposes:g,maxTtlSeconds:I,maxBytes:T}}function sl(e,t,o,n,r,i){if(e===void 0)return null;let d=N(e,t);C(d,["directory","managedFiles","managedFileCopies","notification","workflow","roleAssertions","decimalReservation","dataCommands","recordEdit","ownedSubject","workflowStage"],t,!0),Object.keys(d).length===0&&m("NATIVE_OPERATION_PLATFORM_ACCESS_EMPTY",t);let s={};if(d.dataCommands!==void 0){let a=N(d.dataCommands,`${t}/dataCommands`);C(a,["mode"],`${t}/dataCommands`),F(a.mode,"recoverable-native",`${t}/dataCommands/mode`),s.dataCommands={mode:"recoverable-native"}}if(d.workflowStage!==void 0){try{Ko(d.workflowStage)}catch{m("NATIVE_WORKFLOW_STAGE_DECLARATION_INVALID",`${t}/workflowStage`)}let a=d.workflowStage;(!s.dataCommands||d.decimalReservation!==void 0||!o.has(a.resourceCode)||!r.has(a.workflowCode)||!d.workflow?.codes?.includes(a.workflowCode))&&m("NATIVE_WORKFLOW_STAGE_DECLARATION_INVALID",`${t}/workflowStage`),s.workflowStage={...a,runningNodeIds:B([...a.runningNodeIds]),allowedStatuses:B([...a.allowedStatuses])}}if(d.recordEdit!==void 0){let a=`${t}/recordEdit`,c=N(d.recordEdit,a);C(c,["resourceCode","fieldCodes"],a);let f=H(c.resourceCode,`${a}/resourceCode`),u=n.get(f),p=V(c.fieldCodes,`${a}/fieldCodes`,200);(!u||!p.length||!s.dataCommands)&&m("NATIVE_RECORD_EDIT_DECLARATION_INVALID",a);for(let _ of p){let E=u.get(_);(!E||E.type==="serial-number"||E.type==="subtable")&&m("NATIVE_RECORD_EDIT_FIELD_INVALID",`${a}/fieldCodes`)}s.recordEdit={resourceCode:f,fieldCodes:B(p)}}if(d.roleAssertions!==void 0){let a=N(d.roleAssertions,`${t}/roleAssertions`);C(a,["roleCodes","actorAuthority"],`${t}/roleAssertions`,!0),a.actorAuthority!==void 0&&F(a.actorAuthority,!0,`${t}/roleAssertions/actorAuthority`);let c=V(a.roleCodes,`${t}/roleAssertions/roleCodes`,20);c.length||m("NATIVE_OPERATION_ROLE_ASSERTIONS_REQUIRED",`${t}/roleAssertions/roleCodes`),c.forEach((f,u)=>{i.has(f)||m("NATIVE_ROLE_REFERENCE_MISSING",`${t}/roleAssertions/roleCodes/${u}`)}),s.roleAssertions={roleCodes:B(c),...a.actorAuthority===!0?{actorAuthority:!0}:{}}}if(d.directory!==void 0){let a=N(d.directory,`${t}/directory`);C(a,["mode","fields"],`${t}/directory`),["current-initiator","selected-user"].includes(String(a.mode))||m("NATIVE_OPERATION_DIRECTORY_MODE_INVALID",`${t}/directory/mode`);let c=new Set(["displayName","employeeNumber","primaryDepartment","departments",...a.mode==="current-initiator"?["phone"]:[]]),f=V(a.fields,`${t}/directory/fields`,c.size);(!f.length||f.some(u=>!c.has(u)))&&m("NATIVE_OPERATION_DIRECTORY_FIELDS_INVALID",`${t}/directory/fields`),s.directory={mode:String(a.mode),fields:B(f)}}if(d.managedFiles!==void 0){let a=D(d.managedFiles,`${t}/managedFiles`,16);a.length||m("NATIVE_OPERATION_MANAGED_FILES_REQUIRED",`${t}/managedFiles`);let c=new Set;s.managedFiles=te(a.map((f,u)=>{let p=`${t}/managedFiles/${u}`,_=N(f,p);C(_,["resourceCode","fieldCodes","intents"],p);let E=H(_.resourceCode,`${p}/resourceCode`);(c.has(E)||!o.has(E))&&m("NATIVE_OPERATION_MANAGED_FILE_RESOURCE_INVALID",`${p}/resourceCode`),c.add(E);let A=V(_.fieldCodes,`${p}/fieldCodes`,16);(!A.length||A.some(b=>!["file","image","signature","text.rich"].includes(String(o.get(E)?.get(b)||""))))&&m("NATIVE_OPERATION_MANAGED_FILE_FIELD_INVALID",`${p}/fieldCodes`);let O=V(_.intents,`${p}/intents`,2);return(!O.length||O.some(b=>!["create","update"].includes(b)))&&m("NATIVE_OPERATION_MANAGED_FILE_INTENT_INVALID",`${p}/intents`),{resourceCode:E,fieldCodes:B(A),intents:B(O)}}),f=>f.resourceCode)}if(d.managedFileCopies!==void 0){let a=D(d.managedFileCopies,`${t}/managedFileCopies`,16);a.length||m("NATIVE_OPERATION_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let c=new Set;s.managedFileCopies=te(a.map((f,u)=>{let p=`${t}/managedFileCopies/${u}`,_=N(f,p);C(_,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],p),F(_.mode,"copy",`${p}/mode`);let E=H(_.sourceResourceCode,`${p}/sourceResourceCode`),A=H(_.targetResourceCode,`${p}/targetResourceCode`),O=o.get(E),b=o.get(A);(!O||!b)&&m("NATIVE_OPERATION_MANAGED_FILE_COPY_RESOURCE_INVALID",p);let g=V(_.sourceFieldCodes,`${p}/sourceFieldCodes`,16),I=V(_.targetFieldCodes,`${p}/targetFieldCodes`,16);(!g.length||g.length!==I.length)&&m("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELDS_INVALID",p),g.forEach((l,y)=>{let R=O.get(l),h=b.get(I[y]);(!["file","image"].includes(String(R))||R!==h)&&m("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELD_INVALID",`${p}/sourceFieldCodes/${y}`)});let T=`${E}:${g.join(",")}=>${A}:${I.join(",")}`;return c.has(T)&&m("NATIVE_OPERATION_MANAGED_FILE_COPY_DUPLICATE",p),c.add(T),{mode:"copy",sourceResourceCode:E,sourceFieldCodes:B(g),targetResourceCode:A,targetFieldCodes:B(I)}}),f=>`${f.sourceResourceCode}:${f.sourceFieldCodes.join(",")}=>${f.targetResourceCode}:${f.targetFieldCodes.join(",")}`)}if(d.notification!==void 0){let a=N(d.notification,`${t}/notification`);C(a,["mode"],`${t}/notification`),a.mode!=="business-standard"&&m("NATIVE_OPERATION_NOTIFICATION_MODE_INVALID",`${t}/notification/mode`),s.notification={mode:"business-standard"}}if(d.workflow!==void 0){let a=N(d.workflow,`${t}/workflow`);C(a,["codes"],`${t}/workflow`,["businessCommands"]);let c=V(a.codes,`${t}/workflow/codes`,16);(!c.length||c.some(u=>!r.has(u)))&&m("NATIVE_OPERATION_WORKFLOW_CODE_INVALID",`${t}/workflow/codes`);let f=a.businessCommands===void 0?void 0:V(a.businessCommands,`${t}/workflow/businessCommands`,4);f&&(!f.length||f.some(u=>!["approve","reject","withdraw","resubmit"].includes(u)))&&m("NATIVE_OPERATION_WORKFLOW_BUSINESS_COMMAND_INVALID",`${t}/workflow/businessCommands`),s.workflow={codes:B(c),...f?{businessCommands:B(f)}:{}}}if(d.ownedSubject!==void 0){let a=`${t}/ownedSubject`,c=d.ownedSubject;try{Ht(c)}catch{m("NATIVE_WORKFLOW_OWNED_SUBJECT_INVALID",a)}(!s.workflow||d.decimalReservation!==void 0)&&m("NATIVE_WORKFLOW_OWNED_SUBJECT_INVALID",a);try{wr(c,n,s.managedFiles||[])}catch(f){m(`NATIVE_${f.message}`,a)}s.ownedSubject={mode:"create",resourceCode:c.resourceCode,subtables:te(c.subtables.map(f=>({fieldCode:f.fieldCode,fieldCodes:B([...f.fieldCodes])})),f=>f.fieldCode)}}if(d.decimalReservation!==void 0){let a=`${t}/decimalReservation`,c=N(d.decimalReservation,a);C(c,["mode","resourceCode","amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode","parentRelationValue","childRelationValue","eligibleParentStatuses","eligibleChildStatuses"],a);let f=S(c.mode,`${a}/mode`,16);["reserve","commit","release"].includes(f)||m("NATIVE_DECIMAL_RESERVATION_MODE_INVALID",`${a}/mode`);let u=H(c.resourceCode,`${a}/resourceCode`),p=n.get(u);p||m("NATIVE_DECIMAL_RESERVATION_RESOURCE_MISSING",`${a}/resourceCode`);let E=Object.fromEntries(["amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode"].map(l=>[l,G(c[l],`${a}/${l}`)])),A=l=>p.get(E[l]),O=l=>new Set((A(l)?.options||[]).map(y=>String(y.value))),b=v(c.parentRelationValue,`${a}/parentRelationValue`),g=v(c.childRelationValue,`${a}/childRelationValue`),I=V(c.eligibleParentStatuses,`${a}/eligibleParentStatuses`,16),T=V(c.eligibleChildStatuses,`${a}/eligibleChildStatuses`,16);(A("amountFieldCode")?.type!=="number.decimal"||A("amountFieldCode")?.exactDecimal!==!0||A("amountFieldCode")?.precision!==18||A("amountFieldCode")?.scale!==2||A("currencyFieldCode")?.type!=="option.single"||A("relationFieldCode")?.type!=="option.single"||A("parentFieldCode")?.type!=="resource-ref.single"||A("parentFieldCode")?.source?.resourceCode!==u||A("rootFieldCode")?.type!=="uuid"||A("statusFieldCode")?.type!=="option.single"||b===g||!O("relationFieldCode").has(b)||!O("relationFieldCode").has(g)||!I.length||!T.length||I.some(l=>!O("statusFieldCode").has(l))||T.some(l=>!O("statusFieldCode").has(l)))&&m("NATIVE_DECIMAL_RESERVATION_FIELD_INVALID",a),s.decimalReservation={mode:f,resourceCode:u,...E,parentRelationValue:b,childRelationValue:g,eligibleParentStatuses:B(I),eligibleChildStatuses:B(T)}}return s}function al(e,t,o,n,r){if(e===void 0)return;let i=`${t}/ai`,d=N(e,i);Sc.test(o)||m("NATIVE_OPERATION_AI_CODE_INVALID",`${t}/code`),C(d,["name","description","risk","resources","sideEffects","concurrency","timeoutMs"],i,!0),S(d.name,`${i}/name`,$r),S(d.description,`${i}/description`,$r);let s=S(d.risk,`${i}/risk`,16);["read","write","destructive","external"].includes(s)||m("NATIVE_OPERATION_AI_RISK_INVALID",`${i}/risk`),s==="read"!=(n==="GET")&&m("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${i}/risk`),n==="DELETE"&&!["destructive","external"].includes(s)&&m("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${i}/risk`);let a=V(d.resources,`${i}/resources`,16);a.length===0&&m("NATIVE_OPERATION_AI_RESOURCE_REQUIRED",`${i}/resources`),a.forEach((f,u)=>{let p=H(f,`${i}/resources/${u}`);r.has(p)||m("NATIVE_OPERATION_AI_RESOURCE_MISSING",`${i}/resources/${u}`)});let c=V(d.sideEffects,`${i}/sideEffects`,20);(s==="read"&&c.length!==0||s!=="read"&&c.length===0)&&m("NATIVE_OPERATION_AI_SIDE_EFFECT_INVALID",`${i}/sideEffects`),d.concurrency!==void 0&&!["none","revision"].includes(S(d.concurrency,`${i}/concurrency`,16))&&m("NATIVE_OPERATION_AI_CONCURRENCY_INVALID",`${i}/concurrency`),d.timeoutMs!==void 0&&se(d.timeoutMs,`${i}/timeoutMs`,100,3e4)}function Yn(e){return(e.replace(/\/{2,}/g,"/").replace(/\/$/,"")||"/").split("/").map(o=>o.startsWith(":")?":":o.includes("*")?"*":o).join("/")}function dl(e,t){let o=N(e,t),n=S(o.type,`${t}/type`,32),r=["code","type","label","presentation","required"],i=n==="sso"?[...r,"provider"]:n==="dingtalk"?[...r,"flow"]:r;C(o,i,t);let d=v(o.code,`${t}/code`),s=S(o.label,`${t}/label`,255),a=S(o.presentation,`${t}/presentation`,16);["primary","secondary"].includes(a)||m("NATIVE_APPLICATION_AUTH_METHOD_PRESENTATION_INVALID",`${t}/presentation`);let c=Nt(o.required,`${t}/required`);return["sso","password","dingtalk"].includes(n)||m("NATIVE_APPLICATION_AUTH_METHOD_TYPE_INVALID",`${t}/type`),n==="sso"&&o.provider!=="tenant-default"&&m("NATIVE_APPLICATION_AUTH_SSO_PROVIDER_INVALID",`${t}/provider`),n==="dingtalk"&&!["auto","jsapi","oauth"].includes(S(o.flow,`${t}/flow`,16))&&m("NATIVE_APPLICATION_AUTH_DINGTALK_FLOW_INVALID",`${t}/flow`),{code:d,type:n,label:s,presentation:a,required:c,...n==="sso"?{provider:"tenant-default"}:{},...n==="dingtalk"?{flow:o.flow}:{}}}function bs(e,t,o){let n=N(e,o);C(n,["routeCode","path","defaultRouteCode"],o);let r=v(n.routeCode,`${o}/routeCode`),i=Te(n.path,`${o}/path`),d=t==="desktop"?"/login":"/m/login";return(i!==d||/[:*?#\\]/.test(i))&&m("NATIVE_APPLICATION_AUTH_SURFACE_PATH_INVALID",`${o}/path`,{device:t,expectedPath:d}),{routeCode:r,path:i,defaultRouteCode:v(n.defaultRouteCode,`${o}/defaultRouteCode`)}}function Ws(e,t,o,n){if(e===null)return;let r=N(e,n);C(r,["accountMode","registration","methods","surfaces"],n),F(r.accountMode,"existing-platform-users-only",`${n}/accountMode`);let i=N(r.registration,`${n}/registration`);C(i,["mode"],`${n}/registration`),F(i.mode,"reject",`${n}/registration/mode`);let d=D(r.methods,`${n}/methods`,8);d.length===0&&m("NATIVE_APPLICATION_AUTH_METHOD_REQUIRED",`${n}/methods`);let s=d.map((b,g)=>dl(b,`${n}/methods/${g}`)),a=new Set,c=new Set;for(let[b,g]of s.entries())a.has(g.code)&&m("NATIVE_APPLICATION_AUTH_METHOD_CODE_DUPLICATE",`${n}/methods/${b}/code`),c.has(g.type)&&m("NATIVE_APPLICATION_AUTH_METHOD_TYPE_DUPLICATE",`${n}/methods/${b}/type`),a.add(g.code),c.add(g.type);s.filter(b=>b.presentation==="primary").length!==1&&m("NATIVE_APPLICATION_AUTH_PRIMARY_METHOD_INVALID",`${n}/methods`);let f=N(r.surfaces,`${n}/surfaces`);C(f,["desktop","mobile"],`${n}/surfaces`);let u=bs(f.desktop,"desktop",`${n}/surfaces/desktop`),p=bs(f.mobile,"mobile",`${n}/surfaces/mobile`);u.routeCode===p.routeCode&&m("NATIVE_APPLICATION_AUTH_SURFACE_CODE_DUPLICATE",`${n}/surfaces/mobile/routeCode`);let _=D(t,"/config/frontend/routes",M.routes),E=new Map;for(let[b,g]of _.entries()){let I=N(g,`/config/frontend/routes/${b}`);E.set(String(I.code||""),I)}let A=new Set((Array.isArray(o.data?.resources)?o.data.resources:[]).map(b=>String(b.code||"")).filter(b=>/^[a-z][a-z0-9-]{0,62}$/.test(b)));for(let[b,g]of[["desktop",u],["mobile",p]]){E.has(g.routeCode)&&m("NATIVE_APPLICATION_AUTH_SURFACE_CODE_CONFLICT",`${n}/surfaces/${b}/routeCode`);let I=/^user\.([a-z][a-z0-9-]{0,62})\.(records|submit)$/.exec(String(g.defaultRouteCode||"")),T=E.get(g.defaultRouteCode),l=String(T?.path||"");if(I&&A.has(I[1])){let R=I[2]==="records"?`/my/${I[1]}`:`/my/${I[1]}/submit`;T={surface:"user",path:b==="mobile"?`/m${R}`:R},l=String(T.path)}let y=b==="desktop"?l==="/m"||l.startsWith("/m/"):!(l==="/m"||l.startsWith("/m/"));(!T||T.surface!=="user"||/[:*]/.test(l)||y)&&m("NATIVE_APPLICATION_AUTH_DEFAULT_ROUTE_INVALID",`${n}/surfaces/${b}/defaultRouteCode`)}let O=Us(o).filter(b=>!b.owner.startsWith("authentication:"));for(let[b,g]of[["desktop",u],["mobile",p]]){let I=O.find(T=>Yn(T.path)===Yn(g.path));I&&m("NATIVE_APPLICATION_AUTH_SURFACE_PATH_CONFLICT",`${n}/surfaces/${b}/path`,{owner:I.owner})}}function cl(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=N(e,t),r=N(n.surfaces,`${t}/surfaces`),i={...n,surfaces:{...r,desktop:{...N(r.desktop,`${t}/surfaces/desktop`),defaultRouteCode:"auth-desktop-default"},mobile:{...N(r.mobile,`${t}/surfaces/mobile`),defaultRouteCode:"auth-mobile-default"}}};Ws(i,o.frontend.routes,{...o,frontend:{...o.frontend,authentication:i}},t)}function ll(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 ul=new Set(["draft.read","draft.update","validate","create","own.list","own.read","public.list","public.read"]);function fl(e,t,o){let n=N(e,o);C(n,["policies"],o);let r=D(n.policies,`${o}/policies`,16);r.length<1&&m("NATIVE_PUBLIC_POLICY_REQUIRED",o);let i=new Map(t.frontend.routes.map(c=>[c.code,c])),d=new Map(t.data.resources.map(c=>[c.code,c])),s=new Set,a=new Set(r.map(c=>String(c?.code||"")));r.forEach((c,f)=>{let u=`${o}/policies/${f}`,p=N(c,u);C(p,["code","routeCode","mode","resourceCode","operations","fields"],u,["requiredFields","ownRecordFields","publicRecordFields","publicFilters","serverGeneratedFields","schedule","publicSubtableFields","draft","validations"]);let _=v(p.code,`${u}/code`);s.has(_)&&m("NATIVE_PUBLIC_POLICY_DUPLICATE",`${u}/code`);let E=v(p.routeCode,`${u}/routeCode`),A=i.get(E);(!A||A.surface!=="user"||A.capability!==void 0||A.access!==void 0||/[:*]/.test(String(A.path)))&&m("NATIVE_PUBLIC_ROUTE_INVALID",`${u}/routeCode`),F(p.mode,"anonymous",`${u}/mode`);let O=H(p.resourceCode,`${u}/resourceCode`),b=d.get(O);b||m("NATIVE_PUBLIC_RESOURCE_MISSING",`${u}/resourceCode`);let g=new Map(b.schema.fields.map(P=>[String(P.code),String(P.type)])),I=V(p.operations,`${u}/operations`,8);(I.length<1||I.some(P=>!ul.has(P)))&&m("NATIVE_PUBLIC_OPERATION_INVALID",`${u}/operations`),I.includes("draft.read")!==I.includes("draft.update")&&m("NATIVE_PUBLIC_DRAFT_OPERATION_INCOMPLETE",`${u}/operations`);let T=V(p.fields,`${u}/fields`,64);(T.length<1||T.some(P=>!g.has(P)))&&m("NATIVE_PUBLIC_FIELD_INVALID",`${u}/fields`);for(let P of["requiredFields","ownRecordFields","publicRecordFields"]){if(!Object.prototype.hasOwnProperty.call(p,P))continue;V(p[P],`${u}/${P}`,64).some(x=>!T.includes(x))&&m("NATIVE_PUBLIC_FIELD_SCOPE_INVALID",`${u}/${P}`)}let l=Object.prototype.hasOwnProperty.call(p,"serverGeneratedFields")?D(p.serverGeneratedFields,`${u}/serverGeneratedFields`,16):[],y=new Set;l.forEach((P,U)=>{let x=`${u}/serverGeneratedFields/${U}`,q=N(P,x);C(q,["field","kind"],x);let z=G(q.field,`${x}/field`);(y.has(z)||!g.has(z)||T.includes(z)||g.get(z)!=="text.short"&&g.get(z)!=="text.long")&&m("NATIVE_PUBLIC_SERVER_GENERATED_FIELD_INVALID",`${x}/field`),F(q.kind,"random-token",`${x}/kind`),y.add(z)});let R=Object.prototype.hasOwnProperty.call(p,"schedule")?N(p.schedule,`${u}/schedule`):null;if(R){let P=["campusPolicyCode","rulePolicyCode","campusField","ruleCampusField","ruleWeekdaysField","ruleOpenAtField","ruleCloseAtField","ruleSlotMinutesField","ruleAdvanceHoursField","ruleAdvanceDaysField","campusEnabledField","ruleEnabledField","dateField","timeField"];C(R,P,`${u}/schedule`);for(let U of["campusPolicyCode","rulePolicyCode"])v(R[U],`${u}/schedule/${U}`);for(let U of P.filter(x=>!["campusPolicyCode","rulePolicyCode"].includes(x)))G(R[U],`${u}/schedule/${U}`);for(let U of[R.campusField,R.dateField,R.timeField])T.includes(String(U))||m("NATIVE_PUBLIC_SCHEDULE_FIELD_INVALID",`${u}/schedule`);(!a.has(String(R.campusPolicyCode))||!a.has(String(R.rulePolicyCode)))&&m("NATIVE_PUBLIC_SCHEDULE_POLICY_INVALID",`${u}/schedule`)}let h=Object.prototype.hasOwnProperty.call(p,"publicFilters")?D(p.publicFilters,`${u}/publicFilters`,16):[],$=new Set;h.forEach((P,U)=>{let x=`${u}/publicFilters/${U}`,q=N(P,x);C(q,["field","operator","value"],x);let z=G(q.field,`${x}/field`);$.has(z)&&m("NATIVE_PUBLIC_FILTER_DUPLICATE",`${x}/field`),T.includes(z)||m("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${x}/field`),F(q.operator,"eq",`${x}/operator`),["boolean","text.short","text.long","number.integer","number.decimal","date","time"].includes(g.get(z)||"")||m("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${x}/field`),q.value!==null&&typeof q.value!="string"&&typeof q.value!="number"&&typeof q.value!="boolean"&&m("NATIVE_PUBLIC_FILTER_VALUE_INVALID",`${x}/value`),$.add(z)});let w=Object.prototype.hasOwnProperty.call(p,"publicSubtableFields")?N(p.publicSubtableFields,`${u}/publicSubtableFields`):null;if(w){Object.keys(w).length>64&&m("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${u}/publicSubtableFields`);for(let[P,U]of Object.entries(w)){let x=b.schema.fields.find(J=>String(J.code)===P),q=String(x?.subtable?.resourceCode||""),z=d.get(q),Ae=new Map((z?.schema?.fields||[]).map(J=>[String(J.code),String(J.type)])),Re=V(U,`${u}/publicSubtableFields/${P}`,64);(!T.includes(P)||g.get(P)!=="subtable"||!z||Re.length<1||Re.some(J=>!Ae.has(J))||Re.some(J=>Ae.get(J)==="subtable")||Re.some(J=>Ae.get(J)==="signature"))&&m("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${u}/publicSubtableFields/${P}`)}}if(I.some(P=>P.startsWith("public."))){Object.prototype.hasOwnProperty.call(p,"publicRecordFields")||m("NATIVE_PUBLIC_RECORD_FIELDS_REQUIRED",`${u}/publicRecordFields`);let P=V(p.publicRecordFields,`${u}/publicRecordFields`,64);(P.length<1||P.some(U=>!T.includes(U))||P.some(U=>g.get(U)==="signature"||g.get(U)==="subtable"&&!w?.[U]))&&m("NATIVE_PUBLIC_RECORD_FIELDS_INVALID",`${u}/publicRecordFields`)}let j=Object.prototype.hasOwnProperty.call(p,"requiredFields")?V(p.requiredFields,`${u}/requiredFields`,64):[],L=b.surface||{},Q=L.fields||{},ee=String(L.mutationOwner||"native")==="native"&&L.generated?.create!==!1,Y=b.schema.fields.filter(P=>wt(P,Q[P.code])).map(P=>String(P.code));if(I.includes("create")&&!ee&&m("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${u}/fields`),I.includes("create")&&!Object.prototype.hasOwnProperty.call(p,"draft")&&m("NATIVE_PUBLIC_DRAFT_REQUIRED",`${u}/draft`),I.includes("create"))for(let P of Y){let U=T.includes(P)?j.includes(P)?null:"requiredFields":"fields";U&&m("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${u}/${U}`,{resourceCode:H,fieldCode:P})}if(Object.prototype.hasOwnProperty.call(p,"draft")){let P=N(p.draft,`${u}/draft`);C(P,["enabled","inactivityTtlSeconds","maxBytes"],`${u}/draft`),F(P.enabled,!0,`${u}/draft/enabled`),se(P.inactivityTtlSeconds,`${u}/draft/inactivityTtlSeconds`,3600,7776e3),se(P.maxBytes,`${u}/draft/maxBytes`,4096,262144)}else I.includes("draft.read")&&m("NATIVE_PUBLIC_DRAFT_REQUIRED",`${u}/draft`);let ge=Object.prototype.hasOwnProperty.call(p,"validations")?D(p.validations,`${u}/validations`,16):[],re=new Set;ge.forEach((P,U)=>{let x=`${u}/validations/${U}`,q=N(P,x);C(q,["code","kind","fields","result"],x);let z=v(q.code,`${x}/code`);re.has(z)&&m("NATIVE_PUBLIC_VALIDATION_DUPLICATE",`${x}/code`),F(q.kind,"duplicate",`${x}/kind`),F(q.result,"availability",`${x}/result`);let Ae=V(q.fields,`${x}/fields`,8);(Ae.length<1||Ae.some(Re=>!T.includes(Re))||Ae.some(Re=>["file","subtable"].includes(g.get(Re)||"")))&&m("NATIVE_PUBLIC_VALIDATION_FIELD_INVALID",`${x}/fields`),re.add(z)}),s.add(_)})}function pl(e,t){let o=N(e,t);C(o,["policies"],t),D(o.policies,`${t}/policies`,16).length<1&&m("NATIVE_PUBLIC_POLICY_REQUIRED",t)}function ml(e){return{policies:te(e.frontend.publicAccess.policies.map(t=>({code:t.code,routeCode:t.routeCode,mode:t.mode,resourceCode:t.resourceCode,operations:B(t.operations),fields:B(t.fields),...t.requiredFields?{requiredFields:B(t.requiredFields)}:{},...t.ownRecordFields?{ownRecordFields:B(t.ownRecordFields)}:{},...t.publicRecordFields?{publicRecordFields:B(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,B(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:te(t.validations.map(o=>({code:o.code,kind:o.kind,fields:B(o.fields),result:o.result})),o=>o.code)}:{}})),t=>t.code)}}function Us(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=Ms(o),r=`/admin/resources/${o.code}`,i=[["list",r],["detail",`${r}/:id`],["create",`${r}/new`],["update",`${r}/:id/edit`]];for(let[d,s]of i)n[d]&&t.push({owner:`resource:${o.code}:${d}`,path:s},{owner:`resource:${o.code}:${d}: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 eo(e){let t=new Map(Us(e).map(o=>[Yn(o.path),o]));return te(e.frontend.routes.map((o,n)=>{let r=`/config/frontend/routes/${n}`,i=N(o,r);C(i,["code","path","label","surface","parentCode","capability","access","pinned","tabPersistence","keepAlive"],r,!0),["admin","user"].includes(i.surface)||m("NATIVE_ROUTE_SURFACE_INVALID",`${r}/surface`);let d=Te(i.path,`${r}/path`);i.surface==="admin"&&d!=="/admin"&&!d.startsWith("/admin/")&&m("NATIVE_ADMIN_ROUTE_PATH_INVALID",`${r}/path`),i.surface==="user"&&(d==="/admin"||d.startsWith("/admin/"))&&m("NATIVE_USER_ROUTE_PATH_RESERVED",`${r}/path`);let s=Yn(d),a=t.get(s);a&&m("NATIVE_ROUTE_PATH_CONFLICT",`${r}/path`,{path:d,owner:a.owner}),t.set(s,{owner:`frontend:${String(i.code||n)}`,path:d});let c=/[:*]/.test(d),f=Fr(i,r,e.appCode),u=i.pinned===void 0?void 0:Nt(i.pinned,`${r}/pinned`),p=i.tabPersistence===void 0?c?"none":"session":S(i.tabPersistence,`${r}/tabPersistence`,16),_=i.keepAlive===void 0?"none":S(i.keepAlive,`${r}/keepAlive`,16);return["session","none"].includes(p)||m("NATIVE_ROUTE_TAB_PERSISTENCE_INVALID",`${r}/tabPersistence`),["none","memory"].includes(_)||m("NATIVE_ROUTE_KEEP_ALIVE_INVALID",`${r}/keepAlive`),c&&u===!0&&m("NATIVE_DYNAMIC_ROUTE_PINNED_FORBIDDEN",`${r}/pinned`),c&&p==="session"&&m("NATIVE_DYNAMIC_ROUTE_TAB_PERSISTENCE_FORBIDDEN",`${r}/tabPersistence`),c&&_==="memory"&&m("NATIVE_DYNAMIC_ROUTE_KEEP_ALIVE_FORBIDDEN",`${r}/keepAlive`),{code:v(i.code,`${r}/code`),path:d,label:S(i.label,`${r}/label`,255),surface:i.surface,...i.parentCode===void 0?{}:{parentCode:v(i.parentCode,`${r}/parentCode`)},...f,...u===void 0?{}:{pinned:u},tabPersistence:p,keepAlive:_}}),o=>o.code)}function Ms(e){let t=e.surface===void 0?{}:N(e.surface,"/surface"),o=t.mutationOwner||"native",n=t.generated===void 0?{}:N(t.generated,"/surface/generated"),r=o==="native";return{list:n.list??!0,detail:n.detail??!0,create:n.create??r,update:n.update??r,delete:n.delete??r}}function Bs(e){let t=[];for(let o of te(e.data.resources,n=>n.code).flatMap(n=>[{resource:n,viewCode:void 0},...(n.surface?.views||[]).map(r=>({viewCode:r.code,resource:{...n,name:r.name,surface:yn(n.surface,r.code)}}))])){let{resource:n,viewCode:r}=o,i=`/admin/resources/${n.code}${r?`/views/${r}`:""}`,d=Ms(n),s=[{operation:"list",kind:"resource-list",path:`${i}`,label:n.name,capability:n.capabilities.read,navigationEligible:!0},{operation:"detail",kind:"resource-detail",path:`${i}/:id`,label:`${n.name}\u8BE6\u60C5`,capability:n.capabilities.read,navigationEligible:!1},{operation:"create",kind:"resource-create",path:`${i}/new`,label:`\u65B0\u589E${n.name}`,capability:n.capabilities.create,navigationEligible:!1},{operation:"update",kind:"resource-update",path:`${i}/:id/edit`,label:`\u7F16\u8F91${n.name}`,capability:n.capabilities.update,navigationEligible:!1}];for(let a of s)d[a.operation]&&t.push({code:`resource:${n.code}${r?`:view:${r}`:""}:${a.operation}`,kind:a.kind,path:a.path,label:a.label,navigationEligible:a.navigationEligible,capability:a.capability,resourceCode:n.code,...r?{viewCode:r}:{}})}for(let o of eo(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 Ks(e){return e.kind==="resource"?`resource:${e.resourceCode}${e.viewCode?`:view:${e.viewCode}`:""}:list`:`operation:${e.routeCode}`}function _l(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,r)=>({pageCode:Ks(n.page),...n.label===void 0?{}:{label:n.label},...n.icon===void 0?{}:{icon:n.icon},order:n.order??r})).sort((n,r)=>n.order-r.order||Ie(n.pageCode,r.pageCode))})).sort((t,o)=>t.order-o.order||Ie(t.code,o.code))}function gl(e,t){let o=D(e,t,M.adminNavigationGroups);o.reduce((r,i)=>r+(Array.isArray(i?.items)?i.items.length:0),0)>M.adminNavigationItems&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let n=0;o.forEach((r,i)=>{let d=`${t}/${i}`,s=N(r,d);C(s,["code","label","icon","order","items"],d,!0),v(s.code,`${d}/code`),S(s.label,`${d}/label`,255),Xn(s.icon,`${d}/icon`),Cs(s.order,`${d}/order`);let a=D(s.items,`${d}/items`,500);a.length===0&&m("NATIVE_ADMIN_GROUP_ORPHANED",`${d}/items`),n+=a.length,n>M.adminNavigationItems&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t),a.forEach((c,f)=>{let u=`${d}/items/${f}`,p=N(c,u);C(p,["page","label","icon","order"],u,!0),Al(p.page,`${u}/page`),p.label!==void 0&&S(p.label,`${u}/label`,255),Xn(p.icon,`${u}/icon`),Cs(p.order,`${u}/order`)})})}function Al(e,t){let o=N(e,t),n=S(o.kind,`${t}/kind`,64);if(n==="resource"){C(o,["kind","resourceCode"],t,["viewCode"]),o.viewCode!==void 0&&v(o.viewCode,`${t}/viewCode`),H(o.resourceCode,`${t}/resourceCode`);return}if(n==="operation"){C(o,["kind","routeCode"],t),v(o.routeCode,`${t}/routeCode`);return}m("NATIVE_ADMIN_PAGE_REFERENCE_KIND_INVALID",`${t}/kind`)}function El(e){let t=new Map(Bs(e).map(r=>[String(r.code),r])),o=new Set,n=new Set;e.frontend.admin.navigation.forEach((r,i)=>{let d=`/config/frontend/admin/navigation/${i}`;o.has(r.code)&&m("NATIVE_ADMIN_GROUP_DUPLICATE",`${d}/code`),o.add(r.code),r.label===r.code&&m("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${d}/label`),r.items.forEach((s,a)=>{let c=`${d}/items/${a}`,f=Ks(s.page),u=t.get(f);(!u||u.navigationEligible!==!0)&&m("NATIVE_ADMIN_PAGE_NOT_FOUND",`${c}/page`),n.has(f)&&m("NATIVE_ADMIN_PAGE_DUPLICATE",`${c}/page`),n.add(f);let p=s.page.resourceCode||s.page.routeCode||s.page.workflowCode||f,_=s.label||u.label;(!_||_===p||_===f)&&m("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${c}/label`)})})}function Il(e,t){let o=D(e,t,M.adminPages),n=new Set;o.forEach((r,i)=>{let d=`${t}/${i}`,s=N(r,d);C(s,["code","kind","path","label","navigationEligible","capability","access","resourceCode","viewCode","routeCode"],d,!0);let a=S(s.code,`${d}/code`,255);n.has(a)&&m("NATIVE_ADMIN_PAGE_DUPLICATE",`${d}/code`),n.add(a);let c=S(s.kind,`${d}/kind`,64);if(["resource-list","resource-detail","resource-create","resource-update","operation"].includes(c)||m("NATIVE_ADMIN_PAGE_KIND_INVALID",`${d}/kind`),Te(s.path,`${d}/path`),S(s.label,`${d}/label`,255),Nt(s.navigationEligible,`${d}/navigationEligible`),s.capability!==void 0&&s.access!==void 0&&m("NATIVE_ROUTE_ACCESS_CONFLICT",`${d}/access`),s.capability!==void 0&&S(s.capability,`${d}/capability`,255),s.access!==void 0){let f=N(s.access,`${d}/access`);C(f,["allOf","anyOf"],`${d}/access`,!0);for(let u of["allOf","anyOf"])f[u]!==void 0&&V(f[u],`${d}/access/${u}`,50)}for(let f of["resourceCode","viewCode","routeCode"])s[f]!==void 0&&v(s[f],`${d}/${f}`)})}function yl(e,t){let o=D(e,t,M.adminNavigationGroups);o.reduce((r,i)=>r+(Array.isArray(i?.items)?i.items.length:0),0)>M.adminNavigationItems&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let n=0;o.forEach((r,i)=>{let d=`${t}/${i}`,s=N(r,d);C(s,["code","label","icon","order","items"],d,!0),v(s.code,`${d}/code`),S(s.label,`${d}/label`,255),Xn(s.icon,`${d}/icon`),se(s.order,`${d}/order`,-1e4,1e4);let a=D(s.items,`${d}/items`,500);a.length===0&&m("NATIVE_ADMIN_GROUP_ORPHANED",`${d}/items`),n+=a.length,n>M.adminNavigationItems&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t),a.forEach((c,f)=>{let u=`${d}/items/${f}`,p=N(c,u);C(p,["pageCode","label","icon","order"],u,!0),S(p.pageCode,`${u}/pageCode`,255),p.label!==void 0&&S(p.label,`${u}/label`,255),Xn(p.icon,`${u}/icon`),se(p.order,`${u}/order`,-1e4,1e4)})})}var bl=new Set(["application-todo-center","workflow-work-center","workflow-launch","workflow-task","workflow-instance","resource-records","resource-submit"]);function Ol(e,t,o){let n=N(e,t);C(n,["schemaVersion","appCode","devicePolicy","rootEntry","authentication","routes","digest"],t),F(n.schemaVersion,Vs,`${t}/schemaVersion`),F(n.appCode,o,`${t}/appCode`),Lr(n.devicePolicy,`${t}/devicePolicy`),Nl(n.rootEntry,`${t}/rootEntry`),Tl(n.authentication,`${t}/authentication`),vr(n.digest,`${t}/digest`);let r=D(n.routes,`${t}/routes`,M.routes),i=new Set;r.forEach((d,s)=>{let a=`${t}/routes/${s}`,c=N(d,a),f=c.kind==="resource-records"||c.kind==="resource-submit";C(c,["code","kind","desktop","mobile"],a,["workflowCode",...f?["resourceCode"]:[]]);let u=S(c.code,`${a}/code`,255);i.has(u)&&m("NATIVE_ROUTE_MANIFEST_DUPLICATE",`${a}/code`),i.add(u);let p=S(c.kind,`${a}/kind`,64);if(bl.has(p)||m("NATIVE_ROUTE_MANIFEST_KIND_INVALID",`${a}/kind`),c.workflowCode!==void 0&&v(c.workflowCode,`${a}/workflowCode`),f){let A=H(c.resourceCode,`${a}/resourceCode`);F(u,`user.${A}.${c.kind==="resource-records"?"records":"submit"}`,`${a}/code`)}else c.resourceCode!==void 0&&m("NATIVE_PROPERTY_UNKNOWN",`${a}/resourceCode`);let _=Ns(c.desktop,`${a}/desktop`,o),E=Ns(c.mobile,`${a}/mobile`,o);_.surface!=="user"&&m("NATIVE_ROUTE_MANIFEST_DESKTOP_SURFACE_INVALID",`${a}/desktop/surface`),E.surface!=="user"&&m("NATIVE_ROUTE_MANIFEST_MOBILE_SURFACE_INVALID",`${a}/mobile/surface`),_.routeCode===E.routeCode&&m("NATIVE_ROUTE_MANIFEST_PAIR_DUPLICATE",a)}),F(n.digest,Z({schemaVersion:n.schemaVersion,appCode:n.appCode,devicePolicy:n.devicePolicy,rootEntry:n.rootEntry,authentication:n.authentication,routes:n.routes}),`${t}/digest`)}function Lr(e,t){let o=N(e,t);C(o,["kind","mobileMaxWidthPx","desktopMinWidthPx"],t),F(o.kind,"viewport-family",`${t}/kind`);let n=se(o.mobileMaxWidthPx,`${t}/mobileMaxWidthPx`,320,1600),r=se(o.desktopMinWidthPx,`${t}/desktopMinWidthPx`,320,1600);return r!==n+1&&m("NATIVE_FRONTEND_DEVICE_POLICY_INVALID",t),{kind:"viewport-family",mobileMaxWidthPx:n,desktopMinWidthPx:r}}function Nl(e,t){let o=N(e,t);C(o,["code","desktop","mobile"],t);let n=v(o.code,`${t}/code`),r=Pr(o.desktop,`${t}/desktop`),i=Pr(o.mobile,`${t}/mobile`);return(r===i||i==="/"||!i.startsWith("/m/"))&&m("NATIVE_ROUTE_MANIFEST_ROOT_ENTRY_INVALID",t),r.startsWith("/m/")&&m("NATIVE_ROUTE_MANIFEST_ROOT_ENTRY_INVALID",`${t}/desktop`),{code:n,desktop:r,mobile:i}}function Tl(e,t){let o=N(e,t);C(o,["desktop","mobile"],t);let n=Os(o.desktop,`${t}/desktop`,!1),r=Os(o.mobile,`${t}/mobile`,!0);return(n.routeCode===r.routeCode||n.path===r.path)&&m("NATIVE_ROUTE_MANIFEST_AUTHENTICATION_DUPLICATE",t),{desktop:n,mobile:r}}function Os(e,t,o){let n=N(e,t);C(n,["routeCode","path"],t);let r=v(n.routeCode,`${t}/routeCode`),i=Pr(n.path,`${t}/path`);return(o?!i.startsWith("/m/"):i.startsWith("/m/"))&&m("NATIVE_ROUTE_MANIFEST_AUTHENTICATION_PATH_INVALID",`${t}/path`),{routeCode:r,path:i}}function Pr(e,t){let o=Te(e,t);return/[:*?#\\\\]/.test(o)&&m("NATIVE_ROUTE_MANIFEST_STATIC_PATH_INVALID",t),o}function Ns(e,t,o){let n=N(e,t);C(n,["routeCode","path","surface","pathParams","requiresAuthentication"],t,["capability","access"]),v(n.routeCode,`${t}/routeCode`);let r=Te(n.path,`${t}/path`),i=S(n.surface,`${t}/surface`,16);["admin","user"].includes(i)||m("NATIVE_ROUTE_SURFACE_INVALID",`${t}/surface`);let d=V(n.pathParams,`${t}/pathParams`,8);return d.forEach((s,a)=>{(!/^[A-Za-z][A-Za-z0-9_]*$/.test(s)||s.length>64)&&m("NATIVE_ROUTE_PATH_PARAM_INVALID",`${t}/pathParams/${a}`)}),X(d)!==X(Gs(r))&&m("NATIVE_ROUTE_PATH_PARAMS_MISMATCH",`${t}/pathParams`),Fr(n,t,o),n.requiresAuthentication!==!0&&m("NATIVE_ROUTE_AUTHENTICATION_REQUIRED",`${t}/requiresAuthentication`),n}function Gs(e){return B([...e.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(t=>t[1]))}function Ts(e,t,o,n){return{routeCode:e,path:t,surface:o,pathParams:Gs(t),...n?.capability?{capability:n.capability}:{},...n?.access?{access:n.access}:{},requiresAuthentication:!0}}function Rs(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 Rl(e){let t=e.appCode,o=[],n=(_,E,A,O,b,g,I)=>{o.push({code:_,kind:E,...b?{workflowCode:b}:{},...I?{resourceCode:I}:{},desktop:Ts(Rs(E,"desktop",b,I),A,"user",g),mobile:Ts(Rs(E,"mobile",b,I),O,"user",g)})};e.frontend.user.applicationTodoCenter===!0&&n("application:todo-center","application-todo-center","/todos","/m/todos");let r=qs(e);r.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 _ of r){if(!["standalone","hidden-handoff"].includes(_.launch.mode))continue;let E=B([_.launch.submission?.create?.requiredCapability,_.launch.submission?.existing?.requiredCapability].filter(A=>!!A));n(`workflow:${_.code}:launch`,"workflow-launch","/workflows/:workflowCode/start","/m/workflows/:workflowCode/start",_.code,E.length===1?{capability:E[0]}:E.length>1?{access:{anyOf:E}}:void 0)}let i=o.sort((_,E)=>Ie(String(_.code),String(E.code))),d=eo(e),s=_=>{let E=_==="mobile"?"/m/":"/",A=d.filter(b=>b.surface==="user"&&!/[:*?#\\\\]/.test(b.path)&&b.path===E).sort((b,g)=>Ie(b.code,g.code))[0];if(A)return{code:A.code,path:A.path};let O=d.filter(b=>b.surface==="user"&&!/[:*?#\\\\]/.test(b.path)&&(_==="mobile"?b.path.startsWith("/m/"):!b.path.startsWith("/m/"))).sort((b,g)=>Ie(b.code,g.code))[0];return O?{code:O.code,path:O.path}:{code:_==="mobile"?"application-root-mobile":"application-root",path:E}},a=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"}},c=Lr(e.frontend.devicePolicy,"/config/frontend/devicePolicy"),f=s("desktop"),u=s("mobile"),p={schemaVersion:Vs,appCode:t,devicePolicy:c,rootEntry:{code:f.code,desktop:f.path,mobile:u.path},authentication:a,routes:i};return{...p,digest:Z(p)}}function Xn(e,t){if(e===void 0)return;let o=S(e,t,32);Wc.has(o)||m("NATIVE_ADMIN_ICON_INVALID",t)}function Cs(e,t){e!==void 0&&se(e,t,-1e4,1e4)}function Fr(e,t,o){return e.capability!==void 0&&e.access!==void 0&&m("NATIVE_ROUTE_ACCESS_CONFLICT",`${t}/access`),e.capability!==void 0?{capability:me(e.capability,`${t}/capability`,o)}:e.access===void 0?{}:{access:to(e.access,`${t}/access`,o)}}function to(e,t,o){let n=N(e,t);C(n,["allOf","anyOf"],t,!0);let r=n.allOf===void 0?void 0:B(V(n.allOf,`${t}/allOf`,50).map((d,s)=>me(d,`${t}/allOf/${s}`,o))),i=n.anyOf===void 0?void 0:B(V(n.anyOf,`${t}/anyOf`,50).map((d,s)=>me(d,`${t}/anyOf/${s}`,o)));return(r?.length||0)+(i?.length||0)===0&&m("NATIVE_ROUTE_ACCESS_EMPTY",t),{...r===void 0?{}:{allOf:r},...i===void 0?{}:{anyOf:i}}}function qs(e){let t=new Map(js(e).map(r=>[String(r.code),r])),o=e.workflows.definitions.map((r,i)=>{let d=`/config/workflows/definitions/${i}`,s=N(r,d);C(s,["version","definition","launch"],d,["detailRouteCode"]);let a=N(s.definition,`${d}/definition`),c=s.detailRouteCode===void 0?void 0:Js(s.detailRouteCode,`${d}/detailRouteCode`);return{code:v(a.code,`${d}/definition/code`),title:S(a.title,`${d}/definition/title`,255),version:Ot(s.version,`${d}/version`),launch:Cl(e,a,s.launch,`${d}/launch`,t),...c?{detailRouteCode:c}:{},definition:a}});return B(o.map(r=>r.code)).map(r=>{let i=o.filter(c=>c.code===r),d=e.workflows.activations.find(c=>c.workflowCode===r)?.definitionVersion,s=i.find(c=>c.version===d)||[...i].sort((c,f)=>f.version-c.version)[0],a=new Set;for(let c of i){let f=N(c.definition.nodes,"/config/workflows/definitions/nodes");for(let u of Object.values(f)){let p=N(u,"/config/workflows/definitions/nodes/*");if(p.kind==="approval")for(let _ of V(p.allowedOperations||[],"/config/workflows/definitions/nodes/*/allowedOperations",20))a.add(_)}}return{code:r,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.${r}.submit`}:{},...s.detailRouteCode?{detailRouteCode:s.detailRouteCode}:{},definitionVersions:Ps(i.map(c=>c.version)),bindingVersions:Ps(e.workflows.bindings.map((c,f)=>{let u=`/config/workflows/bindings/${f}`,p=N(c,u),_=N(p.binding,`${u}/binding`);return{code:v(_.workflowCode,`${u}/binding/workflowCode`),version:Ot(p.version,`${u}/version`)}}).filter(c=>c.code===r).map(c=>c.version)),providerCodes:B(e.workflows.providers.map((c,f)=>v(N(c,`/config/workflows/providers/${f}`).code,`/config/workflows/providers/${f}/code`))),allowedOperations:[...a].sort(Ie),editableParameterCodes:B(e.workflows.editableParameters.map((c,f)=>{let u=`/config/workflows/editableParameters/${f}`,p=N(c,u);return{code:v(p.code,`${u}/code`),workflowCode:v(p.workflowCode,`${u}/workflowCode`)}}).filter(c=>c.workflowCode===r).map(c=>c.code))}})}function zs(e,t){let o=N(e,t);C(o,["mode"],t,["submission"]);let n=S(o.mode,`${t}/mode`,32);return["standalone","custom-page","hidden-handoff","work-center-only"].includes(n)||m("NATIVE_WORKFLOW_LAUNCH_MODE_INVALID",`${t}/mode`),{mode:n,...o.submission===void 0?{}:{submission:N(o.submission,`${t}/submission`)}}}function Cl(e,t,o,n,r){let i=zs(o,n);if(!i.submission)return{mode:i.mode};["standalone","hidden-handoff"].includes(i.mode)||m("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${n}/submission`);let d=N(i.submission,`${n}/submission`);C(d,["kind"],`${n}/submission`,["create","existing","context"]),F(d.kind,"named-operation",`${n}/submission/kind`);let s=n.endsWith("/launch")?n.slice(0,-7):n,a=N(t.subject,`${s}/definition/subject`),c=H(a.resourceCode,`${s}/definition/subject/resourceCode`),f=e.data.resources.findIndex(y=>y.code===c),u=e.data.resources[f];(f<0||!u)&&m("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${s}/definition/subject/resourceCode`);let p=new Set(N(u.schema,`/config/data/resources/${f}/schema`).fields.map(y=>String(y.code))),_=new Map(e.backend.operations.map(y=>[String(y.code),y])),E=(y,R)=>{let h=`${n}/submission/${R}`,$=N(y,h);C($,["operationCode","inputs","output"],h);let w=v($.operationCode,`${h}/operationCode`),j=_.get(w),L=r.get(w),Q=L?.platformAccess?.workflow?.codes;(!j||!L||L.method!=="POST"||!Array.isArray(Q)||!Q.includes(t.code))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INVALID",h);let ee=N(j.requestSchema,`${h}/operation/requestSchema`),Y=N(ee.properties,`${h}/operation/requestSchema/properties`),ge=new Set(ee.required===void 0?[]:V(ee.required,`${h}/operation/requestSchema/required`,205)),re=N($.inputs,`${h}/inputs`),P=Object.entries(re);(!P.length||P.length>205)&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${h}/inputs`);let U=new Set,x=new Map,q={},z=L.platformAccess?.ownedSubject;z&&(R!=="create"||z.resourceCode!==c)&&m("NATIVE_WORKFLOW_OWNED_SUBJECT_LAUNCH_MISMATCH",h);for(let[J,ot]of P){(!Es.test(J)||!Object.prototype.hasOwnProperty.call(Y,J))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${h}/inputs/${J}`);let Me=`${h}/inputs/${J}`,ao=N(ot,Me),Be=S(ao.source,`${Me}/source`,32);if(["field","idempotency-key","current-user-reference","subject-id","subject-revision","requested-at"].includes(Be)||m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",Me),C(ao,["source"],Me,Be==="field"?["fieldCode"]:!1),x.set(Be,(x.get(Be)||0)+1),Be==="field"){let rt=G(ao.fieldCode,`${Me}/fieldCode`);(U.has(rt)||!p.has(rt))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${Me}/fieldCode`),U.add(rt),u.schema.fields.find(co=>co.code===rt)?.type==="subtable"&&(!z||!z.subtables.some(co=>co.fieldCode===rt))&&m("NATIVE_WORKFLOW_OWNED_SUBJECT_LAUNCH_REQUIRED",Me),q[J]={source:Be,fieldCode:rt}}else q[J]={source:Be}}([...ge].some(J=>!(J in re))||(x.get("idempotency-key")||0)!==1||!P.some(([J,ot])=>N(ot,`${h}/inputs/${J}`).source==="idempotency-key"&&ge.has(J))||R==="create"&&((x.get("subject-id")||0)>0||(x.get("subject-revision")||0)>0)||R==="existing"&&((x.get("subject-id")||0)!==1||(x.get("subject-revision")||0)!==1))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${h}/inputs`);let Ae=N($.output,`${h}/output`);C(Ae,["subjectId"],`${h}/output`,["subjectRevision","processCommand"]);let Re=N(N(j.responseSchema,`${h}/operation/responseSchema`).properties,`${h}/operation/responseSchema/properties`);for(let J of["subjectId","subjectRevision","processCommand"]){if(Ae[J]===void 0)continue;let ot=S(Ae[J],`${h}/output/${J}`,128);(!Es.test(ot)||!Object.prototype.hasOwnProperty.call(Re,ot))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_OUTPUT_INVALID",`${h}/output/${J}`)}return{operationCode:w,method:"POST",path:L.path,requiredCapability:L.requiredCapability,requestSchemaDigest:L.requestSchemaDigest,responseSchemaDigest:L.responseSchemaDigest,inputs:q,output:{...Ae},fieldCodes:U}},A=d.create===void 0?void 0:E(d.create,"create"),O=d.existing===void 0?void 0:E(d.existing,"existing");!A&&!O&&m("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${n}/submission`);let b=new Set([...A?.fieldCodes||[],...O?.fieldCodes||[]]),g=d.context===void 0?[]:D(d.context,`${n}/submission/context`,16),I=new Set,T=g.map((y,R)=>{let h=`${n}/submission/context/${R}`,$=N(y,h);C($,["queryParameter","fieldCode"],h);let w=S($.queryParameter,`${h}/queryParameter`,64),j=G($.fieldCode,`${h}/fieldCode`);return(!/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(w)||I.has(w)||!b.has(j))&&m("NATIVE_WORKFLOW_LAUNCH_CONTEXT_INVALID",h),I.add(w),{queryParameter:w,fieldCode:j}}),l=y=>{let{fieldCodes:R,...h}=y;return h};return{mode:i.mode,submission:{kind:"named-operation",...A?{create:l(A)}:{},...O?{existing:l(O)}:{},context:T}}}function Js(e,t){let o=N(e,t);C(o,["desktop","mobile"],t);let n=v(o.desktop,`${t}/desktop`),r=v(o.mobile,`${t}/mobile`);return n===r&&m("NATIVE_WORKFLOW_DETAIL_ROUTE_DUPLICATE",t),{desktop:n,mobile:r}}function hl(e,t){let o=new Set(t.map(f=>f.code)),n=new Map;e.data.resources.forEach((f,u)=>{let p=`/config/data/resources/${u}`,_=N(f,p);if(_.recordDeletion!==void 0){let O=`${p}/recordDeletion/delete`;for(let b of _.recordDeletion.delete)me(b,O,e.appCode),o.has(b)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",O)}if(_.recordComments!==void 0)for(let O of["read","create"]){let b=`${p}/recordComments/${O}`;for(let g of _.recordComments[O])me(g,b,e.appCode),o.has(g)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",b)}if(_.recordPrint!==void 0){let O=`${p}/recordPrint/read`;for(let b of _.recordPrint.read)me(b,O,e.appCode),o.has(b)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",O)}if(_.workflowHistory!==void 0){let O=`${p}/workflowHistory/read`;for(let b of _.workflowHistory.read)me(b,O,e.appCode),o.has(b)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",O)}for(let[O,b]of Object.entries(_.fieldPolicies||{})){if(!at(O))continue;let g=`${p}/fieldPolicies/${O}/read`,I=N(b,`${p}/fieldPolicies/${O}`);for(let T of V(I.read||[],g,2e3))o.has(T)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",g)}let E=_.surface===void 0?{}:N(_.surface,`${p}/surface`);if(["native","queued-command"].includes(E.mutationOwner||"native"))return;let A=N(_.capabilities,`${p}/capabilities`);for(let O of["create","update","delete"])O==="delete"&&Array.isArray(_.recordDeletion?.delete)&&_.recordDeletion.delete.length>0||n.set(String(A[O]),O)});let r=new Set;for(let[f,u]of e.authz.roles.entries()){let p=`/config/authz/roles/${f}`,_=N(u,p);C(_,["code","name","description","capabilities"],p,!0);let E=v(_.code,`${p}/code`);r.has(E)&&m("NATIVE_ROLE_DUPLICATE",`${p}/code`),r.add(E),S(_.name,`${p}/name`,255);let A=V(_.capabilities,`${p}/capabilities`,2e3);for(let[O,b]of A.entries())n.has(b)&&m("NATIVE_DATA_SURFACE_MUTATION_GRANT_FORBIDDEN",`${p}/capabilities/${O}`,{operation:n.get(b)}),o.has(b)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",`${p}/capabilities`)}let i=e.authz.authenticatedUserRoleCode===void 0?"":v(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode");i&&!r.has(i)&&m("NATIVE_AUTHENTICATED_USER_ROLE_REFERENCE_MISSING","/config/authz/authenticatedUserRoleCode");let d=new Set,s=0;for(let[f,u]of e.perspectives.entries()){let p=`/config/perspectives/${f}`,_=N(u,p);C(_,["code","name","description","roleCodes","capabilityCodes","default"],p,!0);let E=v(_.code,`${p}/code`);d.has(E)&&m("NATIVE_PERSPECTIVE_DUPLICATE",`${p}/code`),d.add(E),S(_.name,`${p}/name`,255);let A=V(_.roleCodes,`${p}/roleCodes`,20);A.length<1&&m("NATIVE_PERSPECTIVE_ROLE_REQUIRED",`${p}/roleCodes`),A.forEach((g,I)=>{r.has(g)||m("NATIVE_PERSPECTIVE_ROLE_MISSING",`${p}/roleCodes/${I}`)});let O=B(e.authz.roles.filter(g=>A.includes(g.code)).flatMap(g=>g.capabilities)),b=V(_.capabilityCodes,`${p}/capabilityCodes`,2e3);X(O)!==X(b)&&m("NATIVE_PERSPECTIVE_CAPABILITY_PROJECTION_MISMATCH",`${p}/capabilityCodes`),_.default===!0?s+=1:_.default!==void 0&&m("NATIVE_PERSPECTIVE_DEFAULT_INVALID",`${p}/default`)}s>1&&m("NATIVE_PERSPECTIVE_DEFAULT_DUPLICATE","/config/perspectives");for(let[f,u]of e.backend.operations.entries()){let p=N(u,`/config/backend/operations/${f}`);o.has(p.capability)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/backend/operations/${f}/capability`)}let a=new Set,c=new Set;for(let[f,u]of e.frontend.routes.entries()){let p=`/config/frontend/routes/${f}`,_=N(u,p),E=v(_.code,`${p}/code`);a.has(E)&&m("NATIVE_ROUTE_DUPLICATE",`${p}/code`),a.add(E);let A=Te(_.path,`${p}/path`);c.has(A)&&m("NATIVE_ROUTE_PATH_DUPLICATE",`${p}/path`),c.add(A);let O=Fr(_,p,e.appCode);O.capability&&!o.has(O.capability)&&m("NATIVE_CAPABILITY_REFERENCE_MISSING",`${p}/capability`);let b=_.access===void 0?void 0:N(_.access,`${p}/access`);for(let g of["allOf","anyOf"]){let I=b?.[g]===void 0?[]:D(b[g],`${p}/access/${g}`,50);for(let[T,l]of I.entries()){let y=me(l,`${p}/access/${g}/${T}`,e.appCode);o.has(y)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",`${p}/access/${g}/${T}`)}}}if(e.frontend.admin.access!==void 0){let f=to(e.frontend.admin.access,"/config/frontend/admin/access",e.appCode);for(let u of["allOf","anyOf"])for(let[p,_]of(f[u]||[]).entries())o.has(_)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/frontend/admin/access/${u}/${p}`)}for(let[f,u]of e.frontend.routes.entries()){let p=N(u,`/config/frontend/routes/${f}`);p.parentCode&&!a.has(p.parentCode)&&m("NATIVE_ROUTE_PARENT_MISSING",`/config/frontend/routes/${f}/parentCode`)}}function wl(e){let t=new Set(e.authz.roles.map(c=>String(c.code))),o=e.authz.authenticatedUserRoleCode===void 0?"":v(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode"),n=new Map(e.authz.scopeDimensions.map(c=>[String(c.code),{valueType:c.valueType==="uuid"?"uuid":"string",...c.valueSource?.resourceCode?{valueSourceResourceCode:String(c.valueSource.resourceCode)}:{}}])),r=new Set(n.keys()),i=new Map(e.data.resources.map((c,f)=>{let u=tt(c,`/config/data/resources/${f}`,e.appCode);return[u.code,new Map(u.schema.fields.map(p=>[String(p.code),p]))]}));for(let[c,f]of e.authz.scopeDimensions.entries()){let u=`/config/authz/scopeDimensions/${c}`,p=N(f,u);if(C(p,["code","name","resourceCode","valueType","hierarchyMode","valueSource"],u,!0),p.valueSource===void 0)continue;let _=N(p.valueSource,`${u}/valueSource`);C(_,["kind","resourceCode","labelField","enabledField"],`${u}/valueSource`,!0),_.kind!=="native_resource"&&m("NATIVE_SCOPE_VALUE_SOURCE_KIND_INVALID",`${u}/valueSource/kind`),p.valueType!=="uuid"&&m("NATIVE_SCOPE_VALUE_SOURCE_TYPE_INVALID",`${u}/valueType`);let E=H(_.resourceCode,`${u}/valueSource/resourceCode`),A=i.get(E);A||m("NATIVE_SCOPE_VALUE_SOURCE_RESOURCE_MISSING",`${u}/valueSource/resourceCode`);let O=G(_.labelField,`${u}/valueSource/labelField`);if(["text.short","text.long"].includes(String(A.get(O)?.type||""))||m("NATIVE_SCOPE_VALUE_SOURCE_LABEL_FIELD_INVALID",`${u}/valueSource/labelField`),_.enabledField!==void 0){let b=G(_.enabledField,`${u}/valueSource/enabledField`);A.get(b)?.type!=="boolean"&&m("NATIVE_SCOPE_VALUE_SOURCE_ENABLED_FIELD_INVALID",`${u}/valueSource/enabledField`)}}let d=new Set,s=new Set;for(let[c,f]of e.authz.scopeSources.entries()){let u=`/config/authz/scopeSources/${c}`,p=N(f,u);C(p,["code","name","resourceCode","subject","grants","operationField","enabledField","effectiveFromField","effectiveToField","failureMode"],u,!0);let _=v(p.code,`${u}/code`);d.has(_)&&m("NATIVE_SCOPE_SOURCE_DUPLICATE",`${u}/code`),d.add(_),S(p.name,`${u}/name`,255);let E=H(p.resourceCode,`${u}/resourceCode`),A=i.get(E);A||m("NATIVE_SCOPE_SOURCE_RESOURCE_MISSING",`${u}/resourceCode`);let O=N(p.subject,`${u}/subject`),b=S(O.type,`${u}/subject/type`,32);C(O,b==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${u}/subject`),["user","role_membership"].includes(b)||m("NATIVE_SCOPE_SOURCE_SUBJECT_INVALID",`${u}/subject/type`);let g=ft(O.userIdField,A);hn(g)||m("NATIVE_SCOPE_SOURCE_SUBJECT_PATH_INVALID",`${u}/subject/userIdField`),b==="role_membership"&&!t.has(String(O.roleCode))&&m("NATIVE_ROLE_REFERENCE_MISSING",`${u}/subject/roleCode`);let I=new Set;for(let[T,l]of D(p.grants,`${u}/grants`,100).entries()){let y=`${u}/grants/${T}`,R=N(l,y);C(R,["dimensionCode","valueField","parentValueField"],y,!0);let h=v(R.dimensionCode,`${y}/dimensionCode`);(!r.has(h)||I.has(h))&&m("NATIVE_SCOPE_SOURCE_DIMENSION_INVALID",`${y}/dimensionCode`),I.add(h),p.failureMode==="last_known_good"&&s.add(h);for(let $ of["valueField","parentValueField"]){if(R[$]===void 0)continue;let w=ft(R[$],A);jo(w,n.get(h),i)||m("NATIVE_SCOPE_SOURCE_GRANT_PATH_INVALID",`${y}/${$}`)}}I.size===0&&m("NATIVE_SCOPE_SOURCE_GRANT_REQUIRED",`${u}/grants`),["strict","last_known_good"].includes(p.failureMode)||m("NATIVE_SCOPE_SOURCE_FAILURE_MODE_INVALID",`${u}/failureMode`);for(let T of["operationField","enabledField","effectiveFromField","effectiveToField"]){if(p[T]===void 0)continue;let l=G(p[T],`${u}/${T}`);A.has(l)||m("NATIVE_SCOPE_SOURCE_FIELD_MISSING",`${u}/${T}`)}}Dl(e,t,i,o);let a=new Set;for(let[c,f]of e.authz.dataPolicies.entries()){let u=`/config/authz/dataPolicies/${c}`,p=N(f,u);C(p,["code","name","resourceCode","unrestrictedRoleCodes","publicRead","operations","matchMode","rules","readExpression","writeBoundary"],u,!0);let _=v(p.code,`${u}/code`);a.has(_)&&m("NATIVE_DATA_POLICY_DUPLICATE",`${u}/code`),a.add(_);let E=p.readExpression!==void 0,A=V(p.operations||[],`${u}/operations`,4);p.operations!==void 0&&(A.length===0||A.some(l=>!["read","create","update","delete"].includes(l)))&&m("NATIVE_DATA_POLICY_OPERATIONS_INVALID",`${u}/operations`),["AND","OR"].includes(p.matchMode)||m("NATIVE_DATA_POLICY_MATCH_MODE_INVALID",`${u}/matchMode`),E&&p.operations!==void 0&&m("NATIVE_DATA_POLICY_READ_EXPRESSION_OPERATIONS_FORBIDDEN",`${u}/operations`);let O=e.data.resources.find(l=>l.dataPolicyCode===_),b=p.resourceCode||O?.code,g=b?i.get(H(b,`${u}/resourceCode`)):void 0;if(E&&!g&&m("NATIVE_DATA_POLICY_RESOURCE_MISSING",`${u}/resourceCode`),p.publicRead!==void 0){try{let l=e.authz.roles.find(y=>y.code===o);Go({policy:p,resource:e.data.resources.find(y=>y.code===b),baselineRoleCode:o,baselineCapabilities:l?.capabilities||[],baselineDeniedCapabilities:l?.deniedCapabilities||[],pointer:u})}catch(l){if(!(l instanceof mt))throw l;m(l.code,l.pointer)}(p.unrestrictedRoleCodes||[]).includes(o)||m("AUTHENTICATED_PUBLIC_READ_CANONICAL_BASELINE_MISSING",`${u}/unrestrictedRoleCodes`)}else o&&(p.unrestrictedRoleCodes||[]).includes(o)&&m("NATIVE_DATA_POLICY_BASELINE_UNRESTRICTED",`${u}/unrestrictedRoleCodes`);let I=V(p.unrestrictedRoleCodes||[],`${u}/unrestrictedRoleCodes`,100);p.unrestrictedRoleCodes!==void 0&&I.length===0&&m("NATIVE_DATA_POLICY_UNRESTRICTED_ROLES_INVALID",`${u}/unrestrictedRoleCodes`);for(let l of I)t.has(l)||m("NATIVE_ROLE_REFERENCE_MISSING",`${u}/unrestrictedRoleCodes`);let T;try{let l=D(p.rules,`${u}/rules`,100).map((y,R)=>({rule:N(y,`${u}/rules/${R}`),pointer:`${u}/rules/${R}`}));l.length===0?(!E||p.matchMode!=="AND"||p.writeBoundary!=="capability_only")&&m("NATIVE_DATA_POLICY_WRITE_BOUNDARY_REQUIRED",u):p.writeBoundary!==void 0&&m("NATIVE_DATA_POLICY_WRITE_BOUNDARY_INVALID",`${u}/writeBoundary`),T=[...l],E&&(T.push(...Je(p.readExpression,`${u}/readExpression`)),Uo(p.readExpression,`${u}/readExpression`))}catch(l){throw l instanceof pt&&m(l.code,l.pointer),l}for(let{rule:l,pointer:y}of T){if(C(l,["parentRead","subject","dimensionCode","relationCode","resourceCode","field","roleCodes","operation","valuePath","emptyMatchesAll","operator","value","operand"],y,!0),l.parentRead!==void 0){for(let Y of V(l.roleCodes||[],`${y}/roleCodes`,100))t.has(Y)||m("NATIVE_ROLE_REFERENCE_MISSING",`${y}/roleCodes`);continue}let R=G(l.field,`${y}/field`),h=g?.get(R);E&&!h&&m("NATIVE_DATA_POLICY_FIELD_MISSING",`${y}/field`);for(let Y of V(l.roleCodes||[],`${y}/roleCodes`,100))t.has(Y)||m("NATIVE_ROLE_REFERENCE_MISSING",`${y}/roleCodes`);let $=String(l.operator||""),w=l.operand==="db_now",j=["is_null","is_not_null"].includes($),L=["eq","not_eq","in","not_in"].includes($),Q=!w&&(l.operator!==void 0||l.value!==void 0);if([l.subject==="current_user"?"current_user":"",typeof l.dimensionCode=="string"?"dimension":"",typeof l.relationCode=="string"?"relationship":"",Q?"constant":"",w?"db_now":""].filter(Boolean).length!==1&&m("NATIVE_DATA_POLICY_RULE_SOURCE_INVALID",y),l.subject!==void 0&&l.subject!=="current_user"&&m("NATIVE_DATA_POLICY_SUBJECT_INVALID",`${y}/subject`),Q){if(!L&&!j&&m("NATIVE_DATA_POLICY_OPERATOR_INVALID",`${y}/operator`),["in","not_in"].includes($)){let Y=D(l.value,`${y}/value`,100).map((ge,re)=>S(ge,`${y}/value/${re}`,2048));(Y.length===0||new Set(Y).size!==Y.length)&&m("NATIVE_DATA_POLICY_VALUE_INVALID",`${y}/value`)}else["eq","not_eq"].includes($)?S(l.value,`${y}/value`,2048):(l.value!==void 0||l.operand!==void 0)&&m("NATIVE_DATA_POLICY_VALUE_INVALID",`${y}/value`);for(let Y of["operation","valuePath","emptyMatchesAll","resourceCode","operand"])l[Y]!==void 0&&m("NATIVE_DATA_POLICY_CONSTANT_RULE_INVALID",`${y}/${Y}`)}if(w){(!["lt","lte","gt","gte"].includes($)||l.value!==void 0||h?.type!=="datetime")&&m("NATIVE_DATA_POLICY_DB_NOW_INVALID",y);for(let Y of["operation","valuePath","emptyMatchesAll","resourceCode","value"])l[Y]!==void 0&&m("NATIVE_DATA_POLICY_DB_NOW_INVALID",`${y}/${Y}`)}l.dimensionCode&&!r.has(l.dimensionCode)&&m("NATIVE_SCOPE_DIMENSION_MISSING",`${y}/dimensionCode`),s.has(String(l.dimensionCode||""))&&l.operation!=="read"&&m("NATIVE_SCOPE_SOURCE_LAST_KNOWN_GOOD_UNSAFE",`${y}/operation`)}}try{Mo(e.data.resources,e.authz.dataPolicies)}catch(c){throw c instanceof ce&&m(c.code,c.pointer),c}for(let[c,f]of e.data.resources.entries()){let u=N(f,`/config/data/resources/${c}`);u.dataPolicyCode&&!a.has(u.dataPolicyCode)&&m("NATIVE_DATA_POLICY_REFERENCE_MISSING",`/config/data/resources/${c}/dataPolicyCode`)}}function Sl(e){try{yo(e.data.resources,"/config/data/resources"),e.data.resources.forEach((t,o)=>po(t.schema.fields,new Set(e.authz.roles.map(n=>n.code)),new Set(e.authz.scopeDimensions.map(n=>n.code)),`/config/data/resources/${o}/schema/fields`))}catch(t){throw(t instanceof be||t instanceof Le)&&m(t.code,t.pointer),t}}function Dl(e,t,o,n){let r=new Set;for(let[i,d]of e.authz.roleMembershipSources.entries()){let s=`/config/authz/roleMembershipSources/${i}`,a=N(d,s);C(a,["code","name","resourceCode","userIdField","roleCode","enabledField","effectiveFromField","effectiveToField","failureMode"],s,!0);let c=v(a.code,`${s}/code`);c.length>100&&m("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${s}/code`),r.has(c)&&m("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${s}/code`),r.add(c),S(a.name,`${s}/name`,255);let f=hs(a.resourceCode,`${s}/resourceCode`,o);ws(a.userIdField,`${s}/userIdField`,f),t.has(String(a.roleCode||""))||m("NATIVE_ROLE_REFERENCE_MISSING",`${s}/roleCode`),n&&a.roleCode===n&&m("NATIVE_AUTHENTICATED_USER_ROLE_SOURCE_CONFLICT",`${s}/roleCode`),Ss(a,s,f)}for(let[i,d]of e.authz.relationshipGrantSources.entries()){let s=`/config/authz/relationshipGrantSources/${i}`,a=N(d,s);C(a,["code","name","resourceCode","subject","relationCode","targetResourceCode","resourceIdField","operations","enabledField","effectiveFromField","effectiveToField","failureMode"],s,!0);let c=v(a.code,`${s}/code`);c.length>100&&m("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${s}/code`),r.has(c)&&m("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${s}/code`),r.add(c),S(a.name,`${s}/name`,255);let f=hs(a.resourceCode,`${s}/resourceCode`,o),u=N(a.subject,`${s}/subject`),p=S(u.type,`${s}/subject/type`,32);C(u,p==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${s}/subject`),["user","role_membership"].includes(p)||m("NATIVE_AUTHORIZATION_PROJECTION_SUBJECT_INVALID",`${s}/subject/type`),ws(u.userIdField,`${s}/subject/userIdField`,f),p==="role_membership"&&!t.has(String(u.roleCode||""))&&m("NATIVE_ROLE_REFERENCE_MISSING",`${s}/subject/roleCode`),v(a.relationCode,`${s}/relationCode`);let _=H(a.targetResourceCode,`${s}/targetResourceCode`);o.has(_)||m("NATIVE_AUTHORIZATION_PROJECTION_TARGET_RESOURCE_MISSING",`${s}/targetResourceCode`);let E=ft(a.resourceIdField,f),A=E?.field.type==="resource-ref.single"&&E.valuePath==="value"&&E.field.source?.resourceCode===_;(a.resourceIdField==="id"?_!==String(a.resourceCode):!A)&&m("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_ID_FIELD_INVALID",`${s}/resourceIdField`);let O=V(a.operations,`${s}/operations`,20);(O.length===0||O.some(b=>b.length>64||!/^[A-Za-z0-9][A-Za-z0-9:._*-]{0,63}$/.test(b)))&&m("NATIVE_AUTHORIZATION_PROJECTION_OPERATIONS_INVALID",`${s}/operations`),Ss(a,s,f)}}function hs(e,t,o){let n=H(e,t),r=o.get(n);return r||m("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_MISSING",t),r}function ws(e,t,o){let n=ft(e,o);hn(n)||m("NATIVE_AUTHORIZATION_PROJECTION_USER_FIELD_INVALID",t)}function Ss(e,t,o){if(e.failureMode!=="strict"&&m("NATIVE_AUTHORIZATION_PROJECTION_FAILURE_MODE_INVALID",`${t}/failureMode`),e.enabledField!==void 0){let n=G(e.enabledField,`${t}/enabledField`);o.get(n)?.type!=="boolean"&&m("NATIVE_AUTHORIZATION_PROJECTION_ENABLED_FIELD_INVALID",`${t}/enabledField`)}for(let n of["effectiveFromField","effectiveToField"]){if(e[n]===void 0)continue;let r=G(e[n],`${t}/${n}`);["date","datetime"].includes(String(o.get(r)?.type))||m("NATIVE_AUTHORIZATION_PROJECTION_EFFECTIVE_FIELD_INVALID",`${t}/${n}`)}}function kl(e){let t=new Set,o=new Set;e.forEach((n,r)=>{let i=`/config/backend/secrets/${r}`,d=N(n,i);C(d,["name","env","description","required","exposure"],i,!0);let s=S(d.name,`${i}/name`,128),a=S(d.env,`${i}/env`,128);$c.test(s)||m("NATIVE_SECRET_NAME_INVALID",`${i}/name`),(!Pc.test(a)||a.startsWith("OPENXIANGDA_")||["NODE_ENV","PORT"].includes(a))&&m("NATIVE_SECRET_ENV_INVALID",`${i}/env`),t.has(s)&&m("NATIVE_SECRET_NAME_DUPLICATE",`${i}/name`),o.has(a)&&m("NATIVE_SECRET_ENV_DUPLICATE",`${i}/env`),t.add(s),o.add(a),F(d.exposure,"active_only",`${i}/exposure`),d.required!==void 0&&Nt(d.required,`${i}/required`),d.description!==void 0&&xr(d.description,`${i}/description`,2e3)})}function $l(e){let t=new Set,o=new Map,n=new Map(e.data.resources.map(_=>[String(_.code),_])),r=new Map(e.frontend.routes.map((_,E)=>{let A=N(_,`/config/frontend/routes/${E}`);return[v(A.code,`/config/frontend/routes/${E}/code`),A]}));for(let[_,E]of e.workflows.definitions.entries()){let A=`/config/workflows/definitions/${_}`,O=N(E,A);if(C(O,["version","definition","launch"],A,["detailRouteCode"]),zs(O.launch,`${A}/launch`),O.detailRouteCode!==void 0){let w=Js(O.detailRouteCode,`${A}/detailRouteCode`);for(let[j,L,Q]of[["desktop",w.desktop,["admin","user"]],["mobile",w.mobile,["user"]]]){let ee=`${A}/detailRouteCode/${j}`,Y=r.get(L);Y||m("NATIVE_WORKFLOW_DETAIL_ROUTE_MISSING",ee),Q.some(P=>P===Y.surface)||m("NATIVE_WORKFLOW_DETAIL_ROUTE_SURFACE_INVALID",ee);let ge=Te(Y.path,ee),re=[...ge.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(P=>P[1]);(ge.includes("*")||re.length!==1||re[0]!=="instanceId")&&m("NATIVE_WORKFLOW_DETAIL_ROUTE_PATH_INVALID",ee)}}let b=N(O.definition,`${A}/definition`),g=`${b.code}:${Ot(O.version,`${A}/version`)}`;t.has(g)&&m("NATIVE_WORKFLOW_DEFINITION_DUPLICATE",A),t.add(g),vl(b,`${A}/definition`);let I=Un(b);I.length&&m(I[0],`${A}/definition/launchPreflight`);let T=Er(b);T.length&&m(T[0],`${A}/definition/approvedDelegation`);let l=gr(b,e.backend.operations);l.length&&m(l[0],`${A}/definition/commandHandlers`),Pl(b.subject,n,`${A}/definition/subject`);let y=b.commandHandlers?.resubmit?.derivedSubjectFields||[],R=n.get(b.subject.resourceCode);for(let w of y){let j=R?.schema.fields.find(L=>L.code===w);(!j||j.system===!0||R?.surface?.fields?.[w]?.system===!0)&&m("WORKFLOW_CORRECTION_DERIVED_SUBJECT_FIELDS_INVALID",`${A}/definition/commandHandlers/resubmit/derivedSubjectFields`)}let h=Gt(b,new Map((n.get(b.subject.resourceCode)?.schema.fields||[]).map(w=>[w.code,{...n.get(b.subject.resourceCode)?.surface?.fields?.[w.code],...w,system:["id","revision","createdAt","updatedAt","createdBy","updatedBy"].includes(w.code)}])),new Map([...n].map(([w,j])=>[w,new Map(j.schema.fields.map(L=>[L.code,{...j.surface?.fields?.[L.code],...L,system:["id","revision","createdAt","updatedAt","createdBy","updatedBy"].includes(L.code)}]))])),Ct(n.get(b.subject.resourceCode)?.schema||{}));h.length&&m(h[0],`${A}/definition/taskPages`);let $=Zo(b,{appCode:e.appCode,capabilities:e.authz.capabilities.map(w=>w.code),fields:new Map((n.get(b.subject.resourceCode)?.schema.fields||[]).map(w=>[w.code,w]))});$.length&&m("NATIVE_WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID",`${A}/definition/instanceCommands`,{errors:$}),b.title===b.code&&m("NATIVE_WORKFLOW_USER_TITLE_REQUIRED",`${A}/definition/title`),o.set(g,b)}let i=new Set,d=new Map;for(let[_,E]of e.workflows.bindings.entries()){let A=N(E,`/config/workflows/bindings/${_}`),O=N(A.binding,`/config/workflows/bindings/${_}/binding`),b=`${O.workflowCode}:${Ot(A.version,`/config/workflows/bindings/${_}/version`)}`;i.has(b)&&m("NATIVE_WORKFLOW_BINDING_DUPLICATE",`/config/workflows/bindings/${_}`),i.add(b),Vl(O,`/config/workflows/bindings/${_}/binding`),d.set(b,O)}let s=new Set,a=new Map;for(let[_,E]of e.workflows.activations.entries()){let A=`/config/workflows/activations/${_}`,O=N(E,A);C(O,["workflowCode","definitionVersion","bindingVersion","acceptedCommandDeactivationPolicy"],A,["environmentKey"]);let b=v(O.workflowCode,`${A}/workflowCode`);s.has(b)&&m("NATIVE_WORKFLOW_ACTIVATION_DUPLICATE",A),s.add(b);let g=`${b}:${Ot(O.definitionVersion,`${A}/definitionVersion`)}`,I=`${b}:${Ot(O.bindingVersion,`${A}/bindingVersion`)}`;t.has(g)||m("NATIVE_WORKFLOW_DEFINITION_REFERENCE_MISSING",`${A}/definitionVersion`),i.has(I)||m("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${A}/bindingVersion`);let T=o.get(g),l=d.get(I),y=Un(T,l);y.length&&m(y[0],A);let R=jn(T,l);R.length&&m(R[0],A),(!["finish-pinned","cancel-on-deactivate"].includes(O.acceptedCommandDeactivationPolicy)||O.acceptedCommandDeactivationPolicy!==T.acceptedCommandDeactivationPolicy)&&m("NATIVE_WORKFLOW_COMMAND_DEACTIVATION_POLICY_MISMATCH",`${A}/acceptedCommandDeactivationPolicy`),Ll(T,l,`/config/workflows/activations/${_}`);try{let h=n.get(T.subject.resourceCode)?.schema.fields||[];mo(T,l,new Map(h.map($=>[$.code,$])),`${A}/bindings`,new Map([...n].map(([$,w])=>[$,new Map(w.schema.fields.map(j=>[j.code,j]))])))}catch(h){throw h instanceof Le&&m(h.code,h.pointer),h}a.set(b,l)}let c=Cr([...a.values()]);c.length&&m(c[0],"/config/workflows/activations");let f=new Set;e.workflows.providers.forEach((_,E)=>{let A=`/config/workflows/providers/${E}`,O=N(_,A);C(O,["code","endpointPath","timeoutMs"],A,!0);let b=v(O.code,`${A}/code`);f.has(b)&&m("NATIVE_WORKFLOW_PROVIDER_DUPLICATE",`${A}/code`),f.add(b),Te(O.endpointPath,`${A}/endpointPath`),O.timeoutMs!==void 0&&se(O.timeoutMs,`${A}/timeoutMs`,100,1e4)});for(let[_,E]of a.entries())for(let[A,O]of Object.entries(N(E.bindings,"/config/workflows/bindings/*/binding/bindings"))){let b=N(O,`/config/workflows/${_}/bindings/${A}`);b.provider==="application_provider"&&!f.has(b.providerCode)&&m("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`/config/workflows/${_}/bindings/${A}/providerCode`)}let u=new Set(e.authz.roles.map(_=>_.code)),p=new Set;e.workflows.editableParameters.forEach((_,E)=>{let A=`/config/workflows/editableParameters/${E}`,O=N(_,A);C(O,["code","workflowCode","bindingKey","label","valueType","required","allowedRoleCodes","allowedProviderCodes","maxItems"],A,!0);let b=v(O.code,`${A}/code`);p.has(b)&&m("NATIVE_WORKFLOW_EDITABLE_PARAMETER_DUPLICATE",`${A}/code`),p.add(b);let g=no(O.workflowCode,`${A}/workflowCode`),I=Zn(O.bindingKey,`${A}/bindingKey`),T=a.get(g);(!T||!N(T.bindings,`${A}/bindingKey`)[I])&&m("NATIVE_WORKFLOW_EDITABLE_BINDING_MISSING",`${A}/bindingKey`),S(O.label,`${A}/label`,255),["role_code","user_ids","provider_code"].includes(O.valueType)||m("NATIVE_WORKFLOW_EDITABLE_VALUE_TYPE_INVALID",`${A}/valueType`);for(let l of V(O.allowedRoleCodes||[],`${A}/allowedRoleCodes`,100))u.has(l)||m("NATIVE_ROLE_REFERENCE_MISSING",`${A}/allowedRoleCodes`);for(let l of V(O.allowedProviderCodes||[],`${A}/allowedProviderCodes`,100))f.has(l)||m("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`${A}/allowedProviderCodes`);O.required!==void 0&&Nt(O.required,`${A}/required`),O.maxItems!==void 0&&se(O.maxItems,`${A}/maxItems`,1,200)})}function Pl(e,t,o){let n=N(e,o);C(n,["resourceCode","factProjection"],o,["summaryFields"]);let r=H(n.resourceCode,`${o}/resourceCode`),i=t.get(r);i||m("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${o}/resourceCode`);let d=new Set(D(N(i.schema,`${o}/resourceCode`).fields,`${o}/resourceCode`,500).map((c,f)=>G(N(c,`${o}/resourceCode/${f}`).code,`${o}/resourceCode/${f}`))),s=N(n.factProjection,`${o}/factProjection`),a=Object.entries(s);(a.length<1||a.length>64)&&m("NATIVE_WORKFLOW_SUBJECT_FACT_PROJECTION_INVALID",`${o}/factProjection`);for(let[c,f]of a){Lc.test(c)||m("NATIVE_WORKFLOW_SUBJECT_FACT_KEY_INVALID",`${o}/factProjection/${c}`);let u=G(f,`${o}/factProjection/${c}`);d.has(u)||m("NATIVE_WORKFLOW_SUBJECT_FIELD_MISSING",`${o}/factProjection/${c}`)}if(n.summaryFields!==void 0){let c=V(n.summaryFields,`${o}/summaryFields`,Fc).map((E,A)=>G(E,`${o}/summaryFields/${A}`)),f=t.get(r),u=f.surface&&typeof f.surface=="object"&&!Array.isArray(f.surface)?f.surface:{},p=u.fields&&typeof u.fields=="object"&&!Array.isArray(u.fields)?u.fields:{},_=new Map(D(N(f.schema,`${o}/resourceCode`).fields,`${o}/resourceCode`,500).map((E,A)=>{let O=N(E,`${o}/resourceCode/${A}`);return[String(O.code),O]}));for(let[E,A]of c.entries()){let O=_.get(A),b=p[A],g=String(O?.type||""),I=O?.maxLength;(!O||O.system===!0||b&&typeof b=="object"&&!Array.isArray(b)&&b.system===!0||["id","revision","created_by","updated_by","created_at","updated_at"].includes(A)||!jc.has(g)||g==="text.long"&&typeof I=="number"&&Number.isFinite(I)&&I>xc)&&m("NATIVE_WORKFLOW_SUBJECT_SUMMARY_FIELDS_INVALID",`${o}/summaryFields/${E}`)}}}function vl(e,t){C(e,["schemaVersion","code","title","subject","acceptedCommandDeactivationPolicy","startAt","inputSchema","nodes"],t,["organizationContext","instanceCommands","readability","taskPages","rejectionNotification","commandHandlers","launchPreflight","approvedDelegation"]),F(e.schemaVersion,"openxiangda.workflow-definition/v2",`${t}/schemaVersion`),no(e.code,`${t}/code`),S(e.title,`${t}/title`,255),["finish-pinned","cancel-on-deactivate"].includes(e.acceptedCommandDeactivationPolicy)||m("NATIVE_WORKFLOW_COMMAND_DEACTIVATION_POLICY_REQUIRED",`${t}/acceptedCommandDeactivationPolicy`);let o=N(e.nodes,`${t}/nodes`),n=Object.keys(o);(n.length===0||n.length>200)&&m("NATIVE_WORKFLOW_NODE_COUNT_INVALID",`${t}/nodes`);let r=S(e.startAt,`${t}/startAt`,128),i=sr(e);i.length&&m(i[0],`${t}/readability`);let d=jn(e);d.length&&m(d[0],`${t}/nodes`);let s=Wn(e);s.length&&m(s[0],`${t}/nodes`);let a=Et(e);a.length&&m(a[0],`${t}/nodes`);let c=pr(e);c.length&&m(c[0],`${t}/nodes`);let f=_r(e);f.length&&m(f[0],`${t}/rejectionNotification`);let u=Vn(e);u.length&&m(u[0],`${t}/nodes`);let p=Gt(e);p.length&&m(p[0],`${t}/taskPages`);let _=xt(e);_.length&&m(_[0],`${t}/nodes`),o[r]||m("NATIVE_WORKFLOW_START_NODE_MISSING",`${t}/startAt`);let E=new Map;for(let[g,I]of Object.entries(o)){let T=`${t}/nodes/${g}`,l=N(I,T);F(l.id,g,`${T}/id`),["approval","condition","end","cc","action","correction"].includes(l.kind)||m("NATIVE_WORKFLOW_NODE_KIND_INVALID",`${T}/kind`);let y=[];if(l.kind==="approval"){S(l.title,`${T}/title`,255),Zn(l.binding,`${T}/binding`),["single","any","all","sequence"].includes(l.mode)||m("NATIVE_WORKFLOW_APPROVAL_MODE_INVALID",`${T}/mode`),y.push(S(l.onApprove,`${T}/onApprove`,128),S(l.onReject,`${T}/onReject`,128));for(let R of V(l.returnTargets||[],`${T}/returnTargets`,200))o[R]||m("NATIVE_WORKFLOW_TARGET_MISSING",`${T}/returnTargets`);for(let R of V(l.allowedOperations||[],`${T}/allowedOperations`,20))Uc.has(R)||m("NATIVE_WORKFLOW_OPERATION_INVALID",`${T}/allowedOperations`)}else if(l.kind==="correction"){let R=Ir(e);R.length&&m(R[0],T)}else if(l.kind==="action")y.push(S(l.next,`${T}/next`,128));else if(l.kind==="cc")S(l.title,`${T}/title`,255),Zn(l.binding,`${T}/binding`),y.push(S(l.next,`${T}/next`,128));else if(l.kind==="condition"){let R=D(l.branches,`${T}/branches`,100);R.length===0&&m("NATIVE_WORKFLOW_BRANCH_REQUIRED",`${T}/branches`),R.forEach((h,$)=>{let w=N(h,`${T}/branches/${$}`);Zt(w.when,`${T}/branches/${$}/when`,0),y.push(S(w.target,`${T}/branches/${$}/target`,128))}),y.push(S(l.otherwise,`${T}/otherwise`,128))}else S(l.title,`${T}/title`,255),S(l.outcome,`${T}/outcome`,128);for(let R of y)o[R]||m("NATIVE_WORKFLOW_TARGET_MISSING",T);E.set(g,y)}let A=new Set,O=new Set,b=g=>{if(O.has(g)&&m("NATIVE_WORKFLOW_CYCLE_FORBIDDEN",`${t}/nodes/${g}`),!A.has(g)){A.add(g),O.add(g);for(let I of E.get(g)||[])b(I);O.delete(g)}};b(r);for(let g of[...A]){let I=o[g];if(I?.kind==="approval")for(let T of I.returnTargets||[])o[T]?.kind==="correction"&&A.add(T)}A.size!==n.length&&m("NATIVE_WORKFLOW_NODE_UNREACHABLE",`${t}/nodes`)}function Zt(e,t,o){o>20&&m("NATIVE_WORKFLOW_EXPRESSION_DEPTH_EXCEEDED",t);let n=N(e,t),r=S(n.op,`${t}/op`,16);if(r!=="literal"){if(r==="path"){let i=S(n.path,`${t}/path`,255);(!/^[A-Za-z][A-Za-z0-9_.-]{0,254}$/.test(i)||i.split(".").some(d=>["__proto__","constructor","prototype"].includes(d)))&&m("NATIVE_WORKFLOW_EXPRESSION_PATH_INVALID",`${t}/path`);return}if(["eq","neq","gt","gte","lt","lte","in","contains"].includes(r)){Zt(n.left,`${t}/left`,o+1),Zt(n.right,`${t}/right`,o+1);return}if(["and","or"].includes(r)){let i=D(n.values,`${t}/values`,100);i.length===0&&m("NATIVE_WORKFLOW_EXPRESSION_EMPTY",`${t}/values`),i.forEach((d,s)=>Zt(d,`${t}/values/${s}`,o+1));return}if(["not","exists"].includes(r)){Zt(n.value,`${t}/value`,o+1);return}m("NATIVE_WORKFLOW_EXPRESSION_OPERATOR_INVALID",`${t}/op`)}}function Vl(e,t){F(e.schemaVersion,"openxiangda.workflow-binding/v2",`${t}/schemaVersion`),no(e.workflowCode,`${t}/workflowCode`);let o=N(e.bindings,`${t}/bindings`);Object.keys(o).length>200&&m("NATIVE_WORKFLOW_BINDING_LIMIT_EXCEEDED",`${t}/bindings`);for(let[n,r]of Object.entries(o)){Zn(n,`${t}/bindings/${n}`);let i=N(r,`${t}/bindings/${n}`),d=dr(i);d.length&&m(d[0],`${t}/bindings/${n}/selectedInputPath`);let s=Wt(i);s.length&&m(s[0],`${t}/bindings/${n}/roleCodes`);let a=S(i.provider,`${t}/bindings/${n}/provider`,64);if(["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)||m("NATIVE_WORKFLOW_BINDING_PROVIDER_INVALID",`${t}/bindings/${n}/provider`),a==="fixed_users"&&(Array.isArray(i.users)||m("NATIVE_WORKFLOW_BINDING_USERS_REQUIRED",`${t}/bindings/${n}/users`),D(i.users,`${t}/bindings/${n}/users`,200)),["input_users","form_field_users"].includes(a)&&S(i.inputPath,`${t}/bindings/${n}/inputPath`,255),["app_role","app_role_in_scope","initiator_select"].includes(a)&&i.roleCodes===void 0&&v(i.roleCode,`${t}/bindings/${n}/roleCode`),a==="department_supervisor"&&S(i.departmentIdFrom,`${t}/bindings/${n}/departmentIdFrom`,255),a==="application_provider"&&v(i.providerCode,`${t}/bindings/${n}/providerCode`),i.routing!==void 0){let c=Jt(i.routing);c.length&&m(c[0],`${t}/bindings/${n}/routing`)}}}function Ll(e,t,o){F(t.workflowCode,e.code,`${o}/workflowCode`);let n=N(t.bindings,`${o}/bindings`);for(let[s,a]of Object.entries(n))a.provider==="fixed_users"&&!a.users.length&&!fr(e,s)&&m("NATIVE_WORKFLOW_BINDING_USERS_REQUIRED",`${o}/bindings/${s}/users`);let r=Wn(e,t);r.length&&m(r[0],o);let i=Vn(e,t);i.length&&m(i[0],o);let d=xt(e,t);d.length&&m(d[0],o);for(let[s,a]of Object.entries(N(e.nodes,`${o}/nodes`))){let c=N(a,`${o}/nodes/${s}`);["approval","cc"].includes(c.kind)&&!n[c.binding]&&m("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${o}/nodes/${s}/binding`)}}function Fl(e,t,o){let n=N(t.routeManifest,"/contracts/routeManifest"),r=N(e.routeManifest,"/contracts/routeManifest"),i=new Map;for(let f of D(o.data?.resources,"/config/data/resources",M.resources)){let u=N(f,"/config/data/resources");i.set(String(u.code||""),u)}let d=new Set(D(r.routes,"/contracts/routeManifest/routes",M.routes).map(f=>String(N(f,"/contracts/routeManifest/routes").code||""))),s=[];for(let f of D(n.routes,"/contracts/routeManifest/routes",M.routes)){let u=N(f,"/contracts/routeManifest/routes"),p=String(u.kind||"");if(p!=="resource-records"&&p!=="resource-submit")continue;let _=String(u.resourceCode||""),E=i.get(_);E||m("NATIVE_ROUTE_MANIFEST_RESOURCE_UNKNOWN","/contracts/routeManifest/routes");let O=`user.${_}.${p==="resource-records"?"records":"submit"}`;F(String(u.code||""),O,"/contracts/routeManifest/routes/code");let b=p==="resource-records"?"read":"create",g=String(N(E.capabilities,"/config/data/resources/capabilities")[b]||"");for(let I of["desktop","mobile"]){let T=N(u[I],`/contracts/routeManifest/routes/${I}`),l=I==="mobile"?"/m/my/":"/my/",y=p==="resource-records"?`${l}${_}`:`${l}${_}/submit`;F(String(T.path||""),y,`/contracts/routeManifest/routes/${I}/path`),F(String(T.capability||""),g,`/contracts/routeManifest/routes/${I}/capability`),F(String(T.routeCode||""),`${O}.${I}`,`/contracts/routeManifest/routes/${I}/routeCode`)}(d.has(O)||s.some(I=>String(I.code)===O))&&m("NATIVE_ROUTE_MANIFEST_DUPLICATE","/contracts/routeManifest/routes/code"),s.push(u)}if(!s.length)return;r.routes=D([...r.routes,...s],"/contracts/routeManifest/routes",1e3).sort((f,u)=>Ie(String(N(f,"x").code||""),String(N(u,"x").code||"")));let a=String(N(n.rootEntry,"x").code||"");if(s.find(f=>String(f.code)===a&&f.kind==="resource-records")){let f=N(n.rootEntry,"x");r.rootEntry={code:a,desktop:String(f.desktop||""),mobile:String(f.mobile||"")}}r.digest=Z({schemaVersion:r.schemaVersion,appCode:r.appCode,devicePolicy:r.devicePolicy,rootEntry:r.rootEntry,authentication:r.authentication,routes:r.routes})}function tt(e,t,o){let n=N(e,t);C(n,["schemaVersion","appCode","code","name","schema","surface","invariants","decimalReservationLifecycle","uniqueKeys","workflowHistory","recordPrint","recordComments","recordDeletion","capabilities","dataPolicyCode","fieldPolicies"],t,!0),F(n.schemaVersion,"openxiangda.data-resource/v2",`${t}/schemaVersion`),F(n.appCode,o,`${t}/appCode`);let r=H(n.code,`${t}/code`),i=S(n.name,`${t}/name`,255),d=N(n.schema,`${t}/schema`);C(d,["fields","ownedRowLimit"],`${t}/schema`,!0),d.ownedRowLimit!==void 0&&!st(d.ownedRowLimit)&&m("NATIVE_DATA_OWNED_ROW_LIMIT_INVALID",`${t}/schema/ownedRowLimit`);let s,a,c,f;try{c=Nn(n.decimalReservationLifecycle,`${t}/decimalReservationLifecycle`),s=mn(d.fields,`${t}/schema/fields`),f=Jo(n.uniqueKeys,s,`${t}/uniqueKeys`),a=bo(n.invariants,s,`${t}/invariants`),In(n.surface,s,`${t}/surface`)}catch(E){throw(E instanceof be||E instanceof Le||E instanceof ze||E instanceof _t)&&m(E.code,E.pointer),E}if(n.recordComments!==void 0){let E=N(n.recordComments,`${t}/recordComments`);C(E,["read","create"],`${t}/recordComments`);for(let A of["read","create"]){let O=E[A];(!Array.isArray(O)||O.length>20||O.some(b=>typeof b!="string"||!b.trim())||new Set(O).size!==O.length)&&m("NATIVE_RECORD_COMMENTS_POLICY_INVALID",`${t}/recordComments/${A}`)}}if(n.recordDeletion!==void 0){let E=N(n.recordDeletion,`${t}/recordDeletion`);C(E,["delete"],`${t}/recordDeletion`);let A=E.delete;(!Array.isArray(A)||A.length>20||A.some(O=>typeof O!="string"||!O.trim())||new Set(A).size!==A.length)&&m("NATIVE_RECORD_DELETION_DELETE_INVALID",`${t}/recordDeletion/delete`)}if(n.recordPrint!==void 0){let E=N(n.recordPrint,`${t}/recordPrint`);C(E,["read"],`${t}/recordPrint`);let A=E.read;(!Array.isArray(A)||A.length>20||A.some(O=>typeof O!="string"||!O.trim())||new Set(A).size!==A.length)&&m("NATIVE_RECORD_PRINT_READ_INVALID",`${t}/recordPrint/read`)}if(n.workflowHistory!==void 0){let E=N(n.workflowHistory,`${t}/workflowHistory`);C(E,["read"],`${t}/workflowHistory`);let A=E.read;(!Array.isArray(A)||A.length>20||A.some(O=>typeof O!="string"||!O.trim())||new Set(A).size!==A.length)&&m("NATIVE_WORKFLOW_HISTORY_READ_INVALID",`${t}/workflowHistory/read`)}let u=new Set(s.map(E=>E.code)),p=N(n.capabilities,`${t}/capabilities`);C(p,["read","create","update","delete"],`${t}/capabilities`);let _=N(n.fieldPolicies,`${t}/fieldPolicies`);for(let[E,A]of Object.entries(_)){!u.has(E)&&!at(E)&&m("NATIVE_DATA_FIELD_POLICY_FIELD_MISSING",`${t}/fieldPolicies/${E}`);let O=`${t}/fieldPolicies/${E}`,b=N(A,O);at(E)&&(C(b,["read"],O,!0),(!Array.isArray(b.read)||b.read.length>20||b.read.some(g=>typeof g!="string"||!g.trim())||new Set(b.read).size!==b.read.length)&&m("NATIVE_DATA_AUDIT_READ_POLICY_INVALID",`${O}/read`)),C(b,["read","create","update","mask"],O,!0),b.mask!==void 0&&!["omit","null"].includes(b.mask)&&m("NATIVE_DATA_FIELD_POLICY_MASK_INVALID",`${O}/mask`)}return{...n,code:r,name:i,schema:{fields:s,...d.ownedRowLimit!==void 0?{ownedRowLimit:d.ownedRowLimit}:{}},...n.invariants===void 0?{}:{invariants:a},...c?{decimalReservationLifecycle:c}:{},...f!==void 0?{uniqueKeys:f}:{},capabilities:p,fieldPolicies:_}}function Hs(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 Ds(e,t,o,n){let r=e.toString("utf8"),i;try{i=JSON.parse(r)}catch{m(o,t)}let d=N(i,t);return X(d)!==r&&m(n,t),d}function qn(e,t,o){let n=0,r=(i,d,s)=>{if(n+=1,n>o&&m("NATIVE_ARTIFACT_NODE_LIMIT_EXCEEDED",d),s>Kc&&m("NATIVE_ARTIFACT_DEPTH_LIMIT_EXCEEDED",d),typeof i=="string"){Buffer.byteLength(i)>$r&&m("NATIVE_ARTIFACT_STRING_LIMIT_EXCEEDED",d);return}if(Array.isArray(i)){i.forEach((a,c)=>r(a,`${d}/${c}`,s+1));return}if(!(!i||typeof i!="object"))for(let[a,c]of Object.entries(i))["__proto__","prototype","constructor"].includes(a)&&m("NATIVE_ARTIFACT_DANGEROUS_KEY",`${d}/${a}`),xl(a)&&m("NATIVE_ARTIFACT_RUNTIME_FIELD_FORBIDDEN",`${d}/${a}`),r(c,`${d}/${a}`,s+1)};r(e,t,0)}function xl(e){return["environmentKey","environmentId","secretValue","ciphertext","oauthClient","oauthClientId","oauthClientSecret","signingSecret","kubernetesNamespace","nodePort","productionUrl"].includes(e)}function bt(e){return{value:e,digest:Z(e)}}function ks(e,t,o,n){typeof e!="string"&&!Buffer.isBuffer(e)&&!(e instanceof Uint8Array)&&m("NATIVE_ARTIFACT_BYTES_REQUIRED",o);let r=Buffer.isBuffer(e)?e:Buffer.from(e);return r.byteLength===0&&m("NATIVE_ARTIFACT_EMPTY",o),r.byteLength>t&&m(n,o),r}function $s(e,t,o,n){let r=Qn.createHash("sha256").update(e).digest("hex");Qn.timingSafeEqual(Buffer.from(r),Buffer.from(t))||m(n,o)}function N(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&m("NATIVE_OBJECT_REQUIRED",t),e}function D(e,t,o){return Array.isArray(e)||m("NATIVE_ARRAY_REQUIRED",t),e.length>o&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t),e}function V(e,t,o){let n=D(e,t,o).map((r,i)=>S(r,`${t}/${i}`,255));return new Set(n).size!==n.length&&m("NATIVE_ARRAY_DUPLICATE",t),n}function S(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&m("NATIVE_STRING_INVALID",t),e}function xr(e,t,o){return(typeof e!="string"||e.length>o)&&m("NATIVE_STRING_INVALID",t),e}function v(e,t){let o=S(e,t,128);return wc.test(o)||m("NATIVE_CODE_INVALID",t),o}function H(e,t){let o=S(e,t,64);return Dc.test(o)||m("NATIVE_RESOURCE_CODE_INVALID",t),o}function G(e,t){let o=S(e,t,63);return kc.test(o)||m("NATIVE_FIELD_CODE_INVALID",t),o}function no(e,t){let o=S(e,t,128);return vc.test(o)||m("NATIVE_WORKFLOW_CODE_INVALID",t),o}function Zn(e,t){let o=S(e,t,128);return Vc.test(o)||m("NATIVE_WORKFLOW_BINDING_CODE_INVALID",t),o}function me(e,t,o){let n=S(e,t,255);return hc.test(n)||m("NATIVE_CAPABILITY_CODE_INVALID",t),!n.startsWith(`app:${o}:`)&&!Hs(o).some(r=>r.code===n)&&m("NATIVE_CAPABILITY_APP_MISMATCH",t),n}function Te(e,t){let o=S(e,t,2048);return(!o.startsWith("/")||o.startsWith("//")||o.includes("..")||o.includes("?")||o.includes("#"))&&m("NATIVE_ABSOLUTE_PATH_INVALID",t),o}function Ot(e,t){return(!Number.isInteger(e)||Number(e)<1)&&m("NATIVE_POSITIVE_INTEGER_REQUIRED",t),Number(e)}function se(e,t,o,n){return(!Number.isInteger(e)||Number(e)<o||Number(e)>n)&&m("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function Nt(e,t){return typeof e!="boolean"&&m("NATIVE_BOOLEAN_REQUIRED",t),e}function vr(e,t){let o=S(e,t,64).toLowerCase();return Rc.test(o)||m("NATIVE_DIGEST_INVALID",t),o}function F(e,t,o){e!==t&&m("NATIVE_VALUE_MISMATCH",o)}function C(e,t,o,n=!1){let r=new Set([...t,...Array.isArray(n)?n:[]]);for(let i of Object.keys(e))r.has(i)||m("NATIVE_PROPERTY_UNKNOWN",`${o}/${i}`);if(n!==!0)for(let i of t)Object.prototype.hasOwnProperty.call(e,i)||m("NATIVE_PROPERTY_REQUIRED",`${o}/${i}`)}function te(e,t){return[...e].sort((o,n)=>Ie(t(o),t(n)))}function B(e){return[...new Set(e)].sort(Ie)}function Ps(e){return[...new Set(e)].sort((t,o)=>t-o)}function Ie(e,t){return e===t?0:e<t?-1:1}function Ys(e){return!e||typeof e!="object"||Object.isFrozen(e)||(Object.freeze(e),Object.values(e).forEach(t=>Ys(t))),e}function Vr(e,t,o){if(kr(e,t))return o;if(Array.isArray(e)&&Array.isArray(t)){let n=Math.max(e.length,t.length);for(let r=0;r<n;r+=1)if(!kr(e[r],t[r]))return Vr(e[r],t[r],`${o}/${r}`)}if(e&&t&&typeof e=="object"&&typeof t=="object"&&!Array.isArray(e)&&!Array.isArray(t)){let n=B([...Object.keys(e),...Object.keys(t)]);for(let r of n){let i=e[r],d=t[r];if(!kr(i,d))return Vr(i,d,`${o}/${r}`)}}return o}function kr(e,t){return e===void 0||t===void 0?e===t:X(e)===X(t)}function m(e,t,o={}){throw new Hn(e,t,o)}var jl="openxiangda.workflow-step-data-command/v1",Xs="openxiangda.workflow-step-data-resolution/v1";function Wl(e,t,o=!1){let n=s=>!!s&&typeof s=="object"&&!Array.isArray(s),r=s=>typeof s=="string"&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(s),i=()=>{throw new Error("WORKFLOW_STEP_DATA_RESPONSE_INVALID")};if(!n(e)||e.schemaVersion!==Xs||e.executionId!==t||Object.keys(e).some(s=>!["schemaVersion","executionId","outcome","transaction"].includes(s)))return i();if(e.outcome==="not_observed"&&!Object.hasOwn(e,"transaction")&&!o)return e;let d=e.transaction;if(e.outcome!=="committed"||!n(d)||d.schemaVersion!=="openxiangda.data-transaction-result/v2"||d.idempotencyKey!==`workflow-step:${t}`||typeof d.replayed!="boolean"||!Array.isArray(d.items)||d.items.length<1||d.items.length>go||d.evaluatedAt!==void 0&&(typeof d.evaluatedAt!="string"||!Number.isFinite(Date.parse(d.evaluatedAt))))return i();for(let[s,a]of d.items.entries()){if(!n(a)||a.index!==s)return i();if(a.operation==="emitEvent"){if(typeof a.eventType!="string"||!a.eventType||!r(a.eventId))return i()}else if(!["create","update","delete","increment"].includes(a.operation)||typeof a.resourceCode!="string"||!a.resourceCode||!r(a.id)||!Number.isSafeInteger(a.revision)||a.revision<1)return i()}return e}var Mp=50,Bp=131072,oo=class extends Error{constructor(o){super("OPENXIANGDA_NATIVE_AUTHZ_BATCH_INPUT_INVALID");this.pointer=o}pointer;code="OPENXIANGDA_NATIVE_AUTHZ_BATCH_INPUT_INVALID";status=400};function Ul(e){let t=u=>{throw new oo(u)},o=(u,p)=>((!u||typeof u!="object"||Array.isArray(u))&&t(p),u),n=(u,p,_)=>{for(let E of Object.keys(u))p.includes(E)||t(`${_}/${E}`)},r=(u,p,_)=>((typeof u!="string"||!u.trim()||u.length>p)&&t(_),u),i=(u,p)=>{let _=r(u,36,p);return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(_)||t(p),_.toLowerCase()},d=o(e,""),s;try{s=new TextEncoder().encode(JSON.stringify(d)).byteLength}catch{t("")}s>131072&&t(""),n(d,["schemaVersion","environmentKey","items"],""),d.schemaVersion!=="openxiangda.native-role-membership-batch-request/v2"&&t("/schemaVersion"),d.environmentKey!==void 0&&!["preproduction","production"].includes(String(d.environmentKey))&&t("/environmentKey"),(!Array.isArray(d.items)||d.items.length<1||d.items.length>50)&&t("/items");let a=new Set,c=new Set,f;for(let[u,p]of d.items.entries()){let _=`/items/${u}`,E=o(p,_);["create","update","revoke"].includes(String(E.operation))||t(`${_}/operation`),f??=E.operation,f!==E.operation&&t(`${_}/operation`),n(E,["operation","operationId","reason",...f==="create"?["userId","roleCode"]:["membershipId","expectedRevision"],...f!=="revoke"?["scopeGrants","validFrom","validTo"]:[]],_);let A=i(E.operationId,`${_}/operationId`);a.has(A)&&t(`${_}/operationId`),a.add(A),r(E.reason,1e3,`${_}/reason`);let O;if(f==="create"){let b=r(E.userId,255,`${_}/userId`),g=r(E.roleCode,128,`${_}/roleCode`);/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(g)||t(`${_}/roleCode`),O=JSON.stringify([b,g])}else O=i(E.membershipId,`${_}/membershipId`),(!Number.isSafeInteger(E.expectedRevision)||Number(E.expectedRevision)<1)&&t(`${_}/expectedRevision`);c.has(O)&&t(_),c.add(O),E.scopeGrants!==void 0&&(!Array.isArray(E.scopeGrants)||E.scopeGrants.length>100)&&t(`${_}/scopeGrants`);for(let b of["validFrom","validTo"])E[b]!==void 0&&E[b]!==null&&r(E[b],64,`${_}/${b}`)}}var ta="openxiangda.workflow-delegation-administration/v2",na="openxiangda.workflow-delegation-mutation/v2",Zs="openxiangda.workflow-delegation-preview/v2";var en={type:"string",format:"uuid",pattern:"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$"},_e={type:"string",minLength:1,maxLength:255},nt={type:"string",format:"date-time"},Tt={type:"integer",minimum:1},Ml={anyOf:[nt,{type:"null"}]},jr={anyOf:[_e,{type:"null"}]},oa={anyOf:[{type:"string",pattern:"^[A-Za-z0-9._:-]{1,128}$"},{type:"null"}]},ro={type:"string",pattern:"^membership:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},ra={const:"future-assignments-only"},Wr={schemaVersion:{const:ta},id:en,appCode:_e,environmentKey:_e,workflowCode:jr,nodeId:oa,delegatorUserId:_e,delegateUserId:_e,delegatorRoleSubjectKey:ro,delegateRoleSubjectKey:ro,validFrom:nt,validTo:nt,status:{enum:["active","revoked","expired"]},reason:{type:"string",minLength:1,maxLength:4e3},createdBy:_e,createdAt:nt,revokedAt:Ml,revision:Tt,roleCode:_e,roleName:_e,delegatorDisplayName:_e,delegateDisplayName:_e,delegatorRoleSubjectRevision:Tt,delegateRoleSubjectRevision:Tt,effectiveState:{enum:["active","scheduled","expired","revoked","ineligible"]},evaluatedAt:nt,issues:{type:"array",maxItems:20,uniqueItems:!0,items:_e},canRevoke:{type:"boolean"},revokedBy:jr,revokeReason:{type:["string","null"],maxLength:4e3},taskPolicy:ra},Ur={type:"object",additionalProperties:!1,required:Object.keys(Wr).filter(e=>e!=="nodeId"),properties:Wr},Gp={$id:ta,...Ur},ia={schemaVersion:{const:na},operationId:en,environmentKey:{enum:["preproduction","production"]},reason:{type:"string",minLength:1,maxLength:2e3,pattern:"\\S"}},Qs={...ia,operation:{const:"create"},workflowCode:jr,nodeId:oa,delegatorRoleSubjectKey:ro,expectedDelegatorRevision:Tt,delegateUserId:_e,delegateRoleSubjectKey:ro,expectedDelegateRevision:Tt,validFrom:nt,validTo:nt},ea={...ia,operation:{const:"revoke"},delegationId:en,expectedRevision:Tt},sa={$id:na,type:"object",oneOf:[{type:"object",additionalProperties:!1,required:Object.keys(Qs).filter(e=>e!=="nodeId"),properties:Qs,if:{required:["nodeId"],properties:{nodeId:{type:"string"}}},then:{properties:{workflowCode:_e}}},{type:"object",additionalProperties:!1,required:Object.keys(ea),properties:ea}]},Bl={type:"string",pattern:"^[0-9a-f]{64}$"},qp={$id:Zs,type:"object",additionalProperties:!1,required:["schemaVersion","operationId","operation","requestDigest","before","after","taskPolicy"],properties:{schemaVersion:{const:Zs},operationId:en,operation:{enum:["create","revoke"]},requestDigest:Bl,before:{anyOf:[Ur,{type:"null"}]},after:{...Ur,properties:{...Wr,id:{anyOf:[en,{type:"null"}]}}},taskPolicy:ra}};function Kl(e){return e===void 0?"":`
9
+ ${Z(e)}`}function Gl(e,t){let o=e.handlers.find(n=>n.code===t);return Z(o?.workflowStep?o:e)}var ql="openxiangda.data-business-command/v1",aa="openxiangda.data-business-command-resolution/v1",Yp=65536;function zl(e){let t=0,o=0,n=new Set,r=new TextEncoder,i=()=>{throw new Error("OPENXIANGDA_DATA_COMMAND_INTENT_INVALID")},d=a=>(o+=r.encode(a).byteLength,o>65536&&i(),a),s=(a,c)=>{if(++t>1e4||c>32)return i();if(a===null||typeof a=="string"||typeof a=="boolean")return d(JSON.stringify(a));if(typeof a=="number")return Number.isFinite(a)?d(JSON.stringify(a)):i();if(!a||typeof a!="object"||n.has(a)||Object.getOwnPropertySymbols(a).length)return i();n.add(a);let f;if(Array.isArray(a))return Object.keys(a).length!==a.length?i():(f=d("[")+a.map((p,_)=>(_?d(","):"")+s(p,c+1)).join("")+d("]"),n.delete(a),f);let u=Object.getPrototypeOf(a);return u!==Object.prototype&&u!==null?i():(f=d("{")+Object.keys(a).sort().map((p,_)=>(_?d(","):"")+d(JSON.stringify(p))+d(":")+s(a[p],c+1)).join("")+d("}"),n.delete(a),f)};return!e||typeof e!="object"||Array.isArray(e)?i():s(e,0)}function Jl(e,t,o=!1){let n=e,r=()=>{throw new Error("OPENXIANGDA_DATA_COMMAND_RESPONSE_INVALID")};if(!n||typeof n!="object"||n.schemaVersion!==aa)return r();for(let a of["appCode","environmentKey","operationCode","idempotencyKey","intentDigest"])if(n[a]!==t[a])return r();if(typeof n.observedAt!="string"||!Number.isFinite(Date.parse(n.observedAt)))return r();if(n.outcome==="not_observed"&&n.receipt===null&&!o)return n;if(n.outcome!=="committed"||!n.receipt)return r();let i=n.receipt,d=a=>typeof a=="string"&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(a);if(!d(i.id)||!d(i.appVersionId)||!Number.isSafeInteger(i.environmentHeadRevision)||i.environmentHeadRevision<1||typeof i.completedAt!="string"||!Number.isFinite(Date.parse(i.completedAt)))return r();let s=i.transaction;if(!s||s.schemaVersion!=="openxiangda.data-transaction-result/v2"||s.idempotencyKey!==t.idempotencyKey||typeof s.replayed!="boolean"||!Array.isArray(s.items)||!s.items.length||s.items.length>1e3)return r();for(let[a,c]of s.items.entries()){if(!c||c.index!==a)return r();if(c.operation==="emitEvent"){if(!d(c.eventId)||typeof c.eventType!="string"||!c.eventType)return r()}else if(!["create","update","delete","increment"].includes(c.operation)||!d(c.id)||typeof c.resourceCode!="string"||!c.resourceCode||!Number.isSafeInteger(c.revision)||c.revision<1)return r()}return n}var da=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,io=e=>!!e&&typeof e=="object"&&!Array.isArray(e),tn=(e,t)=>typeof e=="string"&&e.length<=t&&e.trim().length>0&&e===e.trim(),Mr=(e,t,o=[])=>t.every(n=>Object.hasOwn(e,n))&&Object.keys(e).every(n=>[...t,...o].includes(n));function Hl(e){if(!io(e)||!Mr(e,["kind","errorCode","anyOf"],["allowAppSuperAdmin"])||e.kind!=="actor-authority"||!tn(e.errorCode,110)||!/^OPENXIANGDA_[A-Z0-9_]{1,96}$/.test(e.errorCode)||Object.hasOwn(e,"allowAppSuperAdmin")&&typeof e.allowAppSuperAdmin!="boolean"||!Array.isArray(e.anyOf)||e.anyOf.length<1||e.anyOf.length>20)return!1;let t=new Set;return e.anyOf.every(o=>{if(!io(o)||!Mr(o,["roleCode"],["scope"])||!tn(o.roleCode,100)||!da.test(o.roleCode))return!1;if(Object.hasOwn(o,"scope")){let i=o.scope;if(!io(i)||!Mr(i,["dimensionCode","value","operation"])||!tn(i.dimensionCode,100)||!da.test(i.dimensionCode)||!tn(i.value,255)||!tn(i.operation,64)||!/^[A-Za-z0-9*][A-Za-z0-9*._:-]*$/.test(i.operation))return!1}let n=o.scope,r=JSON.stringify([o.roleCode,n?.dimensionCode,n?.value,n?.operation]);return t.has(r)?!1:(t.add(r),!0)})}function Yl(e,t,o){if(t.roleSource!=="package"||t.roleCode!==e.roleCode||!o||!t.capabilityCodes.includes(o))return!1;if(!e.scope)return!0;let n;try{n=JSON.parse(t.scopeGrantsJson)}catch{return!1}if(!Array.isArray(n))return!1;let r=e.scope;return n.some(i=>io(i)&&i.dimensionCode===r.dimensionCode&&Array.isArray(i.values)&&i.values.includes(r.value)&&(i.operations===void 0||i.operations===null||Array.isArray(i.operations)&&(!i.operations.length||i.operations.includes("*")||i.operations.includes(r.operation))))}var Qp=500,Xl=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Br=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function Zl(e){if(!Br(e)||e.kind!=="record-set-match"||Object.keys(e).some(o=>!["kind","resourceCode","errorCode","records","where"].includes(o))||typeof e.resourceCode!="string"||e.resourceCode.length>64||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(e.resourceCode)||typeof e.errorCode!="string"||!/^OPENXIANGDA_[A-Z0-9_]{1,96}$/.test(e.errorCode)||!Array.isArray(e.records)||!e.records.length||e.records.length>500||Object.hasOwn(e,"where")&&!Br(e.where))return!1;let t=new Set;return e.records.every(o=>{if(!Br(o)||Object.keys(o).length!==2||typeof o.id!="string"||!Xl.test(o.id)||!Number.isSafeInteger(o.expectedRevision)||Number(o.expectedRevision)<1)return!1;let n=o.id.toLowerCase();return t.has(n)?!1:(t.add(n),!0)})}function ca(e,t){if(t===void 0)return e;let o=e.views?.find(d=>d.code===t);if(!o)throw new Error(`DATA_RESOURCE_VIEW_NOT_FOUND: ${t}`);let n=new Map(o.sections?.flatMap(d=>d.fields.map(s=>[s,d.title]))),{views:r,...i}=e;return{...i,generated:o.generated,list:o.list,form:o.form,detail:o.detail,mobile:o.mobile,fields:Object.fromEntries(Object.entries(e.fields).map(([d,s])=>{let{section:a,...c}=s,f=n.get(d);return[d,{...c,...f?{section:f}:{},list:o.list.fieldOrder?.includes(d)??!1}]}))}}var la="openxiangda.development-configuration/v1",Kr="openxiangda.development-configuration-manifest/v1",Ql="application.development-configuration",eu="/openxiangda-api/v2/applications/{appCode}/dev-sessions/configuration",so=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.data={pointer:n}}code;pointer;status=400;data};function Ue(e){throw new so("OPENXIANGDA_CONNECTED_DEV_CONFIGURATION_INVALID",e)}function ua(e){(!e||typeof e!="object"||Array.isArray(e))&&Ue("/packageManifest");let t=e,o=["schemaVersion","appCode","version","configDigest","contractDigest","source","toolchain","artifacts"];(Object.keys(t).some(r=>!o.includes(r))||t.schemaVersion!==Kr||typeof t.appCode!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(t.appCode)||!/^[a-f0-9]{64}$/.test(t.configDigest)||!/^[a-f0-9]{64}$/.test(t.contractDigest)||t.version!==`development-${t.configDigest}`)&&Ue("/packageManifest"),(!t.source||typeof t.source!="object"||Array.isArray(t.source)||Object.keys(t.source).some(r=>!["repository","commit","dirty"].includes(r))||![null,"string"].includes(t.source.repository===null?null:typeof t.source.repository)||t.source.repository!==null&&(t.source.repository.length>1024||/[\r\n\0]/.test(t.source.repository))||t.source.commit!==null&&(typeof t.source.commit!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(t.source.commit))||typeof t.source.dirty!="boolean")&&Ue("/packageManifest/source"),(!t.toolchain||Object.keys(t.toolchain).some(r=>!["version","contractVersion"].includes(r))||typeof t.toolchain.version!="string"||!/^[A-Za-z0-9][A-Za-z0-9.+_-]{0,127}$/.test(t.toolchain.version)||t.toolchain.contractVersion!==Sr)&&Ue("/packageManifest/toolchain");let n=[{kind:"config",digest:t.configDigest,mediaType:"application/json"},{kind:"contracts",digest:t.contractDigest,mediaType:"application/json"}];return X(t.artifacts)!==X(n)&&Ue("/packageManifest/artifacts"),t}function tu(e,t){return ua({schemaVersion:Kr,appCode:e,version:`development-${t.configDigest}`,configDigest:t.configDigest,contractDigest:t.contractDigest,source:{...t.source},toolchain:{version:t.toolchainVersion,contractVersion:Sr},artifacts:[{kind:"config",digest:t.configDigest,mediaType:"application/json"},{kind:"contracts",digest:t.contractDigest,mediaType:"application/json"}]})}function nu(e,t){return(!Number.isSafeInteger(t)||t<1)&&Ue("/expectedHeadRevision"),`development:${Z({manifest:e,expectedHeadRevision:t})}`}function ou(e,t,o){(!e||typeof e!="object"||Array.isArray(e))&&Ue("/result");let n=e,r=["schemaVersion","appCode","environmentKey","environmentId","appVersionId","configurationRunId","headRevision","configDigest","contractDigest","reused","runtimeArtifactsDeployed","backendEventsAvailable"],i=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i;return(Object.keys(n).some(d=>!r.includes(d))||n.schemaVersion!==la||n.appCode!==t||n.environmentKey!=="preproduction"||n.configDigest!==o.configDigest||n.contractDigest!==o.contractDigest||!i.test(n.environmentId)||!i.test(n.appVersionId)||!i.test(n.configurationRunId)||typeof n.reused!="boolean"||!Number.isSafeInteger(n.headRevision)||n.headRevision<1||!n.reused&&n.headRevision!==o.expectedHeadRevision+1||n.runtimeArtifactsDeployed!==!1||n.backendEventsAvailable!==!1)&&Ue("/result"),n}var ru="application.development-backend-events",iu="openxiangda.development-backend/v1",su="application.development-backend-invocations",fa="openxiangda.development-backend-invocation/v1",im=262144,sm=1048576,am=131072,dm=131072,cm=8,lm=45,au=/^\/__platform\/events\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function du(e){return(e.backend?.operations?.length||0)>0||(e.workflows?.providers?.length||0)>0||(e.events?.subscriptions||[]).some(t=>t.execution?.kind!=="native-data")}function cu(e){return`connected-development:${e}`}function pa(e){if(typeof e!="string"||e.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(e))return null;let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=e.endsWith("==")?2:e.endsWith("=")?1:0;return o&&t.indexOf(e[e.length-o-1])%(o===2?16:4)!==0?null:e.length/4*3-o}function ma(e,t,o){if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)||o.method!==e||typeof t!="string"||t.length>2048||!t.startsWith("/")||t.startsWith("//")||t.startsWith("/__platform")||/[\\?#\s\u0000-\u001f\u007f]/.test(t))return!1;let n=t.split("/"),r=String(o.path||"").split("/");return n.length!==r.length?!1:n.every((i,d)=>{if(d===0)return r[d]==="";let s;try{s=decodeURIComponent(i)}catch{return!1}return!s||[".",".."].includes(s)||/[\/\\\s\u0000-\u001f\u007f]/.test(s)?!1:/^:[A-Za-z][A-Za-z0-9_]*$/.test(r[d]||"")||i===r[d]})}var lu=/^(?:authorization|content-type|content-length|accept|if-match|idempotency-key|x-request-id|x-openxiangda-(?:gateway-assertion|forwarded-by|perspective|csrf-token|mcp-bus-token))$/i,uu=/^(?:content-type|content-disposition|cache-control|etag|last-modified|retry-after)$/i;function _a(e,t=!1){if(!e||typeof e!="object"||Array.isArray(e))return!1;let o=Object.entries(e),n=o.map(([r])=>r.toLowerCase());return o.length<=24&&new Set(n).size===n.length&&o.every(([r,i])=>(t?uu:lu).test(r)&&typeof i=="string"&&i.length<=8192&&!/[\r\n\u0000]/.test(i))}function fu(e){let t=pa(e.body);return e.schemaVersion===fa&&!!e.operation&&typeof e.operation.code=="string"&&e.operation.code.length<=128&&e.operation.code.length>0&&ma(e.method,e.endpointPath,e.operation)&&typeof e.canonicalQuery=="string"&&e.canonicalQuery.length<=8192&&!/[\s#\u0000-\u001f\u007f]/.test(e.canonicalQuery)&&t!==null&&t<=262144&&_a(e.headers)&&Object.entries(e.headers).some(([o,n])=>o.toLowerCase()==="authorization"&&/^Bearer \S+$/.test(n))&&Object.entries(e.headers).some(([o,n])=>o.toLowerCase()==="x-openxiangda-gateway-assertion"&&!!n)}var pu="b6f020da75760227d5bf94bb447f8891729167e27e42a337668fb6e3e8d60f1d";0&&(module.exports={AuthenticatedPublicReadContractError,DATA_AUDIT_METADATA_FIELDS,DATA_BUSINESS_COMMAND_INTENT_MAX_BYTES,DATA_BUSINESS_COMMAND_RESOLUTION_SCHEMA,DATA_BUSINESS_COMMAND_SCHEMA,DATA_EVENT_TYPES_V2,DATA_FORM_DRAFT_MAX_BYTES,DATA_RESOURCE_MAX_FIELDS,DATA_SUBTABLE_DEFAULT_TOTAL_ROWS,DATA_SUBTABLE_MAX_ROWS,DATA_SUBTABLE_MAX_TOTAL_ROWS,DATA_SYSTEM_SORT_FIELD_CODES,DATA_TRANSACTION_MAX_BYTES,DATA_TRANSACTION_MAX_OPERATIONS,DATA_TRANSACTION_RECORD_SET_MAX_RECORDS,DATE_EVENT_RESERVED_DATA_FIELDS_V2,DEVELOPMENT_BACKEND_CONNECTION_TTL_SECONDS,DEVELOPMENT_BACKEND_ENDPOINT_PATTERN,DEVELOPMENT_BACKEND_FEATURE,DEVELOPMENT_BACKEND_INVOCATION_FEATURE,DEVELOPMENT_BACKEND_INVOCATION_MAX_REQUEST_BYTES,DEVELOPMENT_BACKEND_INVOCATION_MAX_RESPONSE_BYTES,DEVELOPMENT_BACKEND_INVOCATION_SCHEMA,DEVELOPMENT_BACKEND_MAX_INFLIGHT,DEVELOPMENT_BACKEND_MAX_REQUEST_BYTES,DEVELOPMENT_BACKEND_MAX_RESPONSE_BYTES,DEVELOPMENT_BACKEND_SCHEMA,DEVELOPMENT_CONFIGURATION_ENDPOINT,DEVELOPMENT_CONFIGURATION_FEATURE,DEVELOPMENT_CONFIGURATION_MANIFEST_SCHEMA,DEVELOPMENT_CONFIGURATION_SCHEMA,DateEventProjectionV2Error,DevelopmentConfigurationContractError,ManagedConcurrencyContractError,NATIVE_ARTIFACT_CAPACITY_V2,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,NATIVE_HIGH_DENSITY_ARTIFACT_CAPACITY_V2,NATIVE_ROLE_MEMBERSHIP_BATCH_MAX_BYTES,NATIVE_ROLE_MEMBERSHIP_BATCH_MAX_ITEMS,NATIVE_UNIQUE_KEY_MAX_BYTES,NATIVE_UNIQUE_KEY_NORMALIZERS,NativeConfigurationCompilerError,NativeDataFieldContractV2Error,NativeDataPolicyExpressionV2Error,NativeDecimalLifecycleContractError,NativeEventActionContractError,NativeParentReadPolicyError,NativeRoleMembershipBatchInputError,NativeScopeSourceFieldPathV2Error,NativeUniqueKeyContractError,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,USER_CANDIDATE_MAX_SELECTIONS,USER_CANDIDATE_SCOPE_FIELD_TYPES,UserCandidateContractError,WORKFLOW_APPROVAL_EMPTY_PROVIDERS,WORKFLOW_APPROVED_DELEGATION_MAX_BYTES,WORKFLOW_APPROVED_DELEGATION_MAX_REQUESTS,WORKFLOW_AUTOMATIC_CC_DEFAULT_RECIPIENTS,WORKFLOW_AUTOMATIC_CC_MAX_RECIPIENTS,WORKFLOW_AUTOMATIC_CC_PROVIDERS,WORKFLOW_BUSINESS_STEP_EVENT,WORKFLOW_BUSINESS_STEP_EVENTS,WORKFLOW_BUSINESS_STEP_FACTS_KEY,WORKFLOW_BUSINESS_STEP_MAX_BYTES,WORKFLOW_BUSINESS_STEP_MAX_RECEIPT_BYTES,WORKFLOW_CONFIGURABLE_OPERATIONS,WORKFLOW_CONFIGURABLE_PROVIDERS,WORKFLOW_EVENT_TYPES_V2,WORKFLOW_LAUNCH_MAX_INPUTS,WORKFLOW_LAUNCH_PREFLIGHT_PROVIDERS,WORKFLOW_REJECTION_NOTIFICATION_MAX_BYTES,WORKFLOW_REJECTION_NOTIFICATION_SCHEMA,WORKFLOW_ROLE_UNION_MAX_ROLES,WORKFLOW_ROUTING_MAX_BYTES,WORKFLOW_ROUTING_MAX_MATCHED_RULES,WORKFLOW_ROUTING_MAX_RULES,WORKFLOW_STEP_DATA_COMMAND_SCHEMA,WORKFLOW_STEP_DATA_RESOLUTION_SCHEMA,WORKFLOW_TASK_PAGE_DEFINITION_MAX_BYTES,WORKFLOW_TASK_PAGE_MAX_BYTES,WORKFLOW_TASK_PAGE_MAX_FIELDS,WORKFLOW_TASK_SUBTABLE_MAX_ROWS,WORKFLOW_TASK_SUBTABLE_MAX_TOTAL_ROWS,WorkflowTaskPageError,applyWorkflowTaskPageValues,applyWorkflowTaskSubtableRows,assertDevelopmentConfigurationManifest,assertDevelopmentConfigurationResult,assertNativeRoleMembershipBatchInput,assertWorkflowNativeStageGuard,assertWorkflowNativeStagePolicy,assertWorkflowNativeStageSourceGuard,assertWorkflowOwnedSubjectCreate,assertWorkflowOwnedSubjectCreateResources,canonicalDataBusinessIntent,compileNativeApplicationConfiguration,compileNativeEventAction,compileNativeEventCapturePlansV2,compileRequiredPlatformCapabilitiesV3,compileWorkflowBusinessStepHandlers,createDevelopmentConfigurationManifest,dataOwnedRowLimit,dateEventProjectionEnvelopeSchemaV2,dateEventProjectionFieldsV2,developmentBackendBase64Bytes,developmentBackendInvocationHeadersValid,developmentBackendInvocationRequestValid,developmentBackendInvocationRevision,developmentBackendOperationMatches,developmentConfigurationKey,evaluateWorkflowTaskPageExpression,formatWorkflowCompletionDeadline,formatWorkflowExpression,generatedCrudCapabilityOperations,hasDataAuditReadPolicy,hasNativeParentReadPolicy,isDataAuditMetadataField,isDataOwnedRowLimit,isDataSystemSortField,isDataTransactionActorAuthorityGuard,isDataTransactionRecordSetMatchGuard,isNativeDataQueryOperatorV2,isNativeMultiValueFieldV2,isWorkflowRejectionNotificationSnapshot,matchesDataActorAuthorityMembership,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,nativeUniqueKeysContractVersion,nativeUniqueKeysJsonSchema,normalizeWorkflowOwnedSubjectCreate,parseDataBusinessCommandResolution,parseDataFieldUserCandidates,parseDecimalReservationLifecycle,parseNativeDataFieldsV2,parseNativeDataResourceInvariantsV2,parseNativeParentReadPolicy,parseNativeUniqueKeys,parseWorkflowStepDataResolution,projectDataResourceView,projectNativeDataResourceViewV2,projectWorkflowGraph,projectWorkflowNodePolicy,quoteNativeIdentifierV2,refreshWorkflowTaskPageFacts,requiresAggregateOwnedSubtableCapacity,requiresDateTimeMinutePrecision,requiresDevelopmentBackendCredential,requiresExtendedArtifactCapacity,requiresExtendedConfigurationBytes,requiresExtendedDeclarationCapacity,requiresExtendedFieldCapacity,requiresExtendedOwnedSubtableCapacity,requiresHighDensityArtifactCapacity,requiresOwnedSubtableMinimumRows,requiresUserCandidateLaunchScope,requiresWorkflowRoleInputSelection,requiresWorkflowRoleUnion,resolveNativeParentReadBinding,resolveNativeScopeSourceFieldPathV2,resolveWorkflowUserCandidates,selectWorkflowAssignmentRoutingRules,serializedDataBytes,userCandidateScopeValue,validateAuthenticatedPublicRead,validateDecimalReservationLifecycles,validateManagedConcurrency,validateNativeDataDraftStateV2,validateNativeDataResourceReferencesV2,validateNativeDataResourceSurfaceV2,validateNativeParentReadPolicies,validateUserCandidateReferences,validateWorkflowAdministration,validateWorkflowApprovalEmptyPolicy,validateWorkflowApprovedDelegation,validateWorkflowAssignmentRoutingBindings,validateWorkflowAssignmentRoutingPolicy,validateWorkflowAssignmentRoutingRules,validateWorkflowAutomaticCc,validateWorkflowBusinessStepHandlerContract,validateWorkflowBusinessStepRequest,validateWorkflowBusinessStepResult,validateWorkflowBusinessStepSchema,validateWorkflowBusinessStepSubscriptions,validateWorkflowBusinessSteps,validateWorkflowCommandHandlers,validateWorkflowCompletionDeadlines,validateWorkflowCorrections,validateWorkflowInitiatorApprovalPolicy,validateWorkflowInstanceCommandPolicies,validateWorkflowLaunchPreflight,validateWorkflowNodeConfigurationPatch,validateWorkflowReadability,validateWorkflowRejectionNotification,validateWorkflowRoleInputSelection,validateWorkflowRoleUnion,validateWorkflowTaskPages,validateWorkflowUserCandidateBindings,workflowApprovalCanSkip,workflowApprovedDelegationRequests,workflowAssignmentRoutingFacts,workflowAssignmentRoutingPolicySchema,workflowAssignmentRoutingSemantic,workflowBindingAllowsEmptyUsers,workflowBindingRoleCodes,workflowBusinessCommandInvocationSchema,workflowBusinessStepFactSchema,workflowBusinessStepHandlerDigest,workflowBusinessStepInput,workflowBusinessStepPath,workflowBusinessStepReceiptSignatureSuffix,workflowBusinessStepValueMatches,workflowDelegationMutationRequestSchema,workflowExpressionPaths,workflowInitiatorApprovalCanComplete,workflowInstanceCommandDeadlineError,workflowInstanceTerminateCapabilityAllowed,workflowInstanceWithdrawalReasonRequired,workflowNativeStagePolicySchema,workflowNodeAllowedOperations,workflowOperationCommentRequired,workflowOperationReasonRequired,workflowOwnedSubjectCreateSchema,workflowPolicyTimestamp,workflowRoleCodesSchema,workflowTaskPageFieldState,workflowTaskPageReplayCoversInvalidation,workflowTaskSubtableRows,workflowVariableLabel});