@elyx-code/project-logic-tree 0.0.6936 → 0.0.6937
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +2 -2
- package/dist/index.js +10 -13
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -3,7 +3,7 @@ Please provide a unique 'name' string.`,severity:ve.Error,code:Ce.NameNotUniqueI
|
|
|
3
3
|
Please provide a unique 'name' string.`,severity:ve.Error,code:Ce.NameNotUniqueInScope}))}return i}function xx(s,p){const i=[];s.name||i.push(new we({id:`${s.id}--${Ce.EmptyName}`,message:`Entity with id "${s.id}" and type "${s.type}" has an empty name. Please provide a 'name' string.`,severity:ve.Error,code:Ce.EmptyName}));const r=s.parent&&Ra(s.parent,p)||p;if(!r)i.push(new we({id:`${s.id}--parent-reference--${Te.ReferencedEntityNotFound}`,message:`The entity with id '${s.parent}' that isn't yet found in the project. Perhaps it should be created first. Or perhaps the ID is incorrect.`,severity:ve.Error,code:Te.ReferencedEntityNotFound}));else{const c=_x(r).filter(e=>e.name===s.name);c.length&&i.push(new we({id:`${s.id}--${Ce.NameNotUniqueInScope}`,message:`Entity with id "${s.id}" and type "${s.type}" has a name "${s.name}" that is not unique in its scope or higher scopes. Entity with id "${c[0].id}" has the same name.
|
|
4
4
|
Please provide a unique 'name' string.`,severity:ve.Error,code:Ce.NameNotUniqueInScope}))}return i}function $x(s,p){const i=[];s.name||i.push(new we({id:`${s.id}--${Ce.EmptyName}`,message:`Entity with id "${s.id}" and type "${s.type}" has an empty name. Please provide a 'name' string.`,severity:ve.Error,code:Ce.EmptyName}));const r=te(s.parent);if(!r)i.push(new we({id:`${s.id}--parent-reference--${Te.InvalidReferenceObjectStructure}`,message:`Reference object at 'parent' property for entity with id "${s.id}" and type "${s.type}" is not a valid reference. A reference needs to be a 'id' string of an existing entity in the project.`,severity:ve.Error,code:Te.InvalidReferenceObjectStructure}));else{const a=p.get(r);if(!a)i.push(new we({id:`${s.id}--parent-reference--${Te.ReferencedEntityNotFound}`,message:`The entity with id '${r}' that isn't yet found in the project. Perhaps it should be created first. Or perhaps the ID is incorrect.`,severity:ve.Error,code:Te.ReferencedEntityNotFound}));else{const e=a.properties.filter(f=>f.name===s.name);e.length&&i.push(new we({id:`${s.id}--${Ce.NameNotUniqueInScope}`,message:`Entity with id "${s.id}" and type "${s.type}" has a name "${s.name}" that is not unique among all properties in the parent entity. Entity with id "${e[0].id}" has the same name.
|
|
5
5
|
Please provide a unique 'name' string.`,severity:ve.Error,code:Ce.NameNotUniqueInScope}))}}return i}function Lx(s,p){const i=[];s.name||i.push(new we({id:`${s.id}--${Ce.EmptyName}`,message:`Entity with id "${s.id}" and type "${s.type}" has an empty name. Please provide a 'name' string.`,severity:ve.Error,code:Ce.EmptyName}));const r=te(s.parent);if(!r)i.push(new we({id:`${s.id}--parent-reference--${Te.InvalidReferenceObjectStructure}`,message:`Reference object at 'parent' property for entity with id "${s.id}" and type "${s.type}" is not a valid reference. A reference needs to be a 'id' string of an existing entity in the project.`,severity:ve.Error,code:Te.InvalidReferenceObjectStructure}));else{const a=p.get(r);if(!a)i.push(new we({id:`${s.id}--parent-reference--${Te.ReferencedEntityNotFound}`,message:`The entity with id '${r}' that isn't yet found in the project. Perhaps it should be created first. Or perhaps the ID is incorrect.`,severity:ve.Error,code:Te.ReferencedEntityNotFound}));else{const e=VL(a).filter(f=>f.name===s.name);e.length&&i.push(new we({id:`${s.id}--${Ce.NameNotUniqueInScope}`,message:`Entity with id "${s.id}" and type "${s.type}" has a name "${s.name}" that is not unique among all inputs declared in the parent entity. Entity with id "${e[0].id}" has the same name.
|
|
6
|
-
Please provide a unique 'name' string.`,severity:ve.Error,code:Ce.NameNotUniqueInScope}))}}return i}function zAi(s,p){switch(s.type){case d.DefinitionEntity:return Px(s,p);case d.FunctionDeclaration:return Nx(s,p);case d.VariableDeclaration:return xx(s,p);case d.Property:return $x(s,p);case d.ArgumentDeclaration:return Lx(s,p);default:return[]}}function vp(s,p){var r;const i=s;switch(s.type){case d.FunctionCall:case d.InternalCall:return Ra(s.declaration,p).codeName;case d.ActionDescriptor:case d.DefinitionEntity:case d.VariableDeclaration:case d.ValueDescriptor:case d.FunctionDeclaration:return s.codeName||null;case d.Property:case d.ArgumentDeclaration:{if(s.codeName)return s.codeName;if((r=s.implements)!=null&&r.length){const a=s.implements.find(c=>{const e=Ra(c,p);return!!(e!=null&&e.codeName)});if(a)return Ra(a,p).codeName||null}break}case d.InputMap:case d.OutputMap:case d.VariableInstance:{if(s.declaration){const a=Ra(s.declaration,p);return vp(a,p)||""}break}}return i.codeName||null}function Cp(s,p){let i=s;if(!!p.some(a=>a.name===i)){const a=s.split(" "),c=a.pop()||"",e=parseInt(c);return!isNaN(e)?a.push(`${e+1}`):(a.push(c),a.push("1")),i=a.join(" "),Cp(i,p)}return i}function P_e(s,p){const r=s.project.getDefinitionEntities(new Set([s.id])).filter(a=>a.id!==a.id&&a.name.toLowerCase()===a.name.toLowerCase());if(r.length){const a=Cp(s.name,r);s.metaSync({name:a},p)}}function N_e(s,p,i){const a=`${Ng(s)}-${p}-id`;return i.instances[a]?x.UUID.uuid():a}function N_(s,p){let i="",r=null;if(s.parent){const c=p.get(s.parent);c&&(r=c)}let a="";return r&&(a=`${Ng(oe(r,p))}-`),i=`${a}${Ng(oe(s,p))}-id`,p.instances[i]?x.UUID.uuid():i}function dn(s,p,i="uuid"){return i==="semantic"?N_e(oe(s,p),s.type,p):x.UUID.uuid()}const YAi=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Bx(s){return typeof s=="string"&&YAi.test(s)}const JAi=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function x_(s){return typeof s=="string"&&JAi.test(s)}function QAi(s){return s instanceof Error&&s.name==="ZodError"&&"issues"in s&&Array.isArray(s.issues)}var XAi=class extends Error{constructor(p,i){super(p,i);R(this,"name");R(this,"details");this.name="ZodValidationError",this.details=egi(i)}toString(){return this.message}};function egi(s){if(s){const p=s.cause;if(QAi(p))return p.issues}return[]}function tgi(s){return s.length!==0}function qj(s){return s.description??""}var igi=/[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*/u;function rgi(s){if(s.length===1){let p=s[0];return typeof p=="symbol"&&(p=qj(p)),p.toString()||'""'}return s.reduce((p,i)=>{if(typeof i=="number")return p+"["+i.toString()+"]";if(typeof i=="symbol"&&(i=qj(i)),i.includes('"'))return p+'["'+ngi(i)+'"]';if(!igi.test(i))return p+'["'+i+'"]';const r=p.length===0?"":".";return p+r+i},"")}function ngi(s){return s.replace(/"/g,'\\"')}var agi="; ",sgi=99,x_e="Validation error",lgi=": ",ogi=", or ";function dgi(s={}){const{issueSeparator:p=agi,unionSeparator:i=ogi,prefixSeparator:r=lgi,prefix:a=x_e,includePath:c=!0,maxIssuesInMessage:e=sgi}=s;return f=>{const h=f.slice(0,e).map(m=>dg({issue:m,issueSeparator:p,unionSeparator:i,includePath:c})).join(p);return ugi(h,a,r)}}function dg(s){const{issue:p,issueSeparator:i,unionSeparator:r,includePath:a}=s;if(p.code===ot.invalid_union)return p.unionErrors.reduce((c,e)=>{const f=e.issues.map(h=>dg({issue:h,issueSeparator:i,unionSeparator:r,includePath:a})).join(i);return c.includes(f)||c.push(f),c},[]).join(r);if(p.code===ot.invalid_arguments)return[p.message,...p.argumentsError.issues.map(c=>dg({issue:c,issueSeparator:i,unionSeparator:r,includePath:a}))].join(i);if(p.code===ot.invalid_return_type)return[p.message,...p.returnTypeError.issues.map(c=>dg({issue:c,issueSeparator:i,unionSeparator:r,includePath:a}))].join(i);if(a&&tgi(p.path)){if(p.path.length===1){const c=p.path[0];if(typeof c=="number")return`${p.message} at index ${c}`}return`${p.message} at "${rgi(p.path)}"`}return p.message}function ugi(s,p,i){return p!==null?s.length>0?[p,s].join(i):p:s.length>0?s:x_e}function pgi(s,p={}){const r=cgi(p)([s]);return new XAi(r,{cause:new fd([s])})}function cgi(s){return"messageBuilder"in s?s.messageBuilder:dgi(s)}async function $_e(s,p={}){var c;const i=z.YieldTracker.from(p),r=[...Rn(s),...Xa(s)];await i.tick();const a=qt(s.errors,r);return await((c=s.dataType)==null?void 0:c.validateAsync({tracker:i})),a}function L_e(s){var i;(i=s.dataType)==null||i.validate();const p=[...Rn(s),...Xa(s)];return qt(s.errors,p)}const fgi=Object.freeze(Object.defineProperty({__proto__:null,validate:L_e,validateAsync:$_e},Symbol.toStringTag,{value:"Module"}));function B_e(s){return s.listAdded.forEach(p=>{const i=s.project.get(p.id);(i==null?void 0:i.type)===d.DefinitionEntity&&i.parent.type!==d.DataType&&(s.project.emit(di.EXPLICIT_DEFINITION_ENTITY_ADDED,i,s),oi(i,ge.PERSISTED_ENTITY)?s.project.emit(di.PERSISTED_DEFINITION_ENTITY_ADDED,i,s):oi(i,ge.RELATIONAL_DATABASE)&&s.project.emit(di.RELATIONAL_DATABASE_DEFINITION_ENTITY_ADDED,i,s))}),s.listUpdated.forEach(p=>{const i=s.project.get(p.id);(i==null?void 0:i.type)===d.DefinitionEntity&&i.parent.type!==d.DataType&&(s.project.emit(di.EXPLICIT_DEFINITION_ENTITY_UPDATED,i,s),oi(i,ge.PERSISTED_ENTITY)?s.project.emit(di.PERSISTED_DEFINITION_ENTITY_UPDATED,i,s):oi(i,ge.RELATIONAL_DATABASE)&&s.project.emit(di.RELATIONAL_DATABASE_DEFINITION_ENTITY_UPDATED,i,s))}),s.listRemoved.forEach(p=>{const i=s.project.get(p.id)||s.project.getDeleted(p.id);(i==null?void 0:i.type)===d.DefinitionEntity&&i.parent.type!==d.DataType&&(s.project.emit(di.EXPLICIT_DEFINITION_ENTITY_REMOVED,i,s),oi(i,ge.PERSISTED_ENTITY)?s.project.emit(di.PERSISTED_DEFINITION_ENTITY_REMOVED,i,s):oi(i,ge.RELATIONAL_DATABASE)&&s.project.emit(di.RELATIONAL_DATABASE_DEFINITION_ENTITY_REMOVED,i,s))}),s}async function M_e(s,p={}){const i=z.YieldTracker.from(p),r=[];for(const a of s.listAdded){const c=s.project.get(a.id);(c==null?void 0:c.type)===d.DefinitionEntity&&c.parent.type!==d.DataType&&(r.push(s.project.emitAsync(di.EXPLICIT_DEFINITION_ENTITY_ADDED,c,s)),oi(c,ge.PERSISTED_ENTITY)?r.push(s.project.emitAsync(di.PERSISTED_DEFINITION_ENTITY_ADDED,c,s)):oi(c,ge.RELATIONAL_DATABASE)&&r.push(s.project.emitAsync(di.RELATIONAL_DATABASE_DEFINITION_ENTITY_ADDED,c,s))),await i.tick()}for(const a of s.listUpdated){const c=s.project.get(a.id);(c==null?void 0:c.type)===d.DefinitionEntity&&c.parent.type!==d.DataType&&(r.push(s.project.emitAsync(di.EXPLICIT_DEFINITION_ENTITY_UPDATED,c,s)),oi(c,ge.PERSISTED_ENTITY)?r.push(s.project.emitAsync(di.PERSISTED_DEFINITION_ENTITY_UPDATED,c,s)):oi(c,ge.RELATIONAL_DATABASE)&&r.push(s.project.emitAsync(di.RELATIONAL_DATABASE_DEFINITION_ENTITY_UPDATED,c,s))),await i.tick()}for(const a of s.listRemoved){const c=s.project.get(a.id)||s.project.getDeleted(a.id);(c==null?void 0:c.type)===d.DefinitionEntity&&c.parent.type!==d.DataType&&(r.push(s.project.emitAsync(di.EXPLICIT_DEFINITION_ENTITY_REMOVED,c,s)),oi(c,ge.PERSISTED_ENTITY)?r.push(s.project.emitAsync(di.PERSISTED_DEFINITION_ENTITY_REMOVED,c,s)):oi(c,ge.RELATIONAL_DATABASE)&&r.push(s.project.emitAsync(di.RELATIONAL_DATABASE_DEFINITION_ENTITY_REMOVED,c,s))),await i.tick()}return await Promise.all(r),s}var y1=(s=>(s.Manual="manual",s.Automatic="automatic",s))(y1||{}),W=(s=>(s.Added="added",s.Updated="updated",s.Removed="removed",s.Affected="affected",s))(W||{}),w=(s=>(s.AddSuccessCall="add-success-call",s.AddErrorCall="add-error-call",s.AddCall="add-call",s.SetParent="set-parent",s.SetStandaloneParent="set-standalone-parent",s.AfterAllChildrenInitialized="after-all-children-initialized",s.UpdateWithShallowTransfer="update-with-shallow-transfer",s.UpdateWithGenerationTarget="update-with-generation-target",s.RemoveFromParent="remove-from-parent",s.RemoveEntity="remove-entity",s.RestoreEntity="restore-entity",s.CloneEntity="clone-entity",s.AddInput="add-input",s.RemoveInput="remove-input",s.SetDataType="set-data-type",s.RemoveDataType="remove-data-type",s.SetAdditionalPropertiesDataType="set-additional-properties-data-type",s.RemoveAdditionalPropertiesDataType="remove-additional-properties-data-type",s.SetAllPropertiesImplement="set-all-properties-implement",s.RemoveAllPropertiesImplement="remove-all-properties-implement",s.RemoveValueReader="remove-value-reader",s.AddValueReader="add-value-reader",s.RemoveValueWriter="remove-value-writer",s.SetValueWriter="set-value-writer",s.AddEntryCaller="add-entry-caller",s.AddSuccessCaller="add-success-caller",s.AddErrorCaller="add-error-caller",s.RemoveCall="remove-call",s.RemoveCaller="remove-caller",s.RemoveChildGroup="remove-child-group",s.AddToAndGroup="add-to-and-group",s.AddToOrGroup="add-to-or-group",s.RemoveUnrecognizedInputs="remove-unrecognized-inputs",s.RemoveUnrecognizedOutputs="remove-unrecognized-outputs",s.SyncInputs="sync-inputs",s.SyncOutputs="sync-outputs",s.SetImplements="set-implements",s.SetExtends="set-extends",s.SetExtension="set-extension",s.AddImplementation="add-implementation",s.RemoveImplementation="remove-implementation",s.AddProperty="add-property",s.RemoveProperty="remove-property",s.AddMethod="add-method",s.RemoveMethod="remove-method",s.AddAbstractMethod="add-abstract-method",s.RemoveAbstractMethod="remove-abstract-method",s.SetValueAsTypeSingle="set-value-as-type-single",s.SetValueAsTypeList="set-value-as-type-list",s.SetValueAsType="set-value-as-type",s.RemoveErrorCatching="remove-error-catching",s.RemoveAllErrorCallers="remove-all-error-callers",s.RemoveAllSuccessCallers="remove-all-success-callers",s.RemoveAllCallers="remove-all-callers",s.RemoveAllErrorCalls="remove-all-error-calls",s.SetDataTypeEntityValue="set-data-type-entity-value",s.MergeDataTypes="merge-data-types",s.SetDataTypeForeignKeyRef="set-data-type-foreign-key-ref",s.SetErrorEntity="set-error-entity",s.AddValueAsTypeToList="add-value-as-type-to-list",s.RemoveValueAsTypeFromList="remove-value-as-type-from-list",s.CreateFromGenerationTarget="create-from-generation-target",s.ConnectExternalAccount="connect-external-account",s.ChangeExternalAccountConnectionUsed="change-external-account-connection-used",s.MoveInlineDefToCanvas="move-inline-def-to-canvas",s.CreateDefFromValue="create-def-from-value",s.PrettifyCanvas="prettify-canvas",s.SetPrimitiveDefaultValue="set-primitive-default-value",s.MakeArgRequired="make-argument-required",s.MakeArgNonRequired="make-argument-non-required",s.RecalculateArg="recalculate-arg",s.RenameArg="rename-argument",s.ChangeArgDescription="changed-argument-description",s.RemoveArgBaseImplementation="remove-argument-base-implementation",s.AddArgBaseImplementation="add-argument-base-implementation",s.ChangeArgDataType="change-argument-data-type",s.RecalculateCondition="recalculate-condition",s.ChangeTypeOfCondition="change-type-of-condition",s.RenameDefinition="rename-definition",s.RecalculateDef="recalculate-definition",s.ChangeDefDescription="changed-definition-description",s.RemoveDefBaseImplementation="remove-definition-base-implementation",s.AddDefBaseImplementation="add-definition-base-implementation",s.RemoveDefExtension="remove-definition-extension",s.SetDefExtends="set-definition-extension",s.MakeDefStatic="make-def-static",s.MakeDefNonStatic="make-def-non-static",s.MakeDefAbstract="make-def-abstract",s.MakeDefNonAbstract="make-def-non-abstract",s.RecalculateFuncCall="recalculate-function-call",s.ChangeFuncCallDeclaration="change-function-call-declaration",s.RenameFuncDecl="rename-function-declaration",s.ChangeFuncDeclDescription="changed-function-declaration-description",s.RecalculateFuncDecl="recalculate-function-declaration",s.SetFuncDeclBaseImplementation="set-function-declaration-base-implementation",s.ChangeFuncDeclOutputDataType="change-function-declaration-output-data-type",s.RecalculateGlobalEvent="recalculate-global-event",s.ChangeGlobalEventDescription="changed-global-event-description",s.ChangeGlobalEventType="changed-global-event-type",s.RecalculateInputMap="recalculate-input",s.ChangeInputMapDescription="changed-input-description",s.ChangeInputMapDataType="change-input-data-type",s.RecalculateLoop="recalculate-loop",s.ChangeLoopType="changed-loop-type",s.RecalculateOperation="recalculate-operation",s.ChangeOperationType="changed-operation-type",s.RecalculateOutputMap="recalculate-output",s.ChangeOutputMapDataType="change-output-data-type",s.RecalculateProperty="recalculate-property",s.MakePropertyRequired="make-property-required",s.MakePropertyNonRequired="make-property-non-required",s.MakePropertyConstant="make-property-constant",s.MakePropertyNonConstant="make-property-non-constant",s.MakePropertyUnique="make-property-unique",s.MakePropertyNonUnique="make-property-non-unique",s.MakePropertyStatic="make-property-static",s.MakePropertyNonStatic="make-property-non-static",s.MakePropertyAbstract="make-property-abstract",s.MakePropertyNonAbstract="make-property-non-abstract",s.RenameProperty="rename-property",s.ChangePropertyDescription="changed-property-description",s.RemovePropertyBaseImplementation="remove-property-base-implementation",s.AddPropertyBaseImplementation="add-property-base-implementation",s.ChangePropertyDataType="change-property-data-type",s.RecalculateSearch="recalculate-search",s.RenameSearch="rename-search",s.ChangeSearchDescription="changed-search-description",s.ChangeSearchQuery="changed-search-query",s.MakeValueDescriptorRequired="make-value-descriptor-required",s.MakeSearchInputRequired="make-search-input-required",s.MakeValueDescriptorNonRequired="make-value-descriptor-non-required",s.MakeSearchInputNonRequired="make-search-input-non-required",s.RenameValueDescriptor="rename-value-descriptor",s.RenameSearchInput="rename-search-input",s.ChangeValueDescriptorDescription="changed-value-descriptor-description",s.ChangeSearchInputDescription="changed-search-input-description",s.ChangeValueDescriptorDataType="change-value-descriptor-data-type",s.RecalculateVarDecl="recalculate-variable-declaration",s.MakeVarDeclConstant="make-variable-declaration-constant",s.MakeVarDeclNonConstant="make-variable-declaration-non-constant",s.RenameVarDecl="rename-variable-declaration",s.ChangeVarDeclDescription="changed-variable-declaration-description",s.ChangeVarDeclDataType="change-variable-declaration-data-type",s.RecalculateVarInst="recalculate-variable-instance",s.ChangeVarInstDeclaration="change-variable-instance-declaration",s.HideFuncDeclBody="hide-function-declaration-body",s.ShowFuncDeclBody="show-function-declaration-body",s.HideGlobalEventBody="hide-global-event-body",s.ShowGlobalEventBody="show-global-event-body",s.HideLoopBody="hide-loop-body",s.ShowLoopBody="show-loop-body",s.HideTriggerBody="hide-trigger-body",s.ShowTriggerBody="show-trigger-body",s.AddNestedAndCondition="add-nested-and-condition",s.AddInputToCondition="add-input-to-condition",s.RecalculateNode="recalculate-node",s.AddInputToFuncDecl="add-input-to-function-declaration",s.ChangeInternalCallToThrowErrors="change-internal-call-to-throw-errors",s.ChangeInternalCallToCatchErrors="change-internal-call-to-catch-errors",s.AddErrorOutputToInternalCall="add-error-output-to-internal-call",s.ChangeLoopToThrowErrors="change-loop-to-throw-errors",s.ChangeLoopToCatchErrors="change-loop-to-catch-errors",s.RecalculateLoopBody="recalculate-loop-body",s.RecalculateMethod="recalculate-method",s.AddArgToLoopBody="add-arg-to-loop-body",s.AddArgToMethod="add-arg-to-method",s.RecalculateNestedCondition="recalculate-nested-condition",s.ChangeNodeToThrowErrors="change-node-to-throw-errors",s.ChangeNodeToCatchErrors="change-node-to-catch-errors",s.ChangeOperationToThrowErrors="change-operation-to-throw-errors",s.ChangeOperationToCatchErrors="change-operation-to-catch-errors",s.ChangeFuncCallToThrowErrors="change-function-call-to-throw-errors",s.ChangeFuncCallToCatchErrors="change-function-call-to-catch-errors",s.ChangeSearchToThrowErrors="change-search-to-throw-errors",s.ChangeSearchToCatchErrors="change-search-to-catch-errors",s.ChangeVarDeclToThrowErrors="change-variable-declaration-to-throw-errors",s.ChangeVarDeclToCatchErrors="change-variable-declaration-to-catch-errors",s.ChangeVarInstToThrowErrors="change-variable-instance-to-throw-errors",s.ChangeVarInstToCatchErrors="change-variable-instance-to-catch-errors",s.AddErrorOutputToNode="add-error-output-to-node",s.AddErrorOutputToOperation="add-error-output-to-operation",s.AddErrorOutputToFuncCall="add-error-output-to-function-call",s.AddErrorOutputToSearch="add-error-output-to-search",s.AddErrorOutputToVarDecl="add-error-output-to-variable-declaration",s.AddErrorOutputToVarInst="add-error-output-to-variable-instance",s.AddInputToNode="add-input-to-node",s.AddInputToOperation="add-input-to-operation",s.AddInputToFuncCall="add-input-to-function-call",s.AddInputToSearch="add-input-to-search",s.AddPropertyToVarDecl="add-property-to-variable-declaration",s.AddPropertyToVarInst="add-property-to-variable-instance",s.AddMethodToDef="add-method-to-definition",s.ReSyncRowTransformer="re-sync-row-transformer",s.ManuallyAddRowTransformer="manually-add-row-transformer",s.AddPropertyToDef="add-property-to-definition",s.RestablishExternalAccountConnection="restablish-external-account-connection",s.AddThrownError="add-thrown-error",s.RecalculateTerminationStatement="recalculate-termination-statement",s.RecalculateReturnStmt="recalculate-return-statement",s.RecalculateContinueStmt="recalculate-continue-statement",s.RecalculateBreakStmt="recalculate-break-statement",s.AddPropertyToTerminationStatement="add-property-to-termination-statement",s.AddPropertyToReturnStmt="add-property-to-return-statement",s.AddPropertyToContinueStmt="add-property-to-continue-statement",s.AddPropertyToBreakStmt="add-property-to-break-statement",s.SetLiteralValueToExplicitlyEmpty="set-literal-value-to-explicitly-empty",s.ModifyLiteralValue="modify-literal-value",s.RemoveLiteralValue="remove-literal-value",s.ModifyLiteralValueAsType="modify-literal-value-as-type",s.UpdateProjectMetadata="update-project-metadata",s.RenameProject="rename-project",s.ChangeProjectDescription="change-project-description",s.RestoreNode="restore-node",s.RestoreDef="restore-definition",s.RestoreFuncDecl="restore-function-declaration",s.RestoreGlobalEvent="restore-global-event",s.RestoreSearch="restore-search",s.RestoreVarDecl="restore-variable-declaration",s.RestoreVarInst="restore-variable-instance",s.RestoreFuncCall="restore-function-call",s.RestoreOperation="restore-operation",s.RestoreCondition="restore-condition",s.RestoreReturnStmt="restore-return-statement",s.RestoreContinueStmt="restore-continue-statement",s.RestoreBreakStmt="restore-break-statement",s.RestoreInstalledProject="restore-installed-project",s.RestoreLoop="restore-loop",s.CreateNewDef="create-new-definition",s.CreateNewFuncDecl="create-new-function-declaration",s.CreateNewGlobalEvent="create-new-global-event",s.CreateNewSearch="create-new-search",s.CreateNewVarDecl="create-new-variable-declaration",s.CreateNewVarInst="create-new-variable-instance",s.CreateNewFuncCall="create-new-function-call",s.CreateNewOperation="create-new-operation",s.CreateNewCondition="create-new-condition",s.CreateNewReturnStmt="create-new-return-statement",s.CreateNewContinueStmt="create-new-continue-statement",s.CreateNewBreakStmt="create-new-break-statement",s.CreateNewInternalCall="create-new-internal-call",s.CreateNewLoop="create-new-loop",s.ImplementBuiltInFunctionalityAsDef="implement-built-in-functionality-as-definition",s.ImplementAbstractEntityAsDef="implement-abstract-entity-as-definition",s.ImplementNewHTTPEndpoint="implement-new-http-endpoint",s.ImplementNewScheduledTrigger="implement-new-scheduled-trigger",s.ImplementNewPersistedEntity="implement-new-persisted-entity",s.AddedNewRowTransformer="added-new-row-transformer",s.AddedSQLConnectionConfig="added-sql-connection-config",s.AddedNewSSLConnectionConfig="added-new-ssl-connection-config",s.AddedGoogleConnection="added-google-connection",s.AddedSlackConnection="added-slack-connection",s.AddedNewExternalAccountConnection="added-new-external-account-connection",s.AddedGoogleDriveConnection="added-google-drive-connection",s.AddedGoogleSheetsConnection="added-google-sheets-connection",s.AddedGoogleSlidesConnection="added-google-slides-connection",s.AddedGoogleMailConnection="added-gmail-connection",s.ManuallyCreateIndividualNode="manually-create-individual-node",s.UpdateNode="update-node",s.CreateNewProjectPublicationCompletedEvent="create-new-project-publication-completed-event",s.CreateNewCountedLoop="create-new-counted-loop",s.CreateNewListLoop="create-new-list-loop",s.CreateNewManualFlowLoop="create-new-manual-flow-loop",s.CreateNewObjectKeysLoop="create-new-object-keys-loop",s.CreateNewObjectValuesLoop="create-new-object-values-loop",s.CreateNewStringLoop="create-new-string-loop",s.CreateNewIsFalseCondition="create-new-is-false-condition",s.CreateNewIsTrueCondition="create-new-is-true-condition",s.CreateNewAndCondition="create-new-and-condition",s.CreateNewOrCondition="create-new-or-condition",s.DisconnectNodes="disconnect-nodes",s.DisconnectExecutions="disconnect-executions",s.DisconnectValues="disconnect-values",s.ConnectNodes="connect-nodes",s.ConnectExecution="connect-execution",s.ConnectValues="connect-values",s.ConnectValueToNewInput="connect-value-to-new-input",s.ConnectValueToNewOperationInput="connect-value-to-new-operation-input",s.ConnectValueToNewConditionInput="connect-value-to-new-condition-input",s.ConnectValueToNewSearchInput="connect-value-to-new-search-input",s.ConnectValueToNewVarDeclProperty="connect-value-to-new-variable-declaration-property",s.ConnectValueToNewVarInstProperty="connect-value-to-new-variable-instance-property",s.ConnectValueToNewReturnStmtProperty="connect-value-to-new-return-statement-property",s.ConnectValueToNewContinueStmtProperty="connect-value-to-new-continue-statement-property",s.ConnectValueToNewBreakStmtProperty="connect-value-to-new-break-statement-property",s.ConnectNewFuncDeclArgToValue="connect-new-function-argument-to-value",s.RemoveNodes="remove-nodes",s.RemoveNode="remove-node",s.InitialLoadAutomaticCanvasRefresh="initial-load-automatic-canvas-refresh",s.MoveNodes="move-nodes",s.MoveNode="move-node",s.CloneNodes="clone-nodes",s.CloneNode="clone-node",s.GenerateSQLMigrationOnPersistedEntityUpdate="generate-sql-migration-on-persisted-entity-update",s))(w||{}),Me=(s=>(s.ActionOwnerEntityNotEditable="action-owner-entity-not-editable",s.ActionCounterpartEntityNotEditable="action-counterpart-entity-not-editable",s.ActionOwnerEntityNonDeletable="action-owner-entity-non-deletable",s.GlobalVariableDeclarationCannnotCatchError="global-variable-declaration-cannot-catch-error",s.GlobalVariableDeclarationCannotReadValue="global-variable-declaration-cannot-read-value",s.GlobalVariableDeclarationCannotBeCalled="global-variable-declaration-cannot-be-called",s.GlobalVariableDeclarationCannotCallFromError="global-variable-declaration-cannot-call-from-error",s.ValueReadingOverridesConstantProperty="value-reading-overrides-constant-property",s.DefaultValueOverridesConstantProperty="default-value-overrides-constant-property",s.ValueReadingOverridesConstantVariable="value-reading-overrides-constant-variable",s.DefaultValueOverridesConstantVariable="default-value-overrides-constant-variable",s.CannotSuccessCallItself="cannot-success-call-itself",s.CannotErrorCallItself="cannot-error-call-itself",s.CannotEntryCallItself="cannot-entry-call-itself",s.CannotValueWriteItself="cannot-value-write-itself",s.CannotBeCalledBeforeDeclaration="cannot-be-called-before-declaration",s.CannotBeCalledInParallelBranchToDeclaration="cannot-be-called-in-parallel-branch-to-declaration",s.CannotBeHigherScopeThanDeclaration="cannot-be-higher-scope-than-declaration",s.InputsInGlobalVariableDeclarationsCannotReadValues="inputs-in-global-variable-declarations-cannot-read-values",s))(Me||{});class G_e{constructor({id:p,action:i,errorReason:r,owner:a,counterpart:c,rootAction:e},f){R(this,"id");R(this,"action");R(this,"errorReason");R(this,"owner",null);R(this,"counterpart",null);R(this,"rootAction",!1);R(this,"parent");this.id=p,this.action=i,this.errorReason=r||null,this.owner=a||null,this.counterpart=c||null,this.rootAction=e||!1,this.parent=f}}class S extends z.Events{constructor(i,r,a,c,e=!1,f=""){super(f?f+"-cs-events":"anonymous-cs-events");R(this,"id",x.UUID.uuid());R(this,"seenEntities",[]);R(this,"added",{});R(this,"updated",{});R(this,"removed",{});R(this,"affected",{});R(this,"self",null);R(this,"author");R(this,"timestamp");R(this,"open",!0);R(this,"startedClose",!1);R(this,"dirty",!0);R(this,"submitting",!1);R(this,"lockedVersions",!1);R(this,"type","manual");R(this,"autoclose",!1);R(this,"actionName","");R(this,"project");R(this,"events",new Map);R(this,"ignoreNonEditable",!1);R(this,"ignoreNonDeletable",!1);R(this,"logger");if(this.project=i,this.author=r||x.sessionAuthor||"",this.timestamp=a,this.self=c,this.autoclose=e,this.actionName=f,this.logger=z.Logger.module("cs:"+(this.actionName?this.actionName+":":"")+this.id),this.autoclose&&!this.actionName)throw new Error("Auto-close change-set must have an auto-close action name.")}get index(){const i=this.project.history.indexOf(this);return i===-1?null:i}get isEmpty(){return Object.keys(this.added).length===0&&Object.keys(this.updated).length===0&&Object.keys(this.removed).length===0}get isValid(){var i;return!(this.isEmpty&&this.self&&!this.affected[(i=this.self)==null?void 0:i.id])}get list(){return[...Object.values(this.added),...Object.values(this.updated),...Object.values(this.removed)]}get listAdded(){return Object.values(this.added)}get listUpdated(){return Object.values(this.updated)}get listRemoved(){return Object.values(this.removed)}get listAffected(){return Object.values(this.affected)}get addedIds(){return Object.keys(this.added)}get updatedIds(){return Object.keys(this.updated)}get removedIds(){return Object.keys(this.removed)}get affectedIds(){return Object.keys(this.affected)}event(i){this.logger.log(`ChangeSet Event: ${i.action} (${i.id})`);const r=new G_e(i,this);this.events.set(i.id,r),this.emit("change-set-event",r)}discardOrphans(){this.added[this.project.id]&&(this.updatedIds.forEach(e=>{const f=this.updated[e];this.added[e]=f,delete this.updated[e]}),this.removedIds.forEach(e=>{this.remove(e)}));const i=[...this.addedIds,...this.updatedIds],a=this.project.toFlatIds().filter(e=>!this.project.diggestedBuiltInBaseEntitiesIds.has(e));if(i.filter(e=>!a.includes(e)).forEach(e=>{const f=this.get(e);this.logger.warn(`[discardOrphans] Entity ${f==null?void 0:f.type} with id "${e}" present in change-set but not in project. Removing from change-set.`),this.remove(e)}),this.added[this.project.id]){const e=[...this.addedIds,...this.updatedIds];this.project.toFlatIds().filter(E=>!this.project.diggestedBuiltInBaseEntitiesIds.has(E)).filter(E=>!e.includes(E)).forEach(E=>{const b=this.project.get(E);this.add(b,"added")})}}async discardOrphansAsync(i={}){const r=z.YieldTracker.from(i),a=this.project.toFlatIds();if(this.added[this.project.id]){for(const h of this.updatedIds){const m=this.updated[h];this.added[h]=m,delete this.updated[h],await r.tick()}for(const h of this.removedIds)this.remove(h),await r.tick()}const c=[...this.addedIds,...this.updatedIds],e=a.filter(h=>!this.project.diggestedBuiltInBaseEntitiesIds.has(h)),f=c.filter(h=>!e.includes(h));for(const h of f){const m=this.get(h);this.logger.warn(`[discardOrphansAsync] Entity ${m==null?void 0:m.type} with id "${h}" present in change-set but not in project. Removing from change-set.`),this.remove(h),await r.tick()}if(this.added[this.project.id]){const h=[...this.addedIds,...this.updatedIds],E=a.filter(b=>!this.project.diggestedBuiltInBaseEntitiesIds.has(b)).filter(b=>!h.includes(b));for(const b of E){const A=this.project.get(b);this.add(A,"added"),await r.tick()}}}captureAllChangesInVersionInstances(){[...this.addedIds,...this.updatedIds].forEach(r=>{const a=this.project.get(r);if(!a){const e=this.added[r],f=this.updated[r],h=e||f;throw new Error(`Entity ${(h==null?void 0:h.type)||"of unknown type"} with id "${r}" was ${e?"added":"updated"} but isn't found in the project state when capturing version for change-set.`)}const c=this.get(r);a.version===c.version&&a.captureVersion()}),this.removedIds.forEach(r=>{const a=this.project.getDeleted(r);if(!a){const e=this.removed[r];throw new Error(`Entity ${(e==null?void 0:e.type)||"of unknown type"} with id "${r}" was removed but isn't found in the project state when capturing version for change-set.`)}const c=this.get(r);a.version===c.version&&a.captureVersion()})}async captureAllChangesInVersionInstancesAsync(i={}){const r=z.YieldTracker.from(i),a=[...this.addedIds,...this.updatedIds];for(const c of a){const e=this.project.get(c);if(!e){const h=this.added[c],m=this.updated[c],E=h||m;throw new Error(`Entity ${(E==null?void 0:E.type)||"of unknown type"} with id "${c}" was ${h?"added":"updated"} but isn't found in the project state when capturing version for change-set.`)}const f=this.get(c);e.version===f.version&&e.captureVersion(),await r.tick()}for(const c of this.removedIds){const e=this.project.getDeleted(c);if(!e){const h=this.removed[c];throw new Error(`Entity ${(h==null?void 0:h.type)||"of unknown type"} with id "${c}" was removed but isn't found in the project state when capturing version for change-set.`)}const f=this.get(c);e.version===f.version&&e.captureVersion(),await r.tick()}}async attemptAutocloseAsync(i,r){var a;return this.autoclose&&this.actionName&&this.actionName===i&&(this.self&&r===((a=this.self)==null?void 0:a.id)||!this.self)&&await this.closeAsync(),this}async closeAsync(i={}){const r=z.YieldTracker.from(i),a={persistType:"sequential",...i};if(!this.open||this.startedClose)return this.logger.warn(`Change-set (${this.id}) is already closed or in the process of closing.`),this;const c=i.awaitBeforeClose??!0,e=i.awaitExternalPersist??!0;return this.startedClose||(this.startedClose=!0,c?await this.beforeCloseAsync({tracker:r}):this.beforeCloseAsync({tracker:r})),!this.isValid&&this.self&&!this.added[this.self.id]&&!this.updated[this.self.id]&&this.removed[this.self.id],await this.discardOrphansAsync({tracker:r}),await this.sanitizeAsync({tracker:r}),await this.recursiveCaptureUpstreamVersionsAsync({tracker:r}),this.lockedVersions||(await this.captureAllChangesInVersionInstancesAsync({tracker:r}),await this.recursiveCaptureUpstreamVersionsAsync({tracker:r})),this.open=!1,this.isEmpty?(this.logger.warn(`[ChangeSet.closeAsync] Empty change-set (${this.id}) discarded upon closing.`),this.dirty=!1,this.project.discardChangeSet(this),this.logger.log("[ChangeSet.closeAsync] Closing pending change-sets..."),this.project.closePersistChangeSetsSequentially(),this):(this.project.emit(di.CHANGE_SET_CLOSED_BEFORE_PERSIST,this),e?a.persistType==="parallel"?await this.project.persistChangeSetInParallel(this):await this.project.persistChangeSetSequentially(this):a.persistType==="parallel"?this.project.persistChangeSetInParallel(this):this.project.persistChangeSetSequentially(this),this.destroy(),this)}attemptAutoclose(i,r){var a;return this.autoclose&&this.actionName&&this.actionName===i&&(this.self&&r===((a=this.self)==null?void 0:a.id)||!this.self)&&this.close(),this}recursiveCaptureUpstreamVersions(){if(this.lockedVersions)return;[...this.addedIds,...this.updatedIds,...this.removedIds].forEach(r=>{const a=this.get(r),{added:c,updated:e,removed:f,affected:h}=a.recursiveCaptureUpstreamVersions(this.timestamp);for(const m of c)this.add(m,"added");for(const m of e)this.add(m,"updated");for(const m of f)this.add(m,"removed");for(const m of h)this.add(m,"affected")})}async recursiveCaptureUpstreamVersionsAsync(i={}){if(this.lockedVersions)return;const r=z.YieldTracker.from(i),a=[...this.addedIds,...this.updatedIds,...this.removedIds];for await(const c of a){const e=this.get(c),{added:f,updated:h,removed:m,affected:E}=e.recursiveCaptureUpstreamVersions(this.timestamp);for(const b of f)this.add(b,"added");for(const b of h)this.add(b,"updated");for(const b of m)this.add(b,"removed");for(const b of E)this.add(b,"affected");await r.tick()}}sanitize(){this.listAdded.forEach(i=>{i.previousVersion=null})}async sanitizeAsync(i={}){const r=z.YieldTracker.from(i);for(const a of this.listAdded)a.previousVersion=null,await r.tick()}syncDependents(){return[...this.list,...this.listAffected].forEach(i=>{const r=this.project.get(i.id);!r||r.deleted||Ig(r,this.project)||r==null||r.syncDependents(this)}),this}async syncDependentsAsync(i={}){const r=z.YieldTracker.from(i);for(const a of[...this.list,...this.listAffected]){const c=this.project.get(a.id);!c||c.deleted||Ig(c,this.project)||(c==null||c.syncDependents(this),await r.tick())}return this}async beforeCloseAsync(i={}){const r=z.YieldTracker.from(i);await this.project.emitAsync(di.BEFORE_CHANGE_SET_CLOSE_BEFORE_SIDE_EFFECTS,this),await this.syncDependentsAsync({tracker:r}),await this.emitAsyncProjectSideEffects({tracker:r}),await this.project.emitAsync(di.BEFORE_CHANGE_SET_CLOSE_AFTER_SIDE_EFFECTS,this),this.teardown()}beforeClose(){this.project.emit(di.BEFORE_CHANGE_SET_CLOSE_BEFORE_SIDE_EFFECTS,this),this.syncDependents(),this.emitProjectSideEffects(),this.project.emit(di.BEFORE_CHANGE_SET_CLOSE_AFTER_SIDE_EFFECTS,this),this.teardown()}teardown(){this.destroy()}emitProjectSideEffects(){return B_e(this)}async emitAsyncProjectSideEffects(i={}){return M_e(this,i)}close(i={}){const r={persistType:"sequential",...i};if(!this.open||this.startedClose)return this.logger.warn(`Change-set (${this.id}) is already closed or in the process of closing.`),this;if(this.startedClose||(this.startedClose=!0,this.beforeClose()),!this.isValid&&this.self&&!this.added[this.self.id]&&!this.updated[this.self.id]&&this.removed[this.self.id],this.discardOrphans(),this.sanitize(),this.captureAllChangesInVersionInstances(),this.lockedVersions||(this.recursiveCaptureUpstreamVersions(),this.captureAllChangesInVersionInstances()),this.open=!1,this.isEmpty)return this.logger.warn(`[ChangeSet.close] Empty change-set (${this.id}) discarded upon closing.`),this.project.discardChangeSet(this),this.logger.log("[ChangeSet.close] Closing pending change-sets..."),this.project.closePersistChangeSetsSequentially(),this;if(this.added[this.project.id]&&this.updatedIds.length)throw new Error("No 'updated' entities should be present in the change-set when the project entity is in the 'added' list. New projects can only have newly added entities");if(this.added[this.project.id]&&this.removedIds.length)throw new Error("No 'removed' entities should be present in the change-set when the project entity is in the 'added' list. New projects can only have newly added entities");if(!this.updated[this.project.id]&&!this.added[this.project.id])throw new Error("Change-set must also have the project entity as 'updated' or 'added'. All changes must propagate upstream until the root project entity.");return this.project.emit(di.CHANGE_SET_CLOSED_BEFORE_PERSIST,this),r.persistType==="parallel"?this.project.persistChangeSetInParallel(this):this.project.persistChangeSetSequentially(this),this.destroy(),this}addDependentsToAffected(i){Object.values(i.detachedDependents).forEach(r=>{const{entity:a,field:c}=r;this.has(a.id)||this.add(a,"affected")})}get(i){return this.added[i]?this.added[i]:this.updated[i]?this.updated[i]:this.removed[i]?this.removed[i]:null}remove(i){return this.has(i)&&(delete this.added[i],delete this.updated[i],delete this.removed[i],delete this.affected[i],this.seenEntities=this.seenEntities.filter(r=>r!==i)),this}add(i,r,a={preventRecursion:!1}){var e,f,h,m;if(!this.open||!this.dirty)return this;if(Ig(i,this.project))return this;if(this.seenEntities.indexOf(i.id)===-1&&this.seenEntities.push(i.id),r==="removed"){if(this.added[i.id])return delete this.added[i.id],delete this.affected[i.id],delete this.updated[i.id],this.seenEntities=this.seenEntities.filter(b=>b!==i.id),delete this.project.deletedInstances[i.id],this;if(this.updated[i.id]&&delete this.updated[i.id],this.affected[i.id]&&delete this.affected[i.id],!this.hasRemoved(i.id)&&!this.lockedVersions&&(i.increaseVersion(this.timestamp),!a.preventRecursion)){const{added:b,updated:A,removed:_,affected:P}=i.recursiveCaptureUpstreamVersions(this.timestamp);for(const V of b)this.add(V,"added");for(const V of A)this.add(V,"updated");for(const V of _)this.add(V,"removed");for(const V of P)this.add(V,"affected")}i.captureVersion();const E=(e=i.knownVersions)==null?void 0:e.get(i.version);if(!E)throw Error(`Version ${i.version} should have a cached version instance but it wasn't found when adding entity to change-set`);return this.removed[i.id]=E,this}if(r==="added"){if(this.removed[i.id])return this;if(this.updated[i.id]&&delete this.updated[i.id],this.affected[i.id]&&delete this.affected[i.id],!this.hasAdded(i.id)&&!this.lockedVersions&&!a.preventRecursion){const{added:b,updated:A,removed:_,affected:P}=i.recursiveCaptureUpstreamVersions(this.timestamp);for(const V of b)this.add(V,"added");for(const V of A)this.add(V,"updated");for(const V of _)this.add(V,"removed");for(const V of P)this.add(V,"affected")}i.previousVersion=null,i.captureVersion();const E=(f=i.knownVersions)==null?void 0:f.get(i.version);if(!E)throw Error(`Version ${i.version} should have a cached version instance but it wasn't found when adding entity to change-set`);return this.added[i.id]=E,delete this.affected[i.id],this.addDependentsToAffected(i),this}if(r==="updated"){if(this.removed[i.id])return this;if(this.added[i.id])return i.captureVersion(),this.addDependentsToAffected(i),this;if(this.affected[i.id]&&delete this.affected[i.id],!this.hasUpdated(i.id)&&!this.lockedVersions&&(i.increaseVersion(this.timestamp),!a.preventRecursion)){const{added:b,updated:A,removed:_,affected:P}=i.recursiveCaptureUpstreamVersions(this.timestamp);for(const V of b)this.add(V,"added");for(const V of A)this.add(V,"updated");for(const V of _)this.add(V,"removed");for(const V of P)this.add(V,"affected")}i.activeVersion=!0,i.captureVersion();const E=(h=i.knownVersions)==null?void 0:h.get(i.version);if(!E)throw Error(`Version ${i.version} should have a cached version instance but it wasn't found when adding entity to change-set`);return this.updated[i.id]=E,this.addDependentsToAffected(i),this}if(r==="affected"){if(this.removed[i.id])return this;if(this.added[i.id])return this;if(this.updated[i.id])return this;if(this.affected[i.id]=i,!this.lockedVersions){const E=i.version+"--"+this.id,b=((m=i.knownVersions)==null?void 0:m.get(E))||i.snapshot();i.apply(b),i.knownVersions=i.knownVersions?i.knownVersions.set(E,b):new Map().set(E,b)}}return this}toJSON(){var f;const i={},r={},a={},c=new Set;for(const h of Object.values(this.added))i[h.id]=h.toShallowJSON();for(const h of Object.values(this.updated))r[h.id]=h.toShallowJSON();for(const h of Object.values(this.removed))a[h.id]=h.toShallowJSON();for(const h of Object.values(this.affected))c.add(h.id);const e=this.get(((f=this.self)==null?void 0:f.id)||"");return{added:i,updated:r,removed:a,affected:Array.from(c),self:e?e.toShallowJSON():null,seenEntities:this.seenEntities,actionName:this.actionName}}has(i){return!!this.added[i]||!!this.removed[i]||!!this.updated[i]||!!this.affected[i]}hasAdded(i){return!!this.added[i]}hasUpdated(i){return!!this.updated[i]}hasRemoved(i){return!!this.removed[i]}hasAffected(i){return!!this.affected[i]}}function ygi(s){return new Set([...Object.keys(s.added),...Object.keys(s.updated),...Object.keys(s.removed),...Array.from(s.affected)])}function $_(s,p,i){var f;const r=new Date().toISOString(),a=new S(i,x.sessionAuthor,r,i);if(a.lockedVersions=!0,s===p)throw z.Logger.error("From: ",s),z.Logger.error("To: ",p),new Error("Cannot generate transitional change set between the same two versions or change-sets");let c;if(s==="initial"?c=!0:p==="initial"?c=!1:B(s.timestamp).isBefore(B(p.timestamp))?c=!0:c=!1,z.Logger.log("Transitioning from ",s==="initial"?"initial":s.index),z.Logger.log("Transitioning to ",p==="initial"?"initial":p.index),z.Logger.log("Is forward: ",c),c){const h=p,m=h.index,E=s==="initial"?0:s.index;z.Logger.log("ownIndex: ",m),z.Logger.log("startIndex: ",E),z.Logger.log("CH ID: ",h.id);const b=m===E?[i.history[m]]:i.history.slice(E+1,m+1);if(b.sort((A,_)=>B(A.timestamp).isAfter(B(_.timestamp))?1:-1),!b.length)throw new Error("No change sets in the history between the history indexes provided");z.Logger.log("REDO change-set: ",b[0].id," ",b[0].timestamp),b.forEach(A=>{L_(A,_=>{const P=i.instances[_.id]||i.deletedInstances[_.id];let V="";try{V=oe(_,i)}catch{}if(!P)throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" doesn't have an 'activeVersion' set.`);if(!P.knownVersions)throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" has an active version instance missing the 'knownVersions' property value.`);if(!P.knownVersions.get(_.version))throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" has an active version instance missing the 'knownVersions' property value for version "${_.version}".`);P.restoreVersion(_.version),P.addSelfToProject(a),a.timestamp=P.createdAt,a.add(P,W.Added,{preventRecursion:!0})},_=>{const P=i.instances[_.id]||i.deletedInstances[_.id];let V="";try{V=oe(_,i)}catch{}if(!P)throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" doesn't have an 'activeVersion' set.`);if(!P.knownVersions)throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" has an active version instance missing the 'knownVersions' property value.`);if(!P.knownVersions.get(_.version))throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" has an active version instance missing the 'knownVersions' property value for version "${_.version}".`);P.restoreVersion(_.version),a.timestamp=P.createdAt,a.add(P,W.Updated,{preventRecursion:!0})},_=>{var G;const P=i.instances[_.id]||i.deletedInstances[_.id];let V="";try{V=oe(_,i)}catch{}if(!P)throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" doesn't have an 'activeVersion' set.`);if(!P.knownVersions)throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" has an active version instance missing the 'knownVersions' property value.`);if(!P.knownVersions.get(_.version))throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" has an active version instance missing the 'knownVersions' property value for version "${_.version}".`);P.restoreVersion(_.version),(G=P.removeFromParent)==null||G.call(P,a),P.unsubscribe(),P.unsubscribeFromDependencies(),i.subscribeDeletedInstance(P),a.timestamp=P.createdAt,a.add(P,W.Removed,{preventRecursion:!0})},_=>{const P=i.instances[_.id]||i.deletedInstances[_.id];let V="";try{V=oe(_,i)}catch{}if(!P)throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" doesn't have an 'activeVersion' set.`);if(!P.knownVersions)throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" has an active version instance missing the 'knownVersions' property value.`);if(!P.knownVersions.get(_.version))throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" has an active version instance missing the 'knownVersions' property value for version "${_.version}".`);const G=_.version+"--"+A.id;P.restoreVersion(G),a.timestamp=P.createdAt,a.add(P,W.Updated,{preventRecursion:!0})})})}else{const h=s,m=h.index,E=p==="initial"?0:p.index;z.Logger.log("CH ID: ",h.id);const b=m===E?[i.history[m]]:i.history.slice(E+1,m+1);if(b.sort((A,_)=>B(_.timestamp).isAfter(B(A.timestamp))?1:-1),!b.length)throw new Error("No change sets in the history between the history indexes provided");z.Logger.log("UNDO change-set: ",b[0].id," ",b[0].timestamp),b.forEach(A=>{L_(A,_=>{var G;const P=i.instances[_.id]||i.deletedInstances[_.id];let V="";try{V=oe(_,i)}catch{}if(!P)throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" doesn't have an 'activeVersion' set.`);if(!P.knownVersions)throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" has an active version instance missing the 'knownVersions' property value.`);if(!P.knownVersions.get(_.version))throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" has an active version instance missing the 'knownVersions' property value for version "${_.version}".`);_.previousVersion&&(P.restoreVersion(_.previousVersion),(G=P.removeFromParent)==null||G.call(P,a),P.unsubscribe(),P.unsubscribeFromDependencies(),i.subscribeDeletedInstance(P)),a.timestamp=P.createdAt,a.add(P,W.Removed,{preventRecursion:!0})},_=>{const P=i.instances[_.id]||i.deletedInstances[_.id];let V="";try{V=oe(_,i)}catch{}if(!P)throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" doesn't have an 'activeVersion' set.`);if(!P.knownVersions)throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" has an active version instance missing the 'knownVersions' property value.`);if(!P.knownVersions.get(_.version))throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" has an active version instance missing the 'knownVersions' property value for version "${_.version}".`);P.restoreVersion(_.previousVersion),a.timestamp=P.createdAt,a.add(P,W.Updated,{preventRecursion:!0})},_=>{const P=i.instances[_.id]||i.deletedInstances[_.id];let V="";try{V=oe(_,i)}catch{}if(!P)throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" doesn't have an 'activeVersion' set.`);if(!P.knownVersions)throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" has an active version instance missing the 'knownVersions' property value.`);if(!P.knownVersions.get(_.version))throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" has an active version instance missing the 'knownVersions' property value for version "${_.version}".`);P.restoreVersion(_.previousVersion),P.addSelfToProject(a),a.timestamp=P.createdAt,a.add(P,W.Added,{preventRecursion:!0})},_=>{const P=i.instances[_.id]||i.deletedInstances[_.id];let V="";try{V=oe(_,i)}catch{}if(!P)throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" doesn't have an 'activeVersion' set.`);if(!P.knownVersions)throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" has an active version instance missing the 'knownVersions' property value.`);if(!P.knownVersions.get(_.version))throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" has an active version instance missing the 'knownVersions' property value for version "${_.version}".`);P.restoreVersion(P.version),a.timestamp=P.createdAt,a.add(P,W.Affected,{preventRecursion:!0})})})}let e;if(p==="initial"){const h=Array.from(((f=i.knownVersions)==null?void 0:f.values())||[]).reduce((m,E)=>!m||B(E.createdAt).isBefore(B(m.createdAt))?E:m,null);if(!h)throw new Error("No oldest version found");e=h.createdAt}else e=p.timestamp;return a.open=!1,{transitionalChangeSet:a,transitionTime:r,timeOfOriginalTargetChanges:e}}function L_(s,p,i,r,a){var h;if(!(s!=null&&s.self))throw new Error("Change set must have a valid `self` entity state to be traversed");const c=((h=s.self)==null?void 0:h.type)===d.Project?s.self:s.self.project,e=new Fn(s.self,{allBuiltInEntityIds:c.diggestedBuiltInBaseEntitiesIds});z.Logger.log("changeSet.added: ",Object.keys(s.added).length),z.Logger.log("changeSet.updated: ",Object.keys(s.updated).length),z.Logger.log("changeSet.removed: ",Object.keys(s.removed).length);const f={...s.added,...s.updated,...s.removed,...s.affected};e.order=Object.keys(f),e.flatRecord=f,e.orderEntities(),z.Logger.log("All entities: ",e.order.map((m,E)=>`${E+1}: ${f[m].type} - ${m}`).join(`,
|
|
6
|
+
Please provide a unique 'name' string.`,severity:ve.Error,code:Ce.NameNotUniqueInScope}))}}return i}function zAi(s,p){switch(s.type){case d.DefinitionEntity:return Px(s,p);case d.FunctionDeclaration:return Nx(s,p);case d.VariableDeclaration:return xx(s,p);case d.Property:return $x(s,p);case d.ArgumentDeclaration:return Lx(s,p);default:return[]}}function vp(s,p){var r;const i=s;switch(s.type){case d.FunctionCall:case d.InternalCall:return Ra(s.declaration,p).codeName;case d.ActionDescriptor:case d.DefinitionEntity:case d.VariableDeclaration:case d.ValueDescriptor:case d.FunctionDeclaration:return s.codeName||null;case d.Property:case d.ArgumentDeclaration:{if(s.codeName)return s.codeName;if((r=s.implements)!=null&&r.length){const a=s.implements.find(c=>{const e=Ra(c,p);return!!(e!=null&&e.codeName)});if(a)return Ra(a,p).codeName||null}break}case d.InputMap:case d.OutputMap:case d.VariableInstance:{if(s.declaration){const a=Ra(s.declaration,p);return vp(a,p)||""}break}}return i.codeName||null}function Cp(s,p){let i=s;if(!!p.some(a=>a.name===i)){const a=s.split(" "),c=a.pop()||"",e=parseInt(c);return!isNaN(e)?a.push(`${e+1}`):(a.push(c),a.push("1")),i=a.join(" "),Cp(i,p)}return i}function P_e(s,p){const r=s.project.getDefinitionEntities(new Set([s.id])).filter(a=>a.id!==s.id&&a.name.toLowerCase()===s.name.toLowerCase());if(r.length){const a=Cp(s.name,r);s.metaSync({name:a},p)}}function N_e(s,p,i){const a=`${Ng(s)}-${p}-id`;return i.instances[a]?x.UUID.uuid():a}function N_(s,p){let i="",r=null;if(s.parent){const c=p.get(s.parent);c&&(r=c)}let a="";return r&&(a=`${Ng(oe(r,p))}-`),i=`${a}${Ng(oe(s,p))}-id`,p.instances[i]?x.UUID.uuid():i}function dn(s,p,i="uuid"){return i==="semantic"?N_e(oe(s,p),s.type,p):x.UUID.uuid()}const YAi=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Bx(s){return typeof s=="string"&&YAi.test(s)}const JAi=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function x_(s){return typeof s=="string"&&JAi.test(s)}function QAi(s){return s instanceof Error&&s.name==="ZodError"&&"issues"in s&&Array.isArray(s.issues)}var XAi=class extends Error{constructor(p,i){super(p,i);R(this,"name");R(this,"details");this.name="ZodValidationError",this.details=egi(i)}toString(){return this.message}};function egi(s){if(s){const p=s.cause;if(QAi(p))return p.issues}return[]}function tgi(s){return s.length!==0}function qj(s){return s.description??""}var igi=/[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*/u;function rgi(s){if(s.length===1){let p=s[0];return typeof p=="symbol"&&(p=qj(p)),p.toString()||'""'}return s.reduce((p,i)=>{if(typeof i=="number")return p+"["+i.toString()+"]";if(typeof i=="symbol"&&(i=qj(i)),i.includes('"'))return p+'["'+ngi(i)+'"]';if(!igi.test(i))return p+'["'+i+'"]';const r=p.length===0?"":".";return p+r+i},"")}function ngi(s){return s.replace(/"/g,'\\"')}var agi="; ",sgi=99,x_e="Validation error",lgi=": ",ogi=", or ";function dgi(s={}){const{issueSeparator:p=agi,unionSeparator:i=ogi,prefixSeparator:r=lgi,prefix:a=x_e,includePath:c=!0,maxIssuesInMessage:e=sgi}=s;return f=>{const h=f.slice(0,e).map(m=>dg({issue:m,issueSeparator:p,unionSeparator:i,includePath:c})).join(p);return ugi(h,a,r)}}function dg(s){const{issue:p,issueSeparator:i,unionSeparator:r,includePath:a}=s;if(p.code===ot.invalid_union)return p.unionErrors.reduce((c,e)=>{const f=e.issues.map(h=>dg({issue:h,issueSeparator:i,unionSeparator:r,includePath:a})).join(i);return c.includes(f)||c.push(f),c},[]).join(r);if(p.code===ot.invalid_arguments)return[p.message,...p.argumentsError.issues.map(c=>dg({issue:c,issueSeparator:i,unionSeparator:r,includePath:a}))].join(i);if(p.code===ot.invalid_return_type)return[p.message,...p.returnTypeError.issues.map(c=>dg({issue:c,issueSeparator:i,unionSeparator:r,includePath:a}))].join(i);if(a&&tgi(p.path)){if(p.path.length===1){const c=p.path[0];if(typeof c=="number")return`${p.message} at index ${c}`}return`${p.message} at "${rgi(p.path)}"`}return p.message}function ugi(s,p,i){return p!==null?s.length>0?[p,s].join(i):p:s.length>0?s:x_e}function pgi(s,p={}){const r=cgi(p)([s]);return new XAi(r,{cause:new fd([s])})}function cgi(s){return"messageBuilder"in s?s.messageBuilder:dgi(s)}async function $_e(s,p={}){var c;const i=z.YieldTracker.from(p),r=[...Rn(s),...Xa(s)];await i.tick();const a=qt(s.errors,r);return await((c=s.dataType)==null?void 0:c.validateAsync({tracker:i})),a}function L_e(s){var i;(i=s.dataType)==null||i.validate();const p=[...Rn(s),...Xa(s)];return qt(s.errors,p)}const fgi=Object.freeze(Object.defineProperty({__proto__:null,validate:L_e,validateAsync:$_e},Symbol.toStringTag,{value:"Module"}));function B_e(s){return s.listAdded.forEach(p=>{const i=s.project.get(p.id);(i==null?void 0:i.type)===d.DefinitionEntity&&i.parent.type!==d.DataType&&(s.project.emit(di.EXPLICIT_DEFINITION_ENTITY_ADDED,i,s),oi(i,ge.PERSISTED_ENTITY)?s.project.emit(di.PERSISTED_DEFINITION_ENTITY_ADDED,i,s):oi(i,ge.RELATIONAL_DATABASE)&&s.project.emit(di.RELATIONAL_DATABASE_DEFINITION_ENTITY_ADDED,i,s))}),s.listUpdated.forEach(p=>{const i=s.project.get(p.id);(i==null?void 0:i.type)===d.DefinitionEntity&&i.parent.type!==d.DataType&&(s.project.emit(di.EXPLICIT_DEFINITION_ENTITY_UPDATED,i,s),oi(i,ge.PERSISTED_ENTITY)?s.project.emit(di.PERSISTED_DEFINITION_ENTITY_UPDATED,i,s):oi(i,ge.RELATIONAL_DATABASE)&&s.project.emit(di.RELATIONAL_DATABASE_DEFINITION_ENTITY_UPDATED,i,s))}),s.listRemoved.forEach(p=>{const i=s.project.get(p.id)||s.project.getDeleted(p.id);(i==null?void 0:i.type)===d.DefinitionEntity&&i.parent.type!==d.DataType&&(s.project.emit(di.EXPLICIT_DEFINITION_ENTITY_REMOVED,i,s),oi(i,ge.PERSISTED_ENTITY)?s.project.emit(di.PERSISTED_DEFINITION_ENTITY_REMOVED,i,s):oi(i,ge.RELATIONAL_DATABASE)&&s.project.emit(di.RELATIONAL_DATABASE_DEFINITION_ENTITY_REMOVED,i,s))}),s}async function M_e(s,p={}){const i=z.YieldTracker.from(p),r=[];for(const a of s.listAdded){const c=s.project.get(a.id);(c==null?void 0:c.type)===d.DefinitionEntity&&c.parent.type!==d.DataType&&(r.push(s.project.emitAsync(di.EXPLICIT_DEFINITION_ENTITY_ADDED,c,s)),oi(c,ge.PERSISTED_ENTITY)?r.push(s.project.emitAsync(di.PERSISTED_DEFINITION_ENTITY_ADDED,c,s)):oi(c,ge.RELATIONAL_DATABASE)&&r.push(s.project.emitAsync(di.RELATIONAL_DATABASE_DEFINITION_ENTITY_ADDED,c,s))),await i.tick()}for(const a of s.listUpdated){const c=s.project.get(a.id);(c==null?void 0:c.type)===d.DefinitionEntity&&c.parent.type!==d.DataType&&(r.push(s.project.emitAsync(di.EXPLICIT_DEFINITION_ENTITY_UPDATED,c,s)),oi(c,ge.PERSISTED_ENTITY)?r.push(s.project.emitAsync(di.PERSISTED_DEFINITION_ENTITY_UPDATED,c,s)):oi(c,ge.RELATIONAL_DATABASE)&&r.push(s.project.emitAsync(di.RELATIONAL_DATABASE_DEFINITION_ENTITY_UPDATED,c,s))),await i.tick()}for(const a of s.listRemoved){const c=s.project.get(a.id)||s.project.getDeleted(a.id);(c==null?void 0:c.type)===d.DefinitionEntity&&c.parent.type!==d.DataType&&(r.push(s.project.emitAsync(di.EXPLICIT_DEFINITION_ENTITY_REMOVED,c,s)),oi(c,ge.PERSISTED_ENTITY)?r.push(s.project.emitAsync(di.PERSISTED_DEFINITION_ENTITY_REMOVED,c,s)):oi(c,ge.RELATIONAL_DATABASE)&&r.push(s.project.emitAsync(di.RELATIONAL_DATABASE_DEFINITION_ENTITY_REMOVED,c,s))),await i.tick()}return await Promise.all(r),s}var y1=(s=>(s.Manual="manual",s.Automatic="automatic",s))(y1||{}),W=(s=>(s.Added="added",s.Updated="updated",s.Removed="removed",s.Affected="affected",s))(W||{}),w=(s=>(s.AddSuccessCall="add-success-call",s.AddErrorCall="add-error-call",s.AddCall="add-call",s.SetParent="set-parent",s.SetStandaloneParent="set-standalone-parent",s.AfterAllChildrenInitialized="after-all-children-initialized",s.UpdateWithShallowTransfer="update-with-shallow-transfer",s.UpdateWithGenerationTarget="update-with-generation-target",s.RemoveFromParent="remove-from-parent",s.RemoveEntity="remove-entity",s.RestoreEntity="restore-entity",s.CloneEntity="clone-entity",s.AddInput="add-input",s.RemoveInput="remove-input",s.SetDataType="set-data-type",s.RemoveDataType="remove-data-type",s.SetAdditionalPropertiesDataType="set-additional-properties-data-type",s.RemoveAdditionalPropertiesDataType="remove-additional-properties-data-type",s.SetAllPropertiesImplement="set-all-properties-implement",s.RemoveAllPropertiesImplement="remove-all-properties-implement",s.RemoveValueReader="remove-value-reader",s.AddValueReader="add-value-reader",s.RemoveValueWriter="remove-value-writer",s.SetValueWriter="set-value-writer",s.AddEntryCaller="add-entry-caller",s.AddSuccessCaller="add-success-caller",s.AddErrorCaller="add-error-caller",s.RemoveCall="remove-call",s.RemoveCaller="remove-caller",s.RemoveChildGroup="remove-child-group",s.AddToAndGroup="add-to-and-group",s.AddToOrGroup="add-to-or-group",s.RemoveUnrecognizedInputs="remove-unrecognized-inputs",s.RemoveUnrecognizedOutputs="remove-unrecognized-outputs",s.SyncInputs="sync-inputs",s.SyncOutputs="sync-outputs",s.SetImplements="set-implements",s.SetExtends="set-extends",s.SetExtension="set-extension",s.AddImplementation="add-implementation",s.RemoveImplementation="remove-implementation",s.AddProperty="add-property",s.RemoveProperty="remove-property",s.AddMethod="add-method",s.RemoveMethod="remove-method",s.AddAbstractMethod="add-abstract-method",s.RemoveAbstractMethod="remove-abstract-method",s.SetValueAsTypeSingle="set-value-as-type-single",s.SetValueAsTypeList="set-value-as-type-list",s.SetValueAsType="set-value-as-type",s.RemoveErrorCatching="remove-error-catching",s.RemoveAllErrorCallers="remove-all-error-callers",s.RemoveAllSuccessCallers="remove-all-success-callers",s.RemoveAllCallers="remove-all-callers",s.RemoveAllErrorCalls="remove-all-error-calls",s.SetDataTypeEntityValue="set-data-type-entity-value",s.MergeDataTypes="merge-data-types",s.SetDataTypeForeignKeyRef="set-data-type-foreign-key-ref",s.SetErrorEntity="set-error-entity",s.AddValueAsTypeToList="add-value-as-type-to-list",s.RemoveValueAsTypeFromList="remove-value-as-type-from-list",s.CreateFromGenerationTarget="create-from-generation-target",s.ConnectExternalAccount="connect-external-account",s.ChangeExternalAccountConnectionUsed="change-external-account-connection-used",s.MoveInlineDefToCanvas="move-inline-def-to-canvas",s.CreateDefFromValue="create-def-from-value",s.PrettifyCanvas="prettify-canvas",s.SetPrimitiveDefaultValue="set-primitive-default-value",s.MakeArgRequired="make-argument-required",s.MakeArgNonRequired="make-argument-non-required",s.RecalculateArg="recalculate-arg",s.RenameArg="rename-argument",s.ChangeArgDescription="changed-argument-description",s.RemoveArgBaseImplementation="remove-argument-base-implementation",s.AddArgBaseImplementation="add-argument-base-implementation",s.ChangeArgDataType="change-argument-data-type",s.RecalculateCondition="recalculate-condition",s.ChangeTypeOfCondition="change-type-of-condition",s.RenameDefinition="rename-definition",s.RecalculateDef="recalculate-definition",s.ChangeDefDescription="changed-definition-description",s.RemoveDefBaseImplementation="remove-definition-base-implementation",s.AddDefBaseImplementation="add-definition-base-implementation",s.RemoveDefExtension="remove-definition-extension",s.SetDefExtends="set-definition-extension",s.MakeDefStatic="make-def-static",s.MakeDefNonStatic="make-def-non-static",s.MakeDefAbstract="make-def-abstract",s.MakeDefNonAbstract="make-def-non-abstract",s.RecalculateFuncCall="recalculate-function-call",s.ChangeFuncCallDeclaration="change-function-call-declaration",s.RenameFuncDecl="rename-function-declaration",s.ChangeFuncDeclDescription="changed-function-declaration-description",s.RecalculateFuncDecl="recalculate-function-declaration",s.SetFuncDeclBaseImplementation="set-function-declaration-base-implementation",s.ChangeFuncDeclOutputDataType="change-function-declaration-output-data-type",s.RecalculateGlobalEvent="recalculate-global-event",s.ChangeGlobalEventDescription="changed-global-event-description",s.ChangeGlobalEventType="changed-global-event-type",s.RecalculateInputMap="recalculate-input",s.ChangeInputMapDescription="changed-input-description",s.ChangeInputMapDataType="change-input-data-type",s.RecalculateLoop="recalculate-loop",s.ChangeLoopType="changed-loop-type",s.RecalculateOperation="recalculate-operation",s.ChangeOperationType="changed-operation-type",s.RecalculateOutputMap="recalculate-output",s.ChangeOutputMapDataType="change-output-data-type",s.RecalculateProperty="recalculate-property",s.MakePropertyRequired="make-property-required",s.MakePropertyNonRequired="make-property-non-required",s.MakePropertyConstant="make-property-constant",s.MakePropertyNonConstant="make-property-non-constant",s.MakePropertyUnique="make-property-unique",s.MakePropertyNonUnique="make-property-non-unique",s.MakePropertyStatic="make-property-static",s.MakePropertyNonStatic="make-property-non-static",s.MakePropertyAbstract="make-property-abstract",s.MakePropertyNonAbstract="make-property-non-abstract",s.RenameProperty="rename-property",s.ChangePropertyDescription="changed-property-description",s.RemovePropertyBaseImplementation="remove-property-base-implementation",s.AddPropertyBaseImplementation="add-property-base-implementation",s.ChangePropertyDataType="change-property-data-type",s.RecalculateSearch="recalculate-search",s.RenameSearch="rename-search",s.ChangeSearchDescription="changed-search-description",s.ChangeSearchQuery="changed-search-query",s.MakeValueDescriptorRequired="make-value-descriptor-required",s.MakeSearchInputRequired="make-search-input-required",s.MakeValueDescriptorNonRequired="make-value-descriptor-non-required",s.MakeSearchInputNonRequired="make-search-input-non-required",s.RenameValueDescriptor="rename-value-descriptor",s.RenameSearchInput="rename-search-input",s.ChangeValueDescriptorDescription="changed-value-descriptor-description",s.ChangeSearchInputDescription="changed-search-input-description",s.ChangeValueDescriptorDataType="change-value-descriptor-data-type",s.RecalculateVarDecl="recalculate-variable-declaration",s.MakeVarDeclConstant="make-variable-declaration-constant",s.MakeVarDeclNonConstant="make-variable-declaration-non-constant",s.RenameVarDecl="rename-variable-declaration",s.ChangeVarDeclDescription="changed-variable-declaration-description",s.ChangeVarDeclDataType="change-variable-declaration-data-type",s.RecalculateVarInst="recalculate-variable-instance",s.ChangeVarInstDeclaration="change-variable-instance-declaration",s.HideFuncDeclBody="hide-function-declaration-body",s.ShowFuncDeclBody="show-function-declaration-body",s.HideGlobalEventBody="hide-global-event-body",s.ShowGlobalEventBody="show-global-event-body",s.HideLoopBody="hide-loop-body",s.ShowLoopBody="show-loop-body",s.HideTriggerBody="hide-trigger-body",s.ShowTriggerBody="show-trigger-body",s.AddNestedAndCondition="add-nested-and-condition",s.AddInputToCondition="add-input-to-condition",s.RecalculateNode="recalculate-node",s.AddInputToFuncDecl="add-input-to-function-declaration",s.ChangeInternalCallToThrowErrors="change-internal-call-to-throw-errors",s.ChangeInternalCallToCatchErrors="change-internal-call-to-catch-errors",s.AddErrorOutputToInternalCall="add-error-output-to-internal-call",s.ChangeLoopToThrowErrors="change-loop-to-throw-errors",s.ChangeLoopToCatchErrors="change-loop-to-catch-errors",s.RecalculateLoopBody="recalculate-loop-body",s.RecalculateMethod="recalculate-method",s.AddArgToLoopBody="add-arg-to-loop-body",s.AddArgToMethod="add-arg-to-method",s.RecalculateNestedCondition="recalculate-nested-condition",s.ChangeNodeToThrowErrors="change-node-to-throw-errors",s.ChangeNodeToCatchErrors="change-node-to-catch-errors",s.ChangeOperationToThrowErrors="change-operation-to-throw-errors",s.ChangeOperationToCatchErrors="change-operation-to-catch-errors",s.ChangeFuncCallToThrowErrors="change-function-call-to-throw-errors",s.ChangeFuncCallToCatchErrors="change-function-call-to-catch-errors",s.ChangeSearchToThrowErrors="change-search-to-throw-errors",s.ChangeSearchToCatchErrors="change-search-to-catch-errors",s.ChangeVarDeclToThrowErrors="change-variable-declaration-to-throw-errors",s.ChangeVarDeclToCatchErrors="change-variable-declaration-to-catch-errors",s.ChangeVarInstToThrowErrors="change-variable-instance-to-throw-errors",s.ChangeVarInstToCatchErrors="change-variable-instance-to-catch-errors",s.AddErrorOutputToNode="add-error-output-to-node",s.AddErrorOutputToOperation="add-error-output-to-operation",s.AddErrorOutputToFuncCall="add-error-output-to-function-call",s.AddErrorOutputToSearch="add-error-output-to-search",s.AddErrorOutputToVarDecl="add-error-output-to-variable-declaration",s.AddErrorOutputToVarInst="add-error-output-to-variable-instance",s.AddInputToNode="add-input-to-node",s.AddInputToOperation="add-input-to-operation",s.AddInputToFuncCall="add-input-to-function-call",s.AddInputToSearch="add-input-to-search",s.AddPropertyToVarDecl="add-property-to-variable-declaration",s.AddPropertyToVarInst="add-property-to-variable-instance",s.AddMethodToDef="add-method-to-definition",s.ReSyncRowTransformer="re-sync-row-transformer",s.ManuallyAddRowTransformer="manually-add-row-transformer",s.AddPropertyToDef="add-property-to-definition",s.RestablishExternalAccountConnection="restablish-external-account-connection",s.AddThrownError="add-thrown-error",s.RecalculateTerminationStatement="recalculate-termination-statement",s.RecalculateReturnStmt="recalculate-return-statement",s.RecalculateContinueStmt="recalculate-continue-statement",s.RecalculateBreakStmt="recalculate-break-statement",s.AddPropertyToTerminationStatement="add-property-to-termination-statement",s.AddPropertyToReturnStmt="add-property-to-return-statement",s.AddPropertyToContinueStmt="add-property-to-continue-statement",s.AddPropertyToBreakStmt="add-property-to-break-statement",s.SetLiteralValueToExplicitlyEmpty="set-literal-value-to-explicitly-empty",s.ModifyLiteralValue="modify-literal-value",s.RemoveLiteralValue="remove-literal-value",s.ModifyLiteralValueAsType="modify-literal-value-as-type",s.UpdateProjectMetadata="update-project-metadata",s.RenameProject="rename-project",s.ChangeProjectDescription="change-project-description",s.RestoreNode="restore-node",s.RestoreDef="restore-definition",s.RestoreFuncDecl="restore-function-declaration",s.RestoreGlobalEvent="restore-global-event",s.RestoreSearch="restore-search",s.RestoreVarDecl="restore-variable-declaration",s.RestoreVarInst="restore-variable-instance",s.RestoreFuncCall="restore-function-call",s.RestoreOperation="restore-operation",s.RestoreCondition="restore-condition",s.RestoreReturnStmt="restore-return-statement",s.RestoreContinueStmt="restore-continue-statement",s.RestoreBreakStmt="restore-break-statement",s.RestoreInstalledProject="restore-installed-project",s.RestoreLoop="restore-loop",s.CreateNewDef="create-new-definition",s.CreateNewFuncDecl="create-new-function-declaration",s.CreateNewGlobalEvent="create-new-global-event",s.CreateNewSearch="create-new-search",s.CreateNewVarDecl="create-new-variable-declaration",s.CreateNewVarInst="create-new-variable-instance",s.CreateNewFuncCall="create-new-function-call",s.CreateNewOperation="create-new-operation",s.CreateNewCondition="create-new-condition",s.CreateNewReturnStmt="create-new-return-statement",s.CreateNewContinueStmt="create-new-continue-statement",s.CreateNewBreakStmt="create-new-break-statement",s.CreateNewInternalCall="create-new-internal-call",s.CreateNewLoop="create-new-loop",s.ImplementBuiltInFunctionalityAsDef="implement-built-in-functionality-as-definition",s.ImplementAbstractEntityAsDef="implement-abstract-entity-as-definition",s.ImplementNewHTTPEndpoint="implement-new-http-endpoint",s.ImplementNewScheduledTrigger="implement-new-scheduled-trigger",s.ImplementNewPersistedEntity="implement-new-persisted-entity",s.AddedNewRowTransformer="added-new-row-transformer",s.AddedSQLConnectionConfig="added-sql-connection-config",s.AddedNewSSLConnectionConfig="added-new-ssl-connection-config",s.AddedGoogleConnection="added-google-connection",s.AddedSlackConnection="added-slack-connection",s.AddedNewExternalAccountConnection="added-new-external-account-connection",s.AddedGoogleDriveConnection="added-google-drive-connection",s.AddedGoogleSheetsConnection="added-google-sheets-connection",s.AddedGoogleSlidesConnection="added-google-slides-connection",s.AddedGoogleMailConnection="added-gmail-connection",s.ManuallyCreateIndividualNode="manually-create-individual-node",s.UpdateNode="update-node",s.CreateNewProjectPublicationCompletedEvent="create-new-project-publication-completed-event",s.CreateNewCountedLoop="create-new-counted-loop",s.CreateNewListLoop="create-new-list-loop",s.CreateNewManualFlowLoop="create-new-manual-flow-loop",s.CreateNewObjectKeysLoop="create-new-object-keys-loop",s.CreateNewObjectValuesLoop="create-new-object-values-loop",s.CreateNewStringLoop="create-new-string-loop",s.CreateNewIsFalseCondition="create-new-is-false-condition",s.CreateNewIsTrueCondition="create-new-is-true-condition",s.CreateNewAndCondition="create-new-and-condition",s.CreateNewOrCondition="create-new-or-condition",s.DisconnectNodes="disconnect-nodes",s.DisconnectExecutions="disconnect-executions",s.DisconnectValues="disconnect-values",s.ConnectNodes="connect-nodes",s.ConnectExecution="connect-execution",s.ConnectValues="connect-values",s.ConnectValueToNewInput="connect-value-to-new-input",s.ConnectValueToNewOperationInput="connect-value-to-new-operation-input",s.ConnectValueToNewConditionInput="connect-value-to-new-condition-input",s.ConnectValueToNewSearchInput="connect-value-to-new-search-input",s.ConnectValueToNewVarDeclProperty="connect-value-to-new-variable-declaration-property",s.ConnectValueToNewVarInstProperty="connect-value-to-new-variable-instance-property",s.ConnectValueToNewReturnStmtProperty="connect-value-to-new-return-statement-property",s.ConnectValueToNewContinueStmtProperty="connect-value-to-new-continue-statement-property",s.ConnectValueToNewBreakStmtProperty="connect-value-to-new-break-statement-property",s.ConnectNewFuncDeclArgToValue="connect-new-function-argument-to-value",s.RemoveNodes="remove-nodes",s.RemoveNode="remove-node",s.InitialLoadAutomaticCanvasRefresh="initial-load-automatic-canvas-refresh",s.MoveNodes="move-nodes",s.MoveNode="move-node",s.CloneNodes="clone-nodes",s.CloneNode="clone-node",s.GenerateSQLMigrationOnPersistedEntityUpdate="generate-sql-migration-on-persisted-entity-update",s))(w||{}),Me=(s=>(s.ActionOwnerEntityNotEditable="action-owner-entity-not-editable",s.ActionCounterpartEntityNotEditable="action-counterpart-entity-not-editable",s.ActionOwnerEntityNonDeletable="action-owner-entity-non-deletable",s.GlobalVariableDeclarationCannnotCatchError="global-variable-declaration-cannot-catch-error",s.GlobalVariableDeclarationCannotReadValue="global-variable-declaration-cannot-read-value",s.GlobalVariableDeclarationCannotBeCalled="global-variable-declaration-cannot-be-called",s.GlobalVariableDeclarationCannotCallFromError="global-variable-declaration-cannot-call-from-error",s.ValueReadingOverridesConstantProperty="value-reading-overrides-constant-property",s.DefaultValueOverridesConstantProperty="default-value-overrides-constant-property",s.ValueReadingOverridesConstantVariable="value-reading-overrides-constant-variable",s.DefaultValueOverridesConstantVariable="default-value-overrides-constant-variable",s.CannotSuccessCallItself="cannot-success-call-itself",s.CannotErrorCallItself="cannot-error-call-itself",s.CannotEntryCallItself="cannot-entry-call-itself",s.CannotValueWriteItself="cannot-value-write-itself",s.CannotBeCalledBeforeDeclaration="cannot-be-called-before-declaration",s.CannotBeCalledInParallelBranchToDeclaration="cannot-be-called-in-parallel-branch-to-declaration",s.CannotBeHigherScopeThanDeclaration="cannot-be-higher-scope-than-declaration",s.InputsInGlobalVariableDeclarationsCannotReadValues="inputs-in-global-variable-declarations-cannot-read-values",s))(Me||{});class G_e{constructor({id:p,action:i,errorReason:r,owner:a,counterpart:c,rootAction:e},f){R(this,"id");R(this,"action");R(this,"errorReason");R(this,"owner",null);R(this,"counterpart",null);R(this,"rootAction",!1);R(this,"parent");this.id=p,this.action=i,this.errorReason=r||null,this.owner=a||null,this.counterpart=c||null,this.rootAction=e||!1,this.parent=f}}class S extends z.Events{constructor(i,r,a,c,e=!1,f=""){super(f?f+"-cs-events":"anonymous-cs-events");R(this,"id",x.UUID.uuid());R(this,"seenEntities",[]);R(this,"added",{});R(this,"updated",{});R(this,"removed",{});R(this,"affected",{});R(this,"self",null);R(this,"author");R(this,"timestamp");R(this,"open",!0);R(this,"startedClose",!1);R(this,"dirty",!0);R(this,"submitting",!1);R(this,"lockedVersions",!1);R(this,"type","manual");R(this,"autoclose",!1);R(this,"actionName","");R(this,"project");R(this,"events",new Map);R(this,"ignoreNonEditable",!1);R(this,"ignoreNonDeletable",!1);R(this,"logger");if(this.project=i,this.author=r||x.sessionAuthor||"",this.timestamp=a,this.self=c,this.autoclose=e,this.actionName=f,this.logger=z.Logger.module("cs:"+(this.actionName?this.actionName+":":"")+this.id),this.autoclose&&!this.actionName)throw new Error("Auto-close change-set must have an auto-close action name.")}get index(){const i=this.project.history.indexOf(this);return i===-1?null:i}get isEmpty(){return Object.keys(this.added).length===0&&Object.keys(this.updated).length===0&&Object.keys(this.removed).length===0}get isValid(){var i;return!(this.isEmpty&&this.self&&!this.affected[(i=this.self)==null?void 0:i.id])}get list(){return[...Object.values(this.added),...Object.values(this.updated),...Object.values(this.removed)]}get listAdded(){return Object.values(this.added)}get listUpdated(){return Object.values(this.updated)}get listRemoved(){return Object.values(this.removed)}get listAffected(){return Object.values(this.affected)}get addedIds(){return Object.keys(this.added)}get updatedIds(){return Object.keys(this.updated)}get removedIds(){return Object.keys(this.removed)}get affectedIds(){return Object.keys(this.affected)}event(i){this.logger.log(`ChangeSet Event: ${i.action} (${i.id})`);const r=new G_e(i,this);this.events.set(i.id,r),this.emit("change-set-event",r)}discardOrphans(){this.added[this.project.id]&&(this.updatedIds.forEach(e=>{const f=this.updated[e];this.added[e]=f,delete this.updated[e]}),this.removedIds.forEach(e=>{this.remove(e)}));const i=[...this.addedIds,...this.updatedIds],a=this.project.toFlatIds().filter(e=>!this.project.diggestedBuiltInBaseEntitiesIds.has(e));if(i.filter(e=>!a.includes(e)).forEach(e=>{const f=this.get(e);this.logger.warn(`[discardOrphans] Entity ${f==null?void 0:f.type} with id "${e}" present in change-set but not in project. Removing from change-set.`),this.remove(e)}),this.added[this.project.id]){const e=[...this.addedIds,...this.updatedIds];this.project.toFlatIds().filter(E=>!this.project.diggestedBuiltInBaseEntitiesIds.has(E)).filter(E=>!e.includes(E)).forEach(E=>{const b=this.project.get(E);this.add(b,"added")})}}async discardOrphansAsync(i={}){const r=z.YieldTracker.from(i),a=this.project.toFlatIds();if(this.added[this.project.id]){for(const h of this.updatedIds){const m=this.updated[h];this.added[h]=m,delete this.updated[h],await r.tick()}for(const h of this.removedIds)this.remove(h),await r.tick()}const c=[...this.addedIds,...this.updatedIds],e=a.filter(h=>!this.project.diggestedBuiltInBaseEntitiesIds.has(h)),f=c.filter(h=>!e.includes(h));for(const h of f){const m=this.get(h);this.logger.warn(`[discardOrphansAsync] Entity ${m==null?void 0:m.type} with id "${h}" present in change-set but not in project. Removing from change-set.`),this.remove(h),await r.tick()}if(this.added[this.project.id]){const h=[...this.addedIds,...this.updatedIds],E=a.filter(b=>!this.project.diggestedBuiltInBaseEntitiesIds.has(b)).filter(b=>!h.includes(b));for(const b of E){const A=this.project.get(b);this.add(A,"added"),await r.tick()}}}captureAllChangesInVersionInstances(){[...this.addedIds,...this.updatedIds].forEach(r=>{const a=this.project.get(r);if(!a){const e=this.added[r],f=this.updated[r],h=e||f;throw new Error(`Entity ${(h==null?void 0:h.type)||"of unknown type"} with id "${r}" was ${e?"added":"updated"} but isn't found in the project state when capturing version for change-set.`)}const c=this.get(r);a.version===c.version&&a.captureVersion()}),this.removedIds.forEach(r=>{const a=this.project.getDeleted(r);if(!a){const e=this.removed[r];throw new Error(`Entity ${(e==null?void 0:e.type)||"of unknown type"} with id "${r}" was removed but isn't found in the project state when capturing version for change-set.`)}const c=this.get(r);a.version===c.version&&a.captureVersion()})}async captureAllChangesInVersionInstancesAsync(i={}){const r=z.YieldTracker.from(i),a=[...this.addedIds,...this.updatedIds];for(const c of a){const e=this.project.get(c);if(!e){const h=this.added[c],m=this.updated[c],E=h||m;throw new Error(`Entity ${(E==null?void 0:E.type)||"of unknown type"} with id "${c}" was ${h?"added":"updated"} but isn't found in the project state when capturing version for change-set.`)}const f=this.get(c);e.version===f.version&&e.captureVersion(),await r.tick()}for(const c of this.removedIds){const e=this.project.getDeleted(c);if(!e){const h=this.removed[c];throw new Error(`Entity ${(h==null?void 0:h.type)||"of unknown type"} with id "${c}" was removed but isn't found in the project state when capturing version for change-set.`)}const f=this.get(c);e.version===f.version&&e.captureVersion(),await r.tick()}}async attemptAutocloseAsync(i,r){var a;return this.autoclose&&this.actionName&&this.actionName===i&&(this.self&&r===((a=this.self)==null?void 0:a.id)||!this.self)&&await this.closeAsync(),this}async closeAsync(i={}){const r=z.YieldTracker.from(i),a={persistType:"sequential",...i};if(!this.open||this.startedClose)return this.logger.warn(`Change-set (${this.id}) is already closed or in the process of closing.`),this;const c=i.awaitBeforeClose??!0,e=i.awaitExternalPersist??!0;return this.startedClose||(this.startedClose=!0,c?await this.beforeCloseAsync({tracker:r}):this.beforeCloseAsync({tracker:r})),!this.isValid&&this.self&&!this.added[this.self.id]&&!this.updated[this.self.id]&&this.removed[this.self.id],await this.discardOrphansAsync({tracker:r}),await this.sanitizeAsync({tracker:r}),await this.recursiveCaptureUpstreamVersionsAsync({tracker:r}),this.lockedVersions||(await this.captureAllChangesInVersionInstancesAsync({tracker:r}),await this.recursiveCaptureUpstreamVersionsAsync({tracker:r})),this.open=!1,this.isEmpty?(this.logger.warn(`[ChangeSet.closeAsync] Empty change-set (${this.id}) discarded upon closing.`),this.dirty=!1,this.project.discardChangeSet(this),this.logger.log("[ChangeSet.closeAsync] Closing pending change-sets..."),this.project.closePersistChangeSetsSequentially(),this):(this.project.emit(di.CHANGE_SET_CLOSED_BEFORE_PERSIST,this),e?a.persistType==="parallel"?await this.project.persistChangeSetInParallel(this):await this.project.persistChangeSetSequentially(this):a.persistType==="parallel"?this.project.persistChangeSetInParallel(this):this.project.persistChangeSetSequentially(this),this.destroy(),this)}attemptAutoclose(i,r){var a;return this.autoclose&&this.actionName&&this.actionName===i&&(this.self&&r===((a=this.self)==null?void 0:a.id)||!this.self)&&this.close(),this}recursiveCaptureUpstreamVersions(){if(this.lockedVersions)return;[...this.addedIds,...this.updatedIds,...this.removedIds].forEach(r=>{const a=this.get(r),{added:c,updated:e,removed:f,affected:h}=a.recursiveCaptureUpstreamVersions(this.timestamp);for(const m of c)this.add(m,"added");for(const m of e)this.add(m,"updated");for(const m of f)this.add(m,"removed");for(const m of h)this.add(m,"affected")})}async recursiveCaptureUpstreamVersionsAsync(i={}){if(this.lockedVersions)return;const r=z.YieldTracker.from(i),a=[...this.addedIds,...this.updatedIds,...this.removedIds];for await(const c of a){const e=this.get(c),{added:f,updated:h,removed:m,affected:E}=e.recursiveCaptureUpstreamVersions(this.timestamp);for(const b of f)this.add(b,"added");for(const b of h)this.add(b,"updated");for(const b of m)this.add(b,"removed");for(const b of E)this.add(b,"affected");await r.tick()}}sanitize(){this.listAdded.forEach(i=>{i.previousVersion=null})}async sanitizeAsync(i={}){const r=z.YieldTracker.from(i);for(const a of this.listAdded)a.previousVersion=null,await r.tick()}syncDependents(){return[...this.list,...this.listAffected].forEach(i=>{const r=this.project.get(i.id);!r||r.deleted||Ig(r,this.project)||r==null||r.syncDependents(this)}),this}async syncDependentsAsync(i={}){const r=z.YieldTracker.from(i);for(const a of[...this.list,...this.listAffected]){const c=this.project.get(a.id);!c||c.deleted||Ig(c,this.project)||(c==null||c.syncDependents(this),await r.tick())}return this}async beforeCloseAsync(i={}){const r=z.YieldTracker.from(i);await this.project.emitAsync(di.BEFORE_CHANGE_SET_CLOSE_BEFORE_SIDE_EFFECTS,this),await this.syncDependentsAsync({tracker:r}),await this.emitAsyncProjectSideEffects({tracker:r}),await this.project.emitAsync(di.BEFORE_CHANGE_SET_CLOSE_AFTER_SIDE_EFFECTS,this),this.teardown()}beforeClose(){this.project.emit(di.BEFORE_CHANGE_SET_CLOSE_BEFORE_SIDE_EFFECTS,this),this.syncDependents(),this.emitProjectSideEffects(),this.project.emit(di.BEFORE_CHANGE_SET_CLOSE_AFTER_SIDE_EFFECTS,this),this.teardown()}teardown(){this.destroy()}emitProjectSideEffects(){return B_e(this)}async emitAsyncProjectSideEffects(i={}){return M_e(this,i)}close(i={}){const r={persistType:"sequential",...i};if(!this.open||this.startedClose)return this.logger.warn(`Change-set (${this.id}) is already closed or in the process of closing.`),this;if(this.startedClose||(this.startedClose=!0,this.beforeClose()),!this.isValid&&this.self&&!this.added[this.self.id]&&!this.updated[this.self.id]&&this.removed[this.self.id],this.discardOrphans(),this.sanitize(),this.captureAllChangesInVersionInstances(),this.lockedVersions||(this.recursiveCaptureUpstreamVersions(),this.captureAllChangesInVersionInstances()),this.open=!1,this.isEmpty)return this.logger.warn(`[ChangeSet.close] Empty change-set (${this.id}) discarded upon closing.`),this.project.discardChangeSet(this),this.logger.log("[ChangeSet.close] Closing pending change-sets..."),this.project.closePersistChangeSetsSequentially(),this;if(this.added[this.project.id]&&this.updatedIds.length)throw new Error("No 'updated' entities should be present in the change-set when the project entity is in the 'added' list. New projects can only have newly added entities");if(this.added[this.project.id]&&this.removedIds.length)throw new Error("No 'removed' entities should be present in the change-set when the project entity is in the 'added' list. New projects can only have newly added entities");if(!this.updated[this.project.id]&&!this.added[this.project.id])throw new Error("Change-set must also have the project entity as 'updated' or 'added'. All changes must propagate upstream until the root project entity.");return this.project.emit(di.CHANGE_SET_CLOSED_BEFORE_PERSIST,this),r.persistType==="parallel"?this.project.persistChangeSetInParallel(this):this.project.persistChangeSetSequentially(this),this.destroy(),this}addDependentsToAffected(i){Object.values(i.detachedDependents).forEach(r=>{const{entity:a,field:c}=r;this.has(a.id)||this.add(a,"affected")})}get(i){return this.added[i]?this.added[i]:this.updated[i]?this.updated[i]:this.removed[i]?this.removed[i]:null}remove(i){return this.has(i)&&(delete this.added[i],delete this.updated[i],delete this.removed[i],delete this.affected[i],this.seenEntities=this.seenEntities.filter(r=>r!==i)),this}add(i,r,a={preventRecursion:!1}){var e,f,h,m;if(!this.open||!this.dirty)return this;if(Ig(i,this.project))return this;if(this.seenEntities.indexOf(i.id)===-1&&this.seenEntities.push(i.id),r==="removed"){if(this.added[i.id])return delete this.added[i.id],delete this.affected[i.id],delete this.updated[i.id],this.seenEntities=this.seenEntities.filter(b=>b!==i.id),delete this.project.deletedInstances[i.id],this;if(this.updated[i.id]&&delete this.updated[i.id],this.affected[i.id]&&delete this.affected[i.id],!this.hasRemoved(i.id)&&!this.lockedVersions&&(i.increaseVersion(this.timestamp),!a.preventRecursion)){const{added:b,updated:A,removed:_,affected:P}=i.recursiveCaptureUpstreamVersions(this.timestamp);for(const V of b)this.add(V,"added");for(const V of A)this.add(V,"updated");for(const V of _)this.add(V,"removed");for(const V of P)this.add(V,"affected")}i.captureVersion();const E=(e=i.knownVersions)==null?void 0:e.get(i.version);if(!E)throw Error(`Version ${i.version} should have a cached version instance but it wasn't found when adding entity to change-set`);return this.removed[i.id]=E,this}if(r==="added"){if(this.removed[i.id])return this;if(this.updated[i.id]&&delete this.updated[i.id],this.affected[i.id]&&delete this.affected[i.id],!this.hasAdded(i.id)&&!this.lockedVersions&&!a.preventRecursion){const{added:b,updated:A,removed:_,affected:P}=i.recursiveCaptureUpstreamVersions(this.timestamp);for(const V of b)this.add(V,"added");for(const V of A)this.add(V,"updated");for(const V of _)this.add(V,"removed");for(const V of P)this.add(V,"affected")}i.previousVersion=null,i.captureVersion();const E=(f=i.knownVersions)==null?void 0:f.get(i.version);if(!E)throw Error(`Version ${i.version} should have a cached version instance but it wasn't found when adding entity to change-set`);return this.added[i.id]=E,delete this.affected[i.id],this.addDependentsToAffected(i),this}if(r==="updated"){if(this.removed[i.id])return this;if(this.added[i.id])return i.captureVersion(),this.addDependentsToAffected(i),this;if(this.affected[i.id]&&delete this.affected[i.id],!this.hasUpdated(i.id)&&!this.lockedVersions&&(i.increaseVersion(this.timestamp),!a.preventRecursion)){const{added:b,updated:A,removed:_,affected:P}=i.recursiveCaptureUpstreamVersions(this.timestamp);for(const V of b)this.add(V,"added");for(const V of A)this.add(V,"updated");for(const V of _)this.add(V,"removed");for(const V of P)this.add(V,"affected")}i.activeVersion=!0,i.captureVersion();const E=(h=i.knownVersions)==null?void 0:h.get(i.version);if(!E)throw Error(`Version ${i.version} should have a cached version instance but it wasn't found when adding entity to change-set`);return this.updated[i.id]=E,this.addDependentsToAffected(i),this}if(r==="affected"){if(this.removed[i.id])return this;if(this.added[i.id])return this;if(this.updated[i.id])return this;if(this.affected[i.id]=i,!this.lockedVersions){const E=i.version+"--"+this.id,b=((m=i.knownVersions)==null?void 0:m.get(E))||i.snapshot();i.apply(b),i.knownVersions=i.knownVersions?i.knownVersions.set(E,b):new Map().set(E,b)}}return this}toJSON(){var f;const i={},r={},a={},c=new Set;for(const h of Object.values(this.added))i[h.id]=h.toShallowJSON();for(const h of Object.values(this.updated))r[h.id]=h.toShallowJSON();for(const h of Object.values(this.removed))a[h.id]=h.toShallowJSON();for(const h of Object.values(this.affected))c.add(h.id);const e=this.get(((f=this.self)==null?void 0:f.id)||"");return{added:i,updated:r,removed:a,affected:Array.from(c),self:e?e.toShallowJSON():null,seenEntities:this.seenEntities,actionName:this.actionName}}has(i){return!!this.added[i]||!!this.removed[i]||!!this.updated[i]||!!this.affected[i]}hasAdded(i){return!!this.added[i]}hasUpdated(i){return!!this.updated[i]}hasRemoved(i){return!!this.removed[i]}hasAffected(i){return!!this.affected[i]}}function ygi(s){return new Set([...Object.keys(s.added),...Object.keys(s.updated),...Object.keys(s.removed),...Array.from(s.affected)])}function $_(s,p,i){var f;const r=new Date().toISOString(),a=new S(i,x.sessionAuthor,r,i);if(a.lockedVersions=!0,s===p)throw z.Logger.error("From: ",s),z.Logger.error("To: ",p),new Error("Cannot generate transitional change set between the same two versions or change-sets");let c;if(s==="initial"?c=!0:p==="initial"?c=!1:B(s.timestamp).isBefore(B(p.timestamp))?c=!0:c=!1,z.Logger.log("Transitioning from ",s==="initial"?"initial":s.index),z.Logger.log("Transitioning to ",p==="initial"?"initial":p.index),z.Logger.log("Is forward: ",c),c){const h=p,m=h.index,E=s==="initial"?0:s.index;z.Logger.log("ownIndex: ",m),z.Logger.log("startIndex: ",E),z.Logger.log("CH ID: ",h.id);const b=m===E?[i.history[m]]:i.history.slice(E+1,m+1);if(b.sort((A,_)=>B(A.timestamp).isAfter(B(_.timestamp))?1:-1),!b.length)throw new Error("No change sets in the history between the history indexes provided");z.Logger.log("REDO change-set: ",b[0].id," ",b[0].timestamp),b.forEach(A=>{L_(A,_=>{const P=i.instances[_.id]||i.deletedInstances[_.id];let V="";try{V=oe(_,i)}catch{}if(!P)throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" doesn't have an 'activeVersion' set.`);if(!P.knownVersions)throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" has an active version instance missing the 'knownVersions' property value.`);if(!P.knownVersions.get(_.version))throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" has an active version instance missing the 'knownVersions' property value for version "${_.version}".`);P.restoreVersion(_.version),P.addSelfToProject(a),a.timestamp=P.createdAt,a.add(P,W.Added,{preventRecursion:!0})},_=>{const P=i.instances[_.id]||i.deletedInstances[_.id];let V="";try{V=oe(_,i)}catch{}if(!P)throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" doesn't have an 'activeVersion' set.`);if(!P.knownVersions)throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" has an active version instance missing the 'knownVersions' property value.`);if(!P.knownVersions.get(_.version))throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" has an active version instance missing the 'knownVersions' property value for version "${_.version}".`);P.restoreVersion(_.version),a.timestamp=P.createdAt,a.add(P,W.Updated,{preventRecursion:!0})},_=>{var G;const P=i.instances[_.id]||i.deletedInstances[_.id];let V="";try{V=oe(_,i)}catch{}if(!P)throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" doesn't have an 'activeVersion' set.`);if(!P.knownVersions)throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" has an active version instance missing the 'knownVersions' property value.`);if(!P.knownVersions.get(_.version))throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" has an active version instance missing the 'knownVersions' property value for version "${_.version}".`);P.restoreVersion(_.version),(G=P.removeFromParent)==null||G.call(P,a),P.unsubscribe(),P.unsubscribeFromDependencies(),i.subscribeDeletedInstance(P),a.timestamp=P.createdAt,a.add(P,W.Removed,{preventRecursion:!0})},_=>{const P=i.instances[_.id]||i.deletedInstances[_.id];let V="";try{V=oe(_,i)}catch{}if(!P)throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" doesn't have an 'activeVersion' set.`);if(!P.knownVersions)throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" has an active version instance missing the 'knownVersions' property value.`);if(!P.knownVersions.get(_.version))throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" has an active version instance missing the 'knownVersions' property value for version "${_.version}".`);const G=_.version+"--"+A.id;P.restoreVersion(G),a.timestamp=P.createdAt,a.add(P,W.Updated,{preventRecursion:!0})})})}else{const h=s,m=h.index,E=p==="initial"?0:p.index;z.Logger.log("CH ID: ",h.id);const b=m===E?[i.history[m]]:i.history.slice(E+1,m+1);if(b.sort((A,_)=>B(_.timestamp).isAfter(B(A.timestamp))?1:-1),!b.length)throw new Error("No change sets in the history between the history indexes provided");z.Logger.log("UNDO change-set: ",b[0].id," ",b[0].timestamp),b.forEach(A=>{L_(A,_=>{var G;const P=i.instances[_.id]||i.deletedInstances[_.id];let V="";try{V=oe(_,i)}catch{}if(!P)throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" doesn't have an 'activeVersion' set.`);if(!P.knownVersions)throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" has an active version instance missing the 'knownVersions' property value.`);if(!P.knownVersions.get(_.version))throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" has an active version instance missing the 'knownVersions' property value for version "${_.version}".`);_.previousVersion&&(P.restoreVersion(_.previousVersion),(G=P.removeFromParent)==null||G.call(P,a),P.unsubscribe(),P.unsubscribeFromDependencies(),i.subscribeDeletedInstance(P)),a.timestamp=P.createdAt,a.add(P,W.Removed,{preventRecursion:!0})},_=>{const P=i.instances[_.id]||i.deletedInstances[_.id];let V="";try{V=oe(_,i)}catch{}if(!P)throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" doesn't have an 'activeVersion' set.`);if(!P.knownVersions)throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" has an active version instance missing the 'knownVersions' property value.`);if(!P.knownVersions.get(_.version))throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" has an active version instance missing the 'knownVersions' property value for version "${_.version}".`);P.restoreVersion(_.previousVersion),a.timestamp=P.createdAt,a.add(P,W.Updated,{preventRecursion:!0})},_=>{const P=i.instances[_.id]||i.deletedInstances[_.id];let V="";try{V=oe(_,i)}catch{}if(!P)throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" doesn't have an 'activeVersion' set.`);if(!P.knownVersions)throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" has an active version instance missing the 'knownVersions' property value.`);if(!P.knownVersions.get(_.version))throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" has an active version instance missing the 'knownVersions' property value for version "${_.version}".`);P.restoreVersion(_.previousVersion),P.addSelfToProject(a),a.timestamp=P.createdAt,a.add(P,W.Added,{preventRecursion:!0})},_=>{const P=i.instances[_.id]||i.deletedInstances[_.id];let V="";try{V=oe(_,i)}catch{}if(!P)throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" doesn't have an 'activeVersion' set.`);if(!P.knownVersions)throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" has an active version instance missing the 'knownVersions' property value.`);if(!P.knownVersions.get(_.version))throw new Error(`Entity ${_.type} ${V?`"${V}" `:""}with id "${_.id}" has an active version instance missing the 'knownVersions' property value for version "${_.version}".`);P.restoreVersion(P.version),a.timestamp=P.createdAt,a.add(P,W.Affected,{preventRecursion:!0})})})}let e;if(p==="initial"){const h=Array.from(((f=i.knownVersions)==null?void 0:f.values())||[]).reduce((m,E)=>!m||B(E.createdAt).isBefore(B(m.createdAt))?E:m,null);if(!h)throw new Error("No oldest version found");e=h.createdAt}else e=p.timestamp;return a.open=!1,{transitionalChangeSet:a,transitionTime:r,timeOfOriginalTargetChanges:e}}function L_(s,p,i,r,a){var h;if(!(s!=null&&s.self))throw new Error("Change set must have a valid `self` entity state to be traversed");const c=((h=s.self)==null?void 0:h.type)===d.Project?s.self:s.self.project,e=new Fn(s.self,{allBuiltInEntityIds:c.diggestedBuiltInBaseEntitiesIds});z.Logger.log("changeSet.added: ",Object.keys(s.added).length),z.Logger.log("changeSet.updated: ",Object.keys(s.updated).length),z.Logger.log("changeSet.removed: ",Object.keys(s.removed).length);const f={...s.added,...s.updated,...s.removed,...s.affected};e.order=Object.keys(f),e.flatRecord=f,e.orderEntities(),z.Logger.log("All entities: ",e.order.map((m,E)=>`${E+1}: ${f[m].type} - ${m}`).join(`,
|
|
7
7
|
`)),z.Logger.log("Traversing additions"),e.visit(async m=>{if(s.added[m.id])try{p(m)}catch(E){z.Logger.error("Error: ",E)}}),z.Logger.log("Traversing updates"),e.visit(async m=>{if(s.updated[m.id])try{i(m)}catch(E){z.Logger.error("Error: ",E)}}),z.Logger.log("Traversing removals"),e.visit(async(m,E)=>{if(s.removed[m.id])try{r(m)}catch(b){z.Logger.error("Error: ",b)}}),z.Logger.log("Traversing affected"),e.visit(async(m,E)=>{if(s.affected[m.id])try{a(m)}catch(b){z.Logger.error("Error: ",b)}})}function B_(s,p,i){const r=s+1;return p.splice(r,p.length-r,i),p.length-1}function hgi(s){[...s.listUpdated,...s.listAdded].forEach(p=>{const i=s.project.get(p.id);i.editable=!0})}function mgi(s){[...s.listUpdated,...s.listAdded].forEach(p=>{const i=s.project.get(p.id);i.deletable=!0})}function Tgi(s){[...s.listUpdated,...s.listAdded].forEach(p=>{const i=s.project.get(p.id);i.editable=!0,i.deletable=!0})}function vgi(s){[...s.listUpdated,...s.listAdded].forEach(p=>{const i=s.project.get(p.id);i.editable=!1})}function Egi(s){[...s.listUpdated,...s.listAdded].forEach(p=>{const i=s.project.get(p.id);i.deletable=!1})}function bgi(s){[...s.listUpdated,...s.listAdded].forEach(p=>{const i=s.project.get(p.id);i.editable=!1,i.deletable=!1})}function Agi(s,p){p?s.metaSync({editable:!1,deletable:!1},p):(s.editable=!1,s.deletable=!1),Ue(s,new Set,{ignoreBuiltInBaseEntities:!0}).forEach(r=>{p?r.metaSync({editable:!1,deletable:!1},p):(r.editable=!1,r.deletable=!1)})}function ggi(s,p){p?s.metaSync({editable:!0,deletable:!0},p):(s.editable=!0,s.deletable=!0),Ue(s,new Set,{ignoreBuiltInBaseEntities:!0}).forEach(r=>{p?r.metaSync({editable:!0,deletable:!0},p):(r.editable=!0,r.deletable=!0)})}function Igi(s){const{projectRecord:p,chain:i,projectId:r,sort:a,order:c}=s,e=a?(i||[]).sort((E,b)=>{const A=E.updated[r],_=b.updated[r];return B(A.createdAt).valueOf()-B(_.createdAt).valueOf()}):i||[],f={...p};e.forEach(E=>{Object.values(E.removed).forEach(A=>{delete f[A.id]}),Object.values(E.added).forEach(A=>{f[A.id]=A}),Object.values(E.updated).forEach(A=>{f[A.id]=A});const b=E.updated[r];f[r]=b});let h=null;if(c){const E=new Fn;E.flatRecord=f,E.orderEntities(),h=E.order}return{project:f[r],record:f,order:h}}class Mx{constructor(p){R(this,"version");R(this,"previousVersion");R(this,"createdAt");R(this,"deleted",!1);R(this,"author");this.version=p.version,this.previousVersion=p.previousVersion,this.createdAt=B(p.createdAt).toISOString(),this.deleted=p.deleted,this.author=p.author}baseMetaSync(p,i,r){this.deleted=p.deleted!==void 0?p.deleted:this.deleted}}class un extends Mx{constructor(i){super(i);R(this,"deletable",!0);R(this,"editable",!0);this.deletable=i.deletable,this.editable=i.editable}checkCanEditWithCounterpartAndSideEffects(i,r,a,c){var e,f;return!this.checkCanEdit(i,c)||!this.checkCanEdit(r,c)?(this.checkCanEdit(r,c)?(z.Logger.warn(`[${a}] User is not allowed to edit this ${i.type} entity with id: ${i.id}`),c==null||c.event({id:`${a}-${i.id}--${r.id}--${Me.ActionOwnerEntityNotEditable}`,action:a,owner:i,counterpart:r,errorReason:Me.ActionOwnerEntityNotEditable,rootAction:((f=c==null?void 0:c.self)==null?void 0:f.id)===i.id&&(c==null?void 0:c.actionName)===a})):(z.Logger.warn(`[${a}] User is not allowed to edit this ${i.type} entity with id: ${i.id} because its counterpart ${r.type} with id: ${r.id} is not editable`),c==null||c.event({id:`${a}-${i.id}--${r.id}--${Me.ActionCounterpartEntityNotEditable}`,action:a,owner:i,counterpart:r,errorReason:Me.ActionCounterpartEntityNotEditable,rootAction:((e=c==null?void 0:c.self)==null?void 0:e.id)===i.id&&(c==null?void 0:c.actionName)===a})),c==null||c.attemptAutoclose(a,i.id),!1):!0}checkCanEditFromScopeOwner(i,r){const a=Ut(i,i.project);return a?this.checkCanEdit(a,r):!0}checkCanEditFromScopeOwnerWithSideEffects(i,r,a){var e;const c=this.checkCanEditFromScopeOwner(i,a);return!c&&!(a!=null&&a.ignoreNonEditable)&&(z.Logger.warn(`[${r}] User is not allowed to edit this ${i.type} entity with id: ${i.id}`),a==null||a.event({id:`${r}-${i.id}--${Me.ActionOwnerEntityNotEditable}`,action:r,owner:i,errorReason:Me.ActionOwnerEntityNotEditable,rootAction:((e=a==null?void 0:a.self)==null?void 0:e.id)===i.id&&(a==null?void 0:a.actionName)===r}),a==null||a.attemptAutoclose(r,i.id)),c}checkCanEdit(i,r){var a;return(a=i.project)!=null&&a.initialized?i.type===d.BuiltInBaseEntity||i.type===d.PrimitiveEntity?!1:i.initialized?!(i.project.diggestedBuiltInBaseEntitiesIds.has(i.id)||i.parent&&!(this.checkCanEdit(i.parent,r)&&i.editable)&&!(r!=null&&r.ignoreNonEditable)||!i.editable&&!(r!=null&&r.ignoreNonEditable)):!0:!0}checkCanDelete(i,r){var a;return i.type!==d.Project&&i.project.diggestedBuiltInBaseEntitiesIds.has(i.id)?!1:i.type===d.Project||(a=i.parent)!=null&&a.deleted?!0:!(!i.deletable&&!(r!=null&&r.ignoreNonDeletable))}baseMetaSync(i,r,a){this.deletable=i.deletable!==void 0?i.deletable:this.deletable,this.editable=i.editable!==void 0?i.editable:this.editable;const c={...i,deleted:this.checkCanDelete(r,a)?i.deleted:!1};super.baseMetaSync(c,r,a)}}var k_e=(s=>(s.ArgumentDataTypeEntityField="data-type-entity-field",s.ArgumentDataTypeField="data-type-field",s.ArgumentImplementsField="argument-implements-field",s))(k_e||{});const bi=class bi extends un{constructor(i,r){super(i);R(this,"initialData");R(this,"id");R(this,"name");R(this,"codeName",null);R(this,"description",null);R(this,"index");R(this,"required");R(this,"constant",!0);R(this,"type",d.ArgumentDeclaration);R(this,"defaultValue",null);R(this,"dataType",null);R(this,"writesValues",[]);R(this,"implements",[]);R(this,"project");R(this,"errors",[]);R(this,"parent");R(this,"detachedDependents",{});R(this,"knownVersions",null);R(this,"activeVersion",!1);R(this,"initialized",!1);R(this,"startedInitialization",!1);R(this,"suggestion",!1);R(this,"_codeNativeValueValidation",null);this.initialData=i,this.project=r,this.id=i.id,this.index=i.index,this.name=i.name,this.description=i.description,this.codeName=i.codeName,this.required=i.required,this.constant=!0}static new(i=null){return{id:x.UUID.uuid(),version:x.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||B().toISOString(),author:(i==null?void 0:i.author)||x.sessionAuthor,previousVersion:null,deleted:!1,deletable:!0,editable:!0,type:d.ArgumentDeclaration,name:"",codeName:null,description:"",index:0,required:!1,constant:!0,implements:[],dataType:null,defaultValue:null,writesValues:[],parent:null}}static fromGenerationTarget(i,r,a){const c=a===void 0?r.addChangeSet(new S(r,x.sessionAuthor,B().toISOString(),r,!0,w.CreateFromGenerationTarget)):a,e=te(i.parent),f=r.get(e),h={id:i.id,version:x.UUID.uuid(),createdAt:(c==null?void 0:c.timestamp)||B().toISOString(),author:(c==null?void 0:c.author)||x.sessionAuthor,previousVersion:null,deleted:!1,name:i.name,deletable:!0,editable:!0,type:d.ArgumentDeclaration,index:f.inputs.length,defaultValue:null,codeName:i.codeName||null,description:i.description||null,required:i.required??!1,constant:!0,implements:[],dataType:null,writesValues:[],parent:f.toReference()},m=Re(h,r);return m.hydrateAncestors(),m.setParent(f,c),m.addSelfToProject(c),c==null||c.add(m,W.Added),m.initChildren(c),c||m.captureVersion(),m}static validateGenerationTarget(i,r){let a=JSON.parse(JSON.stringify(i));const c=[],e=[],f=Bn(a,{parent:{list:!1,types:[d.FunctionDeclaration,d.Search,d.Condition]}},r);c.push(...f.explanations),a=f.modifiedData;const h=Lx(a,r);if(a.parent){const E=r.get(te(a.parent));if(E&&jt.includes(E.type)){const b=E.implements;if(b){const A=b.inputs.find(k=>k.name===a.name),_=b.inputs.filter(k=>!E.inputs.find(ne=>ne.type===d.ArgumentDeclaration&&ne.name===k.name)),P=E.inputs.filter(k=>k.type===d.ArgumentDeclaration),V=P.find(k=>k.name===a.name),G=P.length?`The parent entity already implements the following arguments: ${Et(P.map(k=>`'${k.id}' (${k.name})`),", "," and ")}.`:"The parent entity does not yet have any implemented arguments.",M=_.length?`The parent entity is still missing the following arguments in the implementation: ${Et(_.map(k=>`'${k.id}' (${k.name})`),", "," and ")}.`:"The parent entity has all the arguments it needs implemented.";A?V&&e.push(new we({id:`${a.id}--${Ce.NoOverlapWithImplementedSignature}`,code:Ce.NoOverlapWithImplementedSignature,severity:ve.Error,message:`Entity of type '${d.ArgumentDeclaration}' with id '${a.id}' should not exist in a parent entity of type '${E.type}' with id '${E.id}' that implements a ${d.ActionDescriptor} with fixed arguments.
|
|
8
8
|
Adding a new argument would make the implementation invalid. An argument with the same name already exists in the parent entity.
|
|
9
9
|
${G}
|
|
@@ -602,7 +602,7 @@ Alternatively you can update the entity with 'update' action. Or replace it by f
|
|
|
602
602
|
This is likely an incorrect strategy, either the '${this.type}' entity doesn't need to be updated or it should be deleted and a new one created in the desired parent.`})),(i.readsValue||i.writesValue)&&(r.push(new we({id:`${this.id}--${Ce.InvalidObjectStructure}`,code:Ce.InvalidObjectStructure,severity:ve.Error,message:`Entity of type '${this.type}' with id '${this.id}' is not a value reading or writing entity.`})),a.push({id:Qi.EntitiesWithValues,message:Ph})),{errors:r,explanations:a,modifiedData:i}}onProjectInitialized(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,new Date().toISOString(),this,!0,"on-property-received-project-initialized"))){return r?(hF(this,r),r==null||r.attemptAutoclose("on-property-received-project-initialized",this.id),this):this}subscribeDependents(i){return i.forEach(r=>{this.detachedDependents[r.entity.id]||(this.detachedDependents[r.entity.id]=r)}),this}unsubscribeDependents(i){return i.forEach(r=>{this.detachedDependents[r.entity.id]&&delete this.detachedDependents[r.entity.id]}),this}syncDependents(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"sync-dependents"))){const r=[],a=[],c=[],e=[];return Object.values(this.detachedDependents).forEach(f=>{const h=f.entity.afterAllChildrenInitialized(i);r.push(...h.updated),a.push(...h.added),c.push(...h.removed),e.push(...h.affected)}),i==null||i.attemptAutoclose("sync-dependents",this.id),{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}onDetachedDependencyRemoved(i,r,a){const c=[],e=[],f=[],h=[];if(r==="property-implements-field"&&(this.removeImplementation(i,a),c.push(this)),r==="property-extends-field"){const{updated:m,added:E,removed:b,affected:A}=this.remove({ignoreUpstream:!1},a);c.push(...m),e.push(...E),f.push(...b),h.push(...A)}return{updated:C(c),added:C(e),removed:C(f),affected:C(h),self:this}}onDetachedDependencyRestored(i,r,a){const c=[],e=[],f=[],h=[];if(r==="property-implements-field"&&(this.addImplementation(i,a),c.push(this)),r==="property-extends-field"){const{updated:m,added:E,removed:b,affected:A}=this.restore({},a);c.push(...m),e.push(...E),f.push(...b),h.push(...A)}return{updated:C(c),added:C(e),removed:C(f),affected:C(h),self:this}}unsubscribeFromDependencies(){var i,r,a,c,e,f,h;return this.implements.forEach(m=>{this.project.getBuiltIn(m.id)||m.unsubscribeDependents([{entity:this,field:"property-implements-field"}])}),(r=(i=this.extends)==null?void 0:i.unsubscribeDependents)==null||r.call(i,[{entity:this,field:"property-extends-field"}]),(e=(c=(a=this.dataType)==null?void 0:a.entity)==null?void 0:c.unsubscribeDependents)==null||e.call(c,[{entity:this,field:"property-data-type-entity-field"}]),(h=(f=this.dataType)==null?void 0:f.unsubscribeDependents)==null||h.call(f,[{entity:this,field:"property-data-type-field"}]),this.project.off(di.PROJECT_INITIALIZED,this.onProjectInitialized),this}subscribeToDependencies(){var i,r,a,c,e,f,h;return this.implements.forEach(m=>{this.project.getBuiltIn(m.id)||m.subscribeDependents([{entity:this,field:"property-implements-field"}])}),(r=(i=this.extends)==null?void 0:i.subscribeDependents)==null||r.call(i,[{entity:this,field:"property-extends-field"}]),(e=(c=(a=this.dataType)==null?void 0:a.entity)==null?void 0:c.subscribeDependents)==null||e.call(c,[{entity:this,field:"property-data-type-entity-field"}]),(h=(f=this.dataType)==null?void 0:f.subscribeDependents)==null||h.call(f,[{entity:this,field:"property-data-type-field"}]),PVi(this)&&this.project.on(di.PROJECT_INITIALIZED,this.onProjectInitialized),this}increaseVersion(i){var r;if(this.project.diggestedBuiltInBaseEntitiesIds.has(this.id))return this;if(i&&!B(i).isValid())throw new Error(`The shared timestamp '${i}' is not a valid ISO 8601 date string.`);if(i&&B(i).isSame(B(this.createdAt)))return this;if(!((r=this.knownVersions)!=null&&r.has(this.version))&&this.project.initialized)throw new Error(`The current ${this.type} ${this.id} version '${this.version}' is not captured in the 'knownVersions' map. Capture the current version before increasing it to avoid losing data.`);if(!this.activeVersion)throw new Error(`Only active versions can be increased. Entity with id '${this.id}' and version '${this.version}' is not active.`);return this.previousVersion=this.version,this.version=x.UUID.uuid(),this.createdAt=B(i).toISOString()||B().toISOString(),this}captureVersion(){var r;const i=((r=this.knownVersions)==null?void 0:r.get(this.version))||new mi(this,this.project);if(!this.activeVersion)throw new Error(`Only active versions can be captured. Entity of type ${this.type} with id '${this.id}' and version '${this.version}' is not active.`);if(this.version!==i.version)throw new Error(`Captured ${this.type} with id '${this.id}', version '${i.version}' does not match current entity version '${this.version}'.`);return this.knownVersions=this.knownVersions?this.knownVersions.set(this.version,i):new Map().set(this.version,i),this.apply(i),this}snapshot(){const i=new mi(this,this.project);return this.apply(i)}apply(i){const r=this.toMeta();return i.metaSync(r,null),i.defaultValue=this.defaultValue,i.dataType=this.dataType,i.implements=[...this.implements],i.extends=this.extends,i.parent=this.parent,i}recursiveCaptureUpstreamVersions(i){const r=[],a=[],c=[],e=[];if(this.parent&&this.parent.type!==d.PrimitiveEntity&&this.parent.type!==d.BuiltInBaseEntity){this.parent.increaseVersion(i);const f=this.parent.recursiveCaptureUpstreamVersions(i);r.push(this.parent,...f.updated),a.push(...f.added),c.push(...f.removed)}return{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}async restoreVersion(i,r){var m;const a=[],c=[],e=[],f=[];if(this.version===i&&(r!=null&&r.skipIfSameVersion))return{updated:C(a),added:C(c),removed:C(e),affected:C(f),self:this};if(!this.knownVersions){const E=new Map;for(const[b,A]of this.knownVersions||new Map){if(E.set(b,A),A.activeVersion=!1,A.knownVersions)for(const[_,P]of A.knownVersions)E.set(_,P);A.knownVersions=null}}let h=(m=this.knownVersions)==null?void 0:m.get(i);if(!h){const E=await this.APILoadVersion({},i);if(!E)throw new Error(`Version with id '${i}' for entity with id '${this.id}' not found.`);h=new mi(E,this.project)}return this.metaSync(h.toShallowJSON(),null),this.previousVersion=h.previousVersion,this.version=h.version,this.createdAt=h.createdAt,this.author=h.author,this.deleted=h.deleted,this.defaultValue=h.defaultValue,this.dataType=h.dataType,this.implements=[...h.implements],this.parent=h.parent,{updated:C(a),added:C(c),removed:C(e),affected:C(f),self:this}}updateWithShallowTransfer(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.UpdateWithShallowTransfer))){if(!this.checkCanEdit(this,r))return z.Logger.warn(`[updateWithShallowTransfer] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.UpdateWithShallowTransfer,this.id),this;if(this.metaSync(i,r),this.version=i.version,this.createdAt=i.createdAt,this.author=i.author,this.deleted=i.deleted,this.previousVersion=i.previousVersion,this.unsubscribeFromDependencies(),i.parent){const c=te(i.parent),e=this.project.get(c),f=this.parent;if(f&&f.id!==(e==null?void 0:e.id)&&this.removeFromParent(r),e)this.setParent(e,r),this.addSelfToProject(r);else throw r==null||r.attemptAutoclose(w.UpdateWithShallowTransfer,this.id),new Error(`${this.type} with id '${this.id}' has a 'parent' reference '${c}' that isn't found in the project`)}else throw r==null||r.attemptAutoclose(w.UpdateWithShallowTransfer,this.id),new Error(`${this.type} with id '${this.id}' must have a 'parent'`);if(i.implements.forEach(c=>{const e=te(c),f=this.project.get(e);if(f)this.addImplementation(f,r);else throw new Error(`${fr(this.type)} with id '${this.id}' has a 'implements' reference "${e}" which is missing in the project`)}),this.implements.filter(c=>{const e=te(c);return!i.implements.find(f=>te(f)===e)}).forEach(c=>{this.removeImplementation(c,r)}),i.extends){const c=te(i.extends),e=this.project.get(c);if(e)this.setExtends(e,r);else if(c)throw new Error(`${fr(this.type)} with id '${this.id}' has a 'extends' reference "${c}" which is missing in the project`)}else this.setExtends(null,r);if(i.dataType){const c=te(i.dataType),e=this.project.get(c);e&&this.setDataType(e,r)}else this.setDataType(null,r);if(i.defaultValue){const c=te(i.defaultValue),e=this.project.get(c);e&&this.setDefaultValue(e,r)}else this.setDefaultValue(null,r);return this.captureVersion(),this.subscribeToDependencies(),r==null||r.attemptAutoclose(w.UpdateWithShallowTransfer,this.id),this}updateWithGenerationTarget(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.UpdateWithGenerationTarget))){var a;if(!this.checkCanEdit(this,r))return z.Logger.warn(`[updateWithGenerationTarget] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.UpdateWithGenerationTarget,this.id),this;if(this.metaSync(i,r),i.parent){const c=te(i.parent),e=this.project.get(c),f=this.parent;if(f&&f.id!==(e==null?void 0:e.id)&&this.removeFromParent(r),e)this.setParent(e,r),this.addSelfToProject(r);else throw r==null||r.attemptAutoclose(w.UpdateWithGenerationTarget,this.id),new Error(`${this.type} with id '${this.id}' has a 'parent' reference '${c}' that isn't found in the project`)}if((a=i.implements)==null||a.forEach(c=>{const e=te(c),f=this.project.get(e);if(f)this.addImplementation(f,r);else throw new Error(`${fr(this.type)} with id '${this.id}' has a 'implements' reference "${e}" which is missing in the project`)}),i.implements&&this.implements.filter(e=>{const f=te(e);return!(i.implements||[]).find(h=>te(h)===f)}).forEach(e=>{this.removeImplementation(e,r)}),i.extends){const c=te(i.extends),e=this.project.get(c);if(e)this.setExtends(e,r);else if(c)throw new Error(`${fr(this.type)} with id '${this.id}' has a 'extends' reference "${c}" which is missing in the project`)}else i.extends===null&&this.setExtends(null,r);return this.captureVersion(),this.subscribeToDependencies(),r==null||r.attemptAutoclose(w.UpdateWithGenerationTarget,this.id),this}hydrateAncestors(){const i=[],r=[],a=[],c=[];if(this.initialData.parent){const e=te(this.initialData.parent),f=this.project.get(e);if(f)this.setParent(f,null);else throw new Error(`${this.type} with id '${this.id}' has a 'parent' reference '${e}' that isn't found in the project`)}else throw new Error(`${this.type} with id '${this.id}' must have a 'parent'`);if((this.initialData.implements||[]).forEach(e=>{const f=te(e),h=this.project.get(f);if(h)this.addImplementation(h,null),i.push(h);else throw new Error(`${fr(this.type)} with id '${this.id}' has a 'implements' reference "${f}" which is missing in the project`)}),this.initialData.extends){const e=te(this.initialData.extends),f=this.project.get(e);if(f)this.setExtends(f,null),i.push(f);else if(e)throw new Error(`${fr(this.type)} with id '${this.id}' has a 'extends' reference "${e}" which is missing in the project`)}return{updated:C(i),added:C(r),removed:C(a),affected:C(c),self:this}}afterAllChildrenInitialized(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.AfterAllChildrenInitialized))){var K;if(!this.checkCanEdit(this,i))return z.Logger.warn(`[afterAllChildrenInitialized] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),i==null||i.attemptAutoclose(w.AfterAllChildrenInitialized,this.id),{updated:[],added:[],removed:[],affected:[],self:this};const r=[],a=[],c=[],e=[];if(this.initialized=!0,this.parent.type===d.DefinitionEntity&&this.parentRelationType!==Xd.AllPropertiesImplementationTarget){let ne=this.index||0;const X=this.parent.properties.filter(ie=>!ie.deleted&&ie.id!==this.id);X.length&&(ne>X.length+1?ne=X.length:ne<0&&(ne=0)),X.find(ie=>(ie.index||0)===ne&&!ie.deleted)&&X.filter(ie=>(ie.index||0)>=ne&&!ie.deleted).forEach(ie=>{ie.metaSync({index:(ie.index||0)+1},i),i==null||i.add(ie,W.Updated),r.push(ie)}),this.metaSync({index:ne},i)}if(this.defaultValue&&!this.project.diggestedBuiltInBaseEntitiesIds.has(this.id)&&this.project.diggestedBuiltInBaseEntitiesIds.has(this.defaultValue.id)){const ne=this.defaultValue.clone(i,this);this.setDefaultValue(ne,i)}const{updated:f,added:h,removed:m,affected:E}=this.syncWithImplementation(i);r.push(...f),a.push(...h),c.push(...m),e.push(...E);const{updated:b,added:A,removed:_,affected:P}=hF(this,i);r.push(...b),a.push(...A),c.push(..._),e.push(...P);const{updated:V,added:G,removed:M,affected:k}=this.syncWithExtension(i);return r.push(...V),a.push(...G),c.push(...M),e.push(...k),!this.project.diggestedBuiltInBaseEntitiesIds.has(this.id)&&this.project.initialized&&(this.extends&&((K=this.extends)==null?void 0:K.interactive)===!0&&(this.interactive||(this.metaSync({interactive:!0},i),r.push(this))),this.implements.every(ne=>ne.interactive===!0)&&(this.interactive||(this.metaSync({interactive:!0},i),r.push(this)))),i==null||i.attemptAutoclose(w.AfterAllChildrenInitialized,this.id),{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}addSelfToProject(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"add-self-to-project"))){const r=[this],a=[],c=[],e=[];return this.parentRelationType===Xd.AllPropertiesImplementationTarget?this.parent.setAllPropertiesImplement(this,i):this.parent.addProperty(this,i),r.push(this.parent),this.subscribe(),this.subscribeToDependencies(),i==null||i.attemptAutoclose("add-self-to-project",this.id),{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}setParent(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.SetParent))){var a;return this.checkCanEditWithCounterpartAndSideEffects(this,i,w.SetParent,r)?(((a=this.parent)==null?void 0:a.id)!==(i==null?void 0:i.id)&&(this.parent=i,r&&(r==null||r.add(this,W.Updated))),r==null||r.attemptAutoclose(w.SetParent,this.id),this):this}addImplementation(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.AddImplementation))){return this.checkCanEdit(this,r)?(this.implements.includes(i)||(this.implements.push(i),r==null||r.add(this,W.Updated)),r==null||r.attemptAutoclose(w.AddImplementation,this.id),this):(z.Logger.warn(`[addImplementation] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.AddImplementation,this.id),this)}removeImplementation(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.RemoveImplementation))){return this.checkCanEdit(this,r)?(this.implements.includes(i)&&(this.implements=this.implements.filter(a=>a.id!==i.id),r==null||r.add(this,W.Updated)),r==null||r.attemptAutoclose(w.RemoveImplementation,this.id),this):(z.Logger.warn(`[removeImplementation] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.RemoveImplementation,this.id),this)}setExtends(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.SetExtends))){var a;return this.checkCanEdit(this,r)?(((a=this.extends)==null?void 0:a.id)!==(i==null?void 0:i.id)&&(this.extends=i,this.subscribeToDependencies(),r&&(r==null||r.add(this,W.Updated))),r==null||r.attemptAutoclose(w.SetExtends,this.id),this):(z.Logger.warn(`[setExtends] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.SetExtends,this.id),this)}initChildren(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"init-children"))){if(this.initialized||this.startedInitialization)return this;if(this.startedInitialization=!0,this.initialData.defaultValue&&(this.defaultValue=Re(this.initialData.defaultValue,this.project),this.defaultValue.setParent(this,null),this.defaultValue.initChildren(i)),this.initialData.dataType){const r=Re(this.initialData.dataType,this.project);r.setParent(this,null),r.initChildren(i),this.dataType=r}if(this.implements=this.initialData.implements.map(r=>Re(r,this.project)),this.initialData.extends){const r=Re(this.initialData.extends,this.project);this.setExtends(r,null)}return this.subscribeToDependencies(),this.afterAllChildrenInitialized(i),i==null||i.attemptAutoclose("init-children",this.id),this}subscribe(){var i;return this.activeVersion=!0,(i=this.knownVersions)==null||i.forEach(r=>{r.version!==this.version&&(r.activeVersion=!1)}),this.project.subscribeInstance(this),this}unsubscribe(){return this.project.unsubscribeInstance(this),this}metaSync(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"meta-sync"))){const a=tn(this,i,r),c=en(this,a),e=this.toMeta();return this.name=a.name!==void 0?a.name:e.name,this.codeName=a.codeName!==void 0?a.codeName:e.codeName,this.description=a.description!==void 0?a.description:e.description,this.abstract=a.abstract!==void 0?a.abstract:e.abstract,this.private=a.private!==void 0?a.private:e.private,this.index=a.index||(a.index!==0?e.index:0),this.static=a.static!==void 0?a.static:e.static,this.hidden=a.hidden!==void 0?a.hidden:e.hidden,this.constant=a.constant!==void 0?a.constant:e.constant,this.interactive=a.interactive!==void 0?a.interactive:e.interactive,this.required=a.required!==void 0?a.required:e.required,this.unique=a.unique!==void 0?a.unique:e.unique,super.baseMetaSync(a,this,r),a.deleted===!0&&!e.deleted?r==null||r.add(this,W.Removed):a.deleted===!1&&e.deleted?r==null||r.add(this,W.Added):c&&(r==null||r.add(this,W.Updated)),r==null||r.attemptAutoclose("meta-sync",this.id),this}async APILoad(i=Ke,...r){return await mi.repository.APILoad(this.id,...r),this}async APICreate(i=Ke,...r){return await mi.repository.APICreate(this.toShallowJSON(),...r),this}async APIUpdate(i=Ke,...r){return await mi.repository.APIUpdate(this.toShallowJSON(),...r),this}async APIDelete(i=Ke,...r){return await mi.repository.APIDelete(this.toShallowJSON(),...r),this}async APIClone(i=Ke,...r){return await mi.repository.APIClone(this.id,...r),this}async APILoadVersion(i=Ke,r,...a){return await mi.repository.APILoadVersion(this.id,r,...a)}removeFromParent(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.RemoveFromParent))){if(!this.checkCanEdit(this,i))return z.Logger.warn(`[removeFromParent] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),i==null||i.attemptAutoclose(w.RemoveFromParent,this.id),{added:[],updated:[],removed:[],affected:[],self:this};const r=[],a=[],c=[],e=[];return this.parent.type===d.DefinitionEntity&&(this.parentRelationType===Xd.AllPropertiesImplementationTarget?this.parent.removeAllPropertiesImplement(i):this.parent.removeProperty(this,i),e.push(this.parent)),i==null||i.attemptAutoclose(w.RemoveFromParent,this.id),{added:C(c),updated:C(r),removed:C(a),affected:C(e),self:this}}remove({ignoreUpstream:i}={ignoreUpstream:!1},r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.RemoveEntity))){var h;if(!this.checkCanDelete(this,r))return z.Logger.warn(`[remove] User is not allowed to delete or edit this ${this.type} entity with id: ${this.id}`),r==null||r.event({id:`${w.RemoveEntity}-${this.id}--${Me.ActionOwnerEntityNonDeletable}`,action:w.RemoveEntity,owner:this,errorReason:Me.ActionOwnerEntityNonDeletable,rootAction:((h=r==null?void 0:r.self)==null?void 0:h.id)===this.id&&(r==null?void 0:r.actionName)===w.RemoveEntity}),r==null||r.attemptAutoclose(w.RemoveEntity,this.id),{added:[],updated:[],removed:[],affected:[],self:this};const a=[],c=[],e=[],f=[];if(r!=null&&r.hasRemoved(this.id))return r==null||r.attemptAutoclose(w.RemoveEntity,this.id),{added:[],updated:[],removed:[],affected:[],self:this};if(c.push(this),this.unsubscribe(),this.unsubscribeFromDependencies(),this.project.subscribeDeletedInstance(this),this.metaSync({deleted:!0},r),Object.values(this.detachedDependents).forEach(m=>{const{updated:E,removed:b,added:A}=m.entity.onDetachedDependencyRemoved(this,m.field,r);a.push(...E),c.push(...b),e.push(...A)}),this.defaultValue){const{updated:m,removed:E}=this.defaultValue.remove({ignoreUpstream:!0},r);a.push(...m),c.push(...E)}if(this.dataType){const{updated:m,removed:E}=this.dataType.remove({ignoreUpstream:!0},r);a.push(...m),c.push(...E)}if(!i){const m=this.removeFromParent(r);e.push(...m.added),a.push(...m.updated),c.push(...m.removed),f.push(...m.affected)}return r==null||r.attemptAutoclose(w.RemoveEntity,this.id),{added:C(e),updated:C(a),removed:C(c),affected:C(f),self:this}}restore({}={},i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.RestoreEntity))){if(!this.checkCanEdit(this,i))return z.Logger.warn(`[restore] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),i==null||i.attemptAutoclose(w.RestoreEntity,this.id),{added:[],updated:[],removed:[],affected:[],self:this};const r=[],a=[],c=[],e=[];if(i!=null&&i.hasAdded(this.id))return i==null||i.attemptAutoclose(w.RestoreEntity,this.id),{added:[],updated:[],removed:[],affected:[],self:this};if(this.subscribe(),this.project.unsubscribeDeletedInstance(this),this.metaSync({deleted:!1},i),Object.values(this.detachedDependents).forEach(f=>{const{updated:h,removed:m,added:E}=f.entity.onDetachedDependencyRestored(this,f.field,i);a.push(...h),c.push(...m),r.push(...E)}),this.defaultValue){const{updated:f}=this.defaultValue.restore({},i);a.push(...f)}if(this.dataType){const{updated:f}=this.dataType.restore({},i);a.push(...f)}return this.parent.type===d.DefinitionEntity&&(this.parentRelationType===Xd.AllPropertiesImplementationTarget?this.parent.removeAllPropertiesImplement(i):this.parent.addProperty(this,i),e.push(this.parent)),i==null||i.attemptAutoclose(w.RestoreEntity,this.id),{added:C(r),updated:C(a),removed:C(c),affected:C(e),self:this}}toFlat(i=new Set){var a,c;return i.has(this.id)?[]:(i.add(this.id),[this,...((a=this.defaultValue)==null?void 0:a.toFlat(i))||[],...((c=this.dataType)==null?void 0:c.toFlat(i))||[],...this.parent.toFlat(i)])}toFlatIds(i=new Set){var a,c;if(i.has(this.id))return[];if(i.add(this.id),!this.parent)throw new Error(`Property with id '${this.id}' has no parent and cannot be flattened`);return[this.id,...((a=this.defaultValue)==null?void 0:a.toFlatIds(i))||[],...((c=this.dataType)==null?void 0:c.toFlatIds(i))||[],...this.parent.toFlatIds(i)]}toMeta(){return{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,codeName:this.codeName,description:this.description,index:this.index,hidden:this.hidden,private:this.private,abstract:this.abstract,required:this.required,unique:this.unique,constant:this.constant,interactive:this.interactive,static:this.static,type:this.type,editable:this.editable,deletable:this.deletable,name:this.name}}toJSON(i=new Set){var r,a,c;return i.has(this.id)?this.toReference():(i.add(this.id),{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,editable:this.editable,deletable:this.deletable,name:this.name,codeName:this.codeName,description:this.description,index:this.index,private:this.private,unique:this.unique,required:this.required,static:this.static,constant:this.constant,interactive:this.interactive,abstract:this.abstract,hidden:this.hidden,parentRelationType:this.parentRelationType,defaultValue:((r=this.defaultValue)==null?void 0:r.toJSON(i))||null,dataType:((a=this.dataType)==null?void 0:a.toJSON(i))||null,implements:this.implements.map(e=>e.toJSON(i)),extends:((c=this.extends)==null?void 0:c.toJSON(i))||null,parent:this.parent.toReference()})}toJSONClone(i=at){var a,c,e,f,h,m,E;let r;return(a=i.seenEntityMaps)!=null&&a.has(this.id)?r=i.seenEntityMaps.get(this.id):(r=i.newId||dn(this,this.project,i.uuidStrategy),i.seenEntityMaps&&i.seenEntityMaps.set(this.id,r)),(c=i.seenEntities)!=null&&c.has(r)||(e=i.seenEntities)!=null&&e.has(this.id)?this.toReference({seenEntityMaps:i.seenEntityMaps}):((f=i.seenEntities)==null||f.add(r),(h=i.seenEntities)==null||h.add(this.id),{id:r,version:x.UUID.uuid(),createdAt:i.timestamp||B().toISOString(),author:x.sessionAuthor,previousVersion:null,deleted:!1,type:this.type,editable:this.editable,deletable:this.deletable,name:this.name,codeName:this.codeName,description:this.description,index:this.index,unique:this.unique,private:this.private,required:this.required,static:this.static,constant:this.constant,interactive:this.interactive,abstract:this.abstract,hidden:this.hidden,parentRelationType:this.parentRelationType,defaultValue:((m=this.defaultValue)==null?void 0:m.toJSONClone({...i,newId:null}))||null,dataType:((E=this.dataType)==null?void 0:E.toJSONClone({...i,newId:null}))||null,implements:this.implements.map(b=>this.project.getBuiltIn(b.id)?b.toJSON(i.seenEntities):b.toJSONClone({...i,newId:null})),extends:(()=>{var b;return this.extends&&this.project.getBuiltIn(this.extends.id)?this.extends.toJSON():((b=this.extends)==null?void 0:b.toJSONClone({...i,newId:null}))||null})(),parent:this.parent.toReference({seenEntityMaps:i.seenEntityMaps})})}toReference(i=at){var a;let r=this.id;return(a=i.seenEntityMaps)!=null&&a.has(this.id)&&(r=i.seenEntityMaps.get(this.id)),{id:r+"--"+x.UUID.uuid()+"--ref",type:d.GenericReference,entityId:r,version:this.version,entityType:this.type}}toShallowJSON(i=at){var a,c,e,f;let r=this.id;return(a=i.seenEntityMaps)!=null&&a.has(this.id)&&(r=i.seenEntityMaps.get(this.id)),{id:r,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,name:this.name,codeName:this.codeName,description:this.description,type:this.type,editable:this.editable,deletable:this.deletable,index:this.index,private:this.private,required:this.required,unique:this.unique,abstract:this.abstract,static:this.static,constant:this.constant,interactive:this.interactive,hidden:this.hidden,parentRelationType:this.parentRelationType,defaultValue:((c=this.defaultValue)==null?void 0:c.toReference(i))||null,dataType:((e=this.dataType)==null?void 0:e.toReference(i))||null,implements:this.implements.map(h=>h.toReference(i)),extends:((f=this.extends)==null?void 0:f.toReference(i))||null,parent:this.parent.toReference(i)}}toFlatJSON(i=new Set){var a,c;return i.has(this.id)?[]:(i.add(this.id),[this.toShallowJSON(),...((a=this.defaultValue)==null?void 0:a.toFlatJSON(i))||[],...((c=this.dataType)==null?void 0:c.toFlatJSON(i))||[],...this.implements.flatMap(e=>e.toFlatJSON(i)),...this.parent.toFlatJSON(i)])}toGenerationTarget(i=at){var a,c;let r=this.id;return(a=i.seenEntityMaps)!=null&&a.has(this.id)&&(r=i.seenEntityMaps.get(this.id)),{id:r,name:this.name,description:this.description,type:this.type,private:this.private,required:this.required,abstract:this.abstract,static:this.static,parentRelationType:this.parentRelationType,implements:this.implements.map(e=>e.id),extends:(c=this.extends)==null?void 0:c.id,parent:this.parent.id}}toFlatGenerationTarget(i=new Set){var a,c;return i.has(this.id)?[]:(i.add(this.id),[this.toGenerationTarget(),...((a=this.defaultValue)==null?void 0:a.toFlatGenerationTarget(i))||[],...((c=this.dataType)==null?void 0:c.toFlatGenerationTarget(i))||[],...this.implements.flatMap(e=>e.toFlatGenerationTarget(i))])}clearErrors(){var i,r;return this.errors=[],(i=this.defaultValue)==null||i.clearErrors(),(r=this.dataType)==null||r.clearErrors(),this}validate(){return this.errors=Zje(this),{success:!0}}async validateAsync(i={}){const r=z.YieldTracker.from(i);return this.errors=await Sje(this,{tracker:r}),{success:!0}}getErrors(){var r,a;return[...this.errors,...((r=this.defaultValue)==null?void 0:r.getErrors())||[],...((a=this.dataType)==null?void 0:a.getErrors())||[]]}async getErrorsAsync(i={}){const r=z.YieldTracker.from(i),a=[...this.errors];if(await r.tick(),this.defaultValue){const c=await this.defaultValue.getErrorsAsync({tracker:r});a.push(...c)}if(this.dataType){const c=await this.dataType.getErrorsAsync({tracker:r});a.push(...c)}return a}getShallowErrors(){return this.errors}implement(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"implement-self-as-property")),a=null){var E,b,A;const c=a||x.UUID.uuid(),e=mi.new(r);e.id=c,e.name=this.name,e.description=this.description,e.index=this.index,e.private=this.private,e.required=this.required,e.static=this.static,e.constant=this.constant,e.unique=this.unique,e.hidden=this.hidden,e.interactive=this.interactive,e.parent=i.toReference(),e.implements=[this.toJSON()];const f=Re(e,this.project);f.hydrateAncestors(),f.addSelfToProject(r),r==null||r.add(f,W.Added),f.initChildren(r);const h=(E=this.defaultValue)==null?void 0:E.clone(r,f,x.UUID.uuid());h&&(h.editable=!0,h.deletable=!0);const m=yF(this);if(m.result){let _=!1;if(!f.defaultValue){const P=Lr.new(r);P.value=m.value,P.name=m.name,P.parent=f.toReference();const V=Re(P,this.project);V.hydrateAncestors(),V.addSelfToProject(r),V.initChildren(r),f.setDefaultValue(V,r),_=!0}(b=this.defaultValue)==null||b.metaSync({value:m.value},r),_&&(r||(A=this.defaultValue)==null||A.captureVersion())}return r||f.captureVersion(),f}clone(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.CloneEntity)),r=null,a=null,c=!0){var b,A;const e=Fr(r,this),f=a||x.UUID.uuid(),h=r||this.parent,m={hidden:!1,id:f,version:x.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||B().toISOString(),author:(i==null?void 0:i.author)||"1",previousVersion:null,deleted:!1,type:this.type,editable:!0,deletable:!0,name:this.name,codeName:this.codeName,description:this.description,index:this.index,private:this.private,constant:this.constant,unique:this.unique,interactive:this.interactive,required:this.required,abstract:this.abstract,static:this.static,parentRelationType:this.parentRelationType,defaultValue:null,dataType:null,implements:this.implements.map(_=>_.toJSON()),extends:this.extends,parent:h.toReference()},E=lr(m,e);if(E.hydrateAncestors(),E.setParent(h,i),c&&(E.subscribe(),E.addSelfToProject(i)),E.initChildren(i),i==null||i.add(E,W.Added),this.dataType&&this.project.diggestedBuiltInBaseEntitiesIds.has(this.dataType.id))E.setDataType(e.getBuiltIn(this.dataType.id),i);else{const _=((b=this.dataType)==null?void 0:b.implement(E,i,x.UUID.uuid()))||null;_&&E.setDataType(_,i)}if(this.defaultValue){const _=(A=this.defaultValue)==null?void 0:A.clone(i,E,x.UUID.uuid(),c);E.setDefaultValue(_||null,i)}return this.implements.length&&this.implements.forEach(_=>{const P=e.get(_.id)||e.getBuiltIn(_.id);if(P){E.addImplementation(P,i);return}}),E.addSelfToProject(null),i||E.captureVersion(),i==null||i.attemptAutoclose(w.CloneEntity,this.id),E}setDataType(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.SetDataType))){if(!this.checkCanEdit(this,r))return z.Logger.warn(`[setDataType] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.SetDataType,this.id),this;const a=this.dataType;return(a==null?void 0:a.id)!==(i==null?void 0:i.id)&&(a==null||a.remove({ignoreUpstream:!0},r),this.dataType=i,this.subscribeToDependencies(),r==null||r.add(this,W.Affected)),r==null||r.attemptAutoclose(w.SetDataType,this.id),this}removeDataType(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.RemoveDataType))){return this.checkCanEdit(this,i)?(this.dataType&&(this.dataType.remove({ignoreUpstream:!0},i),i==null||i.add(this,W.Affected),this.dataType=null),i==null||i.attemptAutoclose(w.RemoveDataType,this.id),this):(z.Logger.warn(`[removeDataType] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),i==null||i.attemptAutoclose(w.RemoveDataType,this.id),this)}getDataType(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"get-data-type"))){return i==null||i.attemptAutoclose("get-data-type",this.id),this.dataType}getDefaultValue(){var c;let i=null;for(const e of this.implements){const f=e.getDefaultValue();(!i||Vn(i))&&f&&(i=f)}let r=this.defaultValue;const a=(c=this.extends)==null?void 0:c.getDefaultValue();return Vn(r)&&a&&!Vn(a)&&(r=a),Vn(r)&&i&&!Vn(i)&&(r=i),r}setDefaultValue(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"set-default-value"))){if(!this.checkCanEdit(this,r))return z.Logger.warn(`[setDefaultValue] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose("set-default-value",this.id),this;const a=this.defaultValue;return(a==null?void 0:a.id)!==(i==null?void 0:i.id)&&(a==null||a.remove({ignoreUpstream:!0},r),this.defaultValue=i,r==null||r.add(this,W.Affected)),r==null||r.attemptAutoclose("set-default-value",this.id),this}syncWithImplementation(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"sync-with-implementation"))){var _,P,V,G;if(!this.checkCanEdit(this,i))return z.Logger.warn(`[syncWithImplementation] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),i==null||i.attemptAutoclose("sync-with-implementation",this.id),{added:[],updated:[],removed:[],affected:[],self:this};const r=[],a=[],c=[],e=[];this.parent.type!==d.PrimitiveEntity&&this.interactive&&this.parent.getAllPropertiesImplements().filter(k=>k.id!==this.id).forEach(k=>{this.addImplementation(k,i)}),this.implements.find(M=>M.id===this.id)&&this.removeImplementation(this,i);let f=null,h=this.implements.filter(M=>{var X;if(!M.dataType||!((X=M.dataType)!=null&&X.isResolved))return!1;const k=this.implements.filter(de=>de.id!==M.id);if(!k.length)return!0;const K=vl(Sa(M.dataType),{removeDuplicates:!0,removeNulls:!0}).filter(de=>de.isResolved);return!!k.every(de=>!de.dataType||!de.dataType.isResolved?!0:vl(Sa(de.dataType),{removeDuplicates:!0,removeNulls:!0}).filter(le=>le.isResolved).length>K.length)});if(h.length>1&&this.parent.type!==d.PrimitiveEntity){const M=this.parent.getAllPropertiesImplements()[0]||null;h=h.filter(k=>k.id!==(M==null?void 0:M.id))}if(!h.length&&this.parent.type!==d.PrimitiveEntity){const M=this.parent.getAllPropertiesImplements()[0]||null;M&&h.push(M)}for(const M of h)(_=M.dataType)!=null&&_.isResolved&&(f?((P=M.dataType.orChildrenGroup)!=null&&P.length&&M.dataType.implementationChooseOne||(V=M.dataType.orChildrenGroup)!=null&&V.length&&!M.dataType.implementationChooseOne)&&(f=M.dataType):f=M.dataType);if(f||this.parent.type!==d.PrimitiveEntity&&this.parent.additionalPropertiesDataType&&(f=this.parent.additionalPropertiesDataType),f&&!this.dataType){const M=f.implement(this,i,x.UUID.uuid());this.setDataType(M,i),a.push(M)}if((G=this.dataType)==null||G.merge(f,i,{implementSource:!0}),!this.defaultValue){let M=null;for(const k of this.implements){const K=k.getDefaultValue();K&&(M=K)}if(M){const k=M.clone(i,this,x.UUID.uuid(),!0);this.setDefaultValue(k,i),a.push(k)}}if(!this.defaultValue){const M=yF(this);if(M.result){const k=Lr.new(i);k.name=M.name,k.value=M.value,k.parent=this.toReference();const K=Re(k,this.project);K.hydrateAncestors(),K.addSelfToProject(i),K.initChildren(i),i==null||i.add(K,W.Added),i||K.captureVersion(),this.setDefaultValue(K,i),a.push(K)}}let m=!1,E=!1,b=!1,A=!1;return this.implements.forEach(M=>{M.required&&(m=!0),M.constant&&(b=!0),M.unique&&(E=!0),M.static&&(A=!0)}),this.metaSync({required:m||this.required,constant:b||this.constant,unique:E||this.unique,static:A||this.static},i),i==null||i.attemptAutoclose("sync-with-implementation",this.id),{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}syncWithExtension(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"sync-with-extension"))){var E,b,A;if(!this.checkCanEdit(this,i))return z.Logger.warn(`[syncWithExtension] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),i==null||i.attemptAutoclose("sync-with-extension",this.id),{added:[],updated:[],removed:[],affected:[],self:this};const r=[],a=[],c=[],e=[];if(!this.extends)return i==null||i.attemptAutoclose("sync-with-extension",this.id),{added:[],updated:[],removed:[],affected:[],self:this};const f={...this.extends.toMeta()};if(delete f.id,delete f.version,delete f.createdAt,delete f.previousVersion,delete f.author,delete f.index,this.metaSync(f,i),r.push(this),!this.extends.dataType)return i==null||i.attemptAutoclose("sync-with-extension",this.id),{added:[],updated:[],removed:[],affected:[],self:this};let h=!1;if(!this.dataType){const _=vr.new(i);_.parent=this.toReference();const P=Re(_,this.project);P.hydrateAncestors(),P.addSelfToProject(i),i==null||i.add(P,W.Added),P.afterAllChildrenInitialized(i),h=!0}const m=ni(this.dataType,this.extends.dataType);if((!m.compatible||!m.exact)&&((E=this.dataType)==null||E.merge(this.extends.dataType,i)),h&&(i||(b=this.dataType)==null||b.captureVersion()),this.extends.defaultValue&&!this.defaultValue){const _=this.extends.defaultValue.clone(i,this,x.UUID.uuid(),!0);this.setDefaultValue(_,i),a.push(_)}else this.extends.defaultValue?this.extends.defaultValue&&this.defaultValue&&!VFe(this.defaultValue,this.extends.defaultValue)&&(this.defaultValue.merge(this.extends.defaultValue,i),r.push(this.defaultValue)):((A=this.defaultValue)==null||A.remove({ignoreUpstream:!0},i),this.defaultValue=null,e.push(this));return i==null||i.attemptAutoclose("sync-with-extension",this.id),{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}implementAsInputMap(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"implement-as-input-map")),r,a){const c=Ts.new(i);c.id=a||c.id,c.name=this.name,c.description=this.description,c.parent=r.toReference(),c.declaration=this.toJSON();const e=lr(c,this.project);if(e.hydrateAncestors(),e.addSelfToProject(i),i==null||i.add(e,W.Added),e.initChildren(i),this.dataType)if(this.project.diggestedBuiltInBaseEntitiesIds.has(this.dataType.id))e.setDataType(this.dataType,i),i==null||i.add(e,W.Affected);else{const f=this.dataType.clone(i,e);e.setDataType(f,i)}if(this.defaultValue){const f=this.defaultValue.clone(i,e);e.setDefaultValue(f,i)}return i||e.captureVersion(),i==null||i.attemptAutoclose("implement-as-input-map",this.id),e}};R(mi,"repository",{APICreate:async(i,...r)=>i,APIUpdate:async(i,...r)=>i,APIDelete:async(i,...r)=>i,APIClone:async(i,...r)=>{},APILoad:async(i,...r)=>null,APILoadVersion:async(i,r,...a)=>null}),R(mi,"type",d.Property),R(mi,"USER_MANAGED_PARENT_TYPES",[d.DefinitionEntity]),R(mi,"PARENT_TYPES",[...mi.USER_MANAGED_PARENT_TYPES,d.PrimitiveEntity,d.BuiltInBaseEntity]),R(mi,"MUTABLE_BASE_PROPERTIES",["name","codeName","description","private","abstract","static","required","constant","unique","interactive"]),R(mi,"INMUTABLE_BASE_PROPERTIES",["id","type","version","createdAt","author","previousVersion","parentRelationType"]),R(mi,"BASE_PROPERTIES",[...mi.MUTABLE_BASE_PROPERTIES,...mi.INMUTABLE_BASE_PROPERTIES]),R(mi,"MUTABLE_META_PROPERTIES",[...mi.MUTABLE_BASE_PROPERTIES,"index"]),R(mi,"INMUTABLE_META_PROPERTIES",[...mi.INMUTABLE_BASE_PROPERTIES]),R(mi,"META_PROPERTIES",[...mi.MUTABLE_META_PROPERTIES,...mi.INMUTABLE_META_PROPERTIES]),R(mi,"MUTABLE_UPSTREAM_PROPERTIES",[]),R(mi,"INMUTABLE_UPSTREAM_PROPERTIES",["parent","implements","extends"]),R(mi,"UPSTREAM_PROPERTIES",[...mi.MUTABLE_UPSTREAM_PROPERTIES,...mi.INMUTABLE_UPSTREAM_PROPERTIES]),R(mi,"MUTABLE_DOWNSTREAM_PROPERTIES",["dataType","defaultValue"]),R(mi,"INMUTABLE_DOWNSTREAM_PROPERTIES",[]),R(mi,"DOWNSTREAM_PROPERTIES",[...mi.MUTABLE_DOWNSTREAM_PROPERTIES,...mi.INMUTABLE_DOWNSTREAM_PROPERTIES]),R(mi,"PROPERTIES",[...mi.META_PROPERTIES,...mi.UPSTREAM_PROPERTIES,...mi.DOWNSTREAM_PROPERTIES]);let Es=mi;async function Wje(s,p={}){var E,b;const i=z.YieldTracker.from(p),r=s.implements.flatMap(A=>Qje(s,A)),a=Xje(s,s.extends),c=tUe(s),e=eUe(s),f=gL(s),h=[...r,...a,...c,...e,...f],m=qt(s.errors,h);await i.tick();for(const A of s.properties)await A.validateAsync({tracker:i});for(const A of s.methods)await A.validateAsync({tracker:i});for(const A of s.abstractMethods)await A.validateAsync({tracker:i});return await((E=s.allPropertiesImplement)==null?void 0:E.validateAsync({tracker:i})),await((b=s.additionalPropertiesDataType)==null?void 0:b.validateAsync({tracker:i})),m}function zje(s){var h,m;const p=s.implements.flatMap(E=>Qje(s,E)),i=Xje(s,s.extends),r=tUe(s),a=eUe(s),c=gL(s);s.properties.forEach(E=>{E.validate()}),s.methods.flatMap(E=>E.validate()),s.abstractMethods.flatMap(E=>E.validate()),(h=s.allPropertiesImplement)==null||h.validate(),(m=s.additionalPropertiesDataType)==null||m.validate();const e=[...p,...i,...r,...a,...c];return qt(s.errors,e)}function Yje(s,p){const i=p.properties.filter(c=>c.abstract),r=[];let a=[...s.properties];return i.forEach(c=>{const e=a.find(f=>!!f.implements.find(h=>h.id===c.id));e?a=a.filter(f=>f.id!==e.id):r.push(c)}),r}function Jje(s,p){const i=p.abstractMethods,r=[];let a=[...s.methods];return i.forEach(c=>{const e=a.find(f=>{var h;return((h=f.implements)==null?void 0:h.id)===c.id});e?a=a.filter(f=>f.id!==e.id):r.push(c)}),r}function Qje(s,p){const i=[];if(!p.abstract){const E=It({id:s.id+"--"+Ae.ImplementingNonAbstractEntity,message:`Entity "${s.name}" with id "${s.id}" is implementing a non-abstract entity "${p.name}" with id "${p.id}"`,severity:ve.Error,code:Ae.ImplementingNonAbstractEntity,entity:s});return i.push(E.error),i}const r=p.properties.filter(E=>E.abstract),a=[];let c=[...s.properties];r.forEach(E=>{const b=c.find(A=>!!A.implements.find(_=>_.id===E.id));b?c=c.filter(A=>A.id!==b.id):a.push(E)}),a.length&&a.forEach(E=>{const b=It({id:s.id+"--"+Ae.MissingPropertyImplementation+"--"+E.id,message:`Property "${E.name}" with id "${E.id}" of entity "${p.name}" with id "${p.id}" is not implemented when entity "${s.name}" with id "${s.id}" implements it`,severity:ve.Error,code:Ae.MissingPropertyImplementation,entity:s});i.push(b.error)});const e=[];let f=[...s.methods];p.abstractMethods.forEach(E=>{const b=f.find(A=>{var _;return((_=A.implements)==null?void 0:_.id)===E.id});b?f=f.filter(A=>A.id!==b.id):e.push(E)}),e.length&&e.forEach(E=>{const b=It({id:s.id+"--"+Ae.MissingMethodImplementation+"--"+E.id,message:`Method "${E.name}" with id "${E.id}" of entity "${p.name}" with id "${p.id}" is not implemented when entity "${s.name}" with id "${s.id}" implements it`,severity:ve.Error,code:Ae.MissingMethodImplementation,entity:s});i.push(b.error)});const h=[];p.properties.forEach(E=>{const b=c.find(A=>A.name===E.name);b&&h.push([b,E])}),h.length&&h.forEach(([E])=>{const b=It({id:s.id+"--"+Ce.PropertyOverwritesOtherSiblingWithSameName+"--"+E.id,message:`Property "${E.name}" with id "${E.id}" of entity "${s.name}" with id "${s.id}" overwrites the property with the same name from the base entity "${p.name}" with id "${p.id}"`,severity:ve.Error,code:Ce.PropertyOverwritesOtherSiblingWithSameName,entity:s});i.push(b.error)});const m=[];return p.methods.forEach(E=>{const b=f.find(A=>A.name===E.name);b&&m.push([b,E])}),m.length&&m.forEach(([E])=>{const b=It({id:s.id+"--"+Ce.MethodOverwritesOtherSiblingWithSameName+"--"+E.id,message:`Method "${E.name}" with id "${E.id}" of entity "${s.name}" with id "${s.id}" overwrites the method with the same name from the base entity "${p.name}" with id "${p.id}"`,severity:ve.Error,code:Ce.MethodOverwritesOtherSiblingWithSameName,entity:s});i.push(b.error)}),i}function Xje(s,p){const i=[];if(!p)return i;const r=[];if(!s.abstract&&p.abstract){const c=It({id:s.id+"--"+p.id+"--"+Ae.NonAbstractExtendingAbstractEntity,message:`Entity "${s.name}" with id "${s.id}" is not-abstract but is extending an abstract entity "${p.name}" with id "${p.id}"`,severity:ve.Error,code:Ae.NonAbstractExtendingAbstractEntity,entity:s,firstRelationship:p});return i.push(c.error),i}if(s.abstract&&!p.abstract){const c=It({id:s.id+"--"+p.id+"--"+Ae.AbstractExtendingNonAbstractEntity,message:`Entity "${s.name}" with id "${s.id}" is abstract but is extending an non-abstract entity "${p.name}" with id "${p.id}"`,severity:ve.Error,code:Ae.AbstractExtendingNonAbstractEntity,entity:s,firstRelationship:p});return i.push(c.error),i}s.properties.forEach(c=>{const e=p.properties.find(f=>{var h;return f.name===c.name&&((h=c.extends)==null?void 0:h.id)!==f.id});c.implements.find(f=>f.id===(e==null?void 0:e.id))||e&&r.push(c)}),r.length&&r.forEach(c=>{const e=It({id:s.id+"--"+Ce.PropertyOverwritesOtherSiblingWithSameName,message:`Property "${c.name}" with id "${c.id}" of entity "${s.name}" with id "${s.id}" overwrites the property with the same name from the extended entity "${p.name}" with id "${p.id}"`,severity:ve.Error,code:Ce.PropertyOverwritesOtherSiblingWithSameName,entity:s});i.push(e.error)});const a=[];return s.methods.forEach(c=>{var f;const e=p.methods.find(h=>{var m;return h.name===c.name&&((m=c.extends)==null?void 0:m.id)!==h.id});((f=c.implements)==null?void 0:f.id)!==(e==null?void 0:e.id)&&e&&a.push(c)}),a.length&&a.forEach(c=>{const e=It({id:s.id+"--"+Ce.MethodOverwritesOtherSiblingWithSameName,message:`Method "${c.name}" with id "${c.id}" of entity "${s.name}" with id "${s.id}" overwrites the method with the same name from the extended entity "${p.name}" with id "${p.id}"`,severity:ve.Error,code:Ce.MethodOverwritesOtherSiblingWithSameName,entity:s});i.push(e.error)}),i}function eUe(s){const p=[];if(!s.properties.length){const i=It({id:s.id+"--"+Ae.NoProperties,message:"No properties implemented",severity:ve.Warning,code:Ae.NoProperties,entity:s});p.push(i.error)}return p}function tUe(s){const p=[];if(s.abstract){if(s.methods.length){const i=It({id:s.id+"--"+Ae.AbstractEntityWithNonAbstractMethods,message:`Entity "${s.name}" with id "${s.id}" is marked as abstract but has non-abstract methods`,severity:ve.Error,code:Ae.AbstractEntityWithNonAbstractMethods,entity:s});p.push(i.error)}if(s.properties.some(i=>!i.abstract)){const i=It({id:s.id+"--"+Ae.AbstractEntityWithNonAbstractProperties,message:`Entity "${s.name}" with id "${s.id}" is marked as abstract but has non-abstract properties`,severity:ve.Error,code:Ae.AbstractEntityWithNonAbstractProperties,entity:s});p.push(i.error),s.properties.forEach(r=>{if(!r.abstract){const a=It({id:s.id+"--"+Ae.StaticEntityWithNonStaticProperties+"--"+r.id,message:`Property "${r.name}" with id "${r.id}" of entity "${s.name}" with id "${s.id}" is not marked as abstract but the entity is marked as abstract`,severity:ve.Error,code:Ae.StaticEntityWithNonStaticProperties,entity:s});p.push(a.error)}})}}else{if(s.abstractMethods.length){const i=It({id:s.id+"--"+Ae.AbstractPropertyInNonAbstractEntity,message:`Entity "${s.name}" with id "${s.id}" is not marked as abstract but has abstract methods`,severity:ve.Error,code:Ae.AbstractPropertyInNonAbstractEntity,entity:s});p.push(i.error)}s.properties.some(i=>i.abstract)&&s.properties.forEach(i=>{if(i.abstract){const r=It({id:s.id+"--"+Ae.AbstractPropertyInNonAbstractEntity+"--"+i.id,message:`Property "${i.name}" with id "${i.id}" of entity "${s.name}" with id "${s.id}" is marked as abstract but the entity is not marked as abstract`,severity:ve.Error,code:Ae.AbstractPropertyInNonAbstractEntity,entity:s,firstRelationship:i});p.push(r.error)}})}return s.static&&s.properties.some(i=>!i.static)&&s.properties.forEach(i=>{if(!i.static){const r=It({id:s.id+"--"+Ae.NonStaticPropertyInStaticEntity+"--"+i.id,message:`Property "${i.name}" with id "${i.id}" of entity "${s.name}" with id "${s.id}" is not marked as static but the entity is marked as static`,severity:ve.Error,code:Ae.NonStaticPropertyInStaticEntity,entity:s,firstRelationship:i});p.push(r.error)}}),p}function NVi(s,p){const i=[],r=ea(p);if(!p.abstract){const e=new qi({id:s.id+"--"+p.id+"--"+Ae.ImplementingNonAbstractEntity,message:`Entity "${s.name}" with id "${s.id}" is implementing a non-abstract built-in entity "${p.name}" with id "${p.id}"`,severity:ve.Error,code:Ae.ImplementingNonAbstractEntity,entity:s,firstRelationship:p});i.push(e)}const a=s.implements.filter(e=>e.id!==p.id);if(s.abstract){const e=new qi({id:s.id+"--"+p.id+"--"+Ae.AbstractEntityImplements,message:`Entity "${s.name}" with id "${s.id}" is marked as abstract and cannot implement built-in entity "${p.name}" with id "${p.id}"`,severity:ve.Error,code:Ae.AbstractEntityImplements,entity:s,firstRelationship:p});i.push(e)}if(s.static&&!p.static){const e=new qi({id:s.id+"--"+p.id+"--"+Ae.StaticImplementingNonStaticEntity,message:`Entity "${s.name}" with id "${s.id}" is marked as static and cannot implement non-static built-in entity "${p.name}" with id "${p.id}"`,severity:ve.Error,code:Ae.StaticImplementingNonStaticEntity,entity:s,firstRelationship:p});i.push(e)}if(!s.static&&p.static){const e=new qi({id:s.id+"--"+p.id+"--"+Ae.NonStaticImplementingStaticEntity,message:`Entity "${s.name}" with id "${s.id}" is not marked as static and cannot implement static built-in entity "${p.name}" with id "${p.id}"`,severity:ve.Error,code:Ae.NonStaticImplementingStaticEntity,entity:s,firstRelationship:p});i.push(e)}return a.length&&a.forEach(e=>{if(e.type===d.BuiltInBaseEntity){const f=r.filter(h=>h.id!==e.id);f.length&&f.forEach(h=>{if(h.id!==e.id){const m=new qi({id:s.id+"--"+h.id+"--"+e.id+"--"+Ae.ImplementsIncompatibleEntities,message:`Entity "${s.name}" with id "${s.id}" is implementing built-in entity "${h.name}" with id "${h.id}" but also implements entity "${e.name}" with id "${e.id}" which is incompatible`,severity:ve.Error,code:Ae.ImplementsIncompatibleEntities,entity:s,firstRelationship:h,secondRelationship:e});i.push(m)}})}else{ea(e).forEach(E=>{const b=r.filter(A=>A.id!==E.id);b.length&&b.forEach(A=>{if(A.id!==E.id){const _=new qi({id:s.id+"--"+A.id+"--"+E.id+"--"+Ae.ImplementsIncompatibleEntities,message:`Entity "${s.name}" with id "${s.id}" is implementing built-in entity "${A.name}" with id "${A.id}" but also implements entity "${E.name}" with id "${E.id}" which is incompatible`,severity:ve.Error,code:Ae.ImplementsIncompatibleEntities,entity:s,firstRelationship:A,secondRelationship:E});i.push(_)}})});const h=Jd(p.ownDeclaredProperties,e.ownDeclaredProperties,Ce.PropertyOverwritesOtherImplementedEntitysPropertyWithSameImplementation,Ce.PropertyOverwritesOtherImplementedEntitysPropertyWithSameName);i.push(...h.errors);const m=Jd(p.abstractMethods,[...e.abstractMethods,...e.methods],Ce.MethodOverwritesOtherImplementedEntitysMethodWithSameImplementation,Ce.MethodOverwritesOtherImplementedEntitysMethodWithSameName);i.push(...m.errors)}}),C(s.extends?ea(s.extends):[]).forEach(e=>{if(!r.find(f=>f.id===e.id)){const f=new qi({id:s.id+"--"+p.id+"--"+e.id+"--"+Ae.ExtendsIncompatibleEntities,message:`Entity "${s.name}" with id "${s.id}" is implementing built-in entity "${p.name}" with id "${p.id}" but also extends entity "${e.name}" with id "${e.id}" which is incompatible`,severity:ve.Error,code:Ae.ExtendsIncompatibleEntities,entity:s,firstRelationship:p,secondRelationship:e});i.push(f)}}),i}function xVi(s,p,i=!1){var m,E;const r=[],a=ea(p);if(!s.abstract&&p.abstract){const b=It({id:s.id+"--"+p.id+"--"+Ae.NonAbstractExtendingAbstractEntity,message:`Entity "${s.name}" with id "${s.id}" is not-abstract but is extending an abstract entity "${p.name}" with id "${p.id}"`,severity:ve.Error,code:Ae.NonAbstractExtendingAbstractEntity,entity:s,firstRelationship:p});r.push(b.error)}if(s.abstract&&!p.abstract){const b=It({id:s.id+"--"+p.id+"--"+Ae.AbstractExtendingNonAbstractEntity,message:`Entity "${s.name}" with id "${s.id}" is abstract but is extending an non-abstract entity "${p.name}" with id "${p.id}"`,severity:ve.Error,code:Ae.AbstractExtendingNonAbstractEntity,entity:s,firstRelationship:p});r.push(b.error)}if(!s.static&&p.static){const b=It({id:s.id+"--"+p.id+"--"+Ae.NonStaticExtendingStaticEntity,message:`Entity "${s.name}" with id "${s.id}" is not static but is extending a static entity "${p.name}" with id "${p.id}"`,severity:ve.Error,code:Ae.NonStaticExtendingStaticEntity,entity:s,firstRelationship:p});r.push(b.error)}if(s.static&&!p.static){const b=It({id:s.id+"--"+p.id+"--"+Ae.StaticExtendingNonStaticEntity,message:`Entity "${s.name}" with id "${s.id}" is static but is extending an non-static entity "${p.name}" with id "${p.id}"`,severity:ve.Error,code:Ae.StaticExtendingNonStaticEntity,entity:s,firstRelationship:p});r.push(b.error)}if(!El(p)){const b=It({id:s.id+"--"+p.id+"--"+Ae.ExtendingNonInteractiveEntity,message:`Entity "${s.name}" with id "${s.id}" is extending an non-interactive entity "${p.name}" with id "${p.id}"`,severity:ve.Error,code:Ae.ExtendingNonInteractiveEntity,entity:s,firstRelationship:p});r.push(b.error)}if(s.extends&&((m=s.extends)==null?void 0:m.id)!==p.id)if(((E=s.extends)==null?void 0:E.type)===d.BuiltInBaseEntity){const b=a.filter(A=>{var _;return A.id!==((_=s.extends)==null?void 0:_.id)});b.length&&b.forEach(A=>{var _,P,V,G;if(A.id!==((_=s.extends)==null?void 0:_.id)){const M=It({id:s.id+"--"+A.id+"--"+((P=s.extends)==null?void 0:P.id)+"--"+Ae.ExtendsIncompatibleEntities,message:`Entity "${s.name}" with id "${s.id}" is extending built-in entity "${A.name}" with id "${A.id}" but also extends entity "${(V=s.extends)==null?void 0:V.name}" with id "${(G=s.extends)==null?void 0:G.id}" which is incompatible`,severity:ve.Error,code:Ae.ExtendsIncompatibleEntities,entity:s,firstRelationship:A,secondRelationship:s.extends});r.push(M.error)}})}else{ea(s.extends).forEach(M=>{const k=a.filter(K=>K.id!==M.id);k.length&&k.forEach(K=>{if(K.id!==M.id){const ne=new qi({id:s.id+"--"+K.id+"--"+M.id+"--"+Ae.ImplementsIncompatibleEntities,message:`Entity "${s.name}" with id "${s.id}" is extending built-in entity "${K.name}" with id "${K.id}" but also extends or implements entity "${M.name}" with id "${M.id}" which is incompatible`,severity:ve.Error,code:Ae.ImplementsIncompatibleEntities,entity:s,firstRelationship:K,secondRelationship:M});r.push(ne)}})});const A=!!ea(s.extends).find(M=>M.id===p.id);let _=[...s.extends.properties];A&&(_=_.filter(M=>!p.properties.find(k=>k.id===M.id||k.name===M.name||!!M.implements.find(K=>K.id===k.id))));let P=[...s.extends.methods];A&&(P=P.filter(M=>!p.methods.find(k=>{var K;return k.id===M.id||k.name===M.name||k.id===((K=M.implements)==null?void 0:K.id)})));const V=Jd(p.ownDeclaredProperties,_,Ce.PropertyOverwritesOtherExtendedEntitysPropertyWithSameImplementation,Ce.PropertyOverwritesOtherExtendedEntitysPropertyWithSameName);r.push(...V.errors);const G=Jd(p.abstractMethods,P,Ce.MethodOverwritesOtherExtendedEntitysMethodWithSameImplementation,Ce.MethodOverwritesOtherExtendedEntitysMethodWithSameName);r.push(...G.errors)}i&&z.Logger.log("self.implements.length",s.implements.length),s.implements.length&&s.implements.forEach(b=>{if(b.type===d.BuiltInBaseEntity){const A=a.filter(_=>_.id!==b.id);A.length&&A.forEach(_=>{if(_.id!==b.id){const P=new qi({id:s.id+"--"+_.id+"--"+b.id+"--"+Ae.ImplementsIncompatibleEntities,message:`Entity "${s.name}" with id "${s.id}" is implementing built-in entity "${_.name}" with id "${_.id}" but also implements entity "${b.name}" with id "${b.id}" which is incompatible`,severity:ve.Error,code:Ae.ImplementsIncompatibleEntities,entity:s,firstRelationship:_,secondRelationship:b});r.push(P)}})}else{ea(b).forEach(V=>{const G=a.filter(M=>M.id!==V.id);G.length&&G.forEach(M=>{if(M.id!==V.id){const k=new qi({id:s.id+"--"+M.id+"--"+V.id+"--"+Ae.ImplementsIncompatibleEntities,message:`Entity "${s.name}" with id "${s.id}" is implementing built-in entity "${M.name}" with id "${M.id}" but also implements entity "${V.name}" with id "${V.id}" which is incompatible`,severity:ve.Error,code:Ae.ImplementsIncompatibleEntities,entity:s,firstRelationship:M,secondRelationship:V});r.push(k)}})});const _=Jd(p.ownDeclaredProperties,b.ownDeclaredProperties,Ce.PropertyOverwritesOtherImplementedEntitysPropertyWithSameImplementation,Ce.PropertyOverwritesOtherImplementedEntitysPropertyWithSameName);r.push(..._.errors);const P=Jd(p.abstractMethods,[...b.abstractMethods,...b.methods],Ce.MethodOverwritesOtherImplementedEntitysMethodWithSameImplementation,Ce.MethodOverwritesOtherImplementedEntitysMethodWithSameName);r.push(...P.errors)}});const e=Jd(s.ownDeclaredProperties,p.ownDeclaredProperties,Ce.PropertyOverwritesOtherSiblingWithSameImplementation,Ce.PropertyOverwritesOtherSiblingWithSameName);r.push(...e.errors);const f=Jd(p.methods,p.abstractMethods,Ce.MethodOverwritesOtherSiblingWithSameImplementation,Ce.MethodOverwritesOtherSiblingWithSameName);return r.push(...f.errors),C(s.extends?ea(s.extends):[]).forEach(b=>{if(!a.find(A=>A.id===b.id)){const A=new qi({id:s.id+"--"+p.id+"--"+b.id+"--"+Ae.ImplementsIncompatibleEntities,message:`Entity "${s.name}" with id "${s.id}" is extending built-in entity "${p.name}" with id "${p.id}" but also extends entity "${b.name}" with id "${b.id}" which is incompatible`,severity:ve.Error,code:Ae.ImplementsIncompatibleEntities,entity:s,firstRelationship:p,secondRelationship:b});r.push(A)}}),r}function $Vi(s){const p=[];if(s.implements.forEach(i=>{if(!i.static){const r=new qi({id:s.id+"--"+i.id+"--"+Ae.StaticImplementingNonStaticEntity,message:`Entity "${s.name}" with id "${s.id}" is static but implements entity "${i.name}" with id "${i.id}" which is non-static`,severity:ve.Error,code:Ae.StaticImplementingNonStaticEntity,entity:s,firstRelationship:i});p.push(r)}}),s.extends&&!s.extends.static){const i=new qi({id:s.id+"--"+s.extends.id+"--"+Ae.StaticExtendingNonStaticEntity,message:`Entity "${s.name}" with id "${s.id}" is static but extends entity "${s.extends.name}" with id "${s.extends.id}" which is non-static`,severity:ve.Error,code:Ae.StaticExtendingNonStaticEntity,entity:s,firstRelationship:s.extends});p.push(i)}return p}function LVi(s){const p=[];if(s.implements.length){const i=new qi({id:s.id+"--"+Ae.AbstractEntityImplements,message:`Entity "${s.name}" with id "${s.id}" cannot be marked as abstract because it implements other entities`,severity:ve.Error,code:Ae.AbstractEntityImplements,entity:s});p.push(i)}if(s.extends&&!s.extends.abstract){const i=new qi({id:s.id+"--"+s.extends.id+"--"+Ae.AbstractExtendingNonAbstractEntity,message:`Entity "${s.name}" with id "${s.id}" is abstract but extends entity "${s.extends.name}" with id "${s.extends.id}" which is non-abstract`,severity:ve.Error,code:Ae.AbstractExtendingNonAbstractEntity,entity:s,firstRelationship:s.extends});p.push(i)}return p}function BVi(s){const p=[];if(s.extends&&s.extends.static){const i=new qi({id:s.id+"--"+s.extends.id+"--"+Ae.NonStaticExtendingStaticEntity,message:`Entity "${s.name}" with id "${s.id}" is non-static but extends entity "${s.extends.name}" with id "${s.extends.id}" which is static`,severity:ve.Error,code:Ae.NonStaticExtendingStaticEntity,entity:s,firstRelationship:s.extends});p.push(i)}return p}function MVi(s){const p=[];if(s.extends&&s.extends.abstract){const i=new qi({id:s.id+"--"+s.extends.id+"--"+Ae.NonAbstractExtendingAbstractEntity,message:`Entity "${s.name}" with id "${s.id}" is non-abstract but extends entity "${s.extends.name}" with id "${s.extends.id}" which is abstract`,severity:ve.Error,code:Ae.NonAbstractExtendingAbstractEntity,entity:s,firstRelationship:s.extends});p.push(i)}return p}function gL(s,p){const r=[...s.project.entities].filter(a=>a.id!==s.id);return YE(s,[ir,hd],r,p)}const GVi=Object.freeze(Object.defineProperty({__proto__:null,getBaseMethodsNotImplemented:Jje,getBasePropertiesNotImplemented:Yje,validate:zje,validateAsync:Wje,validateCanBecomeAbstract:LVi,validateCanBecomeNonAbstract:MVi,validateCanBecomeNonStatic:BVi,validateCanBecomeStatic:$Vi,validateCanExtendEntity:xVi,validateCanImplementEntity:NVi,validateDefinitionEntityName:gL},Symbol.toStringTag,{value:"Module"}));function kVi(s,p){const i=[],r=[];if(s.parent)if(s.id===s.parent)r.push(new we({id:`${s.id}--${s.parent}--${Te.SelfReference}`,code:Te.SelfReference,severity:ve.Error,message:`Entity of type "${s.type}" with id "${s.id}", has a reference to itself at 'parent'. This is not allowed. Change the reference string or the 'entityId' property of the reference object.`}));else{const a=p.get(s.parent);a?[d.Project,d.DataType].includes(a.type)||r.push(new we({id:`${s.id}--${s.parent}--${Te.InvalidParentReference}`,code:Te.InvalidParentReference,severity:ve.Error,message:`Entity of type "${s.type}" with id "${s.id}", has a parent reference which is of type ${a.type}, and therefore that isn't pointing to the following valid types for this reference: 'project' or 'data-type'.`})):r.push(new we({id:`${s.id}--${s.parent}--${Te.ReferencedEntityNotFound}`,code:Te.ReferencedEntityNotFound,severity:ve.Error,message:`Entity of type "${s.type}" with id "${s.id}", is referencing an entity with id "${s.parent}" at 'parent' that isn't yet found in the project. Perhaps it should be created first. Or perhaps the ID is incorrect.`}))}return s.implements&&Array.isArray(s.implements)?s.implements.forEach(a=>{if(s.id===a){r.push(new we({id:`${s.id}--${a}--${Te.SelfReference}`,code:Te.SelfReference,severity:ve.Error,message:`Entity of type "${s.type}" with id "${s.id}", has a reference to itself at one of the 'implements' references. This is not allowed. Change the reference string or the 'entityId' property of the reference object.`}));return}const c=p.get(a);c?[d.DefinitionEntity,d.BuiltInBaseEntity].includes(c.type)?c.abstract||r.push(new we({id:`${s.id}--${a}--${Te.InvalidImplementsReference}`,code:Te.InvalidImplementsReference,severity:ve.Error,message:`Entity of type "${s.type}" with id "${s.id}", has an 'implements' reference that isn't pointing to an abstract entity.`})):r.push(new we({id:`${s.id}--${a}--${Te.InvalidImplementsReference}`,code:Te.InvalidImplementsReference,severity:ve.Error,message:`Entity of type "${s.type}" with id "${s.id}", has an 'implements' reference which is of type ${c.type}, and therefore that isn't pointing to the following valid types for this reference: 'definition-entity' or 'built-in-base-entity'.`})):r.push(new we({id:`${s.id}--${a}--${Te.ReferencedEntityNotFound}`,code:Te.ReferencedEntityNotFound,severity:ve.Error,message:`Entity of type "${s.type}" with id "${s.id}", is referencing an entity with id "${a}" at 'implements' that isn't yet found in the project. Perhaps it should be created first. Or perhaps the ID is incorrect.`}))}):r.push(new we({id:`${s.id}--${Ce.InvalidObjectStructure}`,code:Ce.InvalidObjectStructure,severity:ve.Error,message:`Entity of type "${s.type}" with id "${s.id}", has an 'implements' property that isn't an array.`})),s.extends&&Array.isArray(s.extends)&&s.extends.forEach(a=>{const c=p.get(a);c?[d.DefinitionEntity,d.BuiltInBaseEntity].includes(c.type)?c.abstract&&r.push(new we({id:`${s.id}--${a}--${Te.InvalidExtendsReference}`,code:Te.InvalidExtendsReference,severity:ve.Error,message:`Entity of type "${s.type}" with id "${s.id}", has an 'extends' reference that isn't pointing to a non-abstract entity. Did you want to use the property 'implements', which holds a list of references to absract entities, instead?`})):r.push(new we({id:`${s.id}--${a}--${Te.InvalidExtendsReference}`,code:Te.InvalidExtendsReference,severity:ve.Error,message:`Entity of type "${s.type}" with id "${s.id}", has an 'extends' reference which is of type ${c.type}, and therefore that isn't pointing to the following valid types for this reference: 'definition-entity' or 'built-in-base-entity'.`})):r.push(new we({id:`${s.id}--${a}--${Te.ReferencedEntityNotFound}`,code:Te.ReferencedEntityNotFound,severity:ve.Error,message:`Entity of type "${s.type}" with id "${s.id}", is referencing an entity with id "${a}" at 'extends' that isn't yet found in the project. Perhaps it should be created first. Or perhaps the ID is incorrect.`}))}),{errors:r,explanations:i}}var zg=(s=>(s.Extends="extends",s.Implements="implements",s))(zg||{});const Ni=class Ni extends un{constructor(i,r){super(i);R(this,"initialData");R(this,"id");R(this,"name");R(this,"codeName",null);R(this,"description",null);R(this,"x");R(this,"y");R(this,"static");R(this,"abstract");R(this,"type",d.DefinitionEntity);R(this,"additionalProperties",!1);R(this,"properties",[]);R(this,"allPropertiesImplement",null);R(this,"additionalPropertiesDataType",null);R(this,"methods",[]);R(this,"abstractMethods",[]);R(this,"extends",null);R(this,"implements",[]);R(this,"project");R(this,"errors",[]);R(this,"parent");R(this,"detachedDependents",{});R(this,"knownVersions",null);R(this,"activeVersion",!1);R(this,"initialized",!1);R(this,"startedInitialization",!1);R(this,"suggestedProperties",[]);R(this,"suggestedMethods",[]);this.initialData=i,this.project=r,this.id=i.id,this.name=i.name,this.description=i.description,this.x=i.x,this.y=i.y,this.codeName=i.codeName,this.static=i.static,this.abstract=i.abstract}static new(i=null){return{id:x.UUID.uuid(),version:x.UUID.uuid(),createdAt:(i==null?void 0:i.timestamp)||B().toISOString(),author:(i==null?void 0:i.author)||x.sessionAuthor,previousVersion:null,deleted:!1,deletable:!0,editable:!0,type:d.DefinitionEntity,additionalProperties:!1,additionalPropertiesDataType:null,allPropertiesImplement:null,name:"",codeName:null,description:"",static:!1,abstract:!1,properties:[],methods:[],abstractMethods:[],extends:null,implements:[],x:0,y:0,parent:null}}static fromGenerationTarget(i,r,a){const c=a===void 0?r.addChangeSet(new S(r,x.sessionAuthor,B().toISOString(),r,!0,w.CreateFromGenerationTarget)):a;let e=r;if(i.parent){const b=te(i.parent);e=r.get(b)}const f=[];i.implements&&i.implements.forEach(b=>{f.push(r.get(b)||r.getBuiltIn(b))});let h=null;i.extends&&(h=r.get(i.extends)||r.getBuiltIn(i.extends));const m={id:i.id,version:x.UUID.uuid(),createdAt:(c==null?void 0:c.timestamp)||B().toISOString(),author:(c==null?void 0:c.author)||x.sessionAuthor,previousVersion:null,deleted:!1,name:i.name,deletable:!0,editable:!0,type:d.DefinitionEntity,codeName:i.codeName||null,description:i.description||null,static:i.static??!1,abstract:i.abstract??!1,additionalProperties:i.additionalProperties??!1,allPropertiesImplement:null,additionalPropertiesDataType:null,properties:[],methods:[],abstractMethods:[],extends:h,implements:f,x:0,y:0,parent:e.toReference()},E=Re(m,r);return E.hydrateAncestors(),E.setParent(e,c),E.addSelfToProject(c),c==null||c.add(E,W.Added),E.initChildren(c),c||E.captureVersion(),E}static validateGenerationTarget(i,r){var b;let a=JSON.parse(JSON.stringify(i));const c=[],e=[],f=kVi(a,r),h=Px(a,r),m=Xr(a);e.push(...f.errors,...h,...m.errors),c.push(...f.explanations,...m.explanations);const E=a.parent?r.get(a.parent):null;if(E&&E.type===d.DataType){const A=E;A.entity&&A.entity.type===d.DefinitionEntity&&((b=A.entity.parent)==null?void 0:b.id)!==A.id&&e.push(new we({id:`${i.id}--${Te.NewEntityWouldOverriteExisting}`,code:Te.NewEntityWouldOverriteExisting,severity:ve.Error,message:`The entity of type '${i.type}' with id '${i.id}' can't be added to the 'parent' entity with id '${A.id}' because it already has an 'entity' child. Data type entities can only have one 'entity' as children.
|
|
603
603
|
You can inspect the existing 'entity' field with the 'describe_entity' action. Like so:
|
|
604
604
|
${cp({describe_entity:A.entity.id})}
|
|
605
|
-
Alternatively you can update the parent data-type entity with 'update' action to remove the existing value of the field.`}))}return{errors:e,explanations:c,modifiedData:a}}get interactive(){return this.implements.length?this.implements.every(i=>i.interactive):!0}get allMethods(){return C([...this.ownDeclaredMethods,...this.allBaseMethodsFromOriginalParents])}get allProperties(){return C([...this.ownDeclaredProperties,...this.allBasePropertiesFromOriginalParents])}get allBaseMethodsFromOriginalParents(){var a;const i=((a=this.extends)==null?void 0:a.type)===d.DefinitionEntity?this.extends.allMethods:[],r=[...i].filter(c=>!i.some(e=>{var f,h;return e.id!==c.id&&(((f=e.implements)==null?void 0:f.id)===c.id||((h=e.extends)==null?void 0:h.id)===c.id)}));return C([...r,...this.implements.flatMap(c=>{const e=c.type===d.DefinitionEntity?[...c.allMethods]:[];return[...e].filter(h=>!e.some(m=>{var E,b;return m.id!==h.id&&(((E=m.implements)==null?void 0:E.id)===h.id||((b=m.extends)==null?void 0:b.id)===h.id)}))})])}get allBasePropertiesFromOriginalParents(){var c;const i=((c=this.extends)==null?void 0:c.allProperties)||[],r=[...i].filter(e=>!i.some(f=>{var h;return f.id!==e.id&&(!!f.implements.find(m=>m.id===e.id)||((h=f.extends)==null?void 0:h.id)===e.id)}));return C([...r,...this.implements.flatMap(e=>{const f=[...e.allProperties];return[...f].filter(m=>!f.some(E=>{var b;return E.id!==m.id&&(!!E.implements.find(A=>A.id===m.id)||((b=E.extends)==null?void 0:b.id)===m.id)}))})])}get allBasePropertiesFromExtendedAndImplementedEntities(){var c,e;const i=[...((c=this.extends)==null?void 0:c.ownDeclaredProperties)||[],...((e=this.extends)==null?void 0:e.allBasePropertiesFromExtendedAndImplementedEntities)||[]].filter(f=>!f.abstract),r=[...i].filter(f=>!i.some(h=>{var m;return h.id!==f.id&&(!!h.implements.find(E=>E.id===f.id)||((m=h.extends)==null?void 0:m.id)===f.id)})),a=this.implements.reduce((f,h)=>{const m=h.implementedPropertiesFromOriginalParents,E=[...h.ownDeclaredProperties].filter(_=>!_.abstract),b=[...m,...E,...f];return[...b].filter(_=>!!!b.find(V=>{var G;return!!V.implements.find(M=>M.id===_.id)||((G=V.extends)==null?void 0:G.id)===_.id}))},[]);return C([...r,...a])}get allBaseMethodsFromExtendedAndImplementedEntities(){return C([...(this.extends?[this.extends]:[]).reduce((i,r)=>r.type!==d.DefinitionEntity?[]:[...[...r.ownDeclaredMethods,...r.allBaseMethodsFromExtendedAndImplementedEntities].filter(c=>c.type!==d.ActionDescriptor),...i],[]),...this.implements.reduce((i,r)=>r.type!==d.DefinitionEntity?r.abstractMethods:[...[...r.ownDeclaredMethods,...r.allBaseMethodsFromExtendedAndImplementedEntities].filter(c=>c.type!==d.ActionDescriptor),...i],[])])}get extendedPropertiesFromOriginalParents(){var a,c;const i=[...((a=this.extends)==null?void 0:a.ownDeclaredProperties)||[],...((c=this.extends)==null?void 0:c.extendedPropertiesFromOriginalParents)||[]].filter(e=>!e.abstract),r=[...i].filter(e=>!i.some(f=>{var h;return f.id!==e.id&&(!!f.implements.find(m=>m.id===e.id)||((h=f.extends)==null?void 0:h.id)===e.id)}));return C(r)}get implementedPropertiesFromOriginalParents(){return C([...(this.extends?[this.extends]:[]).reduce((i,r)=>{const a=r.implementedPropertiesFromOriginalParents,c=[...r.ownDeclaredProperties].filter(h=>!!h.abstract),e=[...a,...c,...i];return[...e].filter(h=>!!!e.find(E=>{var b;return((b=E.extends)==null?void 0:b.id)===h.id||!!E.implements.find(A=>A.id===h.id)}))},[]),...this.implements.reduce((i,r)=>{const a=r.implementedPropertiesFromOriginalParents,c=[...r.ownDeclaredProperties].filter(h=>!!h.abstract),e=[...a,...c,...i];return[...e].filter(h=>!!!e.find(E=>{var b;return!!E.implements.find(A=>A.id===h.id)||((b=E.extends)==null?void 0:b.id)===h.id}))},[])].filter(i=>!!i.abstract))}get extendedMethodsFromOriginalParents(){return C((this.extends?[this.extends]:[]).reduce((i,r)=>{if(r.type!==d.DefinitionEntity)return[];const a=[...r.ownDeclaredMethods,...r.extendedMethodsFromOriginalParents].filter(c=>c.type!==d.ActionDescriptor);return[...i,...a]},[]))}get implementedMethodsFromOriginalParents(){return C([...(this.extends?[this.extends]:[]).reduce((i,r)=>{const a=r.type===d.DefinitionEntity?r.methods:[],c=[...r.abstractMethods].filter(e=>!a.find(f=>f.name===e.name));return[...a,...c,...i]},[]),...this.implements.reduce((i,r)=>[...r.abstractMethods,...i],[])].filter(i=>i.type===d.ActionDescriptor))}get extendedProperties(){return this.properties.filter(i=>i.isExtendedProperty)}get ownDeclaredProperties(){return this.properties.filter(r=>!r.isExtendedProperty)}get extendedMethods(){return this.methods.filter(i=>i.isExtendedMethod)}get ownDeclaredMethods(){return this.methods.filter(i=>!i.isExtendedMethod)}validateGeneratedUpdate(i){const r=[],a=[];return i.parent&&r.push(new we({id:`${this.id}--${Te.InvalidParentUpdate}`,code:Te.InvalidParentUpdate,severity:ve.Error,message:`Entity of type '${this.type}' with id '${this.id}' cannot have the 'parent' property updated. The 'parent' on an '${this.type}', must be the root project as it is a globally declared entity.`})),{errors:r,explanations:a,modifiedData:i}}subscribeDependents(i){return i.forEach(r=>{this.detachedDependents[r.entity.id]||(this.detachedDependents[r.entity.id]=r)}),this}unsubscribeDependents(i){return i.forEach(r=>{this.detachedDependents[r.entity.id]&&delete this.detachedDependents[r.entity.id]}),this}syncDependents(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"sync-dependents"))){const r=[],a=[],c=[],e=[];return Object.values(this.detachedDependents).forEach(f=>{const h=f.entity.afterAllChildrenInitialized(i);r.push(...h.updated),a.push(...h.added),c.push(...h.removed),e.push(...h.affected)}),i==null||i.attemptAutoclose("sync-dependents",this.id),{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}onDetachedDependencyRemoved(i,r,a){const c=[],e=[],f=[],h=[];return r==="implements"&&(this.removeImplementation(i,a),c.push(this)),r==="extends"&&(this.setExtension(null,a),c.push(this)),{updated:C(c),added:C(e),removed:C(f),affected:C(h),self:this}}onDetachedDependencyRestored(i,r,a){const c=[],e=[],f=[],h=[];return r==="implements"&&(this.addImplementation(i,a),c.push(this)),r==="extends"&&(this.setExtension(i,a),c.push(this)),{updated:C(c),added:C(e),removed:C(f),affected:C(h),self:this}}unsubscribeFromDependencies(){return this.implements.forEach(i=>{ma.includes(i.type)||i.unsubscribeDependents([{entity:this,field:"implements"}])}),this.extends&&(ma.includes(this.extends.type)||this.extends.unsubscribeDependents([{entity:this,field:"extends"}])),this}subscribeToDependencies(){return this.implements.forEach(i=>{ma.includes(i.type)||i.subscribeDependents([{entity:this,field:"implements"}])}),this.extends&&(ma.includes(this.extends.type)||this.extends.subscribeDependents([{entity:this,field:"extends"}])),this}increaseVersion(i){var r;if(this.project.diggestedBuiltInBaseEntitiesIds.has(this.id))return this;if(i&&!B(i).isValid())throw new Error(`The shared timestamp '${i}' is not a valid ISO 8601 date string.`);if(i&&B(i).isSame(B(this.createdAt)))return this;if(!((r=this.knownVersions)!=null&&r.has(this.version))&&this.project.initialized)throw new Error(`The current ${this.type} ${this.id} version '${this.version}' is not captured in the 'knownVersions' map. Capture the current version before increasing it to avoid losing data.`);if(!this.activeVersion)throw new Error(`Only active versions can be increased. Entity with id '${this.id}' and version '${this.version}' is not active.`);return this.previousVersion=this.version,this.version=x.UUID.uuid(),this.createdAt=B(i).toISOString()||B().toISOString(),this}captureVersion(){var r;const i=((r=this.knownVersions)==null?void 0:r.get(this.version))||new Ni(this,this.project);if(!this.activeVersion)throw new Error(`Only active versions can be captured. Entity of type ${this.type} with id '${this.id}' and version '${this.version}' is not active.`);if(this.version!==i.version)throw new Error(`Captured ${this.type} with id '${this.id}', version '${i.version}' does not match current entity version '${this.version}'.`);return this.knownVersions=this.knownVersions?this.knownVersions.set(this.version,i):new Map().set(this.version,i),this.apply(i),this}snapshot(){const i=new Ni(this,this.project);return this.apply(i)}apply(i){const r=this.toMeta();return i.metaSync(r,null),i.properties=[...this.properties],i.methods=[...this.methods],i.abstractMethods=[...this.abstractMethods],i.extends=this.extends,i.implements=[...this.implements],i.allPropertiesImplement=this.allPropertiesImplement,i.additionalPropertiesDataType=this.additionalPropertiesDataType,i.parent=this.parent,i}recursiveCaptureUpstreamVersions(i){const r=[],a=[],c=[],e=[];if(this.parent){this.parent.increaseVersion(i);const f=this.parent.recursiveCaptureUpstreamVersions(i);r.push(this.parent,...f.updated),a.push(...f.added),c.push(...f.removed)}return{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}async restoreVersion(i,r){var m;const a=[],c=[],e=[],f=[];if(this.version===i&&(r!=null&&r.skipIfSameVersion))return{updated:C(a),added:C(c),removed:C(e),affected:C(f),self:this};if(!this.knownVersions){const E=new Map;for(const[b,A]of this.knownVersions||new Map){if(E.set(b,A),A.activeVersion=!1,A.knownVersions)for(const[_,P]of A.knownVersions)E.set(_,P);A.knownVersions=null}}let h=(m=this.knownVersions)==null?void 0:m.get(i);if(!h){const E=await this.APILoadVersion({},i);if(!E)throw new Error(`Version with id '${i}' for entity with id '${this.id}' not found.`);h=new Ni(E,this.project)}return this.metaSync(h.toShallowJSON(),null),this.previousVersion=h.previousVersion,this.version=h.version,this.createdAt=h.createdAt,this.author=h.author,this.deleted=h.deleted,this.properties=[...h.properties],this.methods=[...h.methods],this.abstractMethods=[...h.abstractMethods],this.extends=h.extends,this.implements=[...h.implements],this.allPropertiesImplement=h.allPropertiesImplement,this.additionalPropertiesDataType=h.additionalPropertiesDataType,this.parent=h.parent,{updated:C(a),added:C(c),removed:C(e),affected:C(f),self:this}}updateWithShallowTransfer(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.UpdateWithShallowTransfer))){if(!this.checkCanEdit(this,r))return z.Logger.warn(`[updateWithShallowTransfer] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.UpdateWithShallowTransfer,this.id),this;if(this.metaSync(i,r),this.version=i.version,this.createdAt=i.createdAt,this.author=i.author,this.deleted=i.deleted,this.previousVersion=i.previousVersion,this.unsubscribeFromDependencies(),i.parent){const f=te(i.parent),h=this.project.get(f),m=this.parent;if(m&&m.id!==(h==null?void 0:h.id)&&this.removeFromParent(r),h)this.setParent(h,r),this.addSelfToProject(r);else throw r==null||r.attemptAutoclose(w.UpdateWithShallowTransfer,this.id),new Error(`${this.type} with id '${this.id}' has a 'parent' reference '${f}' that isn't found in the project`)}else throw r==null||r.attemptAutoclose(w.UpdateWithShallowTransfer,this.id),new Error(`${this.type} with id '${this.id}' must have a 'parent'`);if(i.extends){const f=te(i.extends),h=this.project.get(f);h&&this.setExtension(h,r)}else this.setExtension(null,r);if(i.implements.forEach(f=>{const h=te(f),m=this.project.get(h);if(m)this.addImplementation(m,r);else throw new Error(`${fr(this.type)} with id '${this.id}' has a 'implements' reference "${h}" which is missing in the project`)}),this.implements.filter(f=>{const h=te(f);return!i.implements.find(m=>te(m)===h)}).forEach(f=>{this.removeImplementation(f,r)}),i.methods.forEach(f=>{const h=te(f),m=this.project.get(h);m&&this.addMethod(m,r)}),this.methods.filter(f=>{const h=te(f);return!i.methods.find(m=>te(m)===h)}).forEach(f=>{this.removeMethod(f,r)}),i.properties.forEach(f=>{const h=te(f),m=this.project.get(h);m&&this.addProperty(m,r)}),this.properties.filter(f=>{const h=te(f);return!i.properties.find(m=>te(m)===h)}).forEach(f=>{this.removeProperty(f,r)}),i.allPropertiesImplement){const f=te(i.allPropertiesImplement),h=this.project.get(f);h&&this.setAllPropertiesImplement(h,r)}else this.setAllPropertiesImplement(null,r);if(i.additionalPropertiesDataType){const f=te(i.additionalPropertiesDataType),h=this.project.get(f);h&&this.setAdditionalPropertiesDataType(h,r)}else this.setAdditionalPropertiesDataType(null,r);return this.captureVersion(),this.subscribeToDependencies(),r==null||r.attemptAutoclose(w.UpdateWithShallowTransfer,this.id),this}updateWithGenerationTarget(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.UpdateWithGenerationTarget))){var a;if(!this.checkCanEdit(this,r))return z.Logger.warn(`[updateWithGenerationTarget] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.UpdateWithGenerationTarget,this.id),this;if(this.metaSync(i,r),i.parent){const c=te(i.parent),e=this.project.get(c),f=this.parent;if(f&&f.id!==(e==null?void 0:e.id)&&this.removeFromParent(r),e)this.setParent(e,r),this.addSelfToProject(r);else throw r==null||r.attemptAutoclose(w.UpdateWithGenerationTarget,this.id),new Error(`${this.type} with id '${this.id}' has a 'parent' reference '${c}' that isn't found in the project`)}if(i.extends){const c=te(i.extends),e=this.project.get(c);if(e)this.setExtension(e,r);else throw new Error(`${fr(this.type)} with id '${this.id}' has an 'extends' reference "${c}" which is missing in the project`)}else i.extends===null&&this.setExtension(null,r);return(a=i.implements)==null||a.forEach(c=>{const e=te(c),f=this.project.get(e);if(f)this.addImplementation(f,r);else throw new Error(`${fr(this.type)} with id '${this.id}' has a 'implements' reference "${e}" which is missing in the project`)}),i.implements&&this.implements.filter(e=>{const f=te(e);return!(i.implements||[]).find(h=>te(h)===f)}).forEach(e=>{this.removeImplementation(e,r)}),this.captureVersion(),this.subscribeToDependencies(),r==null||r.attemptAutoclose(w.UpdateWithGenerationTarget,this.id),this}hydrateAncestors(){const i=[],r=[],a=[],c=[];if(this.initialData.parent){const e=te(this.initialData.parent),f=this.project.get(e);if(f)this.setParent(f,null),i.push(f);else throw new Error(`${this.type} with id '${this.id}' has a 'parent' reference '${e}' that isn't found in the project`)}else throw new Error(`${this.type} with id '${this.id}' must have a 'parent'`);if(this.initialData.extends){const e=te(this.initialData.extends),f=this.project.get(e);f&&(this.setExtension(f,null),f.type!==d.BuiltInBaseEntity&&i.push(f))}return this.initialData.implements.forEach(e=>{const f=te(e),h=this.project.get(f);if(h)this.addImplementation(h,null),h.type!==d.BuiltInBaseEntity&&i.push(h);else throw new Error(`${fr(this.type)} with id '${this.id}' has a 'implements' reference "${f}" which is missing in the project`)}),{updated:C(i),added:C(r),removed:C(a),affected:C(c),self:this}}afterAllChildrenInitialized(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.AfterAllChildrenInitialized))){if(!this.checkCanEdit(this,i))return z.Logger.warn(`[afterAllChildrenInitialized] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),i==null||i.attemptAutoclose(w.AfterAllChildrenInitialized,this.id),{updated:[],added:[],removed:[],affected:[],self:this};const r=[],a=[],c=[],e=[];this.initialized=!0;const{updated:f,added:h,removed:m,affected:E}=this.syncImplementationProperties(i);r.push(...f),a.push(...h),c.push(...m),e.push(...E);const{updated:b,added:A,removed:_,affected:P}=this.addExtendedProperties(i);r.push(...b),a.push(...A),c.push(..._),e.push(...P);const{updated:V,added:G,removed:M}=this.removeUnrecognizedProperties(i);r.push(...V),a.push(...G),c.push(...M);const{updated:k,added:K,removed:ne,affected:X}=this.syncImplementationMethods(i);r.push(...k),a.push(...K),c.push(...ne),e.push(...X);const{updated:de,added:ie,removed:le,affected:ye}=this.addExtendedMethods(i);r.push(...de),a.push(...ie),c.push(...le),e.push(...ye);const{updated:Y,added:ee,removed:pe}=this.removeUnrecognizedMethods(i);r.push(...Y),a.push(...ee),c.push(...pe),this.addSuggestions(),this.properties.sort((ue,be)=>ue.index-be.index);let he=this.project.getDefinitionEntities(new Set([this.id])).filter(ue=>ue.id!==this.id&&ue.name.toLowerCase()===this.name.toLowerCase());if(he.length){if(this.parent.type===d.Project)for(let ue=0;ue<he.length;ue++){const be=he[ue];be.parent.type!==d.Project&&(P_e(be,i),he=he.filter(Ie=>Ie.id!==be.id))}if(he.length){const ue=Cp(this.name,he);this.metaSync({name:ue},i)}}return i==null||i.attemptAutoclose(w.AfterAllChildrenInitialized,this.id),{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}addSelfToProject(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"add-self-to-project"))){const r=[this],a=[],c=[],e=[];if(this.parent.type===d.DataType){const f=this.parent;f.entity=this,r.push(f)}else this.project.addDefinitionEntity(this);return this.subscribe(),this.subscribeToDependencies(),i==null||i.attemptAutoclose("add-self-to-project",this.id),{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}setParent(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.SetParent))){var a;return this.checkCanEditWithCounterpartAndSideEffects(this,i,w.SetParent,r)?(((a=this.parent)==null?void 0:a.id)!==(i==null?void 0:i.id)&&(this.parent=i,r&&(r==null||r.add(this,W.Updated))),r==null||r.attemptAutoclose(w.SetParent,this.id),this):this}setExtension(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.SetExtension))){var a;return this.checkCanEdit(this,r)?(((a=this.extends)==null?void 0:a.id)!==(i==null?void 0:i.id)&&(this.extends=i,this.subscribeToDependencies(),r&&(r==null||r.add(this,W.Updated))),r==null||r.attemptAutoclose(w.SetExtension,this.id),this):(z.Logger.warn(`[setExtension] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.SetExtension,this.id),this)}addImplementation(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.AddImplementation))){return this.checkCanEdit(this,r)?(this.implements.includes(i)||(this.implements.push(i),this.subscribeToDependencies(),r==null||r.add(this,W.Updated)),r==null||r.attemptAutoclose(w.AddImplementation,this.id),this):(z.Logger.warn(`[addImplementation] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.AddImplementation,this.id),this)}removeImplementation(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.RemoveImplementation))){return this.checkCanEdit(this,r)?(this.implements.includes(i)&&(this.implements=this.implements.filter(a=>a.id!==i.id),r==null||r.add(this,W.Updated)),r==null||r.attemptAutoclose(w.RemoveImplementation,this.id),this):(z.Logger.warn(`[removeImplementation] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.RemoveImplementation,this.id),this)}removeProperty(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.RemoveProperty))){return this.checkCanEdit(this,r)?(this.properties.includes(i)&&(this.properties=this.properties.filter(a=>a.id!==i.id),r==null||r.add(this,W.Updated)),r==null||r.attemptAutoclose(w.RemoveProperty,this.id),this):(z.Logger.warn(`[removeProperty] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.RemoveProperty,this.id),this)}addMethod(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.AddMethod))){return this.checkCanEdit(this,r)?(this.methods.includes(i)||(this.methods.push(i),this.suggestedMethods=this.suggestedMethods.filter(a=>a.name!==i.name),r==null||r.add(this,W.Updated)),r==null||r.attemptAutoclose(w.AddMethod,this.id),this):(z.Logger.warn(`[addMethod] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.AddMethod,this.id),this)}removeMethod(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.RemoveMethod))){return this.checkCanEdit(this,r)?(this.methods.includes(i)&&(this.methods=this.methods.filter(a=>a.id!==i.id),r==null||r.add(this,W.Updated)),r==null||r.attemptAutoclose(w.RemoveMethod,this.id),this):(z.Logger.warn(`[removeMethod] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.RemoveMethod,this.id),this)}addProperty(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.AddProperty))){return this.checkCanEdit(this,r)?(this.properties.includes(i)||(this.properties.push(i),this.suggestedProperties=this.suggestedProperties.filter(a=>a.name!==i.name),r==null||r.add(this,W.Updated)),r==null||r.attemptAutoclose(w.AddProperty,this.id),this):(z.Logger.warn(`[addProperty] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.AddProperty,this.id),this)}addSuggestedProperty(i){return this.suggestedProperties.includes(i)||this.suggestedProperties.push(i),this}addSuggestedMethod(i){return this.suggestedMethods.includes(i)||this.suggestedMethods.push(i),this}removeSuggestedProperty(i){return this.suggestedProperties=this.suggestedProperties.filter(r=>r.id!==i.id),this}removeSuggestedMethod(i){return this.suggestedMethods=this.suggestedMethods.filter(r=>r.id!==i.id),this}addAbstractMethod(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.AddAbstractMethod))){return this.checkCanEdit(this,r)?(this.abstractMethods.includes(i)||(this.abstractMethods.push(i),r==null||r.add(this,W.Updated)),r==null||r.attemptAutoclose(w.AddAbstractMethod,this.id),this):(z.Logger.warn(`[addAbstractMethod] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.AddAbstractMethod,this.id),this)}removeAbstractMethod(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.RemoveAbstractMethod))){return this.checkCanEdit(this,r)?(this.abstractMethods.includes(i)&&(this.abstractMethods=this.abstractMethods.filter(a=>a.id!==i.id),r==null||r.add(this,W.Updated)),r==null||r.attemptAutoclose(w.RemoveAbstractMethod,this.id),this):(z.Logger.warn(`[removeAbstractMethod] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.RemoveAbstractMethod,this.id),this)}initChildren(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"init-children"))){if(this.initialized||this.startedInitialization)return this;if(this.startedInitialization=!0,this.properties=this.initialData.properties.map(r=>{const a=Re(r,this.project);return a.setParent(this,null),a.initChildren(i),a}),this.methods=this.initialData.methods.map(r=>{const a=Re(r,this.project);return a.setParent(this,null),a.initChildren(i),a}),this.abstractMethods=this.initialData.abstractMethods.map(r=>{const a=Re(r,this.project);return a.setParent(this,null),a.initChildren(i),a}),this.initialData.extends&&(this.extends=Re(this.initialData.extends,this.project)),this.implements=this.initialData.implements.map(r=>Re(r,this.project)),this.initialData.allPropertiesImplement){const r=Re(this.initialData.allPropertiesImplement,this.project);r.setParent(this,null),r.initChildren(null),this.setAllPropertiesImplement(r,i)}if(this.initialData.additionalPropertiesDataType){const r=Re(this.initialData.additionalPropertiesDataType,this.project);r.setParent(this,null),r.initChildren(null),this.setAdditionalPropertiesDataType(r,i)}return this.subscribeToDependencies(),this.afterAllChildrenInitialized(i),i==null||i.attemptAutoclose("init-children",this.id),this}removeUnrecognizedProperties(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"remove-unrecognized-properties"))){const r=[],a=[],c=[],e=[];let f=[...this.properties];f=f.filter(b=>b.parent.id===this.id),f=f.filter(b=>!b.isExtendedProperty);const h=this.implementedPropertiesFromOriginalParents,m=this.getAllPropertiesImplements();return f.filter(b=>this.interactive&&!b.implements.length?!1:!b.implements.find(_=>!!h.find(P=>P.id===_.id)||!!m.find(P=>P.id===_.id))).forEach(b=>{const A=b.remove({ignoreUpstream:!1},i);c.push(...A.removed),r.push(...A.updated)}),i==null||i.attemptAutoclose("remove-unrecognized-properties",this.id),{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}removeUnrecognizedMethods(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"remove-unrecognized-methods"))){const r=[],a=[],c=[],e=[];let f=[...this.methods];f=f.filter(m=>m.parent.id===this.id),f=f.filter(m=>!m.isExtendedMethod);const h=this.implementedMethodsFromOriginalParents;return f=f.filter(m=>this.interactive&&!m.implements?!1:!h.find(E=>{var b;return E.id===((b=m.implements)==null?void 0:b.id)})),f.forEach(m=>{const E=m.remove({ignoreUpstream:!1},i);c.push(...E.removed),r.push(...E.updated)}),i==null||i.attemptAutoclose("remove-unrecognized-methods",this.id),{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}syncImplementationMethods(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"sync-implementation-methods"))){const r=[],a=[],c=[],e=[],f=this.methods,h=this.implementedMethodsFromOriginalParents,m=[...this.allBaseMethodsFromExtendedAndImplementedEntities,...f];return h.filter(b=>!m.find(_=>{var P;return((P=_.implements)==null?void 0:P.id)===b.id})).forEach(b=>{if(this.methods.find(V=>{var G;return((G=V.implements)==null?void 0:G.id)===b.id}))return;const _=this.methods.find(V=>{var ne,X;if(V.name===b.name&&!V.implements)return!0;const G=oi(this,ge.CRON_JOB),M=oi(this,ge.HTTP_ENDPOINT),k=((ne=V.implements)==null?void 0:ne.id)===re["built-in-base-entity"].BUILT_IN_HTTP_ENDPOINT_ENTITY.methods.handler.id,K=((X=V.implements)==null?void 0:X.id)===re["built-in-base-entity"].BUILT_IN_CRON_JOB_ENTITY.methods.handler.id;return!!(G&&!K&&!M&&k||M&&!k&&!G&&K)});if(_&&_.type===d.FunctionDeclaration){_.setImplements(b,i),_.metaSync({name:b.name},i),i==null||i.add(_,W.Updated),i==null||i.add(this,W.Updated);return}const P=b.implementAsFunctionDeclaration(i,this);a.push(P),i==null||i.add(P,W.Added),this.addMethod(P,i)}),this.methods.sort((b,A)=>b.index-A.index).forEach(b=>{b.afterAllChildrenInitialized(i)}),i==null||i.attemptAutoclose("sync-implementation-methods",this.id),{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}syncImplementationProperties(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"sync-implementation-properties"))){const r=[],a=[],c=[],e=[],f=this.properties,h=this.implementedPropertiesFromOriginalParents.filter(E=>!this.allBasePropertiesFromExtendedAndImplementedEntities.find(A=>!!A.implements.find(_=>_.id===E.id))),m=[...this.allBasePropertiesFromExtendedAndImplementedEntities,...f];return h.forEach(E=>{const b=m.find(V=>!!V.implements.find(G=>G.id===E.id));if(b){const{updated:V,added:G,removed:M,affected:k}=b.syncWithImplementation(i);r.push(...V),a.push(...G),c.push(...M),e.push(...k);return}if(this.properties.find(V=>!!V.implements.find(G=>G.id===E.id)))return;const _=this.properties.find(V=>V.name===E.name&&!!V.abstract&&!V.implements);if(_){_.addImplementation(E,i),_.metaSync({abstract:!1},i),_.afterAllChildrenInitialized(i);return}const P=E.implement(this,i,x.UUID.uuid());a.push(P),i==null||i.add(P,W.Added)}),this.properties.find(E=>{var b;return E.id===((b=this.allPropertiesImplement)==null?void 0:b.id)})&&this.removeAllPropertiesImplement(i),i==null||i.attemptAutoclose("sync-implementation-properties",this.id),{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}addExtendedMethods(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"add-extended-methods"))){const r=[],a=[],c=[],e=[],f=this.methods,m=this.extendedMethodsFromOriginalParents.filter(b=>b.type===d.FunctionDeclaration),E=new Set(f.filter(b=>{var A;return!!((A=b.extends)!=null&&A.id)}).map(b=>b.extends.id));return m.forEach(b=>{if(E.has(b.id))return;E.add(b.id);const A=b.clone(i,this,x.UUID.uuid());A.setExtends(b,i),A.initChildren(i),a.push(A),i==null||i.add(A,W.Added),this.addMethod(A,i)}),i==null||i.attemptAutoclose("add-extended-methods",this.id),{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}addExtendedProperties(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"add-extended-properties"))){const r=[],a=[],c=[],e=[],f=this.properties,h=this.extendedPropertiesFromOriginalParents,m=h.filter(b=>h.find(_=>!!_.implements.find(P=>P.id===b.id))?!1:!b.abstract),E=new Set(f.filter(b=>{var A;return!!((A=b.extends)!=null&&A.id)}).map(b=>b.extends.id));return m.forEach(b=>{if(E.has(b.id))return;E.add(b.id);const A=b.clone(i,this,x.UUID.uuid());A.setExtends(b,i),A.initChildren(i),a.push(A),i==null||i.add(A,W.Added),this.addProperty(A,i)}),[...this.properties].forEach(b=>{if(b.extends)return;if(m.find(_=>_.name===b.name&&_.implements.every(P=>!!b.implements.find(V=>V.id===P.id)))){const _=b.remove({ignoreUpstream:!1},i);c.push(..._.removed),r.push(..._.updated)}}),this.properties.forEach(b=>{const A=b.afterAllChildrenInitialized(i);r.push(...A.updated),e.push(...A.affected),a.push(...A.added),c.push(...A.removed)}),i==null||i.attemptAutoclose("add-extended-properties",this.id),{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}addSuggestions(){return this.implements.forEach(i=>{Yje(this,i).forEach(c=>{const e=c.toJSON();e.id=`_suggestion--parent--${this.id}--${c.id}`;const f=Re(e,this.project);f.suggestion=!0,f.setParent(this,null),f.initChildren(null),this.addSuggestedProperty(f)}),Jje(this,i).forEach(c=>{const e=`_suggestion--parent--${this.id}--${c.id}`,f=c.implementAsFunctionDeclaration(null,this,e),h=Re(f,this.project);if(h.suggestion=!0,h.setParent(this,null),h.initChildren(null),this.methods=this.methods.filter(m=>m.id!==e),h.inputs.forEach(m=>{m.suggestion=!0}),h.returnStatements.length){const m=h.returnStatements[0];m.suggestion=!0,m.outputs.forEach(E=>{E.suggestion=!0})}this.addSuggestedMethod(h)})}),this}subscribe(){var i;return this.activeVersion=!0,(i=this.knownVersions)==null||i.forEach(r=>{r.version!==this.version&&(r.activeVersion=!1)}),this.project.subscribeInstance(this),this.project.subscribedDefinitionEntities.add(this.id),this}unsubscribe(){return this.project.unsubscribeInstance(this),this.project.subscribedDefinitionEntities.delete(this.id),this}metaSync(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"meta-sync"))){const a=tn(this,i,r),c=en(this,a),e=this.toMeta();return this.name=a.name!==void 0?a.name:e.name,this.codeName=a.codeName!==void 0?a.codeName:e.codeName,this.description=a.description!==void 0?a.description:e.description,this.x=a.x||e.x,this.y=a.y||e.y,this.static=a.static!==void 0?a.static:this.static,this.abstract=a.abstract!==void 0?a.abstract:this.abstract,this.additionalProperties=a.additionalProperties!==void 0?a.additionalProperties:e.additionalProperties,super.baseMetaSync(a,this,r),a.deleted===!0&&!e.deleted?r==null||r.add(this,W.Removed):a.deleted===!1&&e.deleted?r==null||r.add(this,W.Added):c&&(r==null||r.add(this,W.Updated)),r==null||r.attemptAutoclose("meta-sync",this.id),this}async APILoad(i=Ke,...r){return await Ni.repository.APILoad(this.id,...r),this}async APICreate(i=Ke,...r){return await Ni.repository.APICreate(this.toShallowJSON(),...r),this}async APIUpdate(i=Ke,...r){return await Ni.repository.APIUpdate(this.toShallowJSON(),...r),this}async APIDelete(i=Ke,...r){return await Ni.repository.APIDelete(this.toShallowJSON(),...r),this}async APIClone(i=Ke,...r){return await Ni.repository.APIClone(this.id,...r),this}async APILoadVersion(i=Ke,r,...a){return await Ni.repository.APILoadVersion(this.id,r,...a)}removeFromParent(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.RemoveFromParent))){if(!this.checkCanEdit(this,i))return z.Logger.warn(`[removeFromParent] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),i==null||i.attemptAutoclose(w.RemoveFromParent,this.id),{added:[],updated:[],removed:[],affected:[],self:this};const r=[],a=[],c=[],e=[];if(this.parent.type===d.Project)this.parent.removeDefinitionEntity(this);else if(this.parent.type===d.DataType&&this.parent.entity&&this.parent.entity.id===this.id){const f=this.parent.setEntity(null,i);r.push(f)}return i==null||i.attemptAutoclose(w.RemoveFromParent,this.id),{added:C(c),updated:C(r),removed:C(a),affected:C(e),self:this}}remove({ignoreUpstream:i}={ignoreUpstream:!1},r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.RemoveEntity))){var h;if(!this.checkCanDelete(this,r))return z.Logger.warn(`[remove] User is not allowed to delete or edit this ${this.type} entity with id: ${this.id}`),r==null||r.event({id:`${w.RemoveEntity}-${this.id}--${Me.ActionOwnerEntityNonDeletable}`,action:w.RemoveEntity,owner:this,errorReason:Me.ActionOwnerEntityNonDeletable,rootAction:((h=r==null?void 0:r.self)==null?void 0:h.id)===this.id&&(r==null?void 0:r.actionName)===w.RemoveEntity}),r==null||r.attemptAutoclose(w.RemoveEntity,this.id),{added:[],updated:[],removed:[],affected:[],self:this};const a=[],c=[],e=[],f=[];if(r!=null&&r.hasRemoved(this.id))return r==null||r.attemptAutoclose(w.RemoveEntity,this.id),{added:[],updated:[],removed:[],affected:[],self:this};if(c.push(this),this.unsubscribe(),this.unsubscribeFromDependencies(),this.project.subscribeDeletedInstance(this),this.metaSync({deleted:!0},r),Object.values(this.detachedDependents).forEach(m=>{const{updated:E,removed:b,added:A}=m.entity.onDetachedDependencyRemoved(this,m.field,r);a.push(...E),c.push(...b),e.push(...A)}),this.properties.forEach(m=>{const{updated:E,removed:b}=m.remove({ignoreUpstream:!0},r);a.push(...E),c.push(...b)}),this.methods.forEach(m=>{const{updated:E,removed:b}=m.remove({ignoreUpstream:!0},r);a.push(...E),c.push(...b)}),this.abstractMethods.forEach(m=>{const{updated:E,removed:b}=m.remove({ignoreUpstream:!0},r);a.push(...E),c.push(...b)}),this.suggestedProperties.forEach(m=>{const{updated:E,removed:b}=m.remove({ignoreUpstream:!0},r);a.push(...E),c.push(...b)}),this.suggestedMethods.forEach(m=>{const{updated:E,removed:b}=m.remove({ignoreUpstream:!0},r);a.push(...E),c.push(...b)}),!i){const m=this.removeFromParent(r);e.push(...m.added),a.push(...m.updated),c.push(...m.removed),f.push(...m.affected)}return r==null||r.attemptAutoclose(w.RemoveEntity,this.id),{added:C(e),updated:C(a),removed:C(c),affected:C(f),self:this}}restore({}={},i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.RestoreEntity))){if(!this.checkCanEdit(this,i))return z.Logger.warn(`[restore] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),i==null||i.attemptAutoclose(w.RestoreEntity,this.id),{added:[],updated:[],removed:[],affected:[],self:this};const r=[],a=[],c=[],e=[];return i!=null&&i.hasAdded(this.id)?(i==null||i.attemptAutoclose(w.RestoreEntity,this.id),{added:[],updated:[],removed:[],affected:[],self:this}):(this.subscribe(),this.project.unsubscribeDeletedInstance(this),this.metaSync({deleted:!1},i),Object.values(this.detachedDependents).forEach(f=>{const{updated:h,removed:m,added:E}=f.entity.onDetachedDependencyRestored(this,f.field,i);a.push(...h),c.push(...m),r.push(...E)}),this.properties.forEach(f=>{const{updated:h}=f.restore({},i);a.push(...h)}),this.methods.forEach(f=>{const{updated:h}=f.restore({},i);a.push(...h)}),this.abstractMethods.forEach(f=>{const{updated:h}=f.restore({},i);a.push(...h)}),this.suggestedProperties.forEach(f=>{const{updated:h}=f.restore({},i);a.push(...h)}),this.suggestedMethods.forEach(f=>{const{updated:h}=f.restore({},i);a.push(...h)}),i==null||i.attemptAutoclose(w.RestoreEntity,this.id),{added:C(r),updated:C(a),removed:C(c),affected:C(e),self:this})}toFlat(i=new Set){var a;return i.has(this.id)?[]:(i.add(this.id),[this,...((a=this.extends)==null?void 0:a.toFlat(i))||[],...this.implements.flatMap(c=>c.toFlat(i)),...this.properties.flatMap(c=>c.toFlat(i)),...this.methods.flatMap(c=>c.toFlat(i)),...this.abstractMethods.flatMap(c=>c.toFlat(i)),...this.parent.toFlat(i)])}toFlatIds(i=new Set){var a;return i.has(this.id)?[]:(i.add(this.id),[this.id,...((a=this.extends)==null?void 0:a.toFlatIds(i))||[],...this.implements.flatMap(c=>c.toFlatIds(i)),...this.properties.flatMap(c=>c.toFlatIds(i)),...this.methods.flatMap(c=>c.toFlatIds(i)),...this.abstractMethods.flatMap(c=>c.toFlatIds(i)),...this.parent.toFlatIds(i)])}toMeta(){return{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,codeName:this.codeName,description:this.description,static:this.static,abstract:this.abstract,x:this.x,y:this.y,type:this.type,editable:this.editable,deletable:this.deletable,additionalProperties:this.additionalProperties,name:this.name}}toJSON(i=new Set){var r,a,c;return i.has(this.id)?this.toReference():(i.add(this.id),{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,editable:this.editable,deletable:this.deletable,name:this.name,codeName:this.codeName,description:this.description,x:this.x,y:this.y,static:this.static,abstract:this.abstract,additionalProperties:this.additionalProperties,allPropertiesImplement:((r=this.allPropertiesImplement)==null?void 0:r.toJSON(i))||null,additionalPropertiesDataType:((a=this.additionalPropertiesDataType)==null?void 0:a.toJSON(i))||null,properties:this.properties.map(e=>e.toJSON(i)),methods:this.methods.map(e=>e.toJSON(i)),abstractMethods:this.abstractMethods.map(e=>e.toJSON(i)),implements:this.implements.map(e=>e.toJSON(i)),extends:((c=this.extends)==null?void 0:c.toJSON(i))||null,parent:this.parent.toReference()})}toJSONClone(i=at){var a,c,e,f,h,m,E,b,A,_;let r;return(a=i.seenEntityMaps)!=null&&a.has(this.id)?r=i.seenEntityMaps.get(this.id):(r=i.newId||dn(this,this.project,i.uuidStrategy),i.seenEntityMaps&&i.seenEntityMaps.set(this.id,r)),(c=i.seenEntities)!=null&&c.has(r)||(e=i.seenEntities)!=null&&e.has(this.id)?this.toReference({seenEntityMaps:i.seenEntityMaps}):((f=i.seenEntities)==null||f.add(r),(h=i.seenEntities)==null||h.add(this.id),{id:r,version:x.UUID.uuid(),createdAt:i.timestamp||B().toISOString(),author:x.sessionAuthor,previousVersion:null,deleted:!1,type:this.type,editable:this.editable,deletable:this.deletable,name:this.name,codeName:this.codeName,description:this.description,x:this.x,y:this.y,static:this.static,abstract:this.abstract,additionalProperties:this.additionalProperties,allPropertiesImplement:((m=this.allPropertiesImplement)==null?void 0:m.toJSONClone(i))||null,additionalPropertiesDataType:((E=this.additionalPropertiesDataType)==null?void 0:E.toJSONClone(i))||null,properties:this.properties.map(P=>P.toJSONClone({...i,newId:null})),methods:this.methods.map(P=>P.toJSONClone({...i,newId:null})),abstractMethods:this.abstractMethods.map(P=>P.toJSONClone({...i,newId:null})),implements:this.implements.map(P=>P.type===d.BuiltInBaseEntity?P.toJSON(i.seenEntities):P.toJSONClone({...i,newId:null})),extends:((b=this.extends)==null?void 0:b.type)===d.BuiltInBaseEntity?(A=this.extends)==null?void 0:A.toJSON(i.seenEntities):(_=this.extends)==null?void 0:_.toJSONClone({...i,newId:null}),parent:this.parent.toReference({seenEntityMaps:i.seenEntityMaps})})}toReference(i=at){var a;let r=this.id;return(a=i.seenEntityMaps)!=null&&a.has(this.id)&&(r=i.seenEntityMaps.get(this.id)),{id:r+"--"+x.UUID.uuid()+"--ref",type:d.GenericReference,entityId:r,version:this.version,entityType:this.type}}toShallowJSON(i=at){var a,c,e,f;let r=this.id;return(a=i.seenEntityMaps)!=null&&a.has(this.id)&&(r=i.seenEntityMaps.get(this.id)),{id:r,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,name:this.name,codeName:this.codeName,description:this.description,type:this.type,editable:this.editable,deletable:this.deletable,x:this.x,y:this.y,static:this.static,abstract:this.abstract,additionalProperties:this.additionalProperties,allPropertiesImplement:((c=this.allPropertiesImplement)==null?void 0:c.toReference(i))||null,additionalPropertiesDataType:((e=this.additionalPropertiesDataType)==null?void 0:e.toReference(i))||null,properties:this.properties.map(h=>h.toReference(i)),methods:this.methods.map(h=>h.toReference(i)),abstractMethods:this.abstractMethods.map(h=>h.toReference(i)),implements:this.implements.map(h=>h.toReference(i)),extends:((f=this.extends)==null?void 0:f.toReference(i))||null,parent:this.parent.toReference(i)}}toFlatJSON(i=new Set){var a,c,e;return i.has(this.id)?[]:(i.add(this.id),[this.toShallowJSON(),...this.properties.flatMap(f=>f.toFlatJSON(i)),...this.methods.flatMap(f=>f.toFlatJSON(i)),...this.abstractMethods.flatMap(f=>f.toFlatJSON(i)),...this.implements.flatMap(f=>f.toFlatJSON(i)),...((a=this.extends)==null?void 0:a.toFlatJSON(i))||[],...this.parent.toFlatJSON(i),...((c=this.additionalPropertiesDataType)==null?void 0:c.toFlatJSON(i))||[],...((e=this.allPropertiesImplement)==null?void 0:e.toFlatJSON(i))||[]])}toGenerationTarget(i=at){var c,e,f;const r=this.parent.type===d.Project?void 0:(c=i.seenEntityMaps)!=null&&c.has(this.parent.id)?i.seenEntityMaps.get(this.parent.id):this.parent.id;let a=this.id;return(e=i.seenEntityMaps)!=null&&e.has(this.id)&&(a=i.seenEntityMaps.get(this.id)),{id:a,name:this.name,description:this.description,type:this.type,static:this.static,abstract:this.abstract,extends:(f=this.extends)==null?void 0:f.id,additionalProperties:this.additionalProperties,implements:this.implements.map(h=>h.id),parent:r}}toFlatGenerationTarget(i=new Set){var a,c,e;return i.has(this.id)?[]:(i.add(this.id),[this.toGenerationTarget(),...this.properties.flatMap(f=>f.toFlatGenerationTarget(i)),...this.methods.flatMap(f=>f.toFlatGenerationTarget(i)),...this.abstractMethods.flatMap(f=>f.toFlatGenerationTarget(i)),...this.implements.filter(f=>f.type===d.DefinitionEntity).flatMap(f=>f.toFlatGenerationTarget(i)),...((a=this.extends)==null?void 0:a.toFlatGenerationTarget(i))||[],...this.parent.toFlatGenerationTarget(i),...((c=this.additionalPropertiesDataType)==null?void 0:c.toFlatGenerationTarget(i))||[],...((e=this.allPropertiesImplement)==null?void 0:e.toFlatGenerationTarget(i))||[]])}clearErrors(){var i,r;return this.errors=[],this.properties.forEach(a=>a.clearErrors()),this.methods.forEach(a=>a.clearErrors()),this.abstractMethods.forEach(a=>a.clearErrors()),(i=this.additionalPropertiesDataType)==null||i.clearErrors(),(r=this.allPropertiesImplement)==null||r.clearErrors(),this}validate(){return this.errors=zje(this),{success:!0}}async validateAsync(i={}){const r=z.YieldTracker.from(i);return this.errors=await Wje(this,{tracker:r}),{success:!0}}getErrors(){var r,a;return[...this.errors,...this.properties.flatMap(c=>c.getErrors()),...this.methods.flatMap(c=>c.getErrors()),...this.abstractMethods.flatMap(c=>c.getErrors()),...((r=this.additionalPropertiesDataType)==null?void 0:r.getErrors())||[],...((a=this.allPropertiesImplement)==null?void 0:a.getErrors())||[]]}async getErrorsAsync(i={}){const r=z.YieldTracker.from(i),a=[...this.errors];await r.tick();for(const c of this.properties)a.push(...await c.getErrorsAsync({tracker:r}));for(const c of this.methods)a.push(...await c.getErrorsAsync({tracker:r}));for(const c of this.abstractMethods)a.push(...await c.getErrorsAsync({tracker:r}));return this.additionalPropertiesDataType&&a.push(...await this.additionalPropertiesDataType.getErrorsAsync({tracker:r})),this.allPropertiesImplement&&a.push(...await this.allPropertiesImplement.getErrorsAsync({tracker:r})),a}getShallowErrors(){return this.errors}clone(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.CloneEntity)),r=null,a=null,c=!0){var G,M,k;const e=Fr(r,this),f=this.toJSON(),h=a||x.UUID.uuid(),m=r||this.parent;f.properties=[],f.methods=[],f.abstractMethods=[];const E=h.split("-id"),b=E[E.length-1||0]||h;f.id=h,f.version=x.UUID.uuid(),f.createdAt=(i==null?void 0:i.timestamp)||B().toISOString(),f.author=(i==null?void 0:i.author)||"1",f.previousVersion=null,f.deleted=!1,f.editable=!0,f.deletable=!0,f.parent=m.toReference();const A=lr(f,e);A.hydrateAncestors(),A.setParent(m,i),c&&(A.subscribe(),A.addSelfToProject(i)),A.initChildren(i),i==null||i.add(A,W.Added);const _=(G=this.properties)==null?void 0:G.map(K=>this.project.diggestedBuiltInBaseEntitiesIds.has(K.id)?K:K.clone(i,A,x.UUID.uuid(),c));A.properties=_;const P=(M=this.methods)==null?void 0:M.map((K,ne)=>this.project.diggestedBuiltInBaseEntitiesIds.has(K.id)?K:K.clone(i,A,b+"-method-"+ne+"-id",c));A.methods=P;const V=(k=this.abstractMethods)==null?void 0:k.map((K,ne)=>this.project.diggestedBuiltInBaseEntitiesIds.has(K.id)?K:K.clone(i,A,b+"-abstract-method-"+ne+"-id",c));if(A.abstractMethods=V,this.additionalPropertiesDataType)if(this.project.diggestedBuiltInBaseEntitiesIds.has(this.additionalPropertiesDataType.id))A.setAdditionalPropertiesDataType(this.additionalPropertiesDataType,i);else{const K=this.additionalPropertiesDataType.clone(i,A,x.UUID.uuid(),c);A.setAdditionalPropertiesDataType(K,i)}if(this.allPropertiesImplement)if(this.project.diggestedBuiltInBaseEntitiesIds.has(this.allPropertiesImplement.id))A.setAllPropertiesImplement(this.allPropertiesImplement,i);else{const K=this.allPropertiesImplement.clone(i,A,x.UUID.uuid(),c);A.setAllPropertiesImplement(K,i)}return i||A.captureVersion(),i==null||i.attemptAutoclose(w.CloneEntity,this.id),A}getFunctionDeclaration(i){return this.methods.find(r=>r.id===i)}implement(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"implement-definition-entity")),a){const c=m1(this,i,r,a);return r==null||r.attemptAutoclose("implement-definition-entity",this.id),c}getAllPropertiesImplements(){var r;const i=[];return this.allPropertiesImplement&&i.push(this.allPropertiesImplement),i.push(...((r=this.extends)==null?void 0:r.getAllPropertiesImplements())||[],...this.implements.flatMap(a=>a.getAllPropertiesImplements())),i}getAllInteractiveMethods(){var e;const i=this.implements.filter(f=>f.type===d.DefinitionEntity||f.type===d.BuiltInBaseEntity&&f.interactive),r=((e=this.extends)==null?void 0:e.getAllInteractiveMethods())||[],a=i.flatMap(f=>f.getAllInteractiveMethods());return C([...this.methods,...r,...a])}inferFromInputs(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"infer-definition-entity-from-inputs"))){const a=[],c=[],e=[],f=[];if(this.parent.type!==d.DataType||!this.parent.inferred)return r==null||r.attemptAutoclose("infer-definition-entity-from-inputs",this.id),{added:[],updated:[],removed:[],affected:[],self:this};const h=[];i.forEach(b=>{h.find(_=>oe(_,this.project)===oe(b,this.project))||h.push(b)});const m=this.properties.filter(b=>!b.dataType);h.forEach(b=>{var k,K,ne;const A=m.find(X=>oe(X,this.project)===oe(b,this.project));if(!A)return;const P=gr(b.parent).getMasterInputWithValueWriterFromAllInstances(b),V=iu(P,r),G=V==null?void 0:V.clone(r,A,x.UUID.uuid(),!0);G&&((k=A.dataType)==null||k.merge(G,r),G.id!==((K=A.dataType)==null?void 0:K.id)&&G.remove({ignoreUpstream:!1},r),A.dataType&&(A.dataType.metaSync({inferred:!0,like:!0},r),A.setDataType(A.dataType,r),r==null||r.add(A,W.Affected)));let M=null;if(b.declaration&&A.id!==((ne=b.declaration)==null?void 0:ne.id)&&(M=b.declaration),b.setDeclaration(A,r),r==null||r.add(b,W.Updated),M){const{updated:X,removed:de}=M.remove({ignoreUpstream:!1},r);c.push(...X),e.push(...de)}});const E=[];return h.forEach(b=>{if(!b.declaration){E.push(b);return}}),E.length===0?(r==null||r.attemptAutoclose("infer-definition-entity-from-inputs",this.id),{added:[],updated:[],removed:[],affected:[],self:this}):(E.forEach(b=>{var ne,X,de,ie,le;const A=this.properties.find(ye=>oe(ye,this.project)===oe(b,this.project));if(A){if(b.setDeclaration(A,r),!A.getDataType(r)){const Y=gr(b.parent).getMasterInputWithValueWriterFromAllInstances(b),ee=iu(Y),pe=ee==null?void 0:ee.clone(r,A,x.UUID.uuid(),!0);pe&&((ne=A.dataType)==null||ne.merge(pe,r),pe.id!==((X=A.dataType)==null?void 0:X.id)&&pe.remove({ignoreUpstream:!1},r),A.dataType&&(A.dataType.metaSync({inferred:!0,like:!0},r),A.setDataType(A.dataType,r),r==null||r.add(A,W.Affected)))}return}const _=oe(b,this.project),P=b.codeName||vp(b,this.project)||cs(ir(_)),V=Es.new(r);V.parent=this.toReference(),V.index=b.index,V.name=_,V.codeName=P,V.description=b.description;const G=Re(V,this.project);G.hydrateAncestors(),G.addSelfToProject(r),r==null||r.add(G,W.Added),G.setParent(this,r),G.initChildren(r),r||G.captureVersion();const k=gr(b.parent).getMasterInputWithValueWriterFromAllInstances(b),K=iu(k);if(K&&K.id!==((de=G.dataType)==null?void 0:de.id)){const ye=K==null?void 0:K.clone(r,G,x.UUID.uuid(),!0);ye&&((ie=G.dataType)==null||ie.merge(ye,r),ye.id!==((le=G.dataType)==null?void 0:le.id)&&ye.remove({ignoreUpstream:!1},r),G.dataType&&(G.dataType.metaSync({inferred:!0,like:!0},r),G.setDataType(G.dataType,r),r==null||r.add(G,W.Affected)))}return this.addProperty(G,r),b.setDeclaration(G,r),r==null||r.add(b,W.Updated),G}),r==null||r.attemptAutoclose("infer-definition-entity-from-inputs",this.id),{added:C(a),updated:C(c),removed:C(e),affected:C(f),self:this})}getRawDefaultValue(){const i={};return this.properties.forEach(r=>{var e;if(!Ev(r)||!r.defaultValue)return;const a=oe(r,this.project),c=r.codeName||vp(r,this.project)||cs(ir(a));i[c]=((e=r.getDefaultValue())==null?void 0:e.value)||null}),i}getActiveRawDefaultValue(){const i={};return this.properties.forEach(r=>{var f;if(!Ev(r))return;const a=oe(r,this.project),c=r.codeName||vp(r,this.project)||cs(ir(a)),e=(f=this.project.requestActiveDynamicValue(r,!0))==null?void 0:f.value;e&&(i[c]=(e==null?void 0:e.value)||null)}),i}setAdditionalPropertiesDataType(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.SetAdditionalPropertiesDataType))){if(!this.checkCanEdit(this,r))return z.Logger.warn(`[setAdditionalPropertiesDataType] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.SetAdditionalPropertiesDataType,this.id),this;const a=this.additionalPropertiesDataType;return(a==null?void 0:a.id)!==(i==null?void 0:i.id)&&(a==null||a.remove({ignoreUpstream:!0},r),this.additionalPropertiesDataType=i,this.subscribeToDependencies(),r==null||r.add(this,W.Affected)),r==null||r.attemptAutoclose(w.SetAdditionalPropertiesDataType,this.id),this}removeAdditionalPropertiesDataType(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.RemoveAllPropertiesImplement))){return this.checkCanEdit(this,i)?(this.additionalPropertiesDataType&&(this.additionalPropertiesDataType.remove({ignoreUpstream:!0},i),i==null||i.add(this,W.Affected),this.additionalPropertiesDataType=null),i==null||i.attemptAutoclose(w.RemoveAllPropertiesImplement,this.id),this):(z.Logger.warn(`[removeAdditionalPropertiesDataType] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),i==null||i.attemptAutoclose(w.RemoveAllPropertiesImplement,this.id),this)}setAllPropertiesImplement(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.SetAllPropertiesImplement))){if(!this.checkCanEdit(this,r))return z.Logger.warn(`[setAllPropertiesImplement] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.SetAllPropertiesImplement,this.id),this;const a=this.allPropertiesImplement;return(a==null?void 0:a.id)!==(i==null?void 0:i.id)&&(a==null||a.remove({ignoreUpstream:!0},r),this.allPropertiesImplement=i,this.subscribeToDependencies(),r==null||r.add(this,W.Affected)),r==null||r.attemptAutoclose(w.SetAllPropertiesImplement,this.id),this}removeAllPropertiesImplement(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.RemoveAllPropertiesImplement))){return this.checkCanEdit(this,i)?(this.allPropertiesImplement&&(this.properties.find(r=>{var a;return r.id===((a=this.allPropertiesImplement)==null?void 0:a.id)})||this.allPropertiesImplement.remove({ignoreUpstream:!0},i),i==null||i.add(this,W.Affected),this.allPropertiesImplement=null),i==null||i.attemptAutoclose(w.RemoveAllPropertiesImplement,this.id),this):(z.Logger.warn(`[removeAllPropertiesImplement] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),i==null||i.attemptAutoclose(w.RemoveAllPropertiesImplement,this.id),this)}};R(Ni,"repository",{APICreate:async(i,...r)=>i,APIUpdate:async(i,...r)=>i,APIDelete:async(i,...r)=>i,APIClone:async(i,...r)=>{},APILoad:async(i,...r)=>null,APILoadVersion:async(i,r,...a)=>null}),R(Ni,"type",d.DefinitionEntity),R(Ni,"USER_MANAGED_PARENT_TYPES",[d.Project,d.DataType]),R(Ni,"PARENT_TYPES",[...Ni.USER_MANAGED_PARENT_TYPES]),R(Ni,"MUTABLE_BASE_PROPERTIES",["name","codeName","description","static","abstract","additionalProperties"]),R(Ni,"INMUTABLE_BASE_PROPERTIES",["id","type","version","createdAt","author","previousVersion"]),R(Ni,"BASE_PROPERTIES",[...Ni.MUTABLE_BASE_PROPERTIES,...Ni.INMUTABLE_BASE_PROPERTIES]),R(Ni,"MUTABLE_META_PROPERTIES",[...Ni.MUTABLE_BASE_PROPERTIES,"x","y"]),R(Ni,"INMUTABLE_META_PROPERTIES",[...Ni.INMUTABLE_BASE_PROPERTIES]),R(Ni,"META_PROPERTIES",[...Ni.MUTABLE_META_PROPERTIES,...Ni.INMUTABLE_META_PROPERTIES]),R(Ni,"MUTABLE_UPSTREAM_PROPERTIES",["extends","implements"]),R(Ni,"INMUTABLE_UPSTREAM_PROPERTIES",["parent"]),R(Ni,"UPSTREAM_PROPERTIES",[...Ni.MUTABLE_UPSTREAM_PROPERTIES,...Ni.INMUTABLE_UPSTREAM_PROPERTIES]),R(Ni,"MUTABLE_DOWNSTREAM_PROPERTIES",["properties","methods","abstractMethods","allPropertiesImplement","additionalPropertiesDataType"]),R(Ni,"INMUTABLE_DOWNSTREAM_PROPERTIES",[]),R(Ni,"DOWNSTREAM_PROPERTIES",[...Ni.MUTABLE_DOWNSTREAM_PROPERTIES,...Ni.INMUTABLE_DOWNSTREAM_PROPERTIES]),R(Ni,"PROPERTIES",[...Ni.META_PROPERTIES,...Ni.UPSTREAM_PROPERTIES,...Ni.DOWNSTREAM_PROPERTIES]);let Ks=Ni;async function jVi(s,p={}){const i=z.YieldTracker.from(p),r=[],a=qt(s.errors,r);return await i.tick(),a}function UVi(s){const p=[];return qt(s.errors,p)}const lI=class lI extends Mx{constructor(i,r){super(i);R(this,"initialData");R(this,"id");R(this,"name");R(this,"description",null);R(this,"type",d.PrimitiveEntity);R(this,"static");R(this,"abstract");R(this,"properties",[]);R(this,"methods",[]);R(this,"abstractMethods",[]);R(this,"extends",null);R(this,"errors",[]);R(this,"project");this.initialData=i,this.project=r,this.id=i.id,this.name=i.name,this.description=i.description,this.static=i.static,this.abstract=i.abstract,this.properties=this.initialData.properties.map(a=>{const c=Re(a,this.project);return c.setParent(this,null),c.initChildren(null),c}),this.methods=this.initialData.methods.map(a=>{const c=Re(a,this.project);return c.parent=this,c}),this.abstractMethods=this.initialData.abstractMethods.map(a=>{const c=Re(a,this.project);return c.parent=this,c}),this.initialData.extends&&(this.extends=Re(this.initialData.extends,this.project))}get allMethods(){return C([...this.ownDeclaredMethods,...this.allBaseMethodsFromOriginalParents])}get allProperties(){return C([...this.ownDeclaredProperties,...this.allBasePropertiesFromOriginalParents])}get allBaseMethodsFromOriginalParents(){var a;const i=((a=this.extends)==null?void 0:a.allMethods)||[],r=[...i].filter(c=>!i.some(e=>e.id!==c.id));return C(r)}get allBasePropertiesFromOriginalParents(){var a;const i=((a=this.extends)==null?void 0:a.allProperties)||[],r=[...i].filter(c=>!i.some(e=>{var f;return e.id!==c.id&&(e.implements.find(h=>h.id===c.id)||((f=e.extends)==null?void 0:f.id)===c.id)}));return C(r)}get allBasePropertiesFromExtendedAndImplementedEntities(){var a,c;const i=[...((a=this.extends)==null?void 0:a.ownDeclaredProperties)||[],...((c=this.extends)==null?void 0:c.allBasePropertiesFromExtendedAndImplementedEntities)||[]].filter(e=>!e.abstract),r=[...i].filter(e=>!i.some(f=>{var h;return f.id!==e.id&&(f.implements.find(m=>m.id===e.id)||((h=f.extends)==null?void 0:h.id)===e.id)}));return C(r)}get extendedPropertiesFromOriginalParents(){var a,c;const i=[...((a=this.extends)==null?void 0:a.ownDeclaredProperties)||[],...((c=this.extends)==null?void 0:c.extendedPropertiesFromOriginalParents)||[]].filter(e=>!e.abstract),r=[...i].filter(e=>!i.some(f=>{var h;return f.id!==e.id&&(f.implements.find(m=>m.id===e.id)||((h=f.extends)==null?void 0:h.id)===e.id)}));return C(r)}get implementedPropertiesFromOriginalParents(){return C([...(this.extends?[this.extends]:[]).reduce((i,r)=>{const a=r.implementedPropertiesFromOriginalParents,c=[...r.ownDeclaredProperties].filter(h=>!!h.abstract),e=[...a,...c,...i];return[...e].filter(h=>!!!e.find(E=>{var b;return((b=E.extends)==null?void 0:b.id)===h.id||E.implements.find(A=>A.id===h.id)}))},[])])}get extendedProperties(){return this.properties.filter(i=>i.isExtendedProperty)}get ownDeclaredMethods(){return[...this.methods]}get ownDeclaredProperties(){return this.properties.filter(i=>!i.isExtendedProperty)}subscribe(){return this.project.subscribeBuiltInInstance(this),this}unsubscribe(){return this.project.unsubscribeBuiltInInstance(this),this}async APILoad(i=Ke,...r){return await lI.repository.APILoad(this.id,...r),this}toFlat(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this,...this.properties.flatMap(a=>a.toFlat(i)),...this.methods.flatMap(a=>a.toFlat(i)),...this.abstractMethods.flatMap(a=>a.toFlat(i))])}toFlatIds(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this.id,...this.properties.flatMap(a=>a.toFlatIds(i)),...this.methods.flatMap(a=>a.toFlatIds(i)),...this.abstractMethods.flatMap(a=>a.toFlatIds(i))])}toMeta(){return{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,description:this.description,static:this.static,abstract:this.abstract,type:this.type,name:this.name}}toJSON(i=new Set){var r;return i.has(this.id)?this.toReference():(i.add(this.id),{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,name:this.name,description:this.description,static:this.static,abstract:this.abstract,properties:this.properties.map(a=>a.toJSON(i)),methods:this.methods.map(a=>a.toJSON(i)),abstractMethods:this.abstractMethods.map(a=>a.toJSON(i)),extends:((r=this.extends)==null?void 0:r.toJSON(i))||null})}toReference(i=at){return{id:this.id+"--"+x.UUID.uuid()+"--ref",type:d.GenericReference,entityId:this.id,version:this.version,entityType:this.type}}toShallowJSON(i=at){var r;return{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,name:this.name,description:this.description,abstract:this.abstract,static:this.static,properties:this.properties.map(a=>a.toReference()),methods:this.methods.map(a=>a.toReference()),abstractMethods:this.abstractMethods.map(a=>a.toReference()),extends:((r=this.extends)==null?void 0:r.toReference())||null}}toFlatJSON(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this.toShallowJSON(),...this.properties.flatMap(a=>a.toFlatJSON(i)),...this.methods.flatMap(a=>a.toFlatJSON(i)),...this.abstractMethods.flatMap(a=>a.toFlatJSON(i))])}toGenerationTarget(i=at){var r;return{id:this.id,type:this.type,name:this.name,description:this.description,static:this.static,abstract:this.abstract,extends:(r=this.extends)==null?void 0:r.id}}toFlatGenerationTarget(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this.toGenerationTarget(),...this.properties.flatMap(a=>a.toFlatGenerationTarget(i)),...this.methods.flatMap(a=>a.toFlatGenerationTarget(i)),...this.abstractMethods.flatMap(a=>a.toFlatGenerationTarget(i))])}clearErrors(){return this.errors=[],this.properties.forEach(i=>i.clearErrors()),this.methods.forEach(i=>i.clearErrors()),this.abstractMethods.forEach(i=>i.clearErrors()),this}validate(){return this.errors=UVi(this),{success:!0}}async validateAsync(i={}){const r=z.YieldTracker.from(i);return this.errors=await jVi(this,{tracker:r}),{success:!0}}getErrors(){return[...this.errors,...this.properties.flatMap(r=>r.getErrors()),...this.methods.flatMap(r=>r.getErrors()),...this.abstractMethods.flatMap(r=>r.getErrors())]}async getErrorsAsync(i={}){const r=z.YieldTracker.from(i),a=[...this.errors];await r.tick();for(const c of this.properties){const e=await c.getErrorsAsync({tracker:r});a.push(...e)}for(const c of this.methods){const e=await c.getErrorsAsync({tracker:r});a.push(...e)}for(const c of this.abstractMethods){const e=await c.getErrorsAsync({tracker:r});a.push(...e)}return a}getShallowErrors(){return this.errors}getAllInteractiveMethods(){const i=[];return i.push(...this.methods),!this.extends||this.extends.type===d.PrimitiveEntity?i:C(i)}};R(lI,"repository",{APILoad:async(i,...r)=>null});let Nf=lI;function lr(s,p){if(!s)throw new Error("Entity is null");const i=p.get(s.id);switch(s.type){case d.LiteralValue:return i||new Lr(s,p);case d.DefinitionEntity:return i||new Ks(s,p);case d.PrimitiveEntity:return i||new Nf(s,p);case d.FunctionDeclaration:return i||new md(s,p);case d.GlobalEvent:return i||new Vp(s,p);case d.DataType:return i||new vr(s,p);case d.Property:return i||new Es(s,p);case d.FunctionCall:return i||new Op(s,p);case d.Condition:return i||new Np(s,p);case d.Operation:return i||new _p(s,p);case d.VariableDeclaration:return i||new Lp(s,p);case d.VariableInstance:return i||new $p(s,p);case d.OutputMap:return i||new po(s,p);case d.ArgumentDeclaration:return i||new Za(s,p);case d.InputMap:return i||new Ts(s,p);case d.Project:return i||new x(s);case d.InstalledProject:return i||new Mp(s,p);case d.ActionDescriptor:return i||new er(s,p);case d.ReturnStatement:return i||new su(s,p);case d.Loop:return i||new Pp(s,p);case d.Search:return i||new Bp(s,p);case d.ValueDescriptor:return i||new Ed(s,p);case d.BuiltInBaseEntity:return i||new Td(s,p);case d.InternalCall:return i||new Gp(s,p);case d.ContinueStatement:return i||new jp(s,p);case d.BreakStatement:return i||new kp(s,p);case d.GenericReference:return p.get(s.entityId);default:throw new Error("Invalid entity type: "+s.type)}}function Re(s,p){if(!s)throw new Error("Entity is null");const i=lr(s,p);return i.subscribe(),i}function FVi(s,p,i){if(!s)throw new Error("Entity is null");switch(s.type){case d.LiteralValue:return Lr.fromGenerationTarget(s,p,i);case d.DefinitionEntity:return Ks.fromGenerationTarget(s,p,i);case d.FunctionDeclaration:return md.fromGenerationTarget(s,p,i);case d.GlobalEvent:return Vp.fromGenerationTarget(s,p,i);case d.DataType:return vr.fromGenerationTarget(s,p,i);case d.Property:return Es.fromGenerationTarget(s,p,i);case d.FunctionCall:return Op.fromGenerationTarget(s,p,i);case d.Condition:return Np.fromGenerationTarget(s,p,i);case d.Operation:return _p.fromGenerationTarget(s,p,i);case d.VariableDeclaration:return Lp.fromGenerationTarget(s,p,i);case d.VariableInstance:return $p.fromGenerationTarget(s,p,i);case d.OutputMap:return po.fromGenerationTarget(s,p,i);case d.ArgumentDeclaration:return Za.fromGenerationTarget(s,p,i);case d.InputMap:return Ts.fromGenerationTarget(s,p,i);case d.InstalledProject:return Mp.fromGenerationTarget(s,p,i);case d.ReturnStatement:return su.fromGenerationTarget(s,p,i);case d.Loop:return Pp.fromGenerationTarget(s,p,i);case d.Search:return Bp.fromGenerationTarget(s,p,i);case d.ActionDescriptor:return er.fromGenerationTarget(s,p,i);case d.ValueDescriptor:return Ed.fromGenerationTarget(s,p,i);case d.InternalCall:return Gp.fromGenerationTarget(s,p,i);case d.ContinueStatement:return jp.fromGenerationTarget(s,p,i);case d.BreakStatement:return kp.fromGenerationTarget(s,p,i);default:throw new Error("Invalid entity type: "+s.type)}}const at={seenEntityMaps:new Map,seenEntities:new Set,timestamp:B().toISOString()};class iUe{constructor(){R(this,"initialData")}}const Ke={cascade:!1},rUe={APILoad:async(s,...p)=>null},KVi={APICreate:async(s,...p)=>s,APIUpdate:async(s,...p)=>s,APIDelete:async(s,...p)=>s,APIClone:async(s,...p)=>{},APILoadVersion:async(s,p,...i)=>null,...rUe};class qVi{}class nUe extends iUe{}class SVi extends nUe{}class ZVi{}class HVi{}class WVi{}class IL{}class zVi extends IL{}class YVi extends IL{}class JVi{}class py{static initReadsValue(p){if(p.initialData.readsValue&&p.initialData.readsValue.type!==d.GenericReference)p.readsValue=Re(p.initialData.readsValue,p.project);else if(p.initialData.readsValue&&p.initialData.readsValue.type===d.GenericReference){const i=Ra(p.initialData.readsValue,p.project);i&&(p.readsValue=i)}if(p.readsValue){if(Mt.includes(p.readsValue.type)){let i=p.parent;!Dr.includes(i.type)&&i.type!==d.Project&&(i=i.parent);const r=p.type===d.InputMap&&p.parent.type===d.Loop;r&&(i=p.parent.parent),p.readsValue.setParent(i,null),p.readsValue.initChildren(null),i&&i.type!==d.Project&&!r&&i.detachedChildren.includes(p)?i.replaceDetachedChild(p,p.readsValue):i&&i.type!==d.Project&&!r&&i.subscribeDetachedChild(p.readsValue)}p.readsValue.addValueReader(p,null)}return p.readsValue}}class JE{static initWritesValues(p,i){const r=p.initialData.writesValues.reduce((c,e)=>{if(e.type===d.GenericReference||p.writesValues.some(h=>h.id===e.id))return c;const f=Re(e,p.project);return f.setValueWriter(p,null),Mt.includes(f.type)&&(f.setParent(i,null),f.initChildren(null)),[...c,f]},[]),a=[...p.writesValues];return p.writesValues=C([...a,...r]),p.writesValues}}class QVi{}var di=(s=>(s.PROJECT_INITIALIZED="project-initialized",s.BEFORE_CHANGE_SET_CLOSE_BEFORE_SIDE_EFFECTS="before-change-set-close-before-side-effects",s.BEFORE_CHANGE_SET_CLOSE_AFTER_SIDE_EFFECTS="before-change-set-close-after-side-effects",s.CHANGE_SET_CLOSED_BEFORE_PERSIST="change-set-closed-before-persist",s.CHANGE_SET_PERSISTED="change-set-persisted",s.BEFORE_CHANGE_SET_PERSIST="before-change-set-persist",s.EXPLICIT_DEFINITION_ENTITY_ADDED="explicit-definition-entity-added",s.EXPLICIT_DEFINITION_ENTITY_REMOVED="explicit-definition-entity-removed",s.EXPLICIT_DEFINITION_ENTITY_UPDATED="explicit-definition-entity-updated",s.PERSISTED_DEFINITION_ENTITY_ADDED="persisted-definition-entity-added",s.PERSISTED_DEFINITION_ENTITY_REMOVED="persisted-definition-entity-removed",s.PERSISTED_DEFINITION_ENTITY_UPDATED="persisted-definition-entity-updated",s.RELATIONAL_DATABASE_DEFINITION_ENTITY_ADDED="relational-database-definition-entity-added",s.RELATIONAL_DATABASE_DEFINITION_ENTITY_REMOVED="relational-database-definition-entity-removed",s.RELATIONAL_DATABASE_DEFINITION_ENTITY_UPDATED="relational-database-definition-entity-updated",s))(di||{});const RL={...y$,events:new z.Events("def-proj-static-p-ctx-events")},aUe={requestActiveDynamicValue:(s,p=!1)=>null,...RL},Gt=class Gt extends un{constructor(i,r={...aUe,events:new z.Events("def-proj-inst-p-ctx-events")}){super(i);R(this,"initialData");R(this,"id");R(this,"type",d.Project);R(this,"workspaceId");R(this,"name",null);R(this,"description",null);R(this,"x");R(this,"y");R(this,"entities",[]);R(this,"projects",[]);R(this,"functions",[]);R(this,"events",[]);R(this,"variableDeclarations",[]);R(this,"variableInstances",[]);R(this,"conditions",[]);R(this,"operations",[]);R(this,"functionCalls",[]);R(this,"loops",[]);R(this,"searches",[]);R(this,"primitives",[]);R(this,"builtInBaseEntities",[]);R(this,"operationDeclarations",[]);R(this,"globalEventActionDescriptors",[]);R(this,"loopDeclarations",[]);R(this,"loopDeclarationsBodies",[]);R(this,"conditionDeclarations",[]);R(this,"valueDescriptors",[]);R(this,"dataTypes",[]);R(this,"project");R(this,"instances",{});R(this,"builtInInstances",{});R(this,"deletedInstances",{});R(this,"subscribedDefinitionEntities",new Set);R(this,"errors",[]);R(this,"references",[]);R(this,"history",[]);R(this,"undoableStackValueIndex",-1);R(this,"detachedDependents",{});R(this,"knownVersions",null);R(this,"activeVersion",!1);R(this,"initialized",!1);R(this,"startedInitialization",!1);R(this,"diggestedBuiltInBaseEntitiesIds",new Set);R(this,"rejectParallelCS",!1);R(this,"onPersistChangeSetSequentiallyCallback",null);R(this,"onPersistChangeSetInParallelCallback",null);R(this,"onAddChangeSetCallback",null);R(this,"onDiscardChangeSetCallback",null);if(this.parentContext=r,this.initialData=i,this.id=i.id,this.workspaceId=i.workspaceId,this.name=i.name,this.description=i.description,this.x=0,this.y=0,this.instances[this.id]=this,!Gt.UUID)throw new Error("UUID module is already initialized. Please inject a valid UUID module.")}static get UUID(){var i;return(i=this.parentContext.requestExtension("uuid"))==null?void 0:i.module}static new(i=null){return{id:Gt.UUID.uuid(),version:Gt.UUID.uuid(),workspaceId:"",createdAt:(i==null?void 0:i.timestamp)||B().toISOString(),author:(i==null?void 0:i.author)||Gt.sessionAuthor,previousVersion:null,deleted:!1,deletable:!0,editable:!0,type:d.Project,name:"",description:"",entities:[],functions:[],events:[],projects:[],variableDeclarations:[],variableInstances:[],conditions:[],operations:[],functionCalls:[],loops:[],searches:[]}}static validateGenerationTarget(i,r){let a=JSON.parse(JSON.stringify(i));const c=[],e=[],f=Xr(a);return e.push(...f.errors),c.push(...f.explanations),{errors:e,explanations:c,modifiedData:a}}get off(){return this.parentContext.events.off}get on(){return this.parentContext.events.on}get emit(){return this.parentContext.events.emit}get emitAsync(){return this.parentContext.events.emitAsync}get emitAsyncAll(){return this.parentContext.events.emitAsyncAll}get emitAsyncAllSettled(){return this.parentContext.events.emitAsyncAllSettled}get emitAsyncSequentially(){return this.parentContext.events.emitAsyncSequentially}get emitAsyncSequentiallyAll(){return this.parentContext.events.emitAsyncSequentiallyAll}get emitAsyncSequentiallyAllSettled(){return this.parentContext.events.emitAsyncSequentiallyAllSettled}async closePersistChangeSetsSequentially(){z.Logger.log("[ProjectState.closePersistChangeSetsSequentially] called");const i=this.history.find(r=>r.dirty&&!r.open&&!r.submitting);i&&(z.Logger.log(`[ProjectState.closePersistChangeSetsSequentially] closing pending change-set ${i.id} - ${i.actionName}`),await this.persistChangeSetSequentially(i))}async onPersistChangeSetSequentially(i){this.onPersistChangeSetSequentiallyCallback=i,z.Logger.log("[ProjectState.onPersistChangeSetSequentially] onPersistChangeSetSequentiallyCallback has been set. Checking for pending change-sets."),await this.closePersistChangeSetsSequentially()}offPersistChangeSetSequentially(){this.onPersistChangeSetSequentiallyCallback=null}async onPersistChangeSetInParallel(i){this.onPersistChangeSetInParallelCallback=i,z.Logger.log("[ProjectState.onPersistChangeSetInParallel] onPersistChangeSetInParallelCallback has been set. Checking for pending change-sets.");for(const r of this.history)this.persistChangeSetInParallel(r),await new Promise(a=>setTimeout(a,27))}offPersistChangeSetInParallel(){this.onPersistChangeSetInParallelCallback=null}onAddChangeSet(i){this.onAddChangeSetCallback=i}offAddChangeSet(){this.onAddChangeSetCallback=null}onDiscardChangeSet(i){this.onDiscardChangeSetCallback=i}offDiscardChangeSet(){this.onDiscardChangeSetCallback=null}async persistChangeSetSequentially(i){if(z.Logger.log(`[ProjectState.persistChangeSetSequentially] called for change-set ${i.id} - ${i.actionName}`),!i.dirty||i.open||i.submitting){z.Logger.log(`[ProjectState.persistChangeSetSequentially] change-set ${i.id} - ${i.actionName} is not dirty, or is open, or is already being submitted, skipping.`);return}const r=this.history.findIndex(e=>e.id===i.id),a=this.history.slice(0,r),c=a[a.length-1];if(c!=null&&c.dirty){z.Logger.log(`[ProjectState.persistChangeSetSequentially] lastBeforeSelf is dirty: ${c.id} - ${c.actionName}, closing it first.`);return}this.onPersistChangeSetSequentiallyCallback&&(z.Logger.log(`[ProjectState.persistChangeSetSequentially] invoking onPersistChangeSetSequentiallyCallback for change-set ${i.id} - ${i.actionName}`),this.emit("before-change-set-persist",i),i.submitting=!0,(await this.onPersistChangeSetSequentiallyCallback(i)).success&&(i.dirty=!1,this.emit("change-set-persisted",i),z.Logger.log(`[ProjectState.persistChangeSetSequentially] change-set ${i.id} - ${i.actionName} closed successfully, checking for pending change-sets to close.`),this.closePersistChangeSetsSequentially()))}async persistChangeSetInParallel(i){if(z.Logger.log(`[ProjectState.persistChangeSetInParallel] called for change-set ${i.id} - ${i.actionName}`),!i.dirty||i.open||i.submitting){z.Logger.log(`[ProjectState.persistChangeSetInParallel] change-set ${i.id} - ${i.actionName} is not dirty, or is open, or is already being submitted, skipping.`);return}this.onPersistChangeSetInParallelCallback&&(z.Logger.log(`[ProjectState.persistChangeSetInParallel] invoking onPersistChangeSetInParallelCallback for change-set ${i.id} - ${i.actionName}`),this.emit("before-change-set-persist",i),i.submitting=!0,(await this.onPersistChangeSetInParallelCallback(i)).success&&(i.dirty=!1,this.emit("change-set-persisted",i)))}toLatestChangeSet(i,r,a,c=!1,e="here-this"){if(!this.history.length)return new S(this,i,r,a,c,e);const f=this.history[this.history.length-1];return f.open?f:this.addChangeSet(new S(this,i,r,a,c,e))}addChangeSet(i){var a,c;if(!this.history.length)return this.undoableStackValueIndex=B_(this.undoableStackValueIndex,this.history,i),(a=this.onAddChangeSetCallback)==null||a.call(this,i,this.undoableStackValueIndex),i;const r=this.history.find(e=>e.id===(i==null?void 0:i.id));if(r)return r;if(this.rejectParallelCS){const e=this.history.find(f=>f.open);if(e)throw z.Logger.warn("Previous still open: ",e),z.Logger.warn("New change set: ",i),new Error(`There is already an open change-set with id '${e.id}'${e.actionName?` auto-close: ${e.actionName}`:""}${e.self?` root: ${e.self.type} ${oe(e.self,this)}`:""}.`)}return this.undoableStackValueIndex=B_(this.undoableStackValueIndex,this.history,i),(c=this.onAddChangeSetCallback)==null||c.call(this,i,this.undoableStackValueIndex),i}discardChangeSet(i){var a;z.Logger.log(`[ProjectState.discardChangeSet] called for change-set ${i.id} - ${i.actionName}`);const r=this.history.findIndex(c=>c.id===(i==null?void 0:i.id));return r!==-1&&(this.history.splice(r,1),z.Logger.log(`[ProjectState.discardChangeSet] Removed change-set ${i.id} - ${i.actionName} from history.`),this.undoableStackValueIndex=this.undoableStackValueIndex-1,(a=this.onDiscardChangeSetCallback)==null||a.call(this,i),i==null||i.teardown()),this}validateGeneratedUpdate(i){return{errors:[],explanations:[],modifiedData:i}}subscribeDependents(i){return i.forEach(r=>{this.detachedDependents[r.entity.id]||(this.detachedDependents[r.entity.id]=r)}),this}unsubscribeDependents(i){return i.forEach(r=>{this.detachedDependents[r.entity.id]&&delete this.detachedDependents[r.entity.id]}),this}syncDependents(i=this.project.addChangeSet(new S(this.project,Gt.sessionAuthor,B().toISOString(),this,!0,"sync-dependents"))){const r=[],a=[],c=[],e=[];return Object.values(this.detachedDependents).forEach(f=>{const h=f.entity.afterAllChildrenInitialized(i);r.push(...h.updated),a.push(...h.added),c.push(...h.removed),e.push(...h.affected)}),i==null||i.attemptAutoclose("sync-dependents",this.id),{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}onDetachedDependencyRemoved(i,r,a){const c=[],e=[],f=[],h=[];return{updated:C(c),added:C(e),removed:C(f),affected:C(h),self:this}}onDetachedDependencyRestored(i,r,a){const c=[],e=[],f=[],h=[];return{updated:C(c),added:C(e),removed:C(f),affected:C(h),self:this}}unsubscribeFromDependencies(){return this}subscribeToDependencies(){return this}increaseVersion(i){var r;if(i&&!B(i).isValid())throw new Error(`The shared timestamp '${i}' is not a valid ISO 8601 date string.`);if(i&&B(i).isSame(B(this.createdAt)))return this;if(!((r=this.knownVersions)!=null&&r.has(this.version))&&this.initialized)throw new Error(`The current ${this.type} ${this.id} version '${this.version}' is not captured in the 'knownVersions' map. Capture the current version before increasing it to avoid losing data.`);if(!this.activeVersion)throw new Error(`Only active versions can be increased. Entity with id '${this.id}' and version '${this.version}' is not active.`);return this.previousVersion=this.version,this.version=Gt.UUID.uuid(),this.createdAt=B(i).toISOString()||B().toISOString(),this}captureVersion(){var r;const i=((r=this.knownVersions)==null?void 0:r.get(this.version))||new Gt(this);if(!this.activeVersion)throw new Error(`Only active versions can be captured. Entity of type ${this.type} with id '${this.id}' and version '${this.version}' is not active.`);if(this.version!==i.version)throw new Error(`Captured ${this.type} with id '${this.id}', version '${i.version}' does not match current entity version '${this.version}'.`);return this.knownVersions=this.knownVersions?this.knownVersions.set(this.version,i):new Map().set(this.version,i),this.apply(i),this}snapshot(){const i=new Gt(this);return this.apply(i)}apply(i){const r=this.toMeta();return i.metaSync(r,null),i.entities=[...this.entities],i.projects=[...this.projects],i.functions=[...this.functions],i.events=[...this.events],i.variableDeclarations=[...this.variableDeclarations],i.variableInstances=[...this.variableInstances],i.conditions=[...this.conditions],i.operations=[...this.operations],i.functionCalls=[...this.functionCalls],i.loops=[...this.loops],i.searches=[...this.searches],i}recursiveCaptureUpstreamVersions(i){const r=[],a=[],c=[],e=[];return{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}async restoreVersion(i,r){var m;const a=[],c=[],e=[],f=[];if(this.version===i&&(r!=null&&r.skipIfSameVersion))return{updated:C(a),added:C(c),removed:C(e),affected:C(f),self:this};if(!this.knownVersions){const E=new Map;for(const[b,A]of this.knownVersions||new Map){if(E.set(b,A),A.activeVersion=!1,A.knownVersions)for(const[_,P]of A.knownVersions)E.set(_,P);A.knownVersions=null}}let h=(m=this.knownVersions)==null?void 0:m.get(i);if(!h){const E=await this.APILoadVersion({},i);if(!E)throw new Error(`Version with id '${i}' for entity with id '${this.id}' not found.`);h=new Gt(E)}return this.metaSync(h.toShallowJSON(),null),this.previousVersion=h.previousVersion,this.version=h.version,this.createdAt=h.createdAt,this.author=h.author,this.deleted=h.deleted,this.entities=[...h.entities],this.projects=[...h.projects],this.functions=[...h.functions],this.events=[...h.events],this.variableDeclarations=[...h.variableDeclarations],this.variableInstances=[...h.variableInstances],this.conditions=[...h.conditions],this.operations=[...h.operations],this.functionCalls=[...h.functionCalls],this.loops=[...h.loops],this.searches=[...h.searches],{updated:C(a),added:C(c),removed:C(e),affected:C(f),self:this}}updateWithShallowTransfer(i,r=this.project.addChangeSet(new S(this.project,Gt.sessionAuthor,B().toISOString(),this,!0,w.UpdateWithShallowTransfer))){return this.checkCanEdit(this,r)?(this.metaSync(i,r),this.version=i.version,this.createdAt=i.createdAt,this.author=i.author,this.deleted=i.deleted,this.previousVersion=i.previousVersion,this.captureVersion(),this.subscribeToDependencies(),r==null||r.attemptAutoclose(w.UpdateWithShallowTransfer,this.id),this):(z.Logger.warn(`[updateWithShallowTransfer] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.UpdateWithShallowTransfer,this.id),this)}updateWithGenerationTarget(i,r=this.project.addChangeSet(new S(this.project,Gt.sessionAuthor,B().toISOString(),this,!0,w.UpdateWithGenerationTarget))){return this.checkCanEdit(this,r)?(this.metaSync(i,r),this.captureVersion(),this.subscribeToDependencies(),r==null||r.attemptAutoclose(w.UpdateWithGenerationTarget,this.id),this):(z.Logger.warn(`[updateWithGenerationTarget] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.UpdateWithGenerationTarget,this.id),this)}hydrateAncestors(){const i=[],r=[],a=[],c=[];return{updated:C(i),added:C(r),removed:C(a),affected:C(c),self:this}}afterAllChildrenInitialized(i=null){const r=[],a=[],c=[],e=[];return this.initialized||(this.initialized=!0,this.emit("project-initialized",this,i)),this.validate(),{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}addSelfToProject(i){const r=[],a=[],c=[],e=[];return this.subscribe(),this.subscribeToDependencies(),{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}get instancesList(){return Object.values(this.instances)}get builtInInstancesList(){return Object.values(this.builtInInstances)}isOperationDeclaration(i){return this.operationDeclarations.includes(i)}isGlobalEventActionDescriptor(i){return this.globalEventActionDescriptors.includes(i)}isLoopDeclaration(i){return this.loopDeclarations.includes(i)}isConditionDeclaration(i){return this.conditionDeclarations.includes(i)}initChildren(i=this.project.addChangeSet(new S(this.project,Gt.sessionAuthor,B().toISOString(),this,!0,"init-children"))){return this.initialized||this.startedInitialization?this:(this.startedInitialization=!0,this.entities=this.initialData.entities.map(r=>{const a=Re(r,this);return a.setParent(this,null),a.initChildren(i),a}),this.projects=this.initialData.projects.map(r=>{const a=Re(r,this);return a.setParent(this,null),a.initChildren(i),a}),this.variableDeclarations=this.initialData.variableDeclarations.map(r=>{const a=Re(r,this);return a.setParent(this,null),a.initChildren(i),a}),this.variableInstances=this.initialData.variableInstances.map(r=>{const a=Re(r,this);return a.setParent(this,null),a.initChildren(i),a}),this.conditions=this.initialData.conditions.map(r=>{const a=Re(r,this);return a.setParent(this,null),a.initChildren(i),a}),this.operations=this.initialData.operations.map(r=>{const a=Re(r,this);return a.setParent(this,null),a.initChildren(i),a}),this.functions=this.initialData.functions.map(r=>{const a=Re(r,this);return a.setParent(this,null),a.initChildren(i),a}),this.events=this.initialData.events.map(r=>{const a=Re(r,this);return a.setParent(this,null),a.initChildren(i),a}),this.functionCalls=this.initialData.functionCalls.map(r=>{const a=Re(r,this);return a.setParent(this,null),a.initChildren(i),a}),this.loops=this.initialData.loops.map(r=>{const a=Re(r,this);return a.setParent(this,null),a.initChildren(i),a}),this.searches=this.initialData.searches.map(r=>{const a=Re(r,this);return a.setParent(this,null),a.initChildren(i),a}),this.attachOrphanReferences(),this.subscribeToDependencies(),this.afterAllChildrenInitialized(i),i==null||i.attemptAutoclose("init-children",this.id),this)}subscribeInstance(i){return(!this.instances[i.id]||this.instances[i.id]!==i)&&(this.instances[i.id]=i),this}subscribeDeletedInstance(i){return(!this.deletedInstances[i.id]||this.deletedInstances[i.id]!==i)&&(this.deletedInstances[i.id]=i),this}subscribeBuiltInInstance(i){return(!this.builtInInstances[i.id]||this.builtInInstances[i.id]!==i)&&(this.builtInInstances[i.id]=i),this}subscribe(){var i;return this.activeVersion=!0,(i=this.knownVersions)==null||i.forEach(r=>{r.version!==this.version&&(r.activeVersion=!1)}),this.subscribeInstance(this),this}unsubscribe(){return this}unsubscribeInstance(i){return delete this.instances[i.id],this}unsubscribeDeletedInstance(i){return delete this.deletedInstances[i.id],this}unsubscribeBuiltInInstance(i){return delete this.builtInInstances[i.id],this}findSubscribedBuiltInInstance(i){return this.builtInInstances[i.id]||null}get(i){return this.instances[i]||this.builtInInstances[i]||null}getDeleted(i){return this.deletedInstances[i]||null}getManaged(i){return this.getBuiltIn(i)?null:this.instances[i]||null}getBuiltIn(i){return this.builtInInstances[i]||null}findSubscribedInstanceFromReference(i){return this.instances[i.entityId]||null}findSubscribedBuiltInInstanceFromReference(i){return this.builtInInstances[i.entityId]||null}metaSync(i,r=this.project.addChangeSet(new S(this.project,Gt.sessionAuthor,B().toISOString(),this,!0,"meta-sync"))){const a=tn(this,i,r),c=en(this,a),e=this.toMeta();return this.name=a.name!==void 0?a.name:e.name,this.description=a.description!==void 0?a.description:e.description,this.x=a.x||e.x,this.y=a.y||e.y,super.baseMetaSync(a,this,r),a.deleted===!0&&!e.deleted?r==null||r.add(this,W.Removed):a.deleted===!1&&e.deleted?r==null||r.add(this,W.Added):c&&(r==null||r.add(this,W.Updated)),r==null||r.attemptAutoclose("meta-sync",this.id),this}async APILoad(i=Ke,...r){return await Gt.repository.APILoad(this.id,...r),this}async APICreate(i=Ke,...r){return await Gt.repository.APICreate(this.toShallowJSON(),...r),this}async APIUpdate(i=Ke,...r){return await Gt.repository.APIUpdate(this.toShallowJSON(),...r),this}async APIDelete(i=Ke,...r){return await Gt.repository.APIDelete(this.toShallowJSON(),...r),this}async APIClone(i=Ke,...r){return await Gt.repository.APIClone(this.id,...r),this}async APILoadVersion(i=Ke,r,...a){return await Gt.repository.APILoadVersion(this.id,r,...a)}remove({ignoreUpstream:i}={ignoreUpstream:!1},r=this.project.addChangeSet(new S(this.project,Gt.sessionAuthor,B().toISOString(),this,!0,w.RemoveEntity))){return{added:[],updated:[],removed:[],affected:[],self:this}}restore({}={},i=this.project.addChangeSet(new S(this.project,Gt.sessionAuthor,B().toISOString(),this,!0,w.RestoreEntity))){return{added:[],updated:[],removed:[],affected:[],self:this}}getAllBuiltInIds(){const i=new Set;return[...this.primitives.flatMap(r=>r.toFlatIds(i)),...this.builtInBaseEntities.flatMap(r=>r.toFlatIds(i)),...this.operationDeclarations.flatMap(r=>r.toFlatIds(i)),...this.globalEventActionDescriptors.flatMap(r=>r.toFlatIds(i)),...this.loopDeclarations.flatMap(r=>r.toFlatIds(i)),...this.conditionDeclarations.flatMap(r=>r.toFlatIds(i)),...this.valueDescriptors.flatMap(r=>r.toFlatIds(i)),...this.dataTypes.flatMap(r=>r.toFlatIds(i))]}getAllBuiltIn(){const i=new Set;return[...this.primitives.flatMap(r=>r.toFlat(i)),...this.builtInBaseEntities.flatMap(r=>r.toFlat(i)),...this.operationDeclarations.flatMap(r=>r.toFlat(i)),...this.globalEventActionDescriptors.flatMap(r=>r.toFlat(i)),...this.loopDeclarations.flatMap(r=>r.toFlat(i)),...this.conditionDeclarations.flatMap(r=>r.toFlat(i)),...this.valueDescriptors.flatMap(r=>r.toFlat(i)),...this.dataTypes.flatMap(r=>r.toFlat(i))]}toFlat(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this,...this.entities.flatMap(a=>a.toFlat(i)),...this.functions.flatMap(a=>a.toFlat(i)),...this.events.flatMap(a=>a.toFlat(i)),...this.projects.flatMap(a=>a.toFlat(i)),...this.variableDeclarations.flatMap(a=>a.toFlat(i)),...this.variableInstances.flatMap(a=>a.toFlat(i)),...this.conditions.flatMap(a=>a.toFlat(i)),...this.operations.flatMap(a=>a.toFlat(i)),...this.functionCalls.flatMap(a=>a.toFlat(i)),...this.loops.flatMap(a=>a.toFlat(i)),...this.searches.flatMap(a=>a.toFlat(i))])}toFlatIds(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this.id,...this.entities.flatMap(a=>a.toFlatIds(i)),...this.functions.flatMap(a=>a.toFlatIds(i)),...this.events.flatMap(a=>a.toFlatIds(i)),...this.projects.flatMap(a=>a.toFlatIds(i)),...this.variableDeclarations.flatMap(a=>a.toFlatIds(i)),...this.variableInstances.flatMap(a=>a.toFlatIds(i)),...this.conditions.flatMap(a=>a.toFlatIds(i)),...this.operations.flatMap(a=>a.toFlatIds(i)),...this.functionCalls.flatMap(a=>a.toFlatIds(i)),...this.loops.flatMap(a=>a.toFlatIds(i)),...this.searches.flatMap(a=>a.toFlatIds(i))])}toMeta(){return{id:this.id,version:this.version,workspaceId:this.workspaceId,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,description:this.description,type:this.type,editable:this.editable,deletable:this.deletable,name:this.name}}toJSON(i=new Set){return i.has(this.id)?this.toReference():(i.add(this.id),{id:this.id,version:this.version,workspaceId:this.workspaceId,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,editable:this.editable,deletable:this.deletable,name:this.name,description:this.description,entities:this.entities.map(r=>r.toJSON(i)),variableDeclarations:this.variableDeclarations.map(r=>r.toJSON(i)),variableInstances:this.variableInstances.map(r=>r.toJSON(i)),conditions:this.conditions.map(r=>r.toJSON(i)),operations:this.operations.map(r=>r.toJSON(i)),loops:this.loops.map(r=>r.toJSON(i)),searches:this.searches.map(r=>r.toJSON(i)),functions:this.functions.map(r=>r.toJSON(i)),events:this.events.map(r=>r.toJSON(i)),projects:this.projects.map(r=>r.toJSON(i)),functionCalls:this.functionCalls.map(r=>r.toJSON(i))})}toJSONClone(i={uuidStrategy:"uuid"}){const r=new Map,a=new Set,c=this.getAllBuiltInIds();return Object.keys(this.instances).forEach(e=>{if(c.includes(e)){r.set(e,e);return}r.set(e,Gt.UUID.uuid())}),a.add(this.id),{id:r.get(this.id),version:this.version,workspaceId:this.workspaceId,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,editable:this.editable,deletable:this.deletable,name:this.name,description:this.description,entities:this.entities.map(e=>e.toJSONClone({...i,seenEntityMaps:r,seenEntities:a,newId:null})),projects:this.projects.map(e=>e.toJSONClone({...i,seenEntityMaps:r,seenEntities:a,newId:null})),variableDeclarations:this.variableDeclarations.map(e=>e.toJSONClone({...i,seenEntityMaps:r,seenEntities:a,newId:null})),variableInstances:this.variableInstances.map(e=>e.toJSONClone({...i,seenEntityMaps:r,seenEntities:a,newId:null})),conditions:this.conditions.map(e=>e.toJSONClone({...i,seenEntityMaps:r,seenEntities:a,newId:null})),operations:this.operations.map(e=>e.toJSONClone({...i,seenEntityMaps:r,seenEntities:a,newId:null})),functions:this.functions.map(e=>e.toJSONClone({...i,seenEntityMaps:r,seenEntities:a,newId:null})),events:this.events.map(e=>e.toJSONClone({...i,seenEntityMaps:r,seenEntities:a,newId:null})),functionCalls:this.functionCalls.map(e=>e.toJSONClone({...i,seenEntityMaps:r,seenEntities:a,newId:null})),loops:this.loops.map(e=>e.toJSONClone({...i,seenEntityMaps:r,seenEntities:a,newId:null})),searches:this.searches.map(e=>e.toJSONClone({...i,seenEntityMaps:r,seenEntities:a,newId:null}))}}toReference(i=at){var a;let r=this.id;return(a=i.seenEntityMaps)!=null&&a.has(this.id)&&(r=i.seenEntityMaps.get(this.id)),{id:r+"--"+Gt.UUID.uuid()+"--ref",type:d.GenericReference,entityId:r,version:this.version,entityType:this.type}}toShallowJSON(i=at){var a;let r=this.id;return(a=i.seenEntityMaps)!=null&&a.has(this.id)&&(r=i.seenEntityMaps.get(this.id)),{id:r,version:this.version,workspaceId:this.workspaceId,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,editable:this.editable,deletable:this.deletable,name:this.name,description:this.description,entities:this.entities.map(c=>c.toReference(i)),functions:this.functions.map(c=>c.toReference(i)),events:this.events.map(c=>c.toReference(i)),projects:this.projects.map(c=>c.toReference(i)),variableDeclarations:this.variableDeclarations.map(c=>c.toReference(i)),variableInstances:this.variableInstances.map(c=>c.toReference(i)),conditions:this.conditions.map(c=>c.toReference(i)),operations:this.operations.map(c=>c.toReference(i)),functionCalls:this.functionCalls.map(c=>c.toReference(i)),loops:this.loops.map(c=>c.toReference(i)),searches:this.searches.map(c=>c.toReference(i))}}toFlatJSON(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this.toShallowJSON(),...this.entities.flatMap(a=>a.toFlatJSON(i)),...this.functions.flatMap(a=>a.toFlatJSON(i)),...this.events.flatMap(a=>a.toFlatJSON(i)),...this.projects.flatMap(a=>a.toFlatJSON(i)),...this.variableDeclarations.flatMap(a=>a.toFlatJSON(i)),...this.variableInstances.flatMap(a=>a.toFlatJSON(i)),...this.conditions.flatMap(a=>a.toFlatJSON(i)),...this.operations.flatMap(a=>a.toFlatJSON(i)),...this.functionCalls.flatMap(a=>a.toFlatJSON(i)),...this.loops.flatMap(a=>a.toFlatJSON(i)),...this.searches.flatMap(a=>a.toFlatJSON(i))])}toGenerationTarget(i=at){var a;let r=this.id;return(a=i.seenEntityMaps)!=null&&a.has(this.id)&&(r=i.seenEntityMaps.get(this.id)),{id:r,workspaceId:this.workspaceId,type:this.type,name:this.name,description:this.description}}toFlatGenerationTarget(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[...this.entities.flatMap(a=>a.toFlatGenerationTarget(i)),...this.functions.flatMap(a=>a.toFlatGenerationTarget(i)),...this.events.flatMap(a=>a.toFlatGenerationTarget(i)),...this.projects.flatMap(a=>a.toFlatGenerationTarget(i)),...this.variableDeclarations.flatMap(a=>a.toFlatGenerationTarget(i)),...this.variableInstances.flatMap(a=>a.toFlatGenerationTarget(i)),...this.conditions.flatMap(a=>a.toFlatGenerationTarget(i)),...this.operations.flatMap(a=>a.toFlatGenerationTarget(i)),...this.functionCalls.flatMap(a=>a.toFlatGenerationTarget(i)),...this.loops.flatMap(a=>a.toFlatGenerationTarget(i)),...this.searches.flatMap(a=>a.toFlatGenerationTarget(i))])}clearErrors(){return this.errors=[],this.entities.forEach(i=>i.clearErrors()),this.projects.forEach(i=>i.clearErrors()),this.functions.forEach(i=>i.clearErrors()),this.events.forEach(i=>i.clearErrors()),this.variableDeclarations.forEach(i=>i.clearErrors()),this.variableInstances.forEach(i=>i.clearErrors()),this.conditions.forEach(i=>i.clearErrors()),this.operations.forEach(i=>i.clearErrors()),this.functionCalls.forEach(i=>i.clearErrors()),this.loops.forEach(i=>i.clearErrors()),this.searches.forEach(i=>i.clearErrors()),this}validate(){return this.validateChildren(),bE([...this.errors]),{success:!0}}async validateAsync(i={}){const r=z.YieldTracker.from(i);return await this.validateChildrenAsync({tracker:r}),await R_e([...this.errors]),{success:!0}}validateChildren(){this.entities.forEach(i=>i.validate()),this.projects.forEach(i=>i.validate()),this.functions.forEach(i=>i.validate()),this.events.forEach(i=>i.validate()),this.variableDeclarations.forEach(i=>i.validate()),this.variableInstances.forEach(i=>i.validate()),this.conditions.forEach(i=>i.validate()),this.operations.forEach(i=>i.validate()),this.functionCalls.forEach(i=>i.validate()),this.loops.forEach(i=>i.validate()),this.searches.forEach(i=>i.validate())}async validateChildrenAsync(i={}){const r=z.YieldTracker.from(i);for(let a=0;a<this.entities.length;a++)await this.entities[a].validateAsync({tracker:r});for(let a=0;a<this.projects.length;a++)await this.projects[a].validateAsync({tracker:r});for(let a=0;a<this.functions.length;a++)await this.functions[a].validateAsync({tracker:r});for(let a=0;a<this.events.length;a++)await this.events[a].validateAsync({tracker:r});for(let a=0;a<this.variableDeclarations.length;a++)await this.variableDeclarations[a].validateAsync({tracker:r});for(let a=0;a<this.variableInstances.length;a++)await this.variableInstances[a].validateAsync({tracker:r});for(let a=0;a<this.conditions.length;a++)await this.conditions[a].validateAsync({tracker:r});for(let a=0;a<this.operations.length;a++)await this.operations[a].validateAsync({tracker:r});for(let a=0;a<this.functionCalls.length;a++)await this.functionCalls[a].validateAsync({tracker:r});for(let a=0;a<this.loops.length;a++)await this.loops[a].validateAsync({tracker:r});for(let a=0;a<this.searches.length;a++)await this.searches[a].validateAsync({tracker:r})}getErrors(){return[...this.errors,...this.entities.flatMap(r=>r.getErrors()),...this.projects.flatMap(r=>r.getErrors()),...this.functions.flatMap(r=>r.getErrors()),...this.events.flatMap(r=>r.getErrors()),...this.variableDeclarations.flatMap(r=>r.getErrors()),...this.variableInstances.flatMap(r=>r.getErrors()),...this.conditions.flatMap(r=>r.getErrors()),...this.operations.flatMap(r=>r.getErrors()),...this.functionCalls.flatMap(r=>r.getErrors()),...this.loops.flatMap(r=>r.getErrors()),...this.searches.flatMap(r=>r.getErrors())]}async getErrorsAsync(i={}){const r=z.YieldTracker.from(i),a=[...this.errors];await r.tick();for(let c=0;c<this.entities.length;c++){const e=await this.entities[c].getErrorsAsync({tracker:r});a.push(...e)}for(let c=0;c<this.projects.length;c++){const e=await this.projects[c].getErrorsAsync({tracker:r});a.push(...e)}for(let c=0;c<this.functions.length;c++){const e=await this.functions[c].getErrorsAsync({tracker:r});a.push(...e)}for(let c=0;c<this.events.length;c++){const e=await this.events[c].getErrorsAsync({tracker:r});a.push(...e)}for(let c=0;c<this.variableDeclarations.length;c++){const e=await this.variableDeclarations[c].getErrorsAsync({tracker:r});a.push(...e)}for(let c=0;c<this.variableInstances.length;c++){const e=await this.variableInstances[c].getErrorsAsync({tracker:r});a.push(...e)}for(let c=0;c<this.conditions.length;c++){const e=await this.conditions[c].getErrorsAsync({tracker:r});a.push(...e)}for(let c=0;c<this.operations.length;c++){const e=await this.operations[c].getErrorsAsync({tracker:r});a.push(...e)}for(let c=0;c<this.functionCalls.length;c++){const e=await this.functionCalls[c].getErrorsAsync({tracker:r});a.push(...e)}for(let c=0;c<this.loops.length;c++){const e=await this.loops[c].getErrorsAsync({tracker:r});a.push(...e)}for(let c=0;c<this.searches.length;c++){const e=await this.searches[c].getErrorsAsync({tracker:r});a.push(...e)}return a}getShallowErrors(){return this.errors}clone(){return this}addDefinitionEntity(i){return this.entities.includes(i)||this.entities.push(i),i}addFunctionDeclaration(i){return this.functions.includes(i)||this.functions.push(i),i}addFunctionCall(i){return this.functionCalls.includes(i)||this.functionCalls.push(i),i}addVariableDeclaration(i){return this.variableDeclarations.includes(i)||this.variableDeclarations.push(i),i}addVariableInstance(i){return this.variableInstances.includes(i)||this.variableInstances.push(i),i}addInstalledProject(i){return this.projects.includes(i)||this.projects.push(i),this}addGlobalEvent(i){return this.events.includes(i)||this.events.push(i),this}addCondition(i){return this.conditions.includes(i)||this.conditions.push(i),this}addOperation(i){return this.operations.includes(i)||this.operations.push(i),this}addLoop(i){return this.loops.includes(i)||this.loops.push(i),this}addSearch(i){return this.searches.includes(i)||this.searches.push(i),this}removeDefinitionEntity(i){const r=this.entities.findIndex(a=>a.id===i.id);if(r>-1){const a=this.entities[r];return this.entities.splice(r,1),a}return null}removeCondition(i){const r=this.conditions.findIndex(a=>a.id===i.id);if(r>-1){const a=this.conditions[r];return this.conditions.splice(r,1),a}return null}removeOperation(i){const r=this.operations.findIndex(a=>a.id===i.id);if(r>-1){const a=this.operations[r];return this.operations.splice(r,1),a}return null}removeLoop(i){const r=this.loops.findIndex(a=>a.id===i.id);if(r>-1){const a=this.loops[r];return this.loops.splice(r,1),a}return null}removeSearch(i){const r=this.searches.findIndex(a=>a.id===i.id);if(r>-1){const a=this.searches[r];return this.searches.splice(r,1),a}return null}removeFunctionCall(i){const r=this.functionCalls.findIndex(a=>a.id===i.id);if(r>-1){const a=this.functionCalls[r];return this.functionCalls.splice(r,1),a}return null}removeVariableInstance(i){const r=this.variableInstances.findIndex(a=>a.id===i.id);if(r>-1){const a=this.variableInstances[r];return this.variableInstances.splice(r,1),a}return null}removeVariableDeclaration(i){const r=this.variableDeclarations.findIndex(a=>a.id===i.id);if(r>-1){const a=this.variableDeclarations[r];return this.variableDeclarations.splice(r,1),a}return null}removeFunctionDeclaration(i){const r=this.functions.findIndex(a=>a.id===i.id);if(r>-1){const a=this.functions[r];return this.functions.splice(r,1),a}return null}removeInstalledProject(i){const r=this.projects.findIndex(a=>a.id===i.id);if(r>-1){const a=this.projects[r];return this.projects.splice(r,1),a}return null}removeGlobalEvent(i){const r=this.events.findIndex(a=>a.id===i.id);if(r>-1){const a=this.events[r];return this.events.splice(r,1),a}return null}removeTopLevelVariableDeclaration(i){if(i.type!==d.VariableDeclaration)return null;const r=this.variableDeclarations.findIndex(a=>a.id===i.id);if(r>-1){const a=this.variableDeclarations[r];return this.variableDeclarations.splice(r,1),a}return null}getEntryPoints(){return[...this.functions,...this.events,...this.entities.flatMap(r=>r.methods)]}getTerminationStatements(){return[...this.getEntryPoints().reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.ReturnStatement||e.type===d.ContinueStatement||e.type===d.BreakStatement)]},[])]}getFunctionDeclaration(i){return this.functions.find(r=>r.id===i)||null}getConditions(){return[...this.conditions,...this.getEntryPoints().reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Condition)]},[]),...this.functionCalls.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Condition)]},[]),...this.operations.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Condition)]},[]),...this.loops.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Condition)]},[]),...this.searches.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Condition)]},[])]}getOperations(){return[...this.operations,...this.getEntryPoints().reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Operation)]},[]),...this.functionCalls.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Operation)]},[]),...this.conditions.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Operation)]},[]),...this.loops.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Operation)]},[]),...this.searches.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Operation)]},[])]}getFunctionCalls(){return[...this.functionCalls,...this.getEntryPoints().reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.FunctionCall)]},[]),...this.conditions.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.FunctionCall)]},[]),...this.operations.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.FunctionCall)]},[]),...this.loops.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.FunctionCall)]},[]),...this.searches.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.FunctionCall)]},[])]}getDefinitionEntities(i=new Set){return Array.from(this.subscribedDefinitionEntities).filter(a=>!i.has(a)).map(a=>this.get(a))}getVariables(){return[...this.variableDeclarations,...this.getEntryPoints().reduce((r,a)=>{const c=cr(a);return[...r,...c]},[]),...this.functionCalls.reduce((r,a)=>{const c=cr(a);return[...r,...c]},[]),...this.conditions.reduce((r,a)=>{const c=cr(a);return[...r,...c]},[]),...this.operations.reduce((r,a)=>{const c=cr(a);return[...r,...c]},[]),...this.loops.reduce((r,a)=>{const c=cr(a);return[...r,...c]},[]),...this.searches.reduce((r,a)=>{const c=cr(a);return[...r,...c]},[])]}getVariableInstances(){return[...this.variableInstances,...this.entities.reduce((r,a)=>[...r,...a.methods.flatMap(c=>{const f=pt(c).filter(h=>h.type===d.VariableInstance);return[...r,...f]})],[]),...this.getEntryPoints().reduce((r,a)=>{const e=cr(a).filter(f=>f.type===d.VariableInstance);return[...r,...e]},[]),...this.functionCalls.reduce((r,a)=>{const e=cr(a).filter(f=>f.type===d.VariableInstance);return[...r,...e]},[]),...this.conditions.reduce((r,a)=>{const e=cr(a).filter(f=>f.type===d.VariableInstance);return[...r,...e]},[]),...this.operations.reduce((r,a)=>{const e=cr(a).filter(f=>f.type===d.VariableInstance);return[...r,...e]},[]),...this.loops.reduce((r,a)=>{const e=cr(a).filter(f=>f.type===d.VariableInstance);return[...r,...e]},[]),...this.searches.reduce((r,a)=>{const e=cr(a).filter(f=>f.type===d.VariableInstance);return[...r,...e]},[])]}getVariableDeclarations(){return C([...this.variableDeclarations,...this.entities.reduce((r,a)=>[...r,...a.methods.flatMap(c=>{const f=pt(c).filter(h=>h.type===d.VariableDeclaration);return[...r,...f]})],[]),...this.getEntryPoints().reduce((r,a)=>{const e=cr(a).filter(f=>f.type===d.VariableDeclaration);return[...r,...e]},[]),...this.functionCalls.reduce((r,a)=>{const e=cr(a).filter(f=>f.type===d.VariableDeclaration);return[...r,...e]},[]),...this.conditions.reduce((r,a)=>{const e=cr(a).filter(f=>f.type===d.VariableDeclaration);return[...r,...e]},[]),...this.operations.reduce((r,a)=>{const e=cr(a).filter(f=>f.type===d.VariableDeclaration);return[...r,...e]},[]),...this.loops.reduce((r,a)=>{const e=cr(a).filter(f=>f.type===d.VariableDeclaration);return[...r,...e]},[]),...this.searches.reduce((r,a)=>{const e=cr(a).filter(f=>f.type===d.VariableDeclaration);return[...r,...e]},[])])}getLoops(){return[...this.loops,...this.getEntryPoints().reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Loop)]},[]),...this.functionCalls.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Loop)]},[]),...this.conditions.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Loop)]},[]),...this.operations.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Loop)]},[]),...this.searches.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Loop)]},[])]}getSearches(){return[...this.searches,...this.getEntryPoints().reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Search)]},[]),...this.functionCalls.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Search)]},[]),...this.conditions.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Search)]},[]),...this.operations.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Search)]},[]),...this.loops.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Search)]},[])]}attachOrphanReferences(){const i=this.getVariableInstances(),r=this.getVariableDeclarations();return i.forEach(a=>{if(!a.declaration){const c=a.initialData,e=c.declaration.entityId||c.declaration.id,f=r.find(h=>h.id===e);f&&a.setDeclaration(f)}}),this}getBuiltInPersistedEntity(){return this.builtInBaseEntities.find(i=>i.name===ge.PERSISTED_ENTITY)||null}requestActiveDynamicValue(i,r=!1){var c,e;const a=(e=(c=this.parentContext).requestActiveDynamicValue)==null?void 0:e.call(c,i,r);if(!a&&pI.includes(i.type)){const f=i.getDefaultValue();return f?{value:f,type:Be.DefaultValue,inheritanceLink:null,valueOwner:i}:null}return a||null}requestExtension(i){if(this.parentContext.requestExtension){const r=this.parentContext.requestExtension(i);if(r&&!r.module)throw new Error(`Module ${i} is not registered properly.`);return r.module||null}return null}undo(){z.Logger.log("Undoing, from: ",this.undoableStackValueIndex),this.undoableStackValueIndex=this.undoableStackValueIndex-1,z.Logger.log("To: ",this.undoableStackValueIndex);const i=this.history[this.undoableStackValueIndex+1],r=this.history[this.undoableStackValueIndex];return z.Logger.log("Current change set: ",i==null?void 0:i.toJSON()),z.Logger.log("Change set to restore: ",r==null?void 0:r.toJSON()),$_(i||"initial",r||"initial",this)}redo(){z.Logger.log("Undoing, from: ",this.undoableStackValueIndex),this.undoableStackValueIndex=this.undoableStackValueIndex+1,z.Logger.log("To: ",this.undoableStackValueIndex);const i=this.history[this.undoableStackValueIndex-1],r=this.history[this.undoableStackValueIndex];return z.Logger.log("Current change set: ",i==null?void 0:i.toJSON()),z.Logger.log("Change set to restore: ",r.toJSON()),$_(i||"initial",r||"initial",this)}applyExternalChangeSet(i){const r=i.payload,a=this.addChangeSet(new S(this,i.userAuthor,i.emittedAt,this));a.ignoreNonEditable=!0,a.ignoreNonDeletable=!0;const c=r.updated[this.id];if(!c)throw new Error("Project root not found in change set transfer. Cannot apply changes.");const e={...r.added,...r.updated,...r.removed},f=[...Object.keys(r.added),...Object.keys(r.updated),...Object.keys(r.removed)];f.forEach(m=>{var E;if(!e[m]){z.Logger.warn(`Entity '${m}' not found in change set transfer. Cannot apply changes.`);const b=(E=this.get(m))==null?void 0:E.toShallowJSON();throw b?z.Logger.warn("Entity in project: ",b):z.Logger.warn("Entity not in project"),new Error(`Entity '${m}' not found in change set transfer. Cannot apply changes.`)}});const h=new Fn(c,{allBuiltInEntityIds:this.diggestedBuiltInBaseEntitiesIds});return h.flatRecord=e,h.order=f,h.orderEntities(),z.Logger.log("All entities: ",h.order.map((m,E)=>`${E+1}: ${e[m].type} - ${m}`).join(`,
|
|
605
|
+
Alternatively you can update the parent data-type entity with 'update' action to remove the existing value of the field.`}))}return{errors:e,explanations:c,modifiedData:a}}get interactive(){return this.implements.length?this.implements.every(i=>i.interactive):!0}get allMethods(){return C([...this.ownDeclaredMethods,...this.allBaseMethodsFromOriginalParents])}get allProperties(){return C([...this.ownDeclaredProperties,...this.allBasePropertiesFromOriginalParents])}get allBaseMethodsFromOriginalParents(){var a;const i=((a=this.extends)==null?void 0:a.type)===d.DefinitionEntity?this.extends.allMethods:[],r=[...i].filter(c=>!i.some(e=>{var f,h;return e.id!==c.id&&(((f=e.implements)==null?void 0:f.id)===c.id||((h=e.extends)==null?void 0:h.id)===c.id)}));return C([...r,...this.implements.flatMap(c=>{const e=c.type===d.DefinitionEntity?[...c.allMethods]:[];return[...e].filter(h=>!e.some(m=>{var E,b;return m.id!==h.id&&(((E=m.implements)==null?void 0:E.id)===h.id||((b=m.extends)==null?void 0:b.id)===h.id)}))})])}get allBasePropertiesFromOriginalParents(){var c;const i=((c=this.extends)==null?void 0:c.allProperties)||[],r=[...i].filter(e=>!i.some(f=>{var h;return f.id!==e.id&&(!!f.implements.find(m=>m.id===e.id)||((h=f.extends)==null?void 0:h.id)===e.id)}));return C([...r,...this.implements.flatMap(e=>{const f=[...e.allProperties];return[...f].filter(m=>!f.some(E=>{var b;return E.id!==m.id&&(!!E.implements.find(A=>A.id===m.id)||((b=E.extends)==null?void 0:b.id)===m.id)}))})])}get allBasePropertiesFromExtendedAndImplementedEntities(){var c,e;const i=[...((c=this.extends)==null?void 0:c.ownDeclaredProperties)||[],...((e=this.extends)==null?void 0:e.allBasePropertiesFromExtendedAndImplementedEntities)||[]].filter(f=>!f.abstract),r=[...i].filter(f=>!i.some(h=>{var m;return h.id!==f.id&&(!!h.implements.find(E=>E.id===f.id)||((m=h.extends)==null?void 0:m.id)===f.id)})),a=this.implements.reduce((f,h)=>{const m=h.implementedPropertiesFromOriginalParents,E=[...h.ownDeclaredProperties].filter(_=>!_.abstract),b=[...m,...E,...f];return[...b].filter(_=>!!!b.find(V=>{var G;return!!V.implements.find(M=>M.id===_.id)||((G=V.extends)==null?void 0:G.id)===_.id}))},[]);return C([...r,...a])}get allBaseMethodsFromExtendedAndImplementedEntities(){return C([...(this.extends?[this.extends]:[]).reduce((i,r)=>r.type!==d.DefinitionEntity?[]:[...[...r.ownDeclaredMethods,...r.allBaseMethodsFromExtendedAndImplementedEntities].filter(c=>c.type!==d.ActionDescriptor),...i],[]),...this.implements.reduce((i,r)=>r.type!==d.DefinitionEntity?r.abstractMethods:[...[...r.ownDeclaredMethods,...r.allBaseMethodsFromExtendedAndImplementedEntities].filter(c=>c.type!==d.ActionDescriptor),...i],[])])}get extendedPropertiesFromOriginalParents(){var a,c;const i=[...((a=this.extends)==null?void 0:a.ownDeclaredProperties)||[],...((c=this.extends)==null?void 0:c.extendedPropertiesFromOriginalParents)||[]].filter(e=>!e.abstract),r=[...i].filter(e=>!i.some(f=>{var h;return f.id!==e.id&&(!!f.implements.find(m=>m.id===e.id)||((h=f.extends)==null?void 0:h.id)===e.id)}));return C(r)}get implementedPropertiesFromOriginalParents(){return C([...(this.extends?[this.extends]:[]).reduce((i,r)=>{const a=r.implementedPropertiesFromOriginalParents,c=[...r.ownDeclaredProperties].filter(h=>!!h.abstract),e=[...a,...c,...i];return[...e].filter(h=>!!!e.find(E=>{var b;return((b=E.extends)==null?void 0:b.id)===h.id||!!E.implements.find(A=>A.id===h.id)}))},[]),...this.implements.reduce((i,r)=>{const a=r.implementedPropertiesFromOriginalParents,c=[...r.ownDeclaredProperties].filter(h=>!!h.abstract),e=[...a,...c,...i];return[...e].filter(h=>!!!e.find(E=>{var b;return!!E.implements.find(A=>A.id===h.id)||((b=E.extends)==null?void 0:b.id)===h.id}))},[])].filter(i=>!!i.abstract))}get extendedMethodsFromOriginalParents(){return C((this.extends?[this.extends]:[]).reduce((i,r)=>{if(r.type!==d.DefinitionEntity)return[];const a=[...r.ownDeclaredMethods,...r.extendedMethodsFromOriginalParents].filter(c=>c.type!==d.ActionDescriptor);return[...i,...a]},[]))}get implementedMethodsFromOriginalParents(){return C([...(this.extends?[this.extends]:[]).reduce((i,r)=>{const a=r.type===d.DefinitionEntity?r.methods:[],c=[...r.abstractMethods].filter(e=>!a.find(f=>f.name===e.name));return[...a,...c,...i]},[]),...this.implements.reduce((i,r)=>[...r.abstractMethods,...i],[])].filter(i=>i.type===d.ActionDescriptor))}get extendedProperties(){return this.properties.filter(i=>i.isExtendedProperty)}get ownDeclaredProperties(){return this.properties.filter(r=>!r.isExtendedProperty)}get extendedMethods(){return this.methods.filter(i=>i.isExtendedMethod)}get ownDeclaredMethods(){return this.methods.filter(i=>!i.isExtendedMethod)}validateGeneratedUpdate(i){const r=[],a=[];return i.parent&&r.push(new we({id:`${this.id}--${Te.InvalidParentUpdate}`,code:Te.InvalidParentUpdate,severity:ve.Error,message:`Entity of type '${this.type}' with id '${this.id}' cannot have the 'parent' property updated. The 'parent' on an '${this.type}', must be the root project as it is a globally declared entity.`})),{errors:r,explanations:a,modifiedData:i}}subscribeDependents(i){return i.forEach(r=>{this.detachedDependents[r.entity.id]||(this.detachedDependents[r.entity.id]=r)}),this}unsubscribeDependents(i){return i.forEach(r=>{this.detachedDependents[r.entity.id]&&delete this.detachedDependents[r.entity.id]}),this}syncDependents(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"sync-dependents"))){const r=[],a=[],c=[],e=[];return Object.values(this.detachedDependents).forEach(f=>{const h=f.entity.afterAllChildrenInitialized(i);r.push(...h.updated),a.push(...h.added),c.push(...h.removed),e.push(...h.affected)}),i==null||i.attemptAutoclose("sync-dependents",this.id),{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}onDetachedDependencyRemoved(i,r,a){const c=[],e=[],f=[],h=[];return r==="implements"&&(this.removeImplementation(i,a),c.push(this)),r==="extends"&&(this.setExtension(null,a),c.push(this)),{updated:C(c),added:C(e),removed:C(f),affected:C(h),self:this}}onDetachedDependencyRestored(i,r,a){const c=[],e=[],f=[],h=[];return r==="implements"&&(this.addImplementation(i,a),c.push(this)),r==="extends"&&(this.setExtension(i,a),c.push(this)),{updated:C(c),added:C(e),removed:C(f),affected:C(h),self:this}}unsubscribeFromDependencies(){return this.implements.forEach(i=>{ma.includes(i.type)||i.unsubscribeDependents([{entity:this,field:"implements"}])}),this.extends&&(ma.includes(this.extends.type)||this.extends.unsubscribeDependents([{entity:this,field:"extends"}])),this}subscribeToDependencies(){return this.implements.forEach(i=>{ma.includes(i.type)||i.subscribeDependents([{entity:this,field:"implements"}])}),this.extends&&(ma.includes(this.extends.type)||this.extends.subscribeDependents([{entity:this,field:"extends"}])),this}increaseVersion(i){var r;if(this.project.diggestedBuiltInBaseEntitiesIds.has(this.id))return this;if(i&&!B(i).isValid())throw new Error(`The shared timestamp '${i}' is not a valid ISO 8601 date string.`);if(i&&B(i).isSame(B(this.createdAt)))return this;if(!((r=this.knownVersions)!=null&&r.has(this.version))&&this.project.initialized)throw new Error(`The current ${this.type} ${this.id} version '${this.version}' is not captured in the 'knownVersions' map. Capture the current version before increasing it to avoid losing data.`);if(!this.activeVersion)throw new Error(`Only active versions can be increased. Entity with id '${this.id}' and version '${this.version}' is not active.`);return this.previousVersion=this.version,this.version=x.UUID.uuid(),this.createdAt=B(i).toISOString()||B().toISOString(),this}captureVersion(){var r;const i=((r=this.knownVersions)==null?void 0:r.get(this.version))||new Ni(this,this.project);if(!this.activeVersion)throw new Error(`Only active versions can be captured. Entity of type ${this.type} with id '${this.id}' and version '${this.version}' is not active.`);if(this.version!==i.version)throw new Error(`Captured ${this.type} with id '${this.id}', version '${i.version}' does not match current entity version '${this.version}'.`);return this.knownVersions=this.knownVersions?this.knownVersions.set(this.version,i):new Map().set(this.version,i),this.apply(i),this}snapshot(){const i=new Ni(this,this.project);return this.apply(i)}apply(i){const r=this.toMeta();return i.metaSync(r,null),i.properties=[...this.properties],i.methods=[...this.methods],i.abstractMethods=[...this.abstractMethods],i.extends=this.extends,i.implements=[...this.implements],i.allPropertiesImplement=this.allPropertiesImplement,i.additionalPropertiesDataType=this.additionalPropertiesDataType,i.parent=this.parent,i}recursiveCaptureUpstreamVersions(i){const r=[],a=[],c=[],e=[];if(this.parent){this.parent.increaseVersion(i);const f=this.parent.recursiveCaptureUpstreamVersions(i);r.push(this.parent,...f.updated),a.push(...f.added),c.push(...f.removed)}return{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}async restoreVersion(i,r){var m;const a=[],c=[],e=[],f=[];if(this.version===i&&(r!=null&&r.skipIfSameVersion))return{updated:C(a),added:C(c),removed:C(e),affected:C(f),self:this};if(!this.knownVersions){const E=new Map;for(const[b,A]of this.knownVersions||new Map){if(E.set(b,A),A.activeVersion=!1,A.knownVersions)for(const[_,P]of A.knownVersions)E.set(_,P);A.knownVersions=null}}let h=(m=this.knownVersions)==null?void 0:m.get(i);if(!h){const E=await this.APILoadVersion({},i);if(!E)throw new Error(`Version with id '${i}' for entity with id '${this.id}' not found.`);h=new Ni(E,this.project)}return this.metaSync(h.toShallowJSON(),null),this.previousVersion=h.previousVersion,this.version=h.version,this.createdAt=h.createdAt,this.author=h.author,this.deleted=h.deleted,this.properties=[...h.properties],this.methods=[...h.methods],this.abstractMethods=[...h.abstractMethods],this.extends=h.extends,this.implements=[...h.implements],this.allPropertiesImplement=h.allPropertiesImplement,this.additionalPropertiesDataType=h.additionalPropertiesDataType,this.parent=h.parent,{updated:C(a),added:C(c),removed:C(e),affected:C(f),self:this}}updateWithShallowTransfer(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.UpdateWithShallowTransfer))){if(!this.checkCanEdit(this,r))return z.Logger.warn(`[updateWithShallowTransfer] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.UpdateWithShallowTransfer,this.id),this;if(this.metaSync(i,r),this.version=i.version,this.createdAt=i.createdAt,this.author=i.author,this.deleted=i.deleted,this.previousVersion=i.previousVersion,this.unsubscribeFromDependencies(),i.parent){const f=te(i.parent),h=this.project.get(f),m=this.parent;if(m&&m.id!==(h==null?void 0:h.id)&&this.removeFromParent(r),h)this.setParent(h,r),this.addSelfToProject(r);else throw r==null||r.attemptAutoclose(w.UpdateWithShallowTransfer,this.id),new Error(`${this.type} with id '${this.id}' has a 'parent' reference '${f}' that isn't found in the project`)}else throw r==null||r.attemptAutoclose(w.UpdateWithShallowTransfer,this.id),new Error(`${this.type} with id '${this.id}' must have a 'parent'`);if(i.extends){const f=te(i.extends),h=this.project.get(f);h&&this.setExtension(h,r)}else this.setExtension(null,r);if(i.implements.forEach(f=>{const h=te(f),m=this.project.get(h);if(m)this.addImplementation(m,r);else throw new Error(`${fr(this.type)} with id '${this.id}' has a 'implements' reference "${h}" which is missing in the project`)}),this.implements.filter(f=>{const h=te(f);return!i.implements.find(m=>te(m)===h)}).forEach(f=>{this.removeImplementation(f,r)}),i.methods.forEach(f=>{const h=te(f),m=this.project.get(h);m&&this.addMethod(m,r)}),this.methods.filter(f=>{const h=te(f);return!i.methods.find(m=>te(m)===h)}).forEach(f=>{this.removeMethod(f,r)}),i.properties.forEach(f=>{const h=te(f),m=this.project.get(h);m&&this.addProperty(m,r)}),this.properties.filter(f=>{const h=te(f);return!i.properties.find(m=>te(m)===h)}).forEach(f=>{this.removeProperty(f,r)}),i.allPropertiesImplement){const f=te(i.allPropertiesImplement),h=this.project.get(f);h&&this.setAllPropertiesImplement(h,r)}else this.setAllPropertiesImplement(null,r);if(i.additionalPropertiesDataType){const f=te(i.additionalPropertiesDataType),h=this.project.get(f);h&&this.setAdditionalPropertiesDataType(h,r)}else this.setAdditionalPropertiesDataType(null,r);return this.captureVersion(),this.subscribeToDependencies(),r==null||r.attemptAutoclose(w.UpdateWithShallowTransfer,this.id),this}updateWithGenerationTarget(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.UpdateWithGenerationTarget))){var a;if(!this.checkCanEdit(this,r))return z.Logger.warn(`[updateWithGenerationTarget] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.UpdateWithGenerationTarget,this.id),this;if(this.metaSync(i,r),i.parent){const c=te(i.parent),e=this.project.get(c),f=this.parent;if(f&&f.id!==(e==null?void 0:e.id)&&this.removeFromParent(r),e)this.setParent(e,r),this.addSelfToProject(r);else throw r==null||r.attemptAutoclose(w.UpdateWithGenerationTarget,this.id),new Error(`${this.type} with id '${this.id}' has a 'parent' reference '${c}' that isn't found in the project`)}if(i.extends){const c=te(i.extends),e=this.project.get(c);if(e)this.setExtension(e,r);else throw new Error(`${fr(this.type)} with id '${this.id}' has an 'extends' reference "${c}" which is missing in the project`)}else i.extends===null&&this.setExtension(null,r);return(a=i.implements)==null||a.forEach(c=>{const e=te(c),f=this.project.get(e);if(f)this.addImplementation(f,r);else throw new Error(`${fr(this.type)} with id '${this.id}' has a 'implements' reference "${e}" which is missing in the project`)}),i.implements&&this.implements.filter(e=>{const f=te(e);return!(i.implements||[]).find(h=>te(h)===f)}).forEach(e=>{this.removeImplementation(e,r)}),this.captureVersion(),this.subscribeToDependencies(),r==null||r.attemptAutoclose(w.UpdateWithGenerationTarget,this.id),this}hydrateAncestors(){const i=[],r=[],a=[],c=[];if(this.initialData.parent){const e=te(this.initialData.parent),f=this.project.get(e);if(f)this.setParent(f,null),i.push(f);else throw new Error(`${this.type} with id '${this.id}' has a 'parent' reference '${e}' that isn't found in the project`)}else throw new Error(`${this.type} with id '${this.id}' must have a 'parent'`);if(this.initialData.extends){const e=te(this.initialData.extends),f=this.project.get(e);f&&(this.setExtension(f,null),f.type!==d.BuiltInBaseEntity&&i.push(f))}return this.initialData.implements.forEach(e=>{const f=te(e),h=this.project.get(f);if(h)this.addImplementation(h,null),h.type!==d.BuiltInBaseEntity&&i.push(h);else throw new Error(`${fr(this.type)} with id '${this.id}' has a 'implements' reference "${f}" which is missing in the project`)}),{updated:C(i),added:C(r),removed:C(a),affected:C(c),self:this}}afterAllChildrenInitialized(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.AfterAllChildrenInitialized))){if(!this.checkCanEdit(this,i))return z.Logger.warn(`[afterAllChildrenInitialized] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),i==null||i.attemptAutoclose(w.AfterAllChildrenInitialized,this.id),{updated:[],added:[],removed:[],affected:[],self:this};const r=[],a=[],c=[],e=[];this.initialized=!0;const{updated:f,added:h,removed:m,affected:E}=this.syncImplementationProperties(i);r.push(...f),a.push(...h),c.push(...m),e.push(...E);const{updated:b,added:A,removed:_,affected:P}=this.addExtendedProperties(i);r.push(...b),a.push(...A),c.push(..._),e.push(...P);const{updated:V,added:G,removed:M}=this.removeUnrecognizedProperties(i);r.push(...V),a.push(...G),c.push(...M);const{updated:k,added:K,removed:ne,affected:X}=this.syncImplementationMethods(i);r.push(...k),a.push(...K),c.push(...ne),e.push(...X);const{updated:de,added:ie,removed:le,affected:ye}=this.addExtendedMethods(i);r.push(...de),a.push(...ie),c.push(...le),e.push(...ye);const{updated:Y,added:ee,removed:pe}=this.removeUnrecognizedMethods(i);r.push(...Y),a.push(...ee),c.push(...pe),this.addSuggestions(),this.properties.sort((ue,be)=>ue.index-be.index);let he=this.project.getDefinitionEntities(new Set([this.id])).filter(ue=>ue.id!==this.id&&ue.name.toLowerCase()===this.name.toLowerCase());if(he.length&&(this.parent.type===d.Project&&(he.filter(be=>be.parent.type!==d.Project).forEach(be=>{P_e(be,i)}),he=he.filter(be=>be.name.toLowerCase()===this.name.toLowerCase())),he.length)){const ue=Cp(this.name,he);this.metaSync({name:ue},i)}return i==null||i.attemptAutoclose(w.AfterAllChildrenInitialized,this.id),{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}addSelfToProject(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"add-self-to-project"))){const r=[this],a=[],c=[],e=[];if(this.parent.type===d.DataType){const f=this.parent;f.entity=this,r.push(f)}else this.project.addDefinitionEntity(this);return this.subscribe(),this.subscribeToDependencies(),i==null||i.attemptAutoclose("add-self-to-project",this.id),{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}setParent(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.SetParent))){var a;return this.checkCanEditWithCounterpartAndSideEffects(this,i,w.SetParent,r)?(((a=this.parent)==null?void 0:a.id)!==(i==null?void 0:i.id)&&(this.parent=i,r&&(r==null||r.add(this,W.Updated))),r==null||r.attemptAutoclose(w.SetParent,this.id),this):this}setExtension(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.SetExtension))){var a;return this.checkCanEdit(this,r)?(((a=this.extends)==null?void 0:a.id)!==(i==null?void 0:i.id)&&(this.extends=i,this.subscribeToDependencies(),r&&(r==null||r.add(this,W.Updated))),r==null||r.attemptAutoclose(w.SetExtension,this.id),this):(z.Logger.warn(`[setExtension] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.SetExtension,this.id),this)}addImplementation(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.AddImplementation))){return this.checkCanEdit(this,r)?(this.implements.includes(i)||(this.implements.push(i),this.subscribeToDependencies(),r==null||r.add(this,W.Updated)),r==null||r.attemptAutoclose(w.AddImplementation,this.id),this):(z.Logger.warn(`[addImplementation] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.AddImplementation,this.id),this)}removeImplementation(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.RemoveImplementation))){return this.checkCanEdit(this,r)?(this.implements.includes(i)&&(this.implements=this.implements.filter(a=>a.id!==i.id),r==null||r.add(this,W.Updated)),r==null||r.attemptAutoclose(w.RemoveImplementation,this.id),this):(z.Logger.warn(`[removeImplementation] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.RemoveImplementation,this.id),this)}removeProperty(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.RemoveProperty))){return this.checkCanEdit(this,r)?(this.properties.includes(i)&&(this.properties=this.properties.filter(a=>a.id!==i.id),r==null||r.add(this,W.Updated)),r==null||r.attemptAutoclose(w.RemoveProperty,this.id),this):(z.Logger.warn(`[removeProperty] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.RemoveProperty,this.id),this)}addMethod(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.AddMethod))){return this.checkCanEdit(this,r)?(this.methods.includes(i)||(this.methods.push(i),this.suggestedMethods=this.suggestedMethods.filter(a=>a.name!==i.name),r==null||r.add(this,W.Updated)),r==null||r.attemptAutoclose(w.AddMethod,this.id),this):(z.Logger.warn(`[addMethod] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.AddMethod,this.id),this)}removeMethod(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.RemoveMethod))){return this.checkCanEdit(this,r)?(this.methods.includes(i)&&(this.methods=this.methods.filter(a=>a.id!==i.id),r==null||r.add(this,W.Updated)),r==null||r.attemptAutoclose(w.RemoveMethod,this.id),this):(z.Logger.warn(`[removeMethod] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.RemoveMethod,this.id),this)}addProperty(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.AddProperty))){return this.checkCanEdit(this,r)?(this.properties.includes(i)||(this.properties.push(i),this.suggestedProperties=this.suggestedProperties.filter(a=>a.name!==i.name),r==null||r.add(this,W.Updated)),r==null||r.attemptAutoclose(w.AddProperty,this.id),this):(z.Logger.warn(`[addProperty] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.AddProperty,this.id),this)}addSuggestedProperty(i){return this.suggestedProperties.includes(i)||this.suggestedProperties.push(i),this}addSuggestedMethod(i){return this.suggestedMethods.includes(i)||this.suggestedMethods.push(i),this}removeSuggestedProperty(i){return this.suggestedProperties=this.suggestedProperties.filter(r=>r.id!==i.id),this}removeSuggestedMethod(i){return this.suggestedMethods=this.suggestedMethods.filter(r=>r.id!==i.id),this}addAbstractMethod(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.AddAbstractMethod))){return this.checkCanEdit(this,r)?(this.abstractMethods.includes(i)||(this.abstractMethods.push(i),r==null||r.add(this,W.Updated)),r==null||r.attemptAutoclose(w.AddAbstractMethod,this.id),this):(z.Logger.warn(`[addAbstractMethod] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.AddAbstractMethod,this.id),this)}removeAbstractMethod(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.RemoveAbstractMethod))){return this.checkCanEdit(this,r)?(this.abstractMethods.includes(i)&&(this.abstractMethods=this.abstractMethods.filter(a=>a.id!==i.id),r==null||r.add(this,W.Updated)),r==null||r.attemptAutoclose(w.RemoveAbstractMethod,this.id),this):(z.Logger.warn(`[removeAbstractMethod] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.RemoveAbstractMethod,this.id),this)}initChildren(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"init-children"))){if(this.initialized||this.startedInitialization)return this;if(this.startedInitialization=!0,this.properties=this.initialData.properties.map(r=>{const a=Re(r,this.project);return a.setParent(this,null),a.initChildren(i),a}),this.methods=this.initialData.methods.map(r=>{const a=Re(r,this.project);return a.setParent(this,null),a.initChildren(i),a}),this.abstractMethods=this.initialData.abstractMethods.map(r=>{const a=Re(r,this.project);return a.setParent(this,null),a.initChildren(i),a}),this.initialData.extends&&(this.extends=Re(this.initialData.extends,this.project)),this.implements=this.initialData.implements.map(r=>Re(r,this.project)),this.initialData.allPropertiesImplement){const r=Re(this.initialData.allPropertiesImplement,this.project);r.setParent(this,null),r.initChildren(null),this.setAllPropertiesImplement(r,i)}if(this.initialData.additionalPropertiesDataType){const r=Re(this.initialData.additionalPropertiesDataType,this.project);r.setParent(this,null),r.initChildren(null),this.setAdditionalPropertiesDataType(r,i)}return this.subscribeToDependencies(),this.afterAllChildrenInitialized(i),i==null||i.attemptAutoclose("init-children",this.id),this}removeUnrecognizedProperties(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"remove-unrecognized-properties"))){const r=[],a=[],c=[],e=[];let f=[...this.properties];f=f.filter(b=>b.parent.id===this.id),f=f.filter(b=>!b.isExtendedProperty);const h=this.implementedPropertiesFromOriginalParents,m=this.getAllPropertiesImplements();return f.filter(b=>this.interactive&&!b.implements.length?!1:!b.implements.find(_=>!!h.find(P=>P.id===_.id)||!!m.find(P=>P.id===_.id))).forEach(b=>{const A=b.remove({ignoreUpstream:!1},i);c.push(...A.removed),r.push(...A.updated)}),i==null||i.attemptAutoclose("remove-unrecognized-properties",this.id),{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}removeUnrecognizedMethods(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"remove-unrecognized-methods"))){const r=[],a=[],c=[],e=[];let f=[...this.methods];f=f.filter(m=>m.parent.id===this.id),f=f.filter(m=>!m.isExtendedMethod);const h=this.implementedMethodsFromOriginalParents;return f=f.filter(m=>this.interactive&&!m.implements?!1:!h.find(E=>{var b;return E.id===((b=m.implements)==null?void 0:b.id)})),f.forEach(m=>{const E=m.remove({ignoreUpstream:!1},i);c.push(...E.removed),r.push(...E.updated)}),i==null||i.attemptAutoclose("remove-unrecognized-methods",this.id),{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}syncImplementationMethods(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"sync-implementation-methods"))){const r=[],a=[],c=[],e=[],f=this.methods,h=this.implementedMethodsFromOriginalParents,m=[...this.allBaseMethodsFromExtendedAndImplementedEntities,...f];return h.filter(b=>!m.find(_=>{var P;return((P=_.implements)==null?void 0:P.id)===b.id})).forEach(b=>{if(this.methods.find(V=>{var G;return((G=V.implements)==null?void 0:G.id)===b.id}))return;const _=this.methods.find(V=>{var ne,X;if(V.name===b.name&&!V.implements)return!0;const G=oi(this,ge.CRON_JOB),M=oi(this,ge.HTTP_ENDPOINT),k=((ne=V.implements)==null?void 0:ne.id)===re["built-in-base-entity"].BUILT_IN_HTTP_ENDPOINT_ENTITY.methods.handler.id,K=((X=V.implements)==null?void 0:X.id)===re["built-in-base-entity"].BUILT_IN_CRON_JOB_ENTITY.methods.handler.id;return!!(G&&!K&&!M&&k||M&&!k&&!G&&K)});if(_&&_.type===d.FunctionDeclaration){_.setImplements(b,i),_.metaSync({name:b.name},i),i==null||i.add(_,W.Updated),i==null||i.add(this,W.Updated);return}const P=b.implementAsFunctionDeclaration(i,this);a.push(P),i==null||i.add(P,W.Added),this.addMethod(P,i)}),this.methods.sort((b,A)=>b.index-A.index).forEach(b=>{b.afterAllChildrenInitialized(i)}),i==null||i.attemptAutoclose("sync-implementation-methods",this.id),{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}syncImplementationProperties(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"sync-implementation-properties"))){const r=[],a=[],c=[],e=[],f=this.properties,h=this.implementedPropertiesFromOriginalParents.filter(E=>!this.allBasePropertiesFromExtendedAndImplementedEntities.find(A=>!!A.implements.find(_=>_.id===E.id))),m=[...this.allBasePropertiesFromExtendedAndImplementedEntities,...f];return h.forEach(E=>{const b=m.find(V=>!!V.implements.find(G=>G.id===E.id));if(b){const{updated:V,added:G,removed:M,affected:k}=b.syncWithImplementation(i);r.push(...V),a.push(...G),c.push(...M),e.push(...k);return}if(this.properties.find(V=>!!V.implements.find(G=>G.id===E.id)))return;const _=this.properties.find(V=>V.name===E.name&&!!V.abstract&&!V.implements);if(_){_.addImplementation(E,i),_.metaSync({abstract:!1},i),_.afterAllChildrenInitialized(i);return}const P=E.implement(this,i,x.UUID.uuid());a.push(P),i==null||i.add(P,W.Added)}),this.properties.find(E=>{var b;return E.id===((b=this.allPropertiesImplement)==null?void 0:b.id)})&&this.removeAllPropertiesImplement(i),i==null||i.attemptAutoclose("sync-implementation-properties",this.id),{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}addExtendedMethods(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"add-extended-methods"))){const r=[],a=[],c=[],e=[],f=this.methods,m=this.extendedMethodsFromOriginalParents.filter(b=>b.type===d.FunctionDeclaration),E=new Set(f.filter(b=>{var A;return!!((A=b.extends)!=null&&A.id)}).map(b=>b.extends.id));return m.forEach(b=>{if(E.has(b.id))return;E.add(b.id);const A=b.clone(i,this,x.UUID.uuid());A.setExtends(b,i),A.initChildren(i),a.push(A),i==null||i.add(A,W.Added),this.addMethod(A,i)}),i==null||i.attemptAutoclose("add-extended-methods",this.id),{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}addExtendedProperties(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"add-extended-properties"))){const r=[],a=[],c=[],e=[],f=this.properties,h=this.extendedPropertiesFromOriginalParents,m=h.filter(b=>h.find(_=>!!_.implements.find(P=>P.id===b.id))?!1:!b.abstract),E=new Set(f.filter(b=>{var A;return!!((A=b.extends)!=null&&A.id)}).map(b=>b.extends.id));return m.forEach(b=>{if(E.has(b.id))return;E.add(b.id);const A=b.clone(i,this,x.UUID.uuid());A.setExtends(b,i),A.initChildren(i),a.push(A),i==null||i.add(A,W.Added),this.addProperty(A,i)}),[...this.properties].forEach(b=>{if(b.extends)return;if(m.find(_=>_.name===b.name&&_.implements.every(P=>!!b.implements.find(V=>V.id===P.id)))){const _=b.remove({ignoreUpstream:!1},i);c.push(..._.removed),r.push(..._.updated)}}),this.properties.forEach(b=>{const A=b.afterAllChildrenInitialized(i);r.push(...A.updated),e.push(...A.affected),a.push(...A.added),c.push(...A.removed)}),i==null||i.attemptAutoclose("add-extended-properties",this.id),{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}addSuggestions(){return this.implements.forEach(i=>{Yje(this,i).forEach(c=>{const e=c.toJSON();e.id=`_suggestion--parent--${this.id}--${c.id}`;const f=Re(e,this.project);f.suggestion=!0,f.setParent(this,null),f.initChildren(null),this.addSuggestedProperty(f)}),Jje(this,i).forEach(c=>{const e=`_suggestion--parent--${this.id}--${c.id}`,f=c.implementAsFunctionDeclaration(null,this,e),h=Re(f,this.project);if(h.suggestion=!0,h.setParent(this,null),h.initChildren(null),this.methods=this.methods.filter(m=>m.id!==e),h.inputs.forEach(m=>{m.suggestion=!0}),h.returnStatements.length){const m=h.returnStatements[0];m.suggestion=!0,m.outputs.forEach(E=>{E.suggestion=!0})}this.addSuggestedMethod(h)})}),this}subscribe(){var i;return this.activeVersion=!0,(i=this.knownVersions)==null||i.forEach(r=>{r.version!==this.version&&(r.activeVersion=!1)}),this.project.subscribeInstance(this),this.project.subscribedDefinitionEntities.add(this.id),this}unsubscribe(){return this.project.unsubscribeInstance(this),this.project.subscribedDefinitionEntities.delete(this.id),this}metaSync(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"meta-sync"))){const a=tn(this,i,r),c=en(this,a),e=this.toMeta();return this.name=a.name!==void 0?a.name:e.name,this.codeName=a.codeName!==void 0?a.codeName:e.codeName,this.description=a.description!==void 0?a.description:e.description,this.x=a.x||e.x,this.y=a.y||e.y,this.static=a.static!==void 0?a.static:this.static,this.abstract=a.abstract!==void 0?a.abstract:this.abstract,this.additionalProperties=a.additionalProperties!==void 0?a.additionalProperties:e.additionalProperties,super.baseMetaSync(a,this,r),a.deleted===!0&&!e.deleted?r==null||r.add(this,W.Removed):a.deleted===!1&&e.deleted?r==null||r.add(this,W.Added):c&&(r==null||r.add(this,W.Updated)),r==null||r.attemptAutoclose("meta-sync",this.id),this}async APILoad(i=Ke,...r){return await Ni.repository.APILoad(this.id,...r),this}async APICreate(i=Ke,...r){return await Ni.repository.APICreate(this.toShallowJSON(),...r),this}async APIUpdate(i=Ke,...r){return await Ni.repository.APIUpdate(this.toShallowJSON(),...r),this}async APIDelete(i=Ke,...r){return await Ni.repository.APIDelete(this.toShallowJSON(),...r),this}async APIClone(i=Ke,...r){return await Ni.repository.APIClone(this.id,...r),this}async APILoadVersion(i=Ke,r,...a){return await Ni.repository.APILoadVersion(this.id,r,...a)}removeFromParent(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.RemoveFromParent))){if(!this.checkCanEdit(this,i))return z.Logger.warn(`[removeFromParent] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),i==null||i.attemptAutoclose(w.RemoveFromParent,this.id),{added:[],updated:[],removed:[],affected:[],self:this};const r=[],a=[],c=[],e=[];if(this.parent.type===d.Project)this.parent.removeDefinitionEntity(this);else if(this.parent.type===d.DataType&&this.parent.entity&&this.parent.entity.id===this.id){const f=this.parent.setEntity(null,i);r.push(f)}return i==null||i.attemptAutoclose(w.RemoveFromParent,this.id),{added:C(c),updated:C(r),removed:C(a),affected:C(e),self:this}}remove({ignoreUpstream:i}={ignoreUpstream:!1},r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.RemoveEntity))){var h;if(!this.checkCanDelete(this,r))return z.Logger.warn(`[remove] User is not allowed to delete or edit this ${this.type} entity with id: ${this.id}`),r==null||r.event({id:`${w.RemoveEntity}-${this.id}--${Me.ActionOwnerEntityNonDeletable}`,action:w.RemoveEntity,owner:this,errorReason:Me.ActionOwnerEntityNonDeletable,rootAction:((h=r==null?void 0:r.self)==null?void 0:h.id)===this.id&&(r==null?void 0:r.actionName)===w.RemoveEntity}),r==null||r.attemptAutoclose(w.RemoveEntity,this.id),{added:[],updated:[],removed:[],affected:[],self:this};const a=[],c=[],e=[],f=[];if(r!=null&&r.hasRemoved(this.id))return r==null||r.attemptAutoclose(w.RemoveEntity,this.id),{added:[],updated:[],removed:[],affected:[],self:this};if(c.push(this),this.unsubscribe(),this.unsubscribeFromDependencies(),this.project.subscribeDeletedInstance(this),this.metaSync({deleted:!0},r),Object.values(this.detachedDependents).forEach(m=>{const{updated:E,removed:b,added:A}=m.entity.onDetachedDependencyRemoved(this,m.field,r);a.push(...E),c.push(...b),e.push(...A)}),this.properties.forEach(m=>{const{updated:E,removed:b}=m.remove({ignoreUpstream:!0},r);a.push(...E),c.push(...b)}),this.methods.forEach(m=>{const{updated:E,removed:b}=m.remove({ignoreUpstream:!0},r);a.push(...E),c.push(...b)}),this.abstractMethods.forEach(m=>{const{updated:E,removed:b}=m.remove({ignoreUpstream:!0},r);a.push(...E),c.push(...b)}),this.suggestedProperties.forEach(m=>{const{updated:E,removed:b}=m.remove({ignoreUpstream:!0},r);a.push(...E),c.push(...b)}),this.suggestedMethods.forEach(m=>{const{updated:E,removed:b}=m.remove({ignoreUpstream:!0},r);a.push(...E),c.push(...b)}),!i){const m=this.removeFromParent(r);e.push(...m.added),a.push(...m.updated),c.push(...m.removed),f.push(...m.affected)}return r==null||r.attemptAutoclose(w.RemoveEntity,this.id),{added:C(e),updated:C(a),removed:C(c),affected:C(f),self:this}}restore({}={},i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.RestoreEntity))){if(!this.checkCanEdit(this,i))return z.Logger.warn(`[restore] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),i==null||i.attemptAutoclose(w.RestoreEntity,this.id),{added:[],updated:[],removed:[],affected:[],self:this};const r=[],a=[],c=[],e=[];return i!=null&&i.hasAdded(this.id)?(i==null||i.attemptAutoclose(w.RestoreEntity,this.id),{added:[],updated:[],removed:[],affected:[],self:this}):(this.subscribe(),this.project.unsubscribeDeletedInstance(this),this.metaSync({deleted:!1},i),Object.values(this.detachedDependents).forEach(f=>{const{updated:h,removed:m,added:E}=f.entity.onDetachedDependencyRestored(this,f.field,i);a.push(...h),c.push(...m),r.push(...E)}),this.properties.forEach(f=>{const{updated:h}=f.restore({},i);a.push(...h)}),this.methods.forEach(f=>{const{updated:h}=f.restore({},i);a.push(...h)}),this.abstractMethods.forEach(f=>{const{updated:h}=f.restore({},i);a.push(...h)}),this.suggestedProperties.forEach(f=>{const{updated:h}=f.restore({},i);a.push(...h)}),this.suggestedMethods.forEach(f=>{const{updated:h}=f.restore({},i);a.push(...h)}),i==null||i.attemptAutoclose(w.RestoreEntity,this.id),{added:C(r),updated:C(a),removed:C(c),affected:C(e),self:this})}toFlat(i=new Set){var a;return i.has(this.id)?[]:(i.add(this.id),[this,...((a=this.extends)==null?void 0:a.toFlat(i))||[],...this.implements.flatMap(c=>c.toFlat(i)),...this.properties.flatMap(c=>c.toFlat(i)),...this.methods.flatMap(c=>c.toFlat(i)),...this.abstractMethods.flatMap(c=>c.toFlat(i)),...this.parent.toFlat(i)])}toFlatIds(i=new Set){var a;return i.has(this.id)?[]:(i.add(this.id),[this.id,...((a=this.extends)==null?void 0:a.toFlatIds(i))||[],...this.implements.flatMap(c=>c.toFlatIds(i)),...this.properties.flatMap(c=>c.toFlatIds(i)),...this.methods.flatMap(c=>c.toFlatIds(i)),...this.abstractMethods.flatMap(c=>c.toFlatIds(i)),...this.parent.toFlatIds(i)])}toMeta(){return{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,codeName:this.codeName,description:this.description,static:this.static,abstract:this.abstract,x:this.x,y:this.y,type:this.type,editable:this.editable,deletable:this.deletable,additionalProperties:this.additionalProperties,name:this.name}}toJSON(i=new Set){var r,a,c;return i.has(this.id)?this.toReference():(i.add(this.id),{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,editable:this.editable,deletable:this.deletable,name:this.name,codeName:this.codeName,description:this.description,x:this.x,y:this.y,static:this.static,abstract:this.abstract,additionalProperties:this.additionalProperties,allPropertiesImplement:((r=this.allPropertiesImplement)==null?void 0:r.toJSON(i))||null,additionalPropertiesDataType:((a=this.additionalPropertiesDataType)==null?void 0:a.toJSON(i))||null,properties:this.properties.map(e=>e.toJSON(i)),methods:this.methods.map(e=>e.toJSON(i)),abstractMethods:this.abstractMethods.map(e=>e.toJSON(i)),implements:this.implements.map(e=>e.toJSON(i)),extends:((c=this.extends)==null?void 0:c.toJSON(i))||null,parent:this.parent.toReference()})}toJSONClone(i=at){var a,c,e,f,h,m,E,b,A,_;let r;return(a=i.seenEntityMaps)!=null&&a.has(this.id)?r=i.seenEntityMaps.get(this.id):(r=i.newId||dn(this,this.project,i.uuidStrategy),i.seenEntityMaps&&i.seenEntityMaps.set(this.id,r)),(c=i.seenEntities)!=null&&c.has(r)||(e=i.seenEntities)!=null&&e.has(this.id)?this.toReference({seenEntityMaps:i.seenEntityMaps}):((f=i.seenEntities)==null||f.add(r),(h=i.seenEntities)==null||h.add(this.id),{id:r,version:x.UUID.uuid(),createdAt:i.timestamp||B().toISOString(),author:x.sessionAuthor,previousVersion:null,deleted:!1,type:this.type,editable:this.editable,deletable:this.deletable,name:this.name,codeName:this.codeName,description:this.description,x:this.x,y:this.y,static:this.static,abstract:this.abstract,additionalProperties:this.additionalProperties,allPropertiesImplement:((m=this.allPropertiesImplement)==null?void 0:m.toJSONClone(i))||null,additionalPropertiesDataType:((E=this.additionalPropertiesDataType)==null?void 0:E.toJSONClone(i))||null,properties:this.properties.map(P=>P.toJSONClone({...i,newId:null})),methods:this.methods.map(P=>P.toJSONClone({...i,newId:null})),abstractMethods:this.abstractMethods.map(P=>P.toJSONClone({...i,newId:null})),implements:this.implements.map(P=>P.type===d.BuiltInBaseEntity?P.toJSON(i.seenEntities):P.toJSONClone({...i,newId:null})),extends:((b=this.extends)==null?void 0:b.type)===d.BuiltInBaseEntity?(A=this.extends)==null?void 0:A.toJSON(i.seenEntities):(_=this.extends)==null?void 0:_.toJSONClone({...i,newId:null}),parent:this.parent.toReference({seenEntityMaps:i.seenEntityMaps})})}toReference(i=at){var a;let r=this.id;return(a=i.seenEntityMaps)!=null&&a.has(this.id)&&(r=i.seenEntityMaps.get(this.id)),{id:r+"--"+x.UUID.uuid()+"--ref",type:d.GenericReference,entityId:r,version:this.version,entityType:this.type}}toShallowJSON(i=at){var a,c,e,f;let r=this.id;return(a=i.seenEntityMaps)!=null&&a.has(this.id)&&(r=i.seenEntityMaps.get(this.id)),{id:r,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,name:this.name,codeName:this.codeName,description:this.description,type:this.type,editable:this.editable,deletable:this.deletable,x:this.x,y:this.y,static:this.static,abstract:this.abstract,additionalProperties:this.additionalProperties,allPropertiesImplement:((c=this.allPropertiesImplement)==null?void 0:c.toReference(i))||null,additionalPropertiesDataType:((e=this.additionalPropertiesDataType)==null?void 0:e.toReference(i))||null,properties:this.properties.map(h=>h.toReference(i)),methods:this.methods.map(h=>h.toReference(i)),abstractMethods:this.abstractMethods.map(h=>h.toReference(i)),implements:this.implements.map(h=>h.toReference(i)),extends:((f=this.extends)==null?void 0:f.toReference(i))||null,parent:this.parent.toReference(i)}}toFlatJSON(i=new Set){var a,c,e;return i.has(this.id)?[]:(i.add(this.id),[this.toShallowJSON(),...this.properties.flatMap(f=>f.toFlatJSON(i)),...this.methods.flatMap(f=>f.toFlatJSON(i)),...this.abstractMethods.flatMap(f=>f.toFlatJSON(i)),...this.implements.flatMap(f=>f.toFlatJSON(i)),...((a=this.extends)==null?void 0:a.toFlatJSON(i))||[],...this.parent.toFlatJSON(i),...((c=this.additionalPropertiesDataType)==null?void 0:c.toFlatJSON(i))||[],...((e=this.allPropertiesImplement)==null?void 0:e.toFlatJSON(i))||[]])}toGenerationTarget(i=at){var c,e,f;const r=this.parent.type===d.Project?void 0:(c=i.seenEntityMaps)!=null&&c.has(this.parent.id)?i.seenEntityMaps.get(this.parent.id):this.parent.id;let a=this.id;return(e=i.seenEntityMaps)!=null&&e.has(this.id)&&(a=i.seenEntityMaps.get(this.id)),{id:a,name:this.name,description:this.description,type:this.type,static:this.static,abstract:this.abstract,extends:(f=this.extends)==null?void 0:f.id,additionalProperties:this.additionalProperties,implements:this.implements.map(h=>h.id),parent:r}}toFlatGenerationTarget(i=new Set){var a,c,e;return i.has(this.id)?[]:(i.add(this.id),[this.toGenerationTarget(),...this.properties.flatMap(f=>f.toFlatGenerationTarget(i)),...this.methods.flatMap(f=>f.toFlatGenerationTarget(i)),...this.abstractMethods.flatMap(f=>f.toFlatGenerationTarget(i)),...this.implements.filter(f=>f.type===d.DefinitionEntity).flatMap(f=>f.toFlatGenerationTarget(i)),...((a=this.extends)==null?void 0:a.toFlatGenerationTarget(i))||[],...this.parent.toFlatGenerationTarget(i),...((c=this.additionalPropertiesDataType)==null?void 0:c.toFlatGenerationTarget(i))||[],...((e=this.allPropertiesImplement)==null?void 0:e.toFlatGenerationTarget(i))||[]])}clearErrors(){var i,r;return this.errors=[],this.properties.forEach(a=>a.clearErrors()),this.methods.forEach(a=>a.clearErrors()),this.abstractMethods.forEach(a=>a.clearErrors()),(i=this.additionalPropertiesDataType)==null||i.clearErrors(),(r=this.allPropertiesImplement)==null||r.clearErrors(),this}validate(){return this.errors=zje(this),{success:!0}}async validateAsync(i={}){const r=z.YieldTracker.from(i);return this.errors=await Wje(this,{tracker:r}),{success:!0}}getErrors(){var r,a;return[...this.errors,...this.properties.flatMap(c=>c.getErrors()),...this.methods.flatMap(c=>c.getErrors()),...this.abstractMethods.flatMap(c=>c.getErrors()),...((r=this.additionalPropertiesDataType)==null?void 0:r.getErrors())||[],...((a=this.allPropertiesImplement)==null?void 0:a.getErrors())||[]]}async getErrorsAsync(i={}){const r=z.YieldTracker.from(i),a=[...this.errors];await r.tick();for(const c of this.properties)a.push(...await c.getErrorsAsync({tracker:r}));for(const c of this.methods)a.push(...await c.getErrorsAsync({tracker:r}));for(const c of this.abstractMethods)a.push(...await c.getErrorsAsync({tracker:r}));return this.additionalPropertiesDataType&&a.push(...await this.additionalPropertiesDataType.getErrorsAsync({tracker:r})),this.allPropertiesImplement&&a.push(...await this.allPropertiesImplement.getErrorsAsync({tracker:r})),a}getShallowErrors(){return this.errors}clone(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.CloneEntity)),r=null,a=null,c=!0){var G,M,k;const e=Fr(r,this),f=this.toJSON(),h=a||x.UUID.uuid(),m=r||this.parent;f.properties=[],f.methods=[],f.abstractMethods=[];const E=h.split("-id"),b=E[E.length-1||0]||h;f.id=h,f.version=x.UUID.uuid(),f.createdAt=(i==null?void 0:i.timestamp)||B().toISOString(),f.author=(i==null?void 0:i.author)||"1",f.previousVersion=null,f.deleted=!1,f.editable=!0,f.deletable=!0,f.parent=m.toReference();const A=lr(f,e);A.hydrateAncestors(),A.setParent(m,i),c&&(A.subscribe(),A.addSelfToProject(i)),A.initChildren(i),i==null||i.add(A,W.Added);const _=(G=this.properties)==null?void 0:G.map(K=>this.project.diggestedBuiltInBaseEntitiesIds.has(K.id)?K:K.clone(i,A,x.UUID.uuid(),c));A.properties=_;const P=(M=this.methods)==null?void 0:M.map((K,ne)=>this.project.diggestedBuiltInBaseEntitiesIds.has(K.id)?K:K.clone(i,A,b+"-method-"+ne+"-id",c));A.methods=P;const V=(k=this.abstractMethods)==null?void 0:k.map((K,ne)=>this.project.diggestedBuiltInBaseEntitiesIds.has(K.id)?K:K.clone(i,A,b+"-abstract-method-"+ne+"-id",c));if(A.abstractMethods=V,this.additionalPropertiesDataType)if(this.project.diggestedBuiltInBaseEntitiesIds.has(this.additionalPropertiesDataType.id))A.setAdditionalPropertiesDataType(this.additionalPropertiesDataType,i);else{const K=this.additionalPropertiesDataType.clone(i,A,x.UUID.uuid(),c);A.setAdditionalPropertiesDataType(K,i)}if(this.allPropertiesImplement)if(this.project.diggestedBuiltInBaseEntitiesIds.has(this.allPropertiesImplement.id))A.setAllPropertiesImplement(this.allPropertiesImplement,i);else{const K=this.allPropertiesImplement.clone(i,A,x.UUID.uuid(),c);A.setAllPropertiesImplement(K,i)}return i||A.captureVersion(),i==null||i.attemptAutoclose(w.CloneEntity,this.id),A}getFunctionDeclaration(i){return this.methods.find(r=>r.id===i)}implement(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"implement-definition-entity")),a){const c=m1(this,i,r,a);return r==null||r.attemptAutoclose("implement-definition-entity",this.id),c}getAllPropertiesImplements(){var r;const i=[];return this.allPropertiesImplement&&i.push(this.allPropertiesImplement),i.push(...((r=this.extends)==null?void 0:r.getAllPropertiesImplements())||[],...this.implements.flatMap(a=>a.getAllPropertiesImplements())),i}getAllInteractiveMethods(){var e;const i=this.implements.filter(f=>f.type===d.DefinitionEntity||f.type===d.BuiltInBaseEntity&&f.interactive),r=((e=this.extends)==null?void 0:e.getAllInteractiveMethods())||[],a=i.flatMap(f=>f.getAllInteractiveMethods());return C([...this.methods,...r,...a])}inferFromInputs(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"infer-definition-entity-from-inputs"))){const a=[],c=[],e=[],f=[];if(this.parent.type!==d.DataType||!this.parent.inferred)return r==null||r.attemptAutoclose("infer-definition-entity-from-inputs",this.id),{added:[],updated:[],removed:[],affected:[],self:this};const h=[];i.forEach(b=>{h.find(_=>oe(_,this.project)===oe(b,this.project))||h.push(b)});const m=this.properties.filter(b=>!b.dataType);h.forEach(b=>{var k,K,ne;const A=m.find(X=>oe(X,this.project)===oe(b,this.project));if(!A)return;const P=gr(b.parent).getMasterInputWithValueWriterFromAllInstances(b),V=iu(P,r),G=V==null?void 0:V.clone(r,A,x.UUID.uuid(),!0);G&&((k=A.dataType)==null||k.merge(G,r),G.id!==((K=A.dataType)==null?void 0:K.id)&&G.remove({ignoreUpstream:!1},r),A.dataType&&(A.dataType.metaSync({inferred:!0,like:!0},r),A.setDataType(A.dataType,r),r==null||r.add(A,W.Affected)));let M=null;if(b.declaration&&A.id!==((ne=b.declaration)==null?void 0:ne.id)&&(M=b.declaration),b.setDeclaration(A,r),r==null||r.add(b,W.Updated),M){const{updated:X,removed:de}=M.remove({ignoreUpstream:!1},r);c.push(...X),e.push(...de)}});const E=[];return h.forEach(b=>{if(!b.declaration){E.push(b);return}}),E.length===0?(r==null||r.attemptAutoclose("infer-definition-entity-from-inputs",this.id),{added:[],updated:[],removed:[],affected:[],self:this}):(E.forEach(b=>{var ne,X,de,ie,le;const A=this.properties.find(ye=>oe(ye,this.project)===oe(b,this.project));if(A){if(b.setDeclaration(A,r),!A.getDataType(r)){const Y=gr(b.parent).getMasterInputWithValueWriterFromAllInstances(b),ee=iu(Y),pe=ee==null?void 0:ee.clone(r,A,x.UUID.uuid(),!0);pe&&((ne=A.dataType)==null||ne.merge(pe,r),pe.id!==((X=A.dataType)==null?void 0:X.id)&&pe.remove({ignoreUpstream:!1},r),A.dataType&&(A.dataType.metaSync({inferred:!0,like:!0},r),A.setDataType(A.dataType,r),r==null||r.add(A,W.Affected)))}return}const _=oe(b,this.project),P=b.codeName||vp(b,this.project)||cs(ir(_)),V=Es.new(r);V.parent=this.toReference(),V.index=b.index,V.name=_,V.codeName=P,V.description=b.description;const G=Re(V,this.project);G.hydrateAncestors(),G.addSelfToProject(r),r==null||r.add(G,W.Added),G.setParent(this,r),G.initChildren(r),r||G.captureVersion();const k=gr(b.parent).getMasterInputWithValueWriterFromAllInstances(b),K=iu(k);if(K&&K.id!==((de=G.dataType)==null?void 0:de.id)){const ye=K==null?void 0:K.clone(r,G,x.UUID.uuid(),!0);ye&&((ie=G.dataType)==null||ie.merge(ye,r),ye.id!==((le=G.dataType)==null?void 0:le.id)&&ye.remove({ignoreUpstream:!1},r),G.dataType&&(G.dataType.metaSync({inferred:!0,like:!0},r),G.setDataType(G.dataType,r),r==null||r.add(G,W.Affected)))}return this.addProperty(G,r),b.setDeclaration(G,r),r==null||r.add(b,W.Updated),G}),r==null||r.attemptAutoclose("infer-definition-entity-from-inputs",this.id),{added:C(a),updated:C(c),removed:C(e),affected:C(f),self:this})}getRawDefaultValue(){const i={};return this.properties.forEach(r=>{var e;if(!Ev(r)||!r.defaultValue)return;const a=oe(r,this.project),c=r.codeName||vp(r,this.project)||cs(ir(a));i[c]=((e=r.getDefaultValue())==null?void 0:e.value)||null}),i}getActiveRawDefaultValue(){const i={};return this.properties.forEach(r=>{var f;if(!Ev(r))return;const a=oe(r,this.project),c=r.codeName||vp(r,this.project)||cs(ir(a)),e=(f=this.project.requestActiveDynamicValue(r,!0))==null?void 0:f.value;e&&(i[c]=(e==null?void 0:e.value)||null)}),i}setAdditionalPropertiesDataType(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.SetAdditionalPropertiesDataType))){if(!this.checkCanEdit(this,r))return z.Logger.warn(`[setAdditionalPropertiesDataType] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.SetAdditionalPropertiesDataType,this.id),this;const a=this.additionalPropertiesDataType;return(a==null?void 0:a.id)!==(i==null?void 0:i.id)&&(a==null||a.remove({ignoreUpstream:!0},r),this.additionalPropertiesDataType=i,this.subscribeToDependencies(),r==null||r.add(this,W.Affected)),r==null||r.attemptAutoclose(w.SetAdditionalPropertiesDataType,this.id),this}removeAdditionalPropertiesDataType(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.RemoveAllPropertiesImplement))){return this.checkCanEdit(this,i)?(this.additionalPropertiesDataType&&(this.additionalPropertiesDataType.remove({ignoreUpstream:!0},i),i==null||i.add(this,W.Affected),this.additionalPropertiesDataType=null),i==null||i.attemptAutoclose(w.RemoveAllPropertiesImplement,this.id),this):(z.Logger.warn(`[removeAdditionalPropertiesDataType] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),i==null||i.attemptAutoclose(w.RemoveAllPropertiesImplement,this.id),this)}setAllPropertiesImplement(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.SetAllPropertiesImplement))){if(!this.checkCanEdit(this,r))return z.Logger.warn(`[setAllPropertiesImplement] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.SetAllPropertiesImplement,this.id),this;const a=this.allPropertiesImplement;return(a==null?void 0:a.id)!==(i==null?void 0:i.id)&&(a==null||a.remove({ignoreUpstream:!0},r),this.allPropertiesImplement=i,this.subscribeToDependencies(),r==null||r.add(this,W.Affected)),r==null||r.attemptAutoclose(w.SetAllPropertiesImplement,this.id),this}removeAllPropertiesImplement(i=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,w.RemoveAllPropertiesImplement))){return this.checkCanEdit(this,i)?(this.allPropertiesImplement&&(this.properties.find(r=>{var a;return r.id===((a=this.allPropertiesImplement)==null?void 0:a.id)})||this.allPropertiesImplement.remove({ignoreUpstream:!0},i),i==null||i.add(this,W.Affected),this.allPropertiesImplement=null),i==null||i.attemptAutoclose(w.RemoveAllPropertiesImplement,this.id),this):(z.Logger.warn(`[removeAllPropertiesImplement] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),i==null||i.attemptAutoclose(w.RemoveAllPropertiesImplement,this.id),this)}};R(Ni,"repository",{APICreate:async(i,...r)=>i,APIUpdate:async(i,...r)=>i,APIDelete:async(i,...r)=>i,APIClone:async(i,...r)=>{},APILoad:async(i,...r)=>null,APILoadVersion:async(i,r,...a)=>null}),R(Ni,"type",d.DefinitionEntity),R(Ni,"USER_MANAGED_PARENT_TYPES",[d.Project,d.DataType]),R(Ni,"PARENT_TYPES",[...Ni.USER_MANAGED_PARENT_TYPES]),R(Ni,"MUTABLE_BASE_PROPERTIES",["name","codeName","description","static","abstract","additionalProperties"]),R(Ni,"INMUTABLE_BASE_PROPERTIES",["id","type","version","createdAt","author","previousVersion"]),R(Ni,"BASE_PROPERTIES",[...Ni.MUTABLE_BASE_PROPERTIES,...Ni.INMUTABLE_BASE_PROPERTIES]),R(Ni,"MUTABLE_META_PROPERTIES",[...Ni.MUTABLE_BASE_PROPERTIES,"x","y"]),R(Ni,"INMUTABLE_META_PROPERTIES",[...Ni.INMUTABLE_BASE_PROPERTIES]),R(Ni,"META_PROPERTIES",[...Ni.MUTABLE_META_PROPERTIES,...Ni.INMUTABLE_META_PROPERTIES]),R(Ni,"MUTABLE_UPSTREAM_PROPERTIES",["extends","implements"]),R(Ni,"INMUTABLE_UPSTREAM_PROPERTIES",["parent"]),R(Ni,"UPSTREAM_PROPERTIES",[...Ni.MUTABLE_UPSTREAM_PROPERTIES,...Ni.INMUTABLE_UPSTREAM_PROPERTIES]),R(Ni,"MUTABLE_DOWNSTREAM_PROPERTIES",["properties","methods","abstractMethods","allPropertiesImplement","additionalPropertiesDataType"]),R(Ni,"INMUTABLE_DOWNSTREAM_PROPERTIES",[]),R(Ni,"DOWNSTREAM_PROPERTIES",[...Ni.MUTABLE_DOWNSTREAM_PROPERTIES,...Ni.INMUTABLE_DOWNSTREAM_PROPERTIES]),R(Ni,"PROPERTIES",[...Ni.META_PROPERTIES,...Ni.UPSTREAM_PROPERTIES,...Ni.DOWNSTREAM_PROPERTIES]);let Ks=Ni;async function jVi(s,p={}){const i=z.YieldTracker.from(p),r=[],a=qt(s.errors,r);return await i.tick(),a}function UVi(s){const p=[];return qt(s.errors,p)}const lI=class lI extends Mx{constructor(i,r){super(i);R(this,"initialData");R(this,"id");R(this,"name");R(this,"description",null);R(this,"type",d.PrimitiveEntity);R(this,"static");R(this,"abstract");R(this,"properties",[]);R(this,"methods",[]);R(this,"abstractMethods",[]);R(this,"extends",null);R(this,"errors",[]);R(this,"project");this.initialData=i,this.project=r,this.id=i.id,this.name=i.name,this.description=i.description,this.static=i.static,this.abstract=i.abstract,this.properties=this.initialData.properties.map(a=>{const c=Re(a,this.project);return c.setParent(this,null),c.initChildren(null),c}),this.methods=this.initialData.methods.map(a=>{const c=Re(a,this.project);return c.parent=this,c}),this.abstractMethods=this.initialData.abstractMethods.map(a=>{const c=Re(a,this.project);return c.parent=this,c}),this.initialData.extends&&(this.extends=Re(this.initialData.extends,this.project))}get allMethods(){return C([...this.ownDeclaredMethods,...this.allBaseMethodsFromOriginalParents])}get allProperties(){return C([...this.ownDeclaredProperties,...this.allBasePropertiesFromOriginalParents])}get allBaseMethodsFromOriginalParents(){var a;const i=((a=this.extends)==null?void 0:a.allMethods)||[],r=[...i].filter(c=>!i.some(e=>e.id!==c.id));return C(r)}get allBasePropertiesFromOriginalParents(){var a;const i=((a=this.extends)==null?void 0:a.allProperties)||[],r=[...i].filter(c=>!i.some(e=>{var f;return e.id!==c.id&&(e.implements.find(h=>h.id===c.id)||((f=e.extends)==null?void 0:f.id)===c.id)}));return C(r)}get allBasePropertiesFromExtendedAndImplementedEntities(){var a,c;const i=[...((a=this.extends)==null?void 0:a.ownDeclaredProperties)||[],...((c=this.extends)==null?void 0:c.allBasePropertiesFromExtendedAndImplementedEntities)||[]].filter(e=>!e.abstract),r=[...i].filter(e=>!i.some(f=>{var h;return f.id!==e.id&&(f.implements.find(m=>m.id===e.id)||((h=f.extends)==null?void 0:h.id)===e.id)}));return C(r)}get extendedPropertiesFromOriginalParents(){var a,c;const i=[...((a=this.extends)==null?void 0:a.ownDeclaredProperties)||[],...((c=this.extends)==null?void 0:c.extendedPropertiesFromOriginalParents)||[]].filter(e=>!e.abstract),r=[...i].filter(e=>!i.some(f=>{var h;return f.id!==e.id&&(f.implements.find(m=>m.id===e.id)||((h=f.extends)==null?void 0:h.id)===e.id)}));return C(r)}get implementedPropertiesFromOriginalParents(){return C([...(this.extends?[this.extends]:[]).reduce((i,r)=>{const a=r.implementedPropertiesFromOriginalParents,c=[...r.ownDeclaredProperties].filter(h=>!!h.abstract),e=[...a,...c,...i];return[...e].filter(h=>!!!e.find(E=>{var b;return((b=E.extends)==null?void 0:b.id)===h.id||E.implements.find(A=>A.id===h.id)}))},[])])}get extendedProperties(){return this.properties.filter(i=>i.isExtendedProperty)}get ownDeclaredMethods(){return[...this.methods]}get ownDeclaredProperties(){return this.properties.filter(i=>!i.isExtendedProperty)}subscribe(){return this.project.subscribeBuiltInInstance(this),this}unsubscribe(){return this.project.unsubscribeBuiltInInstance(this),this}async APILoad(i=Ke,...r){return await lI.repository.APILoad(this.id,...r),this}toFlat(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this,...this.properties.flatMap(a=>a.toFlat(i)),...this.methods.flatMap(a=>a.toFlat(i)),...this.abstractMethods.flatMap(a=>a.toFlat(i))])}toFlatIds(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this.id,...this.properties.flatMap(a=>a.toFlatIds(i)),...this.methods.flatMap(a=>a.toFlatIds(i)),...this.abstractMethods.flatMap(a=>a.toFlatIds(i))])}toMeta(){return{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,description:this.description,static:this.static,abstract:this.abstract,type:this.type,name:this.name}}toJSON(i=new Set){var r;return i.has(this.id)?this.toReference():(i.add(this.id),{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,name:this.name,description:this.description,static:this.static,abstract:this.abstract,properties:this.properties.map(a=>a.toJSON(i)),methods:this.methods.map(a=>a.toJSON(i)),abstractMethods:this.abstractMethods.map(a=>a.toJSON(i)),extends:((r=this.extends)==null?void 0:r.toJSON(i))||null})}toReference(i=at){return{id:this.id+"--"+x.UUID.uuid()+"--ref",type:d.GenericReference,entityId:this.id,version:this.version,entityType:this.type}}toShallowJSON(i=at){var r;return{id:this.id,version:this.version,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,name:this.name,description:this.description,abstract:this.abstract,static:this.static,properties:this.properties.map(a=>a.toReference()),methods:this.methods.map(a=>a.toReference()),abstractMethods:this.abstractMethods.map(a=>a.toReference()),extends:((r=this.extends)==null?void 0:r.toReference())||null}}toFlatJSON(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this.toShallowJSON(),...this.properties.flatMap(a=>a.toFlatJSON(i)),...this.methods.flatMap(a=>a.toFlatJSON(i)),...this.abstractMethods.flatMap(a=>a.toFlatJSON(i))])}toGenerationTarget(i=at){var r;return{id:this.id,type:this.type,name:this.name,description:this.description,static:this.static,abstract:this.abstract,extends:(r=this.extends)==null?void 0:r.id}}toFlatGenerationTarget(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this.toGenerationTarget(),...this.properties.flatMap(a=>a.toFlatGenerationTarget(i)),...this.methods.flatMap(a=>a.toFlatGenerationTarget(i)),...this.abstractMethods.flatMap(a=>a.toFlatGenerationTarget(i))])}clearErrors(){return this.errors=[],this.properties.forEach(i=>i.clearErrors()),this.methods.forEach(i=>i.clearErrors()),this.abstractMethods.forEach(i=>i.clearErrors()),this}validate(){return this.errors=UVi(this),{success:!0}}async validateAsync(i={}){const r=z.YieldTracker.from(i);return this.errors=await jVi(this,{tracker:r}),{success:!0}}getErrors(){return[...this.errors,...this.properties.flatMap(r=>r.getErrors()),...this.methods.flatMap(r=>r.getErrors()),...this.abstractMethods.flatMap(r=>r.getErrors())]}async getErrorsAsync(i={}){const r=z.YieldTracker.from(i),a=[...this.errors];await r.tick();for(const c of this.properties){const e=await c.getErrorsAsync({tracker:r});a.push(...e)}for(const c of this.methods){const e=await c.getErrorsAsync({tracker:r});a.push(...e)}for(const c of this.abstractMethods){const e=await c.getErrorsAsync({tracker:r});a.push(...e)}return a}getShallowErrors(){return this.errors}getAllInteractiveMethods(){const i=[];return i.push(...this.methods),!this.extends||this.extends.type===d.PrimitiveEntity?i:C(i)}};R(lI,"repository",{APILoad:async(i,...r)=>null});let Nf=lI;function lr(s,p){if(!s)throw new Error("Entity is null");const i=p.get(s.id);switch(s.type){case d.LiteralValue:return i||new Lr(s,p);case d.DefinitionEntity:return i||new Ks(s,p);case d.PrimitiveEntity:return i||new Nf(s,p);case d.FunctionDeclaration:return i||new md(s,p);case d.GlobalEvent:return i||new Vp(s,p);case d.DataType:return i||new vr(s,p);case d.Property:return i||new Es(s,p);case d.FunctionCall:return i||new Op(s,p);case d.Condition:return i||new Np(s,p);case d.Operation:return i||new _p(s,p);case d.VariableDeclaration:return i||new Lp(s,p);case d.VariableInstance:return i||new $p(s,p);case d.OutputMap:return i||new po(s,p);case d.ArgumentDeclaration:return i||new Za(s,p);case d.InputMap:return i||new Ts(s,p);case d.Project:return i||new x(s);case d.InstalledProject:return i||new Mp(s,p);case d.ActionDescriptor:return i||new er(s,p);case d.ReturnStatement:return i||new su(s,p);case d.Loop:return i||new Pp(s,p);case d.Search:return i||new Bp(s,p);case d.ValueDescriptor:return i||new Ed(s,p);case d.BuiltInBaseEntity:return i||new Td(s,p);case d.InternalCall:return i||new Gp(s,p);case d.ContinueStatement:return i||new jp(s,p);case d.BreakStatement:return i||new kp(s,p);case d.GenericReference:return p.get(s.entityId);default:throw new Error("Invalid entity type: "+s.type)}}function Re(s,p){if(!s)throw new Error("Entity is null");const i=lr(s,p);return i.subscribe(),i}function FVi(s,p,i){if(!s)throw new Error("Entity is null");switch(s.type){case d.LiteralValue:return Lr.fromGenerationTarget(s,p,i);case d.DefinitionEntity:return Ks.fromGenerationTarget(s,p,i);case d.FunctionDeclaration:return md.fromGenerationTarget(s,p,i);case d.GlobalEvent:return Vp.fromGenerationTarget(s,p,i);case d.DataType:return vr.fromGenerationTarget(s,p,i);case d.Property:return Es.fromGenerationTarget(s,p,i);case d.FunctionCall:return Op.fromGenerationTarget(s,p,i);case d.Condition:return Np.fromGenerationTarget(s,p,i);case d.Operation:return _p.fromGenerationTarget(s,p,i);case d.VariableDeclaration:return Lp.fromGenerationTarget(s,p,i);case d.VariableInstance:return $p.fromGenerationTarget(s,p,i);case d.OutputMap:return po.fromGenerationTarget(s,p,i);case d.ArgumentDeclaration:return Za.fromGenerationTarget(s,p,i);case d.InputMap:return Ts.fromGenerationTarget(s,p,i);case d.InstalledProject:return Mp.fromGenerationTarget(s,p,i);case d.ReturnStatement:return su.fromGenerationTarget(s,p,i);case d.Loop:return Pp.fromGenerationTarget(s,p,i);case d.Search:return Bp.fromGenerationTarget(s,p,i);case d.ActionDescriptor:return er.fromGenerationTarget(s,p,i);case d.ValueDescriptor:return Ed.fromGenerationTarget(s,p,i);case d.InternalCall:return Gp.fromGenerationTarget(s,p,i);case d.ContinueStatement:return jp.fromGenerationTarget(s,p,i);case d.BreakStatement:return kp.fromGenerationTarget(s,p,i);default:throw new Error("Invalid entity type: "+s.type)}}const at={seenEntityMaps:new Map,seenEntities:new Set,timestamp:B().toISOString()};class iUe{constructor(){R(this,"initialData")}}const Ke={cascade:!1},rUe={APILoad:async(s,...p)=>null},KVi={APICreate:async(s,...p)=>s,APIUpdate:async(s,...p)=>s,APIDelete:async(s,...p)=>s,APIClone:async(s,...p)=>{},APILoadVersion:async(s,p,...i)=>null,...rUe};class qVi{}class nUe extends iUe{}class SVi extends nUe{}class ZVi{}class HVi{}class WVi{}class IL{}class zVi extends IL{}class YVi extends IL{}class JVi{}class py{static initReadsValue(p){if(p.initialData.readsValue&&p.initialData.readsValue.type!==d.GenericReference)p.readsValue=Re(p.initialData.readsValue,p.project);else if(p.initialData.readsValue&&p.initialData.readsValue.type===d.GenericReference){const i=Ra(p.initialData.readsValue,p.project);i&&(p.readsValue=i)}if(p.readsValue){if(Mt.includes(p.readsValue.type)){let i=p.parent;!Dr.includes(i.type)&&i.type!==d.Project&&(i=i.parent);const r=p.type===d.InputMap&&p.parent.type===d.Loop;r&&(i=p.parent.parent),p.readsValue.setParent(i,null),p.readsValue.initChildren(null),i&&i.type!==d.Project&&!r&&i.detachedChildren.includes(p)?i.replaceDetachedChild(p,p.readsValue):i&&i.type!==d.Project&&!r&&i.subscribeDetachedChild(p.readsValue)}p.readsValue.addValueReader(p,null)}return p.readsValue}}class JE{static initWritesValues(p,i){const r=p.initialData.writesValues.reduce((c,e)=>{if(e.type===d.GenericReference||p.writesValues.some(h=>h.id===e.id))return c;const f=Re(e,p.project);return f.setValueWriter(p,null),Mt.includes(f.type)&&(f.setParent(i,null),f.initChildren(null)),[...c,f]},[]),a=[...p.writesValues];return p.writesValues=C([...a,...r]),p.writesValues}}class QVi{}var di=(s=>(s.PROJECT_INITIALIZED="project-initialized",s.BEFORE_CHANGE_SET_CLOSE_BEFORE_SIDE_EFFECTS="before-change-set-close-before-side-effects",s.BEFORE_CHANGE_SET_CLOSE_AFTER_SIDE_EFFECTS="before-change-set-close-after-side-effects",s.CHANGE_SET_CLOSED_BEFORE_PERSIST="change-set-closed-before-persist",s.CHANGE_SET_PERSISTED="change-set-persisted",s.BEFORE_CHANGE_SET_PERSIST="before-change-set-persist",s.EXPLICIT_DEFINITION_ENTITY_ADDED="explicit-definition-entity-added",s.EXPLICIT_DEFINITION_ENTITY_REMOVED="explicit-definition-entity-removed",s.EXPLICIT_DEFINITION_ENTITY_UPDATED="explicit-definition-entity-updated",s.PERSISTED_DEFINITION_ENTITY_ADDED="persisted-definition-entity-added",s.PERSISTED_DEFINITION_ENTITY_REMOVED="persisted-definition-entity-removed",s.PERSISTED_DEFINITION_ENTITY_UPDATED="persisted-definition-entity-updated",s.RELATIONAL_DATABASE_DEFINITION_ENTITY_ADDED="relational-database-definition-entity-added",s.RELATIONAL_DATABASE_DEFINITION_ENTITY_REMOVED="relational-database-definition-entity-removed",s.RELATIONAL_DATABASE_DEFINITION_ENTITY_UPDATED="relational-database-definition-entity-updated",s))(di||{});const RL={...y$,events:new z.Events("def-proj-static-p-ctx-events")},aUe={requestActiveDynamicValue:(s,p=!1)=>null,...RL},Gt=class Gt extends un{constructor(i,r={...aUe,events:new z.Events("def-proj-inst-p-ctx-events")}){super(i);R(this,"initialData");R(this,"id");R(this,"type",d.Project);R(this,"workspaceId");R(this,"name",null);R(this,"description",null);R(this,"x");R(this,"y");R(this,"entities",[]);R(this,"projects",[]);R(this,"functions",[]);R(this,"events",[]);R(this,"variableDeclarations",[]);R(this,"variableInstances",[]);R(this,"conditions",[]);R(this,"operations",[]);R(this,"functionCalls",[]);R(this,"loops",[]);R(this,"searches",[]);R(this,"primitives",[]);R(this,"builtInBaseEntities",[]);R(this,"operationDeclarations",[]);R(this,"globalEventActionDescriptors",[]);R(this,"loopDeclarations",[]);R(this,"loopDeclarationsBodies",[]);R(this,"conditionDeclarations",[]);R(this,"valueDescriptors",[]);R(this,"dataTypes",[]);R(this,"project");R(this,"instances",{});R(this,"builtInInstances",{});R(this,"deletedInstances",{});R(this,"subscribedDefinitionEntities",new Set);R(this,"errors",[]);R(this,"references",[]);R(this,"history",[]);R(this,"undoableStackValueIndex",-1);R(this,"detachedDependents",{});R(this,"knownVersions",null);R(this,"activeVersion",!1);R(this,"initialized",!1);R(this,"startedInitialization",!1);R(this,"diggestedBuiltInBaseEntitiesIds",new Set);R(this,"rejectParallelCS",!1);R(this,"onPersistChangeSetSequentiallyCallback",null);R(this,"onPersistChangeSetInParallelCallback",null);R(this,"onAddChangeSetCallback",null);R(this,"onDiscardChangeSetCallback",null);if(this.parentContext=r,this.initialData=i,this.id=i.id,this.workspaceId=i.workspaceId,this.name=i.name,this.description=i.description,this.x=0,this.y=0,this.instances[this.id]=this,!Gt.UUID)throw new Error("UUID module is already initialized. Please inject a valid UUID module.")}static get UUID(){var i;return(i=this.parentContext.requestExtension("uuid"))==null?void 0:i.module}static new(i=null){return{id:Gt.UUID.uuid(),version:Gt.UUID.uuid(),workspaceId:"",createdAt:(i==null?void 0:i.timestamp)||B().toISOString(),author:(i==null?void 0:i.author)||Gt.sessionAuthor,previousVersion:null,deleted:!1,deletable:!0,editable:!0,type:d.Project,name:"",description:"",entities:[],functions:[],events:[],projects:[],variableDeclarations:[],variableInstances:[],conditions:[],operations:[],functionCalls:[],loops:[],searches:[]}}static validateGenerationTarget(i,r){let a=JSON.parse(JSON.stringify(i));const c=[],e=[],f=Xr(a);return e.push(...f.errors),c.push(...f.explanations),{errors:e,explanations:c,modifiedData:a}}get off(){return this.parentContext.events.off}get on(){return this.parentContext.events.on}get emit(){return this.parentContext.events.emit}get emitAsync(){return this.parentContext.events.emitAsync}get emitAsyncAll(){return this.parentContext.events.emitAsyncAll}get emitAsyncAllSettled(){return this.parentContext.events.emitAsyncAllSettled}get emitAsyncSequentially(){return this.parentContext.events.emitAsyncSequentially}get emitAsyncSequentiallyAll(){return this.parentContext.events.emitAsyncSequentiallyAll}get emitAsyncSequentiallyAllSettled(){return this.parentContext.events.emitAsyncSequentiallyAllSettled}async closePersistChangeSetsSequentially(){z.Logger.log("[ProjectState.closePersistChangeSetsSequentially] called");const i=this.history.find(r=>r.dirty&&!r.open&&!r.submitting);i&&(z.Logger.log(`[ProjectState.closePersistChangeSetsSequentially] closing pending change-set ${i.id} - ${i.actionName}`),await this.persistChangeSetSequentially(i))}async onPersistChangeSetSequentially(i){this.onPersistChangeSetSequentiallyCallback=i,z.Logger.log("[ProjectState.onPersistChangeSetSequentially] onPersistChangeSetSequentiallyCallback has been set. Checking for pending change-sets."),await this.closePersistChangeSetsSequentially()}offPersistChangeSetSequentially(){this.onPersistChangeSetSequentiallyCallback=null}async onPersistChangeSetInParallel(i){this.onPersistChangeSetInParallelCallback=i,z.Logger.log("[ProjectState.onPersistChangeSetInParallel] onPersistChangeSetInParallelCallback has been set. Checking for pending change-sets.");for(const r of this.history)this.persistChangeSetInParallel(r),await new Promise(a=>setTimeout(a,27))}offPersistChangeSetInParallel(){this.onPersistChangeSetInParallelCallback=null}onAddChangeSet(i){this.onAddChangeSetCallback=i}offAddChangeSet(){this.onAddChangeSetCallback=null}onDiscardChangeSet(i){this.onDiscardChangeSetCallback=i}offDiscardChangeSet(){this.onDiscardChangeSetCallback=null}async persistChangeSetSequentially(i){if(z.Logger.log(`[ProjectState.persistChangeSetSequentially] called for change-set ${i.id} - ${i.actionName}`),!i.dirty||i.open||i.submitting){z.Logger.log(`[ProjectState.persistChangeSetSequentially] change-set ${i.id} - ${i.actionName} is not dirty, or is open, or is already being submitted, skipping.`);return}const r=this.history.findIndex(e=>e.id===i.id),a=this.history.slice(0,r),c=a[a.length-1];if(c!=null&&c.dirty){z.Logger.log(`[ProjectState.persistChangeSetSequentially] lastBeforeSelf is dirty: ${c.id} - ${c.actionName}, closing it first.`);return}this.onPersistChangeSetSequentiallyCallback&&(z.Logger.log(`[ProjectState.persistChangeSetSequentially] invoking onPersistChangeSetSequentiallyCallback for change-set ${i.id} - ${i.actionName}`),this.emit("before-change-set-persist",i),i.submitting=!0,(await this.onPersistChangeSetSequentiallyCallback(i)).success&&(i.dirty=!1,this.emit("change-set-persisted",i),z.Logger.log(`[ProjectState.persistChangeSetSequentially] change-set ${i.id} - ${i.actionName} closed successfully, checking for pending change-sets to close.`),this.closePersistChangeSetsSequentially()))}async persistChangeSetInParallel(i){if(z.Logger.log(`[ProjectState.persistChangeSetInParallel] called for change-set ${i.id} - ${i.actionName}`),!i.dirty||i.open||i.submitting){z.Logger.log(`[ProjectState.persistChangeSetInParallel] change-set ${i.id} - ${i.actionName} is not dirty, or is open, or is already being submitted, skipping.`);return}this.onPersistChangeSetInParallelCallback&&(z.Logger.log(`[ProjectState.persistChangeSetInParallel] invoking onPersistChangeSetInParallelCallback for change-set ${i.id} - ${i.actionName}`),this.emit("before-change-set-persist",i),i.submitting=!0,(await this.onPersistChangeSetInParallelCallback(i)).success&&(i.dirty=!1,this.emit("change-set-persisted",i)))}toLatestChangeSet(i,r,a,c=!1,e="here-this"){if(!this.history.length)return new S(this,i,r,a,c,e);const f=this.history[this.history.length-1];return f.open?f:this.addChangeSet(new S(this,i,r,a,c,e))}addChangeSet(i){var a,c;if(!this.history.length)return this.undoableStackValueIndex=B_(this.undoableStackValueIndex,this.history,i),(a=this.onAddChangeSetCallback)==null||a.call(this,i,this.undoableStackValueIndex),i;const r=this.history.find(e=>e.id===(i==null?void 0:i.id));if(r)return r;if(this.rejectParallelCS){const e=this.history.find(f=>f.open);if(e)throw z.Logger.warn("Previous still open: ",e),z.Logger.warn("New change set: ",i),new Error(`There is already an open change-set with id '${e.id}'${e.actionName?` auto-close: ${e.actionName}`:""}${e.self?` root: ${e.self.type} ${oe(e.self,this)}`:""}.`)}return this.undoableStackValueIndex=B_(this.undoableStackValueIndex,this.history,i),(c=this.onAddChangeSetCallback)==null||c.call(this,i,this.undoableStackValueIndex),i}discardChangeSet(i){var a;z.Logger.log(`[ProjectState.discardChangeSet] called for change-set ${i.id} - ${i.actionName}`);const r=this.history.findIndex(c=>c.id===(i==null?void 0:i.id));return r!==-1&&(this.history.splice(r,1),z.Logger.log(`[ProjectState.discardChangeSet] Removed change-set ${i.id} - ${i.actionName} from history.`),this.undoableStackValueIndex=this.undoableStackValueIndex-1,(a=this.onDiscardChangeSetCallback)==null||a.call(this,i),i==null||i.teardown()),this}validateGeneratedUpdate(i){return{errors:[],explanations:[],modifiedData:i}}subscribeDependents(i){return i.forEach(r=>{this.detachedDependents[r.entity.id]||(this.detachedDependents[r.entity.id]=r)}),this}unsubscribeDependents(i){return i.forEach(r=>{this.detachedDependents[r.entity.id]&&delete this.detachedDependents[r.entity.id]}),this}syncDependents(i=this.project.addChangeSet(new S(this.project,Gt.sessionAuthor,B().toISOString(),this,!0,"sync-dependents"))){const r=[],a=[],c=[],e=[];return Object.values(this.detachedDependents).forEach(f=>{const h=f.entity.afterAllChildrenInitialized(i);r.push(...h.updated),a.push(...h.added),c.push(...h.removed),e.push(...h.affected)}),i==null||i.attemptAutoclose("sync-dependents",this.id),{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}onDetachedDependencyRemoved(i,r,a){const c=[],e=[],f=[],h=[];return{updated:C(c),added:C(e),removed:C(f),affected:C(h),self:this}}onDetachedDependencyRestored(i,r,a){const c=[],e=[],f=[],h=[];return{updated:C(c),added:C(e),removed:C(f),affected:C(h),self:this}}unsubscribeFromDependencies(){return this}subscribeToDependencies(){return this}increaseVersion(i){var r;if(i&&!B(i).isValid())throw new Error(`The shared timestamp '${i}' is not a valid ISO 8601 date string.`);if(i&&B(i).isSame(B(this.createdAt)))return this;if(!((r=this.knownVersions)!=null&&r.has(this.version))&&this.initialized)throw new Error(`The current ${this.type} ${this.id} version '${this.version}' is not captured in the 'knownVersions' map. Capture the current version before increasing it to avoid losing data.`);if(!this.activeVersion)throw new Error(`Only active versions can be increased. Entity with id '${this.id}' and version '${this.version}' is not active.`);return this.previousVersion=this.version,this.version=Gt.UUID.uuid(),this.createdAt=B(i).toISOString()||B().toISOString(),this}captureVersion(){var r;const i=((r=this.knownVersions)==null?void 0:r.get(this.version))||new Gt(this);if(!this.activeVersion)throw new Error(`Only active versions can be captured. Entity of type ${this.type} with id '${this.id}' and version '${this.version}' is not active.`);if(this.version!==i.version)throw new Error(`Captured ${this.type} with id '${this.id}', version '${i.version}' does not match current entity version '${this.version}'.`);return this.knownVersions=this.knownVersions?this.knownVersions.set(this.version,i):new Map().set(this.version,i),this.apply(i),this}snapshot(){const i=new Gt(this);return this.apply(i)}apply(i){const r=this.toMeta();return i.metaSync(r,null),i.entities=[...this.entities],i.projects=[...this.projects],i.functions=[...this.functions],i.events=[...this.events],i.variableDeclarations=[...this.variableDeclarations],i.variableInstances=[...this.variableInstances],i.conditions=[...this.conditions],i.operations=[...this.operations],i.functionCalls=[...this.functionCalls],i.loops=[...this.loops],i.searches=[...this.searches],i}recursiveCaptureUpstreamVersions(i){const r=[],a=[],c=[],e=[];return{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}async restoreVersion(i,r){var m;const a=[],c=[],e=[],f=[];if(this.version===i&&(r!=null&&r.skipIfSameVersion))return{updated:C(a),added:C(c),removed:C(e),affected:C(f),self:this};if(!this.knownVersions){const E=new Map;for(const[b,A]of this.knownVersions||new Map){if(E.set(b,A),A.activeVersion=!1,A.knownVersions)for(const[_,P]of A.knownVersions)E.set(_,P);A.knownVersions=null}}let h=(m=this.knownVersions)==null?void 0:m.get(i);if(!h){const E=await this.APILoadVersion({},i);if(!E)throw new Error(`Version with id '${i}' for entity with id '${this.id}' not found.`);h=new Gt(E)}return this.metaSync(h.toShallowJSON(),null),this.previousVersion=h.previousVersion,this.version=h.version,this.createdAt=h.createdAt,this.author=h.author,this.deleted=h.deleted,this.entities=[...h.entities],this.projects=[...h.projects],this.functions=[...h.functions],this.events=[...h.events],this.variableDeclarations=[...h.variableDeclarations],this.variableInstances=[...h.variableInstances],this.conditions=[...h.conditions],this.operations=[...h.operations],this.functionCalls=[...h.functionCalls],this.loops=[...h.loops],this.searches=[...h.searches],{updated:C(a),added:C(c),removed:C(e),affected:C(f),self:this}}updateWithShallowTransfer(i,r=this.project.addChangeSet(new S(this.project,Gt.sessionAuthor,B().toISOString(),this,!0,w.UpdateWithShallowTransfer))){return this.checkCanEdit(this,r)?(this.metaSync(i,r),this.version=i.version,this.createdAt=i.createdAt,this.author=i.author,this.deleted=i.deleted,this.previousVersion=i.previousVersion,this.captureVersion(),this.subscribeToDependencies(),r==null||r.attemptAutoclose(w.UpdateWithShallowTransfer,this.id),this):(z.Logger.warn(`[updateWithShallowTransfer] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.UpdateWithShallowTransfer,this.id),this)}updateWithGenerationTarget(i,r=this.project.addChangeSet(new S(this.project,Gt.sessionAuthor,B().toISOString(),this,!0,w.UpdateWithGenerationTarget))){return this.checkCanEdit(this,r)?(this.metaSync(i,r),this.captureVersion(),this.subscribeToDependencies(),r==null||r.attemptAutoclose(w.UpdateWithGenerationTarget,this.id),this):(z.Logger.warn(`[updateWithGenerationTarget] User is not allowed to edit this ${this.type} entity with id: ${this.id}`),r==null||r.attemptAutoclose(w.UpdateWithGenerationTarget,this.id),this)}hydrateAncestors(){const i=[],r=[],a=[],c=[];return{updated:C(i),added:C(r),removed:C(a),affected:C(c),self:this}}afterAllChildrenInitialized(i=null){const r=[],a=[],c=[],e=[];return this.initialized||(this.initialized=!0,this.emit("project-initialized",this,i)),this.validate(),{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}addSelfToProject(i){const r=[],a=[],c=[],e=[];return this.subscribe(),this.subscribeToDependencies(),{updated:C(r),added:C(a),removed:C(c),affected:C(e),self:this}}get instancesList(){return Object.values(this.instances)}get builtInInstancesList(){return Object.values(this.builtInInstances)}isOperationDeclaration(i){return this.operationDeclarations.includes(i)}isGlobalEventActionDescriptor(i){return this.globalEventActionDescriptors.includes(i)}isLoopDeclaration(i){return this.loopDeclarations.includes(i)}isConditionDeclaration(i){return this.conditionDeclarations.includes(i)}initChildren(i=this.project.addChangeSet(new S(this.project,Gt.sessionAuthor,B().toISOString(),this,!0,"init-children"))){return this.initialized||this.startedInitialization?this:(this.startedInitialization=!0,this.entities=this.initialData.entities.map(r=>{const a=Re(r,this);return a.setParent(this,null),a.initChildren(i),a}),this.projects=this.initialData.projects.map(r=>{const a=Re(r,this);return a.setParent(this,null),a.initChildren(i),a}),this.variableDeclarations=this.initialData.variableDeclarations.map(r=>{const a=Re(r,this);return a.setParent(this,null),a.initChildren(i),a}),this.variableInstances=this.initialData.variableInstances.map(r=>{const a=Re(r,this);return a.setParent(this,null),a.initChildren(i),a}),this.conditions=this.initialData.conditions.map(r=>{const a=Re(r,this);return a.setParent(this,null),a.initChildren(i),a}),this.operations=this.initialData.operations.map(r=>{const a=Re(r,this);return a.setParent(this,null),a.initChildren(i),a}),this.functions=this.initialData.functions.map(r=>{const a=Re(r,this);return a.setParent(this,null),a.initChildren(i),a}),this.events=this.initialData.events.map(r=>{const a=Re(r,this);return a.setParent(this,null),a.initChildren(i),a}),this.functionCalls=this.initialData.functionCalls.map(r=>{const a=Re(r,this);return a.setParent(this,null),a.initChildren(i),a}),this.loops=this.initialData.loops.map(r=>{const a=Re(r,this);return a.setParent(this,null),a.initChildren(i),a}),this.searches=this.initialData.searches.map(r=>{const a=Re(r,this);return a.setParent(this,null),a.initChildren(i),a}),this.attachOrphanReferences(),this.subscribeToDependencies(),this.afterAllChildrenInitialized(i),i==null||i.attemptAutoclose("init-children",this.id),this)}subscribeInstance(i){return(!this.instances[i.id]||this.instances[i.id]!==i)&&(this.instances[i.id]=i),this}subscribeDeletedInstance(i){return(!this.deletedInstances[i.id]||this.deletedInstances[i.id]!==i)&&(this.deletedInstances[i.id]=i),this}subscribeBuiltInInstance(i){return(!this.builtInInstances[i.id]||this.builtInInstances[i.id]!==i)&&(this.builtInInstances[i.id]=i),this}subscribe(){var i;return this.activeVersion=!0,(i=this.knownVersions)==null||i.forEach(r=>{r.version!==this.version&&(r.activeVersion=!1)}),this.subscribeInstance(this),this}unsubscribe(){return this}unsubscribeInstance(i){return delete this.instances[i.id],this}unsubscribeDeletedInstance(i){return delete this.deletedInstances[i.id],this}unsubscribeBuiltInInstance(i){return delete this.builtInInstances[i.id],this}findSubscribedBuiltInInstance(i){return this.builtInInstances[i.id]||null}get(i){return this.instances[i]||this.builtInInstances[i]||null}getDeleted(i){return this.deletedInstances[i]||null}getManaged(i){return this.getBuiltIn(i)?null:this.instances[i]||null}getBuiltIn(i){return this.builtInInstances[i]||null}findSubscribedInstanceFromReference(i){return this.instances[i.entityId]||null}findSubscribedBuiltInInstanceFromReference(i){return this.builtInInstances[i.entityId]||null}metaSync(i,r=this.project.addChangeSet(new S(this.project,Gt.sessionAuthor,B().toISOString(),this,!0,"meta-sync"))){const a=tn(this,i,r),c=en(this,a),e=this.toMeta();return this.name=a.name!==void 0?a.name:e.name,this.description=a.description!==void 0?a.description:e.description,this.x=a.x||e.x,this.y=a.y||e.y,super.baseMetaSync(a,this,r),a.deleted===!0&&!e.deleted?r==null||r.add(this,W.Removed):a.deleted===!1&&e.deleted?r==null||r.add(this,W.Added):c&&(r==null||r.add(this,W.Updated)),r==null||r.attemptAutoclose("meta-sync",this.id),this}async APILoad(i=Ke,...r){return await Gt.repository.APILoad(this.id,...r),this}async APICreate(i=Ke,...r){return await Gt.repository.APICreate(this.toShallowJSON(),...r),this}async APIUpdate(i=Ke,...r){return await Gt.repository.APIUpdate(this.toShallowJSON(),...r),this}async APIDelete(i=Ke,...r){return await Gt.repository.APIDelete(this.toShallowJSON(),...r),this}async APIClone(i=Ke,...r){return await Gt.repository.APIClone(this.id,...r),this}async APILoadVersion(i=Ke,r,...a){return await Gt.repository.APILoadVersion(this.id,r,...a)}remove({ignoreUpstream:i}={ignoreUpstream:!1},r=this.project.addChangeSet(new S(this.project,Gt.sessionAuthor,B().toISOString(),this,!0,w.RemoveEntity))){return{added:[],updated:[],removed:[],affected:[],self:this}}restore({}={},i=this.project.addChangeSet(new S(this.project,Gt.sessionAuthor,B().toISOString(),this,!0,w.RestoreEntity))){return{added:[],updated:[],removed:[],affected:[],self:this}}getAllBuiltInIds(){const i=new Set;return[...this.primitives.flatMap(r=>r.toFlatIds(i)),...this.builtInBaseEntities.flatMap(r=>r.toFlatIds(i)),...this.operationDeclarations.flatMap(r=>r.toFlatIds(i)),...this.globalEventActionDescriptors.flatMap(r=>r.toFlatIds(i)),...this.loopDeclarations.flatMap(r=>r.toFlatIds(i)),...this.conditionDeclarations.flatMap(r=>r.toFlatIds(i)),...this.valueDescriptors.flatMap(r=>r.toFlatIds(i)),...this.dataTypes.flatMap(r=>r.toFlatIds(i))]}getAllBuiltIn(){const i=new Set;return[...this.primitives.flatMap(r=>r.toFlat(i)),...this.builtInBaseEntities.flatMap(r=>r.toFlat(i)),...this.operationDeclarations.flatMap(r=>r.toFlat(i)),...this.globalEventActionDescriptors.flatMap(r=>r.toFlat(i)),...this.loopDeclarations.flatMap(r=>r.toFlat(i)),...this.conditionDeclarations.flatMap(r=>r.toFlat(i)),...this.valueDescriptors.flatMap(r=>r.toFlat(i)),...this.dataTypes.flatMap(r=>r.toFlat(i))]}toFlat(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this,...this.entities.flatMap(a=>a.toFlat(i)),...this.functions.flatMap(a=>a.toFlat(i)),...this.events.flatMap(a=>a.toFlat(i)),...this.projects.flatMap(a=>a.toFlat(i)),...this.variableDeclarations.flatMap(a=>a.toFlat(i)),...this.variableInstances.flatMap(a=>a.toFlat(i)),...this.conditions.flatMap(a=>a.toFlat(i)),...this.operations.flatMap(a=>a.toFlat(i)),...this.functionCalls.flatMap(a=>a.toFlat(i)),...this.loops.flatMap(a=>a.toFlat(i)),...this.searches.flatMap(a=>a.toFlat(i))])}toFlatIds(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this.id,...this.entities.flatMap(a=>a.toFlatIds(i)),...this.functions.flatMap(a=>a.toFlatIds(i)),...this.events.flatMap(a=>a.toFlatIds(i)),...this.projects.flatMap(a=>a.toFlatIds(i)),...this.variableDeclarations.flatMap(a=>a.toFlatIds(i)),...this.variableInstances.flatMap(a=>a.toFlatIds(i)),...this.conditions.flatMap(a=>a.toFlatIds(i)),...this.operations.flatMap(a=>a.toFlatIds(i)),...this.functionCalls.flatMap(a=>a.toFlatIds(i)),...this.loops.flatMap(a=>a.toFlatIds(i)),...this.searches.flatMap(a=>a.toFlatIds(i))])}toMeta(){return{id:this.id,version:this.version,workspaceId:this.workspaceId,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,description:this.description,type:this.type,editable:this.editable,deletable:this.deletable,name:this.name}}toJSON(i=new Set){return i.has(this.id)?this.toReference():(i.add(this.id),{id:this.id,version:this.version,workspaceId:this.workspaceId,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,editable:this.editable,deletable:this.deletable,name:this.name,description:this.description,entities:this.entities.map(r=>r.toJSON(i)),variableDeclarations:this.variableDeclarations.map(r=>r.toJSON(i)),variableInstances:this.variableInstances.map(r=>r.toJSON(i)),conditions:this.conditions.map(r=>r.toJSON(i)),operations:this.operations.map(r=>r.toJSON(i)),loops:this.loops.map(r=>r.toJSON(i)),searches:this.searches.map(r=>r.toJSON(i)),functions:this.functions.map(r=>r.toJSON(i)),events:this.events.map(r=>r.toJSON(i)),projects:this.projects.map(r=>r.toJSON(i)),functionCalls:this.functionCalls.map(r=>r.toJSON(i))})}toJSONClone(i={uuidStrategy:"uuid"}){const r=new Map,a=new Set,c=this.getAllBuiltInIds();return Object.keys(this.instances).forEach(e=>{if(c.includes(e)){r.set(e,e);return}r.set(e,Gt.UUID.uuid())}),a.add(this.id),{id:r.get(this.id),version:this.version,workspaceId:this.workspaceId,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,editable:this.editable,deletable:this.deletable,name:this.name,description:this.description,entities:this.entities.map(e=>e.toJSONClone({...i,seenEntityMaps:r,seenEntities:a,newId:null})),projects:this.projects.map(e=>e.toJSONClone({...i,seenEntityMaps:r,seenEntities:a,newId:null})),variableDeclarations:this.variableDeclarations.map(e=>e.toJSONClone({...i,seenEntityMaps:r,seenEntities:a,newId:null})),variableInstances:this.variableInstances.map(e=>e.toJSONClone({...i,seenEntityMaps:r,seenEntities:a,newId:null})),conditions:this.conditions.map(e=>e.toJSONClone({...i,seenEntityMaps:r,seenEntities:a,newId:null})),operations:this.operations.map(e=>e.toJSONClone({...i,seenEntityMaps:r,seenEntities:a,newId:null})),functions:this.functions.map(e=>e.toJSONClone({...i,seenEntityMaps:r,seenEntities:a,newId:null})),events:this.events.map(e=>e.toJSONClone({...i,seenEntityMaps:r,seenEntities:a,newId:null})),functionCalls:this.functionCalls.map(e=>e.toJSONClone({...i,seenEntityMaps:r,seenEntities:a,newId:null})),loops:this.loops.map(e=>e.toJSONClone({...i,seenEntityMaps:r,seenEntities:a,newId:null})),searches:this.searches.map(e=>e.toJSONClone({...i,seenEntityMaps:r,seenEntities:a,newId:null}))}}toReference(i=at){var a;let r=this.id;return(a=i.seenEntityMaps)!=null&&a.has(this.id)&&(r=i.seenEntityMaps.get(this.id)),{id:r+"--"+Gt.UUID.uuid()+"--ref",type:d.GenericReference,entityId:r,version:this.version,entityType:this.type}}toShallowJSON(i=at){var a;let r=this.id;return(a=i.seenEntityMaps)!=null&&a.has(this.id)&&(r=i.seenEntityMaps.get(this.id)),{id:r,version:this.version,workspaceId:this.workspaceId,createdAt:this.createdAt,previousVersion:this.previousVersion,author:this.author,deleted:this.deleted,type:this.type,editable:this.editable,deletable:this.deletable,name:this.name,description:this.description,entities:this.entities.map(c=>c.toReference(i)),functions:this.functions.map(c=>c.toReference(i)),events:this.events.map(c=>c.toReference(i)),projects:this.projects.map(c=>c.toReference(i)),variableDeclarations:this.variableDeclarations.map(c=>c.toReference(i)),variableInstances:this.variableInstances.map(c=>c.toReference(i)),conditions:this.conditions.map(c=>c.toReference(i)),operations:this.operations.map(c=>c.toReference(i)),functionCalls:this.functionCalls.map(c=>c.toReference(i)),loops:this.loops.map(c=>c.toReference(i)),searches:this.searches.map(c=>c.toReference(i))}}toFlatJSON(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[this.toShallowJSON(),...this.entities.flatMap(a=>a.toFlatJSON(i)),...this.functions.flatMap(a=>a.toFlatJSON(i)),...this.events.flatMap(a=>a.toFlatJSON(i)),...this.projects.flatMap(a=>a.toFlatJSON(i)),...this.variableDeclarations.flatMap(a=>a.toFlatJSON(i)),...this.variableInstances.flatMap(a=>a.toFlatJSON(i)),...this.conditions.flatMap(a=>a.toFlatJSON(i)),...this.operations.flatMap(a=>a.toFlatJSON(i)),...this.functionCalls.flatMap(a=>a.toFlatJSON(i)),...this.loops.flatMap(a=>a.toFlatJSON(i)),...this.searches.flatMap(a=>a.toFlatJSON(i))])}toGenerationTarget(i=at){var a;let r=this.id;return(a=i.seenEntityMaps)!=null&&a.has(this.id)&&(r=i.seenEntityMaps.get(this.id)),{id:r,workspaceId:this.workspaceId,type:this.type,name:this.name,description:this.description}}toFlatGenerationTarget(i=new Set){return i.has(this.id)?[]:(i.add(this.id),[...this.entities.flatMap(a=>a.toFlatGenerationTarget(i)),...this.functions.flatMap(a=>a.toFlatGenerationTarget(i)),...this.events.flatMap(a=>a.toFlatGenerationTarget(i)),...this.projects.flatMap(a=>a.toFlatGenerationTarget(i)),...this.variableDeclarations.flatMap(a=>a.toFlatGenerationTarget(i)),...this.variableInstances.flatMap(a=>a.toFlatGenerationTarget(i)),...this.conditions.flatMap(a=>a.toFlatGenerationTarget(i)),...this.operations.flatMap(a=>a.toFlatGenerationTarget(i)),...this.functionCalls.flatMap(a=>a.toFlatGenerationTarget(i)),...this.loops.flatMap(a=>a.toFlatGenerationTarget(i)),...this.searches.flatMap(a=>a.toFlatGenerationTarget(i))])}clearErrors(){return this.errors=[],this.entities.forEach(i=>i.clearErrors()),this.projects.forEach(i=>i.clearErrors()),this.functions.forEach(i=>i.clearErrors()),this.events.forEach(i=>i.clearErrors()),this.variableDeclarations.forEach(i=>i.clearErrors()),this.variableInstances.forEach(i=>i.clearErrors()),this.conditions.forEach(i=>i.clearErrors()),this.operations.forEach(i=>i.clearErrors()),this.functionCalls.forEach(i=>i.clearErrors()),this.loops.forEach(i=>i.clearErrors()),this.searches.forEach(i=>i.clearErrors()),this}validate(){return this.validateChildren(),bE([...this.errors]),{success:!0}}async validateAsync(i={}){const r=z.YieldTracker.from(i);return await this.validateChildrenAsync({tracker:r}),await R_e([...this.errors]),{success:!0}}validateChildren(){this.entities.forEach(i=>i.validate()),this.projects.forEach(i=>i.validate()),this.functions.forEach(i=>i.validate()),this.events.forEach(i=>i.validate()),this.variableDeclarations.forEach(i=>i.validate()),this.variableInstances.forEach(i=>i.validate()),this.conditions.forEach(i=>i.validate()),this.operations.forEach(i=>i.validate()),this.functionCalls.forEach(i=>i.validate()),this.loops.forEach(i=>i.validate()),this.searches.forEach(i=>i.validate())}async validateChildrenAsync(i={}){const r=z.YieldTracker.from(i);for(let a=0;a<this.entities.length;a++)await this.entities[a].validateAsync({tracker:r});for(let a=0;a<this.projects.length;a++)await this.projects[a].validateAsync({tracker:r});for(let a=0;a<this.functions.length;a++)await this.functions[a].validateAsync({tracker:r});for(let a=0;a<this.events.length;a++)await this.events[a].validateAsync({tracker:r});for(let a=0;a<this.variableDeclarations.length;a++)await this.variableDeclarations[a].validateAsync({tracker:r});for(let a=0;a<this.variableInstances.length;a++)await this.variableInstances[a].validateAsync({tracker:r});for(let a=0;a<this.conditions.length;a++)await this.conditions[a].validateAsync({tracker:r});for(let a=0;a<this.operations.length;a++)await this.operations[a].validateAsync({tracker:r});for(let a=0;a<this.functionCalls.length;a++)await this.functionCalls[a].validateAsync({tracker:r});for(let a=0;a<this.loops.length;a++)await this.loops[a].validateAsync({tracker:r});for(let a=0;a<this.searches.length;a++)await this.searches[a].validateAsync({tracker:r})}getErrors(){return[...this.errors,...this.entities.flatMap(r=>r.getErrors()),...this.projects.flatMap(r=>r.getErrors()),...this.functions.flatMap(r=>r.getErrors()),...this.events.flatMap(r=>r.getErrors()),...this.variableDeclarations.flatMap(r=>r.getErrors()),...this.variableInstances.flatMap(r=>r.getErrors()),...this.conditions.flatMap(r=>r.getErrors()),...this.operations.flatMap(r=>r.getErrors()),...this.functionCalls.flatMap(r=>r.getErrors()),...this.loops.flatMap(r=>r.getErrors()),...this.searches.flatMap(r=>r.getErrors())]}async getErrorsAsync(i={}){const r=z.YieldTracker.from(i),a=[...this.errors];await r.tick();for(let c=0;c<this.entities.length;c++){const e=await this.entities[c].getErrorsAsync({tracker:r});a.push(...e)}for(let c=0;c<this.projects.length;c++){const e=await this.projects[c].getErrorsAsync({tracker:r});a.push(...e)}for(let c=0;c<this.functions.length;c++){const e=await this.functions[c].getErrorsAsync({tracker:r});a.push(...e)}for(let c=0;c<this.events.length;c++){const e=await this.events[c].getErrorsAsync({tracker:r});a.push(...e)}for(let c=0;c<this.variableDeclarations.length;c++){const e=await this.variableDeclarations[c].getErrorsAsync({tracker:r});a.push(...e)}for(let c=0;c<this.variableInstances.length;c++){const e=await this.variableInstances[c].getErrorsAsync({tracker:r});a.push(...e)}for(let c=0;c<this.conditions.length;c++){const e=await this.conditions[c].getErrorsAsync({tracker:r});a.push(...e)}for(let c=0;c<this.operations.length;c++){const e=await this.operations[c].getErrorsAsync({tracker:r});a.push(...e)}for(let c=0;c<this.functionCalls.length;c++){const e=await this.functionCalls[c].getErrorsAsync({tracker:r});a.push(...e)}for(let c=0;c<this.loops.length;c++){const e=await this.loops[c].getErrorsAsync({tracker:r});a.push(...e)}for(let c=0;c<this.searches.length;c++){const e=await this.searches[c].getErrorsAsync({tracker:r});a.push(...e)}return a}getShallowErrors(){return this.errors}clone(){return this}addDefinitionEntity(i){return this.entities.includes(i)||this.entities.push(i),i}addFunctionDeclaration(i){return this.functions.includes(i)||this.functions.push(i),i}addFunctionCall(i){return this.functionCalls.includes(i)||this.functionCalls.push(i),i}addVariableDeclaration(i){return this.variableDeclarations.includes(i)||this.variableDeclarations.push(i),i}addVariableInstance(i){return this.variableInstances.includes(i)||this.variableInstances.push(i),i}addInstalledProject(i){return this.projects.includes(i)||this.projects.push(i),this}addGlobalEvent(i){return this.events.includes(i)||this.events.push(i),this}addCondition(i){return this.conditions.includes(i)||this.conditions.push(i),this}addOperation(i){return this.operations.includes(i)||this.operations.push(i),this}addLoop(i){return this.loops.includes(i)||this.loops.push(i),this}addSearch(i){return this.searches.includes(i)||this.searches.push(i),this}removeDefinitionEntity(i){const r=this.entities.findIndex(a=>a.id===i.id);if(r>-1){const a=this.entities[r];return this.entities.splice(r,1),a}return null}removeCondition(i){const r=this.conditions.findIndex(a=>a.id===i.id);if(r>-1){const a=this.conditions[r];return this.conditions.splice(r,1),a}return null}removeOperation(i){const r=this.operations.findIndex(a=>a.id===i.id);if(r>-1){const a=this.operations[r];return this.operations.splice(r,1),a}return null}removeLoop(i){const r=this.loops.findIndex(a=>a.id===i.id);if(r>-1){const a=this.loops[r];return this.loops.splice(r,1),a}return null}removeSearch(i){const r=this.searches.findIndex(a=>a.id===i.id);if(r>-1){const a=this.searches[r];return this.searches.splice(r,1),a}return null}removeFunctionCall(i){const r=this.functionCalls.findIndex(a=>a.id===i.id);if(r>-1){const a=this.functionCalls[r];return this.functionCalls.splice(r,1),a}return null}removeVariableInstance(i){const r=this.variableInstances.findIndex(a=>a.id===i.id);if(r>-1){const a=this.variableInstances[r];return this.variableInstances.splice(r,1),a}return null}removeVariableDeclaration(i){const r=this.variableDeclarations.findIndex(a=>a.id===i.id);if(r>-1){const a=this.variableDeclarations[r];return this.variableDeclarations.splice(r,1),a}return null}removeFunctionDeclaration(i){const r=this.functions.findIndex(a=>a.id===i.id);if(r>-1){const a=this.functions[r];return this.functions.splice(r,1),a}return null}removeInstalledProject(i){const r=this.projects.findIndex(a=>a.id===i.id);if(r>-1){const a=this.projects[r];return this.projects.splice(r,1),a}return null}removeGlobalEvent(i){const r=this.events.findIndex(a=>a.id===i.id);if(r>-1){const a=this.events[r];return this.events.splice(r,1),a}return null}removeTopLevelVariableDeclaration(i){if(i.type!==d.VariableDeclaration)return null;const r=this.variableDeclarations.findIndex(a=>a.id===i.id);if(r>-1){const a=this.variableDeclarations[r];return this.variableDeclarations.splice(r,1),a}return null}getEntryPoints(){return[...this.functions,...this.events,...this.entities.flatMap(r=>r.methods)]}getTerminationStatements(){return[...this.getEntryPoints().reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.ReturnStatement||e.type===d.ContinueStatement||e.type===d.BreakStatement)]},[])]}getFunctionDeclaration(i){return this.functions.find(r=>r.id===i)||null}getConditions(){return[...this.conditions,...this.getEntryPoints().reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Condition)]},[]),...this.functionCalls.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Condition)]},[]),...this.operations.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Condition)]},[]),...this.loops.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Condition)]},[]),...this.searches.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Condition)]},[])]}getOperations(){return[...this.operations,...this.getEntryPoints().reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Operation)]},[]),...this.functionCalls.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Operation)]},[]),...this.conditions.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Operation)]},[]),...this.loops.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Operation)]},[]),...this.searches.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Operation)]},[])]}getFunctionCalls(){return[...this.functionCalls,...this.getEntryPoints().reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.FunctionCall)]},[]),...this.conditions.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.FunctionCall)]},[]),...this.operations.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.FunctionCall)]},[]),...this.loops.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.FunctionCall)]},[]),...this.searches.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.FunctionCall)]},[])]}getDefinitionEntities(i=new Set){return Array.from(this.subscribedDefinitionEntities).filter(a=>!i.has(a)).map(a=>this.get(a))}getVariables(){return[...this.variableDeclarations,...this.getEntryPoints().reduce((r,a)=>{const c=cr(a);return[...r,...c]},[]),...this.functionCalls.reduce((r,a)=>{const c=cr(a);return[...r,...c]},[]),...this.conditions.reduce((r,a)=>{const c=cr(a);return[...r,...c]},[]),...this.operations.reduce((r,a)=>{const c=cr(a);return[...r,...c]},[]),...this.loops.reduce((r,a)=>{const c=cr(a);return[...r,...c]},[]),...this.searches.reduce((r,a)=>{const c=cr(a);return[...r,...c]},[])]}getVariableInstances(){return[...this.variableInstances,...this.entities.reduce((r,a)=>[...r,...a.methods.flatMap(c=>{const f=pt(c).filter(h=>h.type===d.VariableInstance);return[...r,...f]})],[]),...this.getEntryPoints().reduce((r,a)=>{const e=cr(a).filter(f=>f.type===d.VariableInstance);return[...r,...e]},[]),...this.functionCalls.reduce((r,a)=>{const e=cr(a).filter(f=>f.type===d.VariableInstance);return[...r,...e]},[]),...this.conditions.reduce((r,a)=>{const e=cr(a).filter(f=>f.type===d.VariableInstance);return[...r,...e]},[]),...this.operations.reduce((r,a)=>{const e=cr(a).filter(f=>f.type===d.VariableInstance);return[...r,...e]},[]),...this.loops.reduce((r,a)=>{const e=cr(a).filter(f=>f.type===d.VariableInstance);return[...r,...e]},[]),...this.searches.reduce((r,a)=>{const e=cr(a).filter(f=>f.type===d.VariableInstance);return[...r,...e]},[])]}getVariableDeclarations(){return C([...this.variableDeclarations,...this.entities.reduce((r,a)=>[...r,...a.methods.flatMap(c=>{const f=pt(c).filter(h=>h.type===d.VariableDeclaration);return[...r,...f]})],[]),...this.getEntryPoints().reduce((r,a)=>{const e=cr(a).filter(f=>f.type===d.VariableDeclaration);return[...r,...e]},[]),...this.functionCalls.reduce((r,a)=>{const e=cr(a).filter(f=>f.type===d.VariableDeclaration);return[...r,...e]},[]),...this.conditions.reduce((r,a)=>{const e=cr(a).filter(f=>f.type===d.VariableDeclaration);return[...r,...e]},[]),...this.operations.reduce((r,a)=>{const e=cr(a).filter(f=>f.type===d.VariableDeclaration);return[...r,...e]},[]),...this.loops.reduce((r,a)=>{const e=cr(a).filter(f=>f.type===d.VariableDeclaration);return[...r,...e]},[]),...this.searches.reduce((r,a)=>{const e=cr(a).filter(f=>f.type===d.VariableDeclaration);return[...r,...e]},[])])}getLoops(){return[...this.loops,...this.getEntryPoints().reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Loop)]},[]),...this.functionCalls.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Loop)]},[]),...this.conditions.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Loop)]},[]),...this.operations.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Loop)]},[]),...this.searches.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Loop)]},[])]}getSearches(){return[...this.searches,...this.getEntryPoints().reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Search)]},[]),...this.functionCalls.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Search)]},[]),...this.conditions.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Search)]},[]),...this.operations.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Search)]},[]),...this.loops.reduce((r,a)=>{const c=pt(a);return[...r,...c.filter(e=>e.type===d.Search)]},[])]}attachOrphanReferences(){const i=this.getVariableInstances(),r=this.getVariableDeclarations();return i.forEach(a=>{if(!a.declaration){const c=a.initialData,e=c.declaration.entityId||c.declaration.id,f=r.find(h=>h.id===e);f&&a.setDeclaration(f)}}),this}getBuiltInPersistedEntity(){return this.builtInBaseEntities.find(i=>i.name===ge.PERSISTED_ENTITY)||null}requestActiveDynamicValue(i,r=!1){var c,e;const a=(e=(c=this.parentContext).requestActiveDynamicValue)==null?void 0:e.call(c,i,r);if(!a&&pI.includes(i.type)){const f=i.getDefaultValue();return f?{value:f,type:Be.DefaultValue,inheritanceLink:null,valueOwner:i}:null}return a||null}requestExtension(i){if(this.parentContext.requestExtension){const r=this.parentContext.requestExtension(i);if(r&&!r.module)throw new Error(`Module ${i} is not registered properly.`);return r.module||null}return null}undo(){z.Logger.log("Undoing, from: ",this.undoableStackValueIndex),this.undoableStackValueIndex=this.undoableStackValueIndex-1,z.Logger.log("To: ",this.undoableStackValueIndex);const i=this.history[this.undoableStackValueIndex+1],r=this.history[this.undoableStackValueIndex];return z.Logger.log("Current change set: ",i==null?void 0:i.toJSON()),z.Logger.log("Change set to restore: ",r==null?void 0:r.toJSON()),$_(i||"initial",r||"initial",this)}redo(){z.Logger.log("Undoing, from: ",this.undoableStackValueIndex),this.undoableStackValueIndex=this.undoableStackValueIndex+1,z.Logger.log("To: ",this.undoableStackValueIndex);const i=this.history[this.undoableStackValueIndex-1],r=this.history[this.undoableStackValueIndex];return z.Logger.log("Current change set: ",i==null?void 0:i.toJSON()),z.Logger.log("Change set to restore: ",r.toJSON()),$_(i||"initial",r||"initial",this)}applyExternalChangeSet(i){const r=i.payload,a=this.addChangeSet(new S(this,i.userAuthor,i.emittedAt,this));a.ignoreNonEditable=!0,a.ignoreNonDeletable=!0;const c=r.updated[this.id];if(!c)throw new Error("Project root not found in change set transfer. Cannot apply changes.");const e={...r.added,...r.updated,...r.removed},f=[...Object.keys(r.added),...Object.keys(r.updated),...Object.keys(r.removed)];f.forEach(m=>{var E;if(!e[m]){z.Logger.warn(`Entity '${m}' not found in change set transfer. Cannot apply changes.`);const b=(E=this.get(m))==null?void 0:E.toShallowJSON();throw b?z.Logger.warn("Entity in project: ",b):z.Logger.warn("Entity not in project"),new Error(`Entity '${m}' not found in change set transfer. Cannot apply changes.`)}});const h=new Fn(c,{allBuiltInEntityIds:this.diggestedBuiltInBaseEntitiesIds});return h.flatRecord=e,h.order=f,h.orderEntities(),z.Logger.log("All entities: ",h.order.map((m,E)=>`${E+1}: ${e[m].type} - ${m}`).join(`,
|
|
606
606
|
`)),z.Logger.log("Persisting new additions"),h.visit(async(m,E)=>{if(r.added[m.id]){z.Logger.log("Adding: ",m.id);try{const b=Re(m,this);if(b.hydrateAncestors(),b.addSelfToProject(a),a.add(b,W.Added),a||b.captureVersion(),!this.get(m.id))throw new Error(`Entity ${m.id} was not added to the project`)}catch(b){z.Logger.error("Error: ",b),z.Logger.error("Errored entity: ",m)}}}),z.Logger.log("Persisting updates"),h.visit(async(m,E)=>{if(r.updated[m.id]){z.Logger.log("Updating: ",m.id);try{const b=this.get(m.id);b?(b.updateWithShallowTransfer(m,a),a.add(b,W.Updated),a||b.captureVersion()):z.Logger.warn(`Active version of ${m.id} not found when applying external changes`)}catch(b){z.Logger.error("Error: ",b),z.Logger.error("Errored entity: ",m)}}}),z.Logger.log("Persisting removals"),h.visit(async(m,E)=>{if(r.removed[m.id]){z.Logger.log("Removing: ",m.id);try{const b=this.get(m.id);b&&(b.remove({ignoreUpstream:!1},a),a.add(b,W.Removed),a||b.captureVersion())}catch(b){z.Logger.error("Error: ",b),z.Logger.error("Errored entity: ",m)}}}),a.open=!1,a}toBuiltInShallowRecord(){const i={};return Object.values(this.builtInInstances).forEach(r=>{const a=r.toShallowJSON();i[r.id]=a}),i}toShallowRecord(){const i={};return Object.values(this.instances).forEach(r=>{const a=r.toShallowJSON();i[r.id]=a}),i}toFullProjectTransfer(i){const r={shallowErrors:!1,...i},a=new Fn(void 0,{allBuiltInEntityIds:this.diggestedBuiltInBaseEntitiesIds});a.flatRecord={};for(const f of Object.values(this.instances))this.diggestedBuiltInBaseEntitiesIds.has(f.id)||(a.flatRecord[f.id]=f);a.order=Object.keys(a.flatRecord),a.orderEntities();const c={},e=[];return a.visit(f=>{try{const h=f.toShallowJSON();c[f.id]=h,e.push(f.id)}catch(h){if(z.Logger.error(`[toFullProjectTransfer] Error serializing ${f.type} ${f.id}`,h),!r.shallowErrors)throw h}}),{order:e,size:e.length,record:c}}async toFullProjectTransferAsync(i={}){const r={shallowErrors:!1,...i},a=z.YieldTracker.from(r),c=new Fn(void 0,{allBuiltInEntityIds:this.diggestedBuiltInBaseEntitiesIds});c.flatRecord={};for(const h of Object.values(this.instances))await a.tick(),!this.diggestedBuiltInBaseEntitiesIds.has(h.id)&&(c.flatRecord[h.id]=h);c.order=Object.keys(c.flatRecord);const e=[];if(r.seenEntityMaps)for(const h of c.order){const m=r.seenEntityMaps.get(h)??h;this.diggestedBuiltInBaseEntitiesIds.has(m)}await c.orderEntitiesAsync({tracker:a});const f={};return await c.visitAsync(async h=>{try{if(this.diggestedBuiltInBaseEntitiesIds.has(h.id))return;const m=h.toShallowJSON({seenEntityMaps:r.seenEntityMaps});r.resetVersionOptions&&(m.version=Gt.UUID.uuid(),m.createdAt=r.resetVersionOptions.commonTimestamp||B().toISOString(),m.author=r.resetVersionOptions.author||Gt.sessionAuthor||"1",m.previousVersion=null),f[m.id]=m,e.push(m.id),r!=null&&r.onVisit&&await r.onVisit(m)}catch(m){if(z.Logger.error(`[toFullProjectTransferAsync] Error serializing ${h.type} ${h.id}`,m),!r.shallowErrors)throw m}},{tracker:a}),{order:e,size:e.length,record:f}}async toFullProjectGenerationTargetAsync(i={}){const r={shallowErrors:!1,...i},a=z.YieldTracker.from(r),c=new Fn(void 0,{allBuiltInEntityIds:this.diggestedBuiltInBaseEntitiesIds});c.flatRecord={};for(const h of Object.values(this.instances))await a.tick(),!this.diggestedBuiltInBaseEntitiesIds.has(h.id)&&(c.flatRecord[h.id]=h);c.order=Object.keys(c.flatRecord);const e=[];if(r.seenEntityMaps)for(const h of c.order){const m=r.seenEntityMaps.get(h)??h;this.diggestedBuiltInBaseEntitiesIds.has(m)}await c.orderEntitiesAsync({tracker:a});const f={};return await c.visitAsync(async h=>{try{if(this.diggestedBuiltInBaseEntitiesIds.has(h.id))return;const m=h.toGenerationTarget({seenEntityMaps:r.seenEntityMaps});f[m.id]=m,e.push(m.id),r!=null&&r.onVisit&&await r.onVisit(m)}catch(m){if(z.Logger.error(`[toFullProjectTransferAsync] Error serializing ${h.type} ${h.id}`,m),!r.shallowErrors)throw m}},{tracker:a}),{order:e,size:e.length,record:f}}};R(Gt,"parentContext",RL),R(Gt,"sessionAuthor","1"),R(Gt,"repository",{APICreate:async(i,...r)=>i,APIUpdate:async(i,...r)=>i,APIDelete:async(i,...r)=>i,APIClone:async(i,...r)=>{},APILoad:async(i,...r)=>null,APILoadVersion:async(i,r,...a)=>null}),R(Gt,"type",d.Project),R(Gt,"USER_MANAGED_PARENT_TYPES",[]),R(Gt,"PARENT_TYPES",[...Gt.USER_MANAGED_PARENT_TYPES]),R(Gt,"MUTABLE_BASE_PROPERTIES",["name","description"]),R(Gt,"INMUTABLE_BASE_PROPERTIES",["id","type","workspaceId","version","createdAt","author","previousVersion"]),R(Gt,"BASE_PROPERTIES",[...Gt.MUTABLE_BASE_PROPERTIES,...Gt.INMUTABLE_BASE_PROPERTIES]),R(Gt,"MUTABLE_META_PROPERTIES",[...Gt.MUTABLE_BASE_PROPERTIES,"x","y"]),R(Gt,"INMUTABLE_META_PROPERTIES",[...Gt.INMUTABLE_BASE_PROPERTIES]),R(Gt,"META_PROPERTIES",[...Gt.MUTABLE_META_PROPERTIES,...Gt.INMUTABLE_META_PROPERTIES]),R(Gt,"MUTABLE_UPSTREAM_PROPERTIES",[]),R(Gt,"INMUTABLE_UPSTREAM_PROPERTIES",["primitives","builtInBaseEntities","operationDeclarations","globalEventActionDescriptors","loopDeclarations","builtInInstances"]),R(Gt,"UPSTREAM_PROPERTIES",[...Gt.MUTABLE_UPSTREAM_PROPERTIES,...Gt.INMUTABLE_UPSTREAM_PROPERTIES]),R(Gt,"MUTABLE_DOWNSTREAM_PROPERTIES",["entities","projects","functions","events","variableDeclarations","variableInstances","conditions","operations","functionCalls","loops","searches"]),R(Gt,"INMUTABLE_DOWNSTREAM_PROPERTIES",[]),R(Gt,"DOWNSTREAM_PROPERTIES",[...Gt.MUTABLE_DOWNSTREAM_PROPERTIES,...Gt.INMUTABLE_DOWNSTREAM_PROPERTIES]),R(Gt,"PROPERTIES",[...Gt.META_PROPERTIES,...Gt.UPSTREAM_PROPERTIES,...Gt.DOWNSTREAM_PROPERTIES]);let x=Gt;class XVi extends er{constructor(p){super(oE,p)}}class ePi extends er{constructor(i){super(am,i);R(this,"autoexecutable",!0)}getEntityToMatchInputMap(i){return i.inputs.find(r=>{var a;return((a=r.declaration)==null?void 0:a.id)===re.operation[Le.Validate].inputs.entityToMatch.id})||null}getDataToValidateInputMap(i){return i.inputs.find(r=>{var a;return((a=r.declaration)==null?void 0:a.id)===re.operation[Le.Validate].inputs.dataToValidate.id})||null}getOutputDataOutputMap(i){return i.outputs.find(r=>{var a;return((a=r.declaration)==null?void 0:a.id)===re.operation[Le.Validate].dataType.entity.properties.outputEntity.id})||null}getEntityToMatch(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"get-entity-to-match-validate-data"))){var e;const a=((e=this.project.requestActiveDynamicValue(i))==null?void 0:e.value)||null,c=a==null?void 0:a.valueAsTypeSingle;return r==null||r.attemptAutoclose("get-entity-to-match-validate-data",this.id),c}syncOperationInstance(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"sync-operation-instance-validate-data"))){const a=[],c=[],e=[],f=[],h=this.getEntityToMatchInputMap(i);if(h){const{added:b,updated:A,removed:_,affected:P}=this.syncEntityToMatchInputMapDataType(h,r);a.push(...A),c.push(...b),e.push(..._),f.push(...P)}const m=this.getDataToValidateInputMap(i);if(m){const{added:b,updated:A,removed:_,affected:P}=this.syncDataToValidateInputMapDataType(m,r);a.push(...A),c.push(...b),e.push(..._),f.push(...P)}const E=this.getOutputDataOutputMap(i);if(E){const{added:b,updated:A,removed:_,affected:P}=this.syncOutputDataOutputMapDataType(E,r);a.push(...A),c.push(...b),e.push(..._),f.push(...P)}return r==null||r.attemptAutoclose("sync-operation-instance-validate-data",this.id),{updated:C(a),added:C(c),removed:C(e),affected:C(f),self:i}}syncEntityToMatchInputMapDataType(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"sync-entity-to-match-input-map-data-type"))){var E,b,A,_,P,V,G,M,k,K,ne,X,de,ie,le,ye,Y,ee;const a=[],c=[],e=[],f=[];if(((E=i.declaration)==null?void 0:E.id)!==re.operation[Le.Validate].inputs.entityToMatch.id)return r==null||r.attemptAutoclose("sync-entity-to-match-input-map-data-type",this.id),{updated:[],added:[],removed:[],affected:[],self:null};const h=((b=this.project.requestActiveDynamicValue(i))==null?void 0:b.value)||null,m=h==null?void 0:h.valueAsTypeSingle;if(!i.dataType){const pe={id:x.UUID.uuid(),version:x.UUID.uuid(),createdAt:(r==null?void 0:r.timestamp)||new Date().toISOString(),author:(r==null?void 0:r.author)||x.sessionAuthor,previousVersion:null,deleted:!1,deletable:!0,editable:!0,type:d.DataType,parentRelationType:null,options:((A=i.declaration.dataType)==null?void 0:A.options)||null,implementationChooseOne:((_=i.declaration.dataType)==null?void 0:_.implementationChooseOne)||!1,staticEntities:((P=i.declaration.dataType)==null?void 0:P.staticEntities)??null,interactiveEntities:((V=i.declaration.dataType)==null?void 0:V.interactiveEntities)??null,actionEntities:((G=i.declaration.dataType)==null?void 0:G.actionEntities)??null,index:((M=i.declaration.dataType)==null?void 0:M.index)??null,isList:((k=i.declaration.dataType)==null?void 0:k.isList)||!1,foreignKeyAllowed:((K=i.declaration.dataType)==null?void 0:K.foreignKeyAllowed)??null,andChildrenGroup:null,orChildrenGroup:null,foreignKeyRef:null,asType:!0,entity:(m==null?void 0:m.toJSON())||null,like:!0,inferred:!0,parent:i.toReference()},se=Re(pe,i.project);se.hydrateAncestors(),se.addSelfToProject(r),r==null||r.add(se,W.Added),se.setParent(i,r),se.initChildren(r),se.setEntity(m,r),a.push(se),i.setDataType(se,r),r||se.captureVersion()}return(Y=i.dataType)==null||Y.metaSync({inferred:!0,like:!1,asType:!0,options:((ne=i.declaration.dataType)==null?void 0:ne.options)||null,implementationChooseOne:((X=i.declaration.dataType)==null?void 0:X.implementationChooseOne)||!1,staticEntities:((de=i.declaration.dataType)==null?void 0:de.staticEntities)??null,interactiveEntities:((ie=i.declaration.dataType)==null?void 0:ie.interactiveEntities)??null,actionEntities:((le=i.declaration.dataType)==null?void 0:le.actionEntities)??null,isList:((ye=i.declaration.dataType)==null?void 0:ye.isList)||!1},r),(ee=i.dataType)==null||ee.setEntity(m,r),i.dataType&&c.push(i.dataType),r==null||r.attemptAutoclose("sync-entity-to-match-input-map-data-type",this.id),{updated:C(c),added:C(a),removed:C(e),affected:C(f),self:i.dataType}}syncDataToValidateInputMapDataType(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"sync-data-to-validate-input-map-data-type"))){var b,A,_;const a=[],c=[],e=[],f=[];if(((b=i.declaration)==null?void 0:b.id)!==re.operation[Le.Validate].inputs.dataToValidate.id)return r==null||r.attemptAutoclose("sync-data-to-validate-input-map-data-type",this.id),{updated:[],added:[],removed:[],affected:[],self:null};const h=this.getEntityToMatchInputMap(i.parent);if(!h)return r==null||r.attemptAutoclose("sync-data-to-validate-input-map-data-type",this.id),{updated:[],added:[],removed:[],affected:[],self:null};if(!this.getEntityToMatch(h,r))return r==null||r.attemptAutoclose("sync-data-to-validate-input-map-data-type",this.id),{updated:[],added:[],removed:[],affected:[],self:null};if(!i.dataType){const P={id:x.UUID.uuid(),version:x.UUID.uuid(),createdAt:(r==null?void 0:r.timestamp)||new Date().toISOString(),author:(r==null?void 0:r.author)||x.sessionAuthor,previousVersion:null,deleted:!1,deletable:!0,editable:!0,type:d.DataType,index:null,parentRelationType:null,options:null,implementationChooseOne:!1,foreignKeyAllowed:null,isList:!1,foreignKeyRef:null,andChildrenGroup:null,orChildrenGroup:null,staticEntities:null,interactiveEntities:null,actionEntities:null,asType:!1,entity:null,like:!0,inferred:!0,parent:i.toReference()},V=Re(P,i.project);V.hydrateAncestors(),V.addSelfToProject(r),r==null||r.add(V,W.Added),V.setParent(i,r),V.initChildren(r),a.push(V),i.setDataType(V,r),r||V.captureVersion()}(A=i.dataType)==null||A.metaSync({inferred:!0,like:!0,asType:!1},r);const E=this.getEntityToMatch(h,r);return(_=i.dataType)==null||_.setEntity(E,r),i.dataType&&c.push(i.dataType),r==null||r.attemptAutoclose("sync-data-to-validate-input-map-data-type",this.id),{updated:C(c),added:C(a),removed:C(e),affected:C(f),self:i.dataType}}syncOutputDataOutputMapDataType(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"sync-output-data-output-map-data-type"))){var A,_,P,V;const a=[],c=[],e=[],f=[];if(((A=i.declaration)==null?void 0:A.id)!==re.operation[Le.Validate].dataType.entity.properties.outputEntity.id)return r==null||r.attemptAutoclose("sync-output-data-output-map-data-type",this.id),{updated:[],added:[],removed:[],affected:[],self:null};const h=this.getEntityToMatchInputMap(i.parent);if(!h)return r==null||r.attemptAutoclose("sync-output-data-output-map-data-type",this.id),{updated:[],added:[],removed:[],affected:[],self:null};if(!this.getEntityToMatch(h,r))return r==null||r.attemptAutoclose("sync-output-data-output-map-data-type",this.id),{updated:[],added:[],removed:[],affected:[],self:null};const E=((_=this.project.requestActiveDynamicValue(h))==null?void 0:_.value)||null,b=(E==null?void 0:E.valueAsTypeSingle)||null;if(!i.dataType){const G={id:x.UUID.uuid(),version:x.UUID.uuid(),createdAt:(r==null?void 0:r.timestamp)||new Date().toISOString(),author:(r==null?void 0:r.author)||x.sessionAuthor,previousVersion:null,deleted:!1,deletable:!0,editable:!0,type:d.DataType,parentRelationType:null,options:null,foreignKeyRef:null,implementationChooseOne:!1,foreignKeyAllowed:null,staticEntities:null,interactiveEntities:null,index:null,actionEntities:null,isList:!1,andChildrenGroup:null,orChildrenGroup:null,asType:!1,entity:(b==null?void 0:b.toJSON())||null,like:!0,inferred:!0,parent:i.toReference()},M=Re(G,i.project);M.hydrateAncestors(),M.addSelfToProject(r),r==null||r.add(M,W.Added),M.setParent(i,r),M.initChildren(r),M.setEntity(b,r),a.push(M),i.setDataType(M,r),r||M.captureVersion()}return(P=i.dataType)==null||P.metaSync({inferred:!0,like:!0,asType:!1},r),(V=i.dataType)==null||V.setEntity(b,r),i.dataType&&c.push(i.dataType),r==null||r.attemptAutoclose("sync-output-data-output-map-data-type",this.id),{updated:C(c),added:C(a),removed:C(e),affected:C(f),self:i.dataType}}inferInputMapDataType(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"infer-input-map-data-type-validate-data"))){var c,e,f;if(((c=i.declaration)==null?void 0:c.id)===re.operation[Le.Validate].inputs.entityToMatch.id){const{added:h,updated:m,removed:E,affected:b}=r?this.syncEntityToMatchInputMapDataType(i,r):{added:[],updated:[],removed:[],affected:[]};return r==null||r.attemptAutoclose("infer-input-map-data-type",this.id),{updated:C(m),added:C(h),removed:C(E),affected:C(b),self:i.dataType}}if(((e=i.declaration)==null?void 0:e.id)===re.operation[Le.Validate].inputs.dataToValidate.id){const{added:h,updated:m,removed:E,affected:b}=this.syncDataToValidateInputMapDataType(i,r);return r==null||r.attemptAutoclose("infer-input-map-data-type",this.id),{updated:C(m),added:C(h),removed:C(E),affected:C(b),self:i.dataType}}const a=(f=i.declaration)==null?void 0:f.getDataType(r);if(a&&a.isResolved)return r==null||r.attemptAutoclose("infer-input-map-data-type-validate-data",this.id),{updated:[],added:[],removed:[],affected:[],self:a};if(i.readsValue){const h=iu(i.readsValue,r);return r==null||r.attemptAutoclose("infer-input-map-data-type-validate-data",this.id),{updated:[],added:[],removed:[],affected:[],self:h}}return r==null||r.attemptAutoclose("infer-input-map-data-type-validate-data",this.id),{updated:[],added:[],removed:[],affected:[],self:null}}inferOutputMapDataType(i,r=this.project.addChangeSet(new S(this.project,x.sessionAuthor,B().toISOString(),this,!0,"infer-output-map-data-type-validate-data"))){var a;if(((a=i.declaration)==null?void 0:a.id)===re.operation[Le.Validate].dataType.entity.properties.outputEntity.id){const{added:c,updated:e,removed:f,affected:h}=this.syncOutputDataOutputMapDataType(i,r);return r==null||r.attemptAutoclose("infer-output-map-data-type-validate-data",this.id),{updated:C(e),added:C(c),removed:C(f),affected:C(h),self:i.dataType}}return{updated:[],added:[],removed:[],affected:[],self:null}}}class tPi extends er{constructor(p){super(EP,p)}}class iPi extends er{constructor(p){super(bP,p)}}class rPi extends er{constructor(p){super(AP,p)}}class nPi extends er{constructor(p){super(zI,p)}}class aPi extends er{constructor(p){super(yI,p)}}class sPi extends er{constructor(p){super(Iv,p)}}function sUe(s){const p=[new CVe(s),new XVi(s),new ePi(s),new nPi(s),new tPi(s),new rPi(s),new iPi(s),new aPi(s),new sPi(s)];return qN.forEach(i=>{p.some(r=>r.id===i.id)||p.push(new er(i,s))}),p.forEach(i=>{i.initChildren(null),s.subscribeBuiltInInstance(i)}),s.operationDeclarations=p,p}const lPi=[];function lUe(s){const p=[new bVe(s),new IVe(s),new DVe(s),new wVe(s)];return hx.forEach(i=>{!p.some(r=>r.id===i.id)&&!lPi.includes(i.id)&&p.push(new Td(i,s))}),p.forEach(i=>{s.subscribeBuiltInInstance(i)}),s.builtInBaseEntities=p,p}function oUe(s){const p=[];return PV.forEach(i=>{p.some(r=>r.id===i.id)||p.push(new Nf(i,s))}),p.forEach(i=>{s.subscribeBuiltInInstance(i)}),s.primitives=p,p}function dUe(s){const p=[new er(f1,s)];return p.forEach(i=>{i.initChildren(null),s.subscribeBuiltInInstance(i)}),s.globalEventActionDescriptors=p,p}function uUe(s){const p=[new er(EE,s),new er(ty,s),new er(TE,s),new er(_m,s),new er(Vm,s),new er(HR,s)];p.forEach(r=>{r.initChildren(null),s.subscribeBuiltInInstance(r)}),s.loopDeclarations=p;const i=[new er(r1,s),new er(vE,s),new er(JR,s),new er(YN,s),new er(XN,s),new er(WR,s)];return i.forEach(r=>{r.initChildren(null),s.subscribeBuiltInInstance(r)}),s.loopDeclarationsBodies=i,p}function pUe(s){const p=[new Ed(gx,s)];return p.forEach(i=>{i.initChildren(null),s.subscribeBuiltInInstance(i)}),s.valueDescriptors=p,p}function cUe(s){const p=[new er(Tx,s),new er(mx,s),new er(vx,s),new er(Ex,s)];return bx.forEach(i=>{p.some(r=>r.id===i.id)||p.push(new er(i,s))}),p.forEach(i=>{i.initChildren(null),s.subscribeBuiltInInstance(i)}),s.conditionDeclarations=p,p}function jT(s){return s&&typeof s.then=="function"}function oPi(s,p){const i=new Fn(s[0],{allBuiltInEntityIds:p.allBuiltInEntityIds}),r=s.map(c=>c.id),a={};return s.forEach(c=>{a[c.id]=c}),i.order=r,i.flatRecord=a,i.orderEntities(),i.order.map(c=>i.flatRecord[c])}function dPi(s,p){const i=new Fn(Object.values(s)[0],{allBuiltInEntityIds:p.allBuiltInEntityIds}),r=Object.keys(s);return i.order=r,i.flatRecord=s,i.orderEntities(),i.order}async function uPi(s,p){const i=z.YieldTracker.from(p),r=new Fn(s[0],{allBuiltInEntityIds:p.allBuiltInEntityIds}),a=s.map(e=>e.id),c={};for(const e of s)c[e.id]=e,await i.tick();return r.order=a,r.flatRecord=c,await r.orderEntitiesAsync({tracker:i}),r.order.map(e=>r.flatRecord[e])}async function pPi(s,p){const i=z.YieldTracker.from(p),r=new Fn(Object.values(s)[0],{allBuiltInEntityIds:p.allBuiltInEntityIds}),a=Object.keys(s);return r.order=a,r.flatRecord=s,await r.orderEntitiesAsync({tracker:i}),r.order}class Fn{constructor(p,i={}){R(this,"order",[]);R(this,"flatRecord",{});R(this,"allBuiltInEntityIds");R(this,"onGoingVisits",{});R(this,"cachedReferences",{});if(i.allBuiltInEntityIds&&(this.allBuiltInEntityIds=i.allBuiltInEntityIds),!p)return;const r={asyncInitialOrder:!1,...i};r.asyncInitialOrder?this.flattenAsync(p).then(()=>{this.orderEntitiesAsync({...r}).then(()=>{var a;(a=r.onOrdered)==null||a.call(r)})}):(this.flatten(p),this.orderEntities())}flatten(p){this.allBuiltInEntityIds||(this.allBuiltInEntityIds=new Set(oD()));const i=C(Ue(p,new Set(this.allBuiltInEntityIds),{ignoreBuiltInBaseEntities:!0,diggestedBuiltInBaseEntitiesIds:this.allBuiltInEntityIds})),r=new Set;for(const a of i)this.flatRecord[a.id]=a,r.add(a.id);this.order=Array.from(r)}async flattenAsync(p,i={}){const r=z.YieldTracker.from(i);this.allBuiltInEntityIds||(this.allBuiltInEntityIds=await dD({tracker:r}));const a=await gp(await je(p,new Set(this.allBuiltInEntityIds),{ignoreBuiltInBaseEntities:!0,diggestedBuiltInBaseEntitiesIds:this.allBuiltInEntityIds,tracker:r}),{tracker:r}),c=new Set;for(const e of a)this.flatRecord[e.id]=e,c.add(e.id),await r.tick();this.order=Array.from(c)}moveEntityAfterDependencies(p){const i=this.cachedReferences[p.id]||lo(p,this.flatRecord,{ignoreBuiltInBaseEntities:!0,allBuiltInEntityIds:this.allBuiltInEntityIds});this.cachedReferences[p.id]=i;const{upstream:r}=i;for(const a of Object.keys(r)){const c=this.order.indexOf(a),e=this.order.indexOf(p.id);if(c>e)return this.order.splice(e,1),this.order.splice(c,0,p.id),!0}return!1}orderEntities(){let p=!1;for(let i=0;i<this.order.length;i++){const r=this.order[i],a=this.flatRecord[r];if(a||z.Logger.warn(`Entity with id ${r} not found in flatRecord. Skipping...`),this.moveEntityAfterDependencies(a)){p=!0;break}}p&&this.orderEntities()}async orderEntitiesAsync(p={}){let i=!1;const r=z.YieldTracker.from(p);for(let a=0;a<this.order.length;a++){const c=this.order[a],e=this.flatRecord[c];if(e||z.Logger.warn(`Entity with id ${c} not found in flatRecord. Skipping...`),this.moveEntityAfterDependencies(e)){i=!0;break}await r.tick()}i&&await this.orderEntitiesAsync({tracker:r})}getUpstreamOngoingDependenciesVisits(p,i){const r=this.cachedReferences[p]||lo(this.flatRecord[p],this.flatRecord,{ignoreBuiltInBaseEntities:!0,allBuiltInEntityIds:this.allBuiltInEntityIds});this.cachedReferences[p]=r;const{upstream:a}=r,c={};return Object.entries(this.onGoingVisits[i]||{}).forEach(([e,f])=>{Object.keys(a).includes(e)&&(c[e]=f)}),c}getDownstreamOngoingDependenciesVisits(p,i){const r=Object.keys(this.onGoingVisits[i]||{}),a=new Set(r.flatMap(e=>{const f=this.cachedReferences[e]||lo(this.flatRecord[e],this.flatRecord,{ignoreBuiltInBaseEntities:!0,allBuiltInEntityIds:this.allBuiltInEntityIds});return this.cachedReferences[e]=f,Object.keys(f.downstream)})),c={};return Array.from(a).forEach(e=>{e===p&&(c[e]=this.onGoingVisits[i][e])}),c}async settlePromises(p,i){const r=Object.values(p);r.length&&await Promise.all(r),Object.keys(p).forEach(a=>{delete this.onGoingVisits[i][a]})}visit(p){const i=this.order;for(const r of i)p(this.flatRecord[r],this.flatRecord);return this}reverseVisit(p){const i=this.order.slice().reverse();for(const r of i)p(this.flatRecord[r],this.flatRecord);return this}async visitAsync(p,i={}){const{parallelise:r}={parallelise:!0,...i},a=z.YieldTracker.from(i),c=this.order;if(!r){for(const f of c){const h=p(this.flatRecord[f],this.flatRecord);jT(h)&&await h,await a.tick()}return this}const e=Math.random().toString(36).substring(7);this.onGoingVisits[e]={};for(const f of c){const h=this.getUpstreamOngoingDependenciesVisits(f,e);Object.keys(h).length&&await this.settlePromises(h,e);const m=p(this.flatRecord[f],this.flatRecord);jT(m)&&(this.onGoingVisits[e][f]=m),await a.tick()}return await this.settlePromises(this.onGoingVisits[e],e),this.onGoingVisits[e]={},this}async reverseVisitAsync(p,i={}){const{parallelise:r}={parallelise:!0,...i},a=z.YieldTracker.from(i),c=this.order.slice().reverse();if(!r){for(const f of c){const h=p(this.flatRecord[f],this.flatRecord);jT(h)&&await h,await a.tick()}return this}const e=Math.random().toString(36).substring(7);this.onGoingVisits[e]={};for(const f of c){const h=this.getDownstreamOngoingDependenciesVisits(f,e);Object.keys(h).length&&await this.settlePromises(h,e);const m=p(this.flatRecord[f],this.flatRecord);jT(m)&&(this.onGoingVisits[e][f]=m),await a.tick()}return await this.settlePromises(this.onGoingVisits[e],e),this.onGoingVisits[e]={},this}}const If={},ag={},fv={empty:!1,enrich:!0,mock:!1,ignoreCache:!1,onFetch:async()=>null,manuallyInit:!1};function fUe(s,p={enrich:!0,shallowErrors:!1},i){const r={enrich:!0,shallowErrors:!1,...p},{enrich:a,shallowErrors:c}=r,e=s.project,f=s.record,h=iD(s.project,{shallowErrors:c},i);h.instances[e.id]=h;const m=new Fn(e,{allBuiltInEntityIds:h.diggestedBuiltInBaseEntitiesIds}),E=new Set;f[e.id]=e,E.add(e.id);const b=B().toISOString();Object.values(f).forEach(_=>{!_||m.allBuiltInEntityIds.has(_.id)||E.add(_.id)}),m.order=Array.from(E),m.flatRecord=f,m.orderEntities();const A=a?h.addChangeSet(new S(h,x.sessionAuthor,b,h,!0,"project-init-from-fetch-result")):null;return m.visit(_=>{if(_.id===h.id)return;const P=Re(_,h);try{P.hydrateAncestors(),P.addSelfToProject(null);const V=lo(_);Object.keys(V.downstream).forEach(G=>{const M=h.get(G);M&&M.hydrateAncestors()})}catch(V){if(c)z.Logger.error("Error hydrating ancestors: ",V);else throw V}}),a?(m.visit(_=>{if(_.id===h.id)return;const P=h.get(_.id);if(P)try{P.afterAllChildrenInitialized(A),P.captureVersion()}catch(V){if(c)z.Logger.error("Error in afterAllChildrenInitialized: ",V);else throw V}}),h.afterAllChildrenInitialized(A),h.subscribe(),h.captureVersion()):(ju(h,b).forEach(P=>{P.remove({ignoreUpstream:!0},null)}),m.visit(P=>{if(P.id===h.id)return;const V=h.get(P.id);V&&(V.initialized=!0,V.captureVersion())}),h.initialized=!0,h.subscribe(),h.captureVersion()),h.initialized=!0,h.emit(di.PROJECT_INITIALIZED,h,A),A==null||A.attemptAutoclose("project-init-from-fetch-result",h.id),h}async function cPi(s,p={enrich:!0,shallowErrors:!1,yieldEvery:100},i){const r={enrich:!0,shallowErrors:!1,yieldEvery:100,...p},{enrich:a,shallowErrors:c,yieldEvery:e}=r,f=z.YieldTracker.from({yieldEvery:e}),h=s.project,m=s.record,E=await rD(s.project,{shallowErrors:c,tracker:f},i);E.instances[h.id]=E;const b=new Fn(void 0,{allBuiltInEntityIds:E.diggestedBuiltInBaseEntitiesIds});await b.flattenAsync(h,{tracker:f}),await b.orderEntitiesAsync({tracker:f});const A=new Set;m[h.id]=h,A.add(h.id);const _=B().toISOString();for(const[V,G]of Object.entries(m))!G||b.allBuiltInEntityIds.has(G.id)||(A.add(G.id),await f.tick());b.order=Array.from(A),b.flatRecord=m,await b.orderEntitiesAsync({tracker:f});const P=a?E.addChangeSet(new S(E,x.sessionAuthor,_,E,!0,"project-init-from-fetch-result")):null;if(await b.visitAsync(V=>{if(V.id===E.id)return;const G=Re(V,E);try{G.hydrateAncestors(),G.addSelfToProject(null);const M=lo(V);Object.keys(M.downstream).forEach(k=>{const K=E.get(k);K&&K.hydrateAncestors()})}catch(M){if(c)z.Logger.error("Error hydrating ancestors: ",M);else throw z.Logger.log("Error hydrating ancestors: ",M),M}},{tracker:f}),a){try{await b.visitAsync(V=>{if(V.id===E.id)return;const G=E.get(V.id);G&&(G.afterAllChildrenInitialized(P),G.captureVersion())},{tracker:f})}catch(V){if(c)z.Logger.error("Error in afterAllChildrenInitialized: ",V);else throw z.Logger.log("Error in afterAllChildrenInitialized: ",V),V}E.afterAllChildrenInitialized(P),E.subscribe(),E.captureVersion()}else ju(E,_).forEach(G=>{G.remove({ignoreUpstream:!0},null)}),await b.visitAsync(G=>{if(G.id===E.id)return;const M=E.get(G.id);M&&(M.initialized=!0,M.captureVersion())},{tracker:f}),E.initialized=!0,E.subscribe(),E.captureVersion();return E.initialized=!0,E.emit(di.PROJECT_INITIALIZED,E,P),P==null||P.attemptAutoclose("project-init-from-fetch-result",E.id),E}async function fPi(s,p=fv){const i={...fv,...p};if(i.empty)return{data:{project:{id:s.id,workspaceId:"",deletable:!0,editable:!0,type:d.Project,version:x.UUID.uuid(),createdAt:B().toISOString(),author:x.sessionAuthor,previousVersion:null,deleted:!1,name:null,description:null,projects:[],entities:[],operations:[],functions:[],variableDeclarations:[],variableInstances:[],functionCalls:[],conditions:[],loops:[],searches:[],events:[]},record:{}}};if(i.mock){const a={...AB};return a.id=s.id,{data:{project:a,record:{}}}}return z.Logger.log("Fetching project from external API"),new Promise(async a=>{try{if(i.onFetch){const c=await i.onFetch(s.id);if(c){a({data:c});return}}else a({data:null})}catch(c){z.Logger.error("Error fetching project: ",c),a({data:null})}})}function iD(s,p={shallowErrors:!1},i){const r=new x(s,i);oUe(r),lUe(r),sUe(r),dUe(r),uUe(r),pUe(r),cUe(r);const a=p.allBuiltInIds??new Set([...r.getAllBuiltInIds(),...oD()]);return r.diggestedBuiltInBaseEntitiesIds=a,a.forEach(c=>{if(!r.builtInInstances[c]&&r.instances[c])r.builtInInstances[c]=r.instances[c],delete r.instances[c];else if(!r.builtInInstances[c]&&!p.shallowErrors)throw new Error(`Built in entity was not properly initialized: ${c}`)}),r.instances[r.id]=r,r.activeVersion=!0,r}async function rD(s,p={shallowErrors:!1},i){const r=z.YieldTracker.from(p),a=new x(s,i);oUe(a),lUe(a),await z.yieldToEventLoop(),sUe(a),await z.yieldToEventLoop(),dUe(a),uUe(a),pUe(a),cUe(a),await z.yieldToEventLoop();const c=p.allBuiltInIds??new Set([...a.getAllBuiltInIds(),...await dD()]);a.diggestedBuiltInBaseEntitiesIds=c;for(const e of c){if(!a.builtInInstances[e]&&a.instances[e])a.builtInInstances[e]=a.instances[e],delete a.instances[e];else if(!a.builtInInstances[e]&&!p.shallowErrors)throw new Error(`Built in entity was not properly initialized: ${e}`);a.instances[e]&&delete a.instances[e],await r.tick()}return a.instances[a.id]=a,a.activeVersion=!0,a}function ju(s,p){return s.instancesList.filter(r=>B(r.createdAt).isAfter(B(p)||!!r.previousVersion))}function yPi(s,{enrich:p,shallowErrors:i,...r}={enrich:!0,shallowErrors:!1},a){var _,P;const c=new Map,e=new Map;Object.keys(s.instances).forEach(V=>{if(s.diggestedBuiltInBaseEntitiesIds.has(V)){c.set(V,V),e.set(V,V);return}const G=s.get(V);if(!mD(G,{...s.instances,...s.builtInInstances}).every(ne=>!s.diggestedBuiltInBaseEntitiesIds.has(ne))){c.set(V,V),e.set(V,V);return}const K=x.UUID.uuid();c.set(V,K),e.set(K,V)});const f=((_=r.resetVersionOptions)==null?void 0:_.commonTimestamp)??B().toISOString(),h=s.toShallowJSON({seenEntityMaps:c});h.previousVersion=null,h.createdAt=f,h.version=x.UUID.uuid(),h.author=((P=r.resetVersionOptions)==null?void 0:P.author)??(x.sessionAuthor||"1");const m=iD(h,{shallowErrors:i,allBuiltInIds:s.diggestedBuiltInBaseEntitiesIds},a);m.instances[m.id]=m;const E=p?m.addChangeSet(new S(m,x.sessionAuthor,f,m,!0,"project-clone")):null,b=new Fn(s,{allBuiltInEntityIds:s.diggestedBuiltInBaseEntitiesIds}),A=OL(b.flatRecord,c);return b.visit(V=>{var K;const G=V.toShallowJSON({seenEntityMaps:c});G.previousVersion=null,G.createdAt=f,G.version=x.UUID.uuid(),G.author=((K=r.resetVersionOptions)==null?void 0:K.author)??(x.sessionAuthor||"1");const M=lo(G,A);if(Object.keys(M.upstream).length){let ne=!1;if(Object.keys(M.upstream).forEach(X=>{if(!ne&&(!m.get(X)||m.getDeleted(X))){ne=!0;return}}),ne)return}const k=Re(G,m);k.hydrateAncestors(),k.addSelfToProject(E),E==null||E.add(k,W.Added),r.onVisit&&r.onVisit(G)}),p?(b.visit(V=>{if(V.id===m.id)return;const G=m.get(c.get(V.id));G&&(G.afterAllChildrenInitialized(E),G.captureVersion())}),m.afterAllChildrenInitialized(E),m.subscribe(),m.captureVersion()):(ju(m,f).forEach(G=>{G.remove({ignoreUpstream:!0},null)}),b.visit(G=>{if(G.id===m.id)return;const M=m.get(G.id);M&&(M.initialized=!0,M.captureVersion())}),m.initialized=!0,m.subscribe(),m.captureVersion()),m.instancesList.forEach(V=>{V.previousVersion=null}),E==null||E.attemptAutoclose("project-clone",m.id),{project:m,maps:c}}async function hPi(s,{shallowErrors:p,...i}={shallowErrors:!1,yieldEvery:100}){var m,E;const r=z.YieldTracker.from(i),a=new Map,c=new Map;Object.keys(s.instances).forEach(b=>{if(s.diggestedBuiltInBaseEntitiesIds.has(b)){a.set(b,b),c.set(b,b);return}const A=x.UUID.uuid();a.set(b,A),c.set(A,b)});const e=((m=i.resetVersionOptions)==null?void 0:m.commonTimestamp)??B().toISOString(),f=s.toShallowJSON({seenEntityMaps:a});f.previousVersion=null,f.createdAt=e,f.version=x.UUID.uuid(),f.author=((E=i.resetVersionOptions)==null?void 0:E.author)??(x.sessionAuthor||"1");const h=await s.toFullProjectTransferAsync({tracker:r,seenEntityMaps:a,resetVersionOptions:i.resetVersionOptions,onVisit:i.onVisit});return{project:f,record:h.record,order:h.order,maps:a}}async function mPi(s,{enrich:p,shallowErrors:i,...r}={enrich:!0,shallowErrors:!1,yieldEvery:100},a){var P,V;const c=z.YieldTracker.from(r),e=new Map,f=new Map;for(const G of Object.keys(s.instances)){if(s.diggestedBuiltInBaseEntitiesIds.has(G)){e.set(G,G),f.set(G,G),await c.tick();continue}const M=x.UUID.uuid();e.set(G,M),f.set(M,G),await c.tick()}const h=((P=r.resetVersionOptions)==null?void 0:P.commonTimestamp)??B().toISOString(),m=s.toShallowJSON({seenEntityMaps:e});m.previousVersion=null,m.createdAt=h,m.version=x.UUID.uuid(),m.author=((V=r.resetVersionOptions)==null?void 0:V.author)??(x.sessionAuthor||"1");const E=await rD(m,{shallowErrors:i,tracker:c},a);E.diggestedBuiltInBaseEntitiesIds=s.diggestedBuiltInBaseEntitiesIds,E.instances[E.id]=E;const b=p?E.addChangeSet(new S(E,x.sessionAuthor,h,E,!0,"project-clone")):null,A=new Fn(void 0,{allBuiltInEntityIds:s.diggestedBuiltInBaseEntitiesIds}),_=await s.toFullProjectTransferAsync({tracker:c,seenEntityMaps:e,resetVersionOptions:r.resetVersionOptions,onVisit:r.onVisit,shallowErrors:i});A.flatRecord=_.record,A.order=_.order,await A.visitAsync(G=>{var ne;if(s.diggestedBuiltInBaseEntitiesIds.has(G.id))return;const M=G;M.previousVersion=null,M.createdAt=h,M.version=x.UUID.uuid(),M.author=((ne=r.resetVersionOptions)==null?void 0:ne.author)??(x.sessionAuthor||"1");const k=lo(M,A.flatRecord);if(Object.keys(k.upstream).length){let X=!1;if(Object.keys(k.upstream).forEach(de=>{if(!X&&(!E.get(de)||E.getDeleted(de))){X=!0;return}}),X)return}const K=Re(M,E);K.hydrateAncestors(),K.addSelfToProject(b),b==null||b.add(K,W.Added)},{tracker:c}),p?(await A.visitAsync(G=>{if(G.id===E.id||s.diggestedBuiltInBaseEntitiesIds.has(G.id))return;const M=E.get(e.get(G.id));M&&(M.afterAllChildrenInitialized(b),M.captureVersion())},{tracker:c}),E.afterAllChildrenInitialized(b),E.subscribe(),E.captureVersion()):(ju(E,h).forEach(M=>{M.remove({ignoreUpstream:!0},null)}),await A.visitAsync(M=>{if(M.id===E.id)return;const k=E.get(M.id);k&&(k.initialized=!0,k.captureVersion())},{tracker:c}),E.initialized=!0,E.subscribe(),E.captureVersion());for(const G of E.instancesList)G.previousVersion=null,await c.tick();return b==null||b.attemptAutoclose("project-clone",E.id),{project:E,maps:e}}function TPi(s,p,i=p.addChangeSet(new S(p,x.sessionAuthor,B().toISOString(),p,!0,w.AfterAllChildrenInitialized)),{enrich:r,shallowErrors:a,...c}={shallowErrors:!1,enrich:!0}){var A,_;const e=new Map,f=new Map;Object.keys(s.instances).forEach(P=>{if(s.diggestedBuiltInBaseEntitiesIds.has(P)){e.set(P,P),f.set(P,P);return}if(P===s.id){e.set(P,p.id),f.set(p.id,P);return}const V=s.get(P);if(!mD(V,{...s.instances,...s.builtInInstances}).every(K=>!s.diggestedBuiltInBaseEntitiesIds.has(K))){e.set(P,P),f.set(P,P);return}const k=x.UUID.uuid();e.set(P,k),f.set(k,P)});const h=((A=c.resetVersionOptions)==null?void 0:A.commonTimestamp)??B().toISOString(),m=s.toShallowJSON({seenEntityMaps:e});m.previousVersion=null,m.createdAt=h,m.version=x.UUID.uuid(),m.author=((_=c.resetVersionOptions)==null?void 0:_.author)??(x.sessionAuthor||"1");const E=new Fn(s,{allBuiltInEntityIds:s.diggestedBuiltInBaseEntitiesIds}),b=OL(E.flatRecord,e);return E.visit(P=>{var M;if(P.id===p.id)return;const V=P.toShallowJSON({seenEntityMaps:e});V.previousVersion=null,V.createdAt=h,V.version=x.UUID.uuid(),V.author=((M=c.resetVersionOptions)==null?void 0:M.author)??(x.sessionAuthor||"1");const G=lo(V,b);if(Object.keys(G.upstream).length){let k=!1;if(Object.keys(G.upstream).forEach(K=>{if(!k&&(!p.get(K)||p.getDeleted(K))){k=!0;return}}),k)return}try{const k=Re(V,p);k.hydrateAncestors(),k.addSelfToProject(i),i==null||i.add(k,W.Added),c.onVisit&&c.onVisit(V)}catch(k){if(a)z.Logger.error("Error cloning entity onto existing project: ",k);else throw z.Logger.log("Error cloning entity onto existing project: ",k),k}}),r?(E.visit(P=>{if(P.id===p.id)return;const V=p.get(e.get(P.id));V&&(V.afterAllChildrenInitialized(i),V.previousVersion=null,V.captureVersion())}),p.afterAllChildrenInitialized(i),p.subscribe(),p.captureVersion()):(ju(p,h).forEach(V=>{V.remove({ignoreUpstream:!0},null)}),E.visit(V=>{if(V.id===p.id)return;const G=p.get(V.id);G&&(G.initialized=!0,G.previousVersion=null,G.captureVersion())}),p.initialized=!0,p.subscribe(),p.captureVersion()),p.afterAllChildrenInitialized(i),p.captureVersion(),{project:p,maps:e,changeSet:i}}async function vPi(s,p,i=p.addChangeSet(new S(p,x.sessionAuthor,B().toISOString(),p,!0,w.AfterAllChildrenInitialized)),{enrich:r,shallowErrors:a,...c}={enrich:!0,shallowErrors:!1,yieldEvery:100}){var _,P;const e=z.YieldTracker.from(c),f=new Map,h=new Map;for(const V of Object.keys(s.instances)){if(s.diggestedBuiltInBaseEntitiesIds.has(V)){f.set(V,V),h.set(V,V),await e.tick();continue}if(V===s.id){f.set(V,p.id),h.set(p.id,V),await e.tick();continue}const G=x.UUID.uuid();f.set(V,G),h.set(G,V),await e.tick()}const m=((_=c.resetVersionOptions)==null?void 0:_.commonTimestamp)??B().toISOString(),E=s.toShallowJSON({seenEntityMaps:f});E.previousVersion=null,E.createdAt=m,E.version=x.UUID.uuid(),E.author=((P=c.resetVersionOptions)==null?void 0:P.author)??(x.sessionAuthor||"1"),p.diggestedBuiltInBaseEntitiesIds=s.diggestedBuiltInBaseEntitiesIds;const b=new Fn(void 0,{allBuiltInEntityIds:s.diggestedBuiltInBaseEntitiesIds}),A=await s.toFullProjectTransferAsync({tracker:e,seenEntityMaps:f,resetVersionOptions:c.resetVersionOptions,onVisit:c.onVisit,shallowErrors:a});return b.flatRecord=A.record,b.order=A.order,await b.visitAsync(V=>{var k;if(s.diggestedBuiltInBaseEntitiesIds.has(V.id)||V.id===p.id)return;const G=V;G.previousVersion=null,G.createdAt=m,G.version=x.UUID.uuid(),G.author=((k=c.resetVersionOptions)==null?void 0:k.author)??(x.sessionAuthor||"1");const M=lo(G,b.flatRecord);if(Object.keys(M.upstream).length){let K=!1;if(Object.keys(M.upstream).forEach(ne=>{if(!K&&(!p.get(ne)||p.getDeleted(ne))){K=!0;return}}),K)return}try{const K=Re(G,p);K.hydrateAncestors(),K.addSelfToProject(i),i==null||i.add(K,W.Added)}catch(K){if(a)z.Logger.error("Error cloning entity onto existing project: ",K);else throw z.Logger.log("Error cloning entity onto existing project: ",K),K}},{tracker:e}),r?(await b.visitAsync(V=>{if(V.id===p.id||s.diggestedBuiltInBaseEntitiesIds.has(V.id))return;const G=p.get(f.get(V.id));G&&(G.afterAllChildrenInitialized(i),G.previousVersion=null,G.captureVersion())},{tracker:e}),p.afterAllChildrenInitialized(i),p.subscribe(),p.captureVersion()):(ju(p,m).forEach(G=>{G.remove({ignoreUpstream:!0},null)}),await b.visitAsync(G=>{if(G.id===p.id)return;const M=p.get(G.id);M&&(M.initialized=!0,M.previousVersion=null,M.captureVersion())},{tracker:e}),p.initialized=!0,p.subscribe(),p.captureVersion()),p.afterAllChildrenInitialized(i),p.captureVersion(),{project:p,maps:f,changeSet:i}}function yUe(s,{enrich:p,shallowErrors:i}={enrich:!0,shallowErrors:!1},r){const a=iD(s,{shallowErrors:i},r);a.activeVersion=!0;const c=B().toISOString(),e=p?a.addChangeSet(new S(a,x.sessionAuthor,c,a,!0,"project-init")):null;e&&(e.type=y1.Automatic);const f=new Fn(s,{allBuiltInEntityIds:a.diggestedBuiltInBaseEntitiesIds});return f.visit(h=>{const m=Re(h,a);m.hydrateAncestors(),m.addSelfToProject(e)}),p?(f.visit(h=>{if(h.id===a.id)return;const m=a.get(h.id);m&&(m.afterAllChildrenInitialized(e),m.captureVersion())}),a.afterAllChildrenInitialized(e),a.subscribe(),a.captureVersion()):(ju(a,c).forEach(m=>{m.remove({ignoreUpstream:!0},null)}),f.visit(m=>{if(m.id===a.id)return;const E=a.get(m.id);E&&(E.initialized=!0,E.captureVersion())}),a.initialized=!0,a.subscribe(),a.captureVersion()),a.initialized=!0,a.emit(di.PROJECT_INITIALIZED,a,e),e==null||e.attemptAutoclose("project-init",a.id),a}async function EPi(s,{enrich:p,shallowErrors:i,yieldEvery:r}={enrich:!0,shallowErrors:!1,yieldEvery:100},a){const c=z.YieldTracker.from({yieldEvery:r}),e=await rD(s,{shallowErrors:i,tracker:c},a),f=B().toISOString(),h=p?e.addChangeSet(new S(e,x.sessionAuthor,f,e,!0,"project-init")):null;h&&(h.type=y1.Automatic);const m=new Fn(void 0,{allBuiltInEntityIds:e.diggestedBuiltInBaseEntitiesIds});return await m.flattenAsync(s,{tracker:c}),await m.orderEntitiesAsync({tracker:c}),await m.visitAsync(E=>{const b=Re(E,e);b.hydrateAncestors(),b.addSelfToProject(h)},{tracker:c}),p?(await m.visitAsync(E=>{if(E.id===e.id)return;const b=e.get(E.id);b&&(b.afterAllChildrenInitialized(h),b.captureVersion())},{tracker:c}),e.afterAllChildrenInitialized(h),e.subscribe(),e.captureVersion()):(ju(e,f).forEach(b=>{b.remove({ignoreUpstream:!0},null)}),await m.visitAsync(b=>{if(b.id===e.id)return;const A=e.get(b.id);A&&(A.initialized=!0,A.captureVersion())},{tracker:c}),e.initialized=!0,e.subscribe(),e.captureVersion()),e.initialized=!0,e.emit(di.PROJECT_INITIALIZED,e,h),h==null||h.attemptAutoclose("project-init",e.id),e}async function bPi(s,p=fv,i){const r={...fv,...p};if(s.id&&If[s.id]&&!r.ignoreCache)return If[s.id];if(s.id&&ag[s.id]&&!r.ignoreCache)return await ag[s.id],If[s.id];const a=fPi(s,r);s.id&&(ag[s.id]=a);const c=await a;if(c.data){let e;return r.mock?e=yUe(AB,{enrich:!!r.enrich},i):c.data instanceof x?e=c.data:e=fUe(c.data,{enrich:!!r.enrich},i),If[s.id]=e,s.id&&delete ag[s.id],e}return null}function APi(s){return If[s.id]&&delete If[s.id],null}const yv=vt([He(),Va(),Tr(),au()]),hUe=Bm([ln.CurrentDateAndTime,ln.Random,ln.Unique]),nD=st({type:hUe,rangeStart:yv.nullable(),rangeEnd:yv.nullable()}),QE=nD.extend({type:rt(ln.Random),rangeStart:yv,rangeEnd:yv}),mUe=nD.extend({type:rt(ln.Unique),rangeStart:ms(),rangeEnd:ms()}),TUe=nD.extend({type:rt(ln.CurrentDateAndTime),rangeStart:ms(),rangeEnd:ms()}),aD=QE.extend({rangeStart:Va().nullable(),rangeEnd:Va().nullable()}),vUe=aD.extend({rangeStart:Va(),rangeEnd:ms()}),EUe=aD.extend({rangeStart:ms(),rangeEnd:Va()}),bUe=aD.extend({rangeStart:Va(),rangeEnd:Va()}),sD=QE.extend({rangeStart:Va().nullable(),rangeEnd:Va().nullable()}),AUe=sD.extend({rangeStart:Va(),rangeEnd:ms()}),gUe=sD.extend({rangeStart:ms(),rangeEnd:Va()}),IUe=sD.extend({rangeStart:Va(),rangeEnd:Va()}),lD=QE.extend({rangeStart:au().nullable(),rangeEnd:au().nullable()}),RUe=lD.extend({rangeStart:au(),rangeEnd:ms()}),DUe=lD.extend({rangeStart:ms(),rangeEnd:au()}),wUe=lD.extend({rangeStart:au(),rangeEnd:au()}),CUe=QE.extend({rangeStart:ms(),rangeEnd:ms()}),OUe=vt([AUe,gUe,IUe]),_Ue=vt([vUe,EUe,bUe]),VUe=vt([RUe,DUe,wUe,TUe]),gPi=vt([OUe,_Ue,VUe,mUe,CUe]);function oD(){const s=new Set;return new Set(Ix.flatMap(i=>Ue(i,s)).map(i=>i.id))}function Fo(s){return[...s.calledByEntry||[],...s.calledByError||[],...s.calledBySuccess||[]].filter(p=>p.type!==d.GenericReference)}function PUe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.ActionDescriptor)throw new Error("Entity must be an action descriptor to be flattened");return[s,...s.inputs.flatMap(r=>Ue(r,p,i)),...s.dataType?Ue(s.dataType,p,i):[],...s.error?Ue(s.error,p,i):[],...s.parent?Ue(s.parent,p,i):[]]}function NUe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.ArgumentDeclaration)throw new Error("Entity must be an argument declaration to be flattened");return[s,...s.defaultValue?Ue(s.defaultValue,p):[],...s.writesValues.flatMap(r=>Ue(r,p,i)),...s.implements.flatMap(r=>Ue(r,p,i)),...s.dataType?Ue(s.dataType,p,i):[],...s.parent?Ue(s.parent,p,i):[]]}function xUe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.BreakStatement)throw new Error("Entity must be a break statement to be flattened");return[s,...s.outputs.flatMap(r=>Ue(r,p,i)),...s.throws?Ue(s.throws,p,i):[],...s.dataType?Ue(s.dataType,p,i):[],...s.readsValue?Ue(s.readsValue,p,i):[],...(Fo(s)||[]).flatMap(r=>Ue(r,p,i)),...s.parent?Ue(s.parent,p,i):[]]}function $Ue(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.BuiltInBaseEntity)throw new Error("Entity must be a built-in base entity to be flattened");return[s,...(s.properties||[]).flatMap(r=>Ue(r,p,i)),...(s.methods||[]).flatMap(r=>Ue(r,p,i)),...(s.abstractMethods||[]).flatMap(r=>Ue(r,p,i)),...s.allPropertiesImplement?Ue(s.allPropertiesImplement,p,i):[],...s.additionalPropertiesDataType?Ue(s.additionalPropertiesDataType,p,i):[],...s.extends?Ue(s.extends,p,i):[]]}function LUe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.Condition)throw new Error("Entity must be a condition to be flattened");return[s,...(s.andChildrenGroup||[]).flatMap(r=>Ue(r,p,i)),...(s.orChildrenGroup||[]).flatMap(r=>Ue(r,p,i)),...(s.inputs||[]).flatMap(r=>Ue(r,p,i)),...(s.successCalls||[]).flatMap(r=>Ue(r,p,i)),...(s.errorCalls||[]).flatMap(r=>Ue(r,p,i)),...(Fo(s)||[]).flatMap(r=>Ue(r,p,i)),...s.parent?Ue(s.parent,p,i):[]]}function BUe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.ContinueStatement)throw new Error("Entity must be a continue statement to be flattened");return[s,...s.outputs.flatMap(r=>Ue(r,p,i)),...s.readsValue?Ue(s.readsValue,p,i):[],...s.throws?Ue(s.throws,p,i):[],...s.dataType?Ue(s.dataType,p,i):[],...(Fo(s)||[]).flatMap(r=>Ue(r,p,i)),...s.parent?Ue(s.parent,p,i):[]]}function MUe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.DefinitionEntity)throw new Error("Entity must be a definition entity to be flattened");return[s,...s.extends?Ue(s.extends,p,i):[],...(s.implements||[]).flatMap(r=>Ue(r,p,i)),...(s.properties||[]).flatMap(r=>Ue(r,p,i)),...(s.methods||[]).flatMap(r=>Ue(r,p,i)),...(s.abstractMethods||[]).flatMap(r=>Ue(r,p,i)),...s.allPropertiesImplement?Ue(s.allPropertiesImplement,p,i):[],...s.additionalPropertiesDataType?Ue(s.additionalPropertiesDataType,p,i):[],...s.parent?Ue(s.parent,p,i):[]]}function GUe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.DataType)throw new Error("Entity must be a data type to be flattened");return[s,...(s.andChildrenGroup||[]).flatMap(r=>Ue(r,p,i)),...(s.orChildrenGroup||[]).flatMap(r=>Ue(r,p,i)),...s.entity?Ue(s.entity,p,i):[],...s.foreignKeyRef?Ue(s.foreignKeyRef,p,i):[],...s.parent?Ue(s.parent,p,i):[]]}function kUe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.FunctionCall)throw new Error("Entity must be a function call to be flattened");return[s,...(s.inputs||[]).flatMap(r=>Ue(r,p,i)),...(s.outputs||[]).flatMap(r=>Ue(r,p,i)),...s.error?Ue(s.error,p,i):[],...(Fo(s)||[]).flatMap(r=>Ue(r,p,i)),...(s.successCalls||[]).flatMap(r=>Ue(r,p,i)),...(s.errorCalls||[]).flatMap(r=>Ue(r,p,i)),...(s.writesValues||[]).flatMap(r=>Ue(r,p,i)),...s.parent?Ue(s.parent,p,i):[]]}function jUe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.FunctionDeclaration)throw new Error("Entity must be a function declaration to be flattened");return[s,...(s.inputs||[]).flatMap(r=>Ue(r,p,i)),...(s.calls||[]).flatMap(r=>Ue(r,p,i)),...s.dataType?Ue(s.dataType,p,i):[],...s.implements?Ue(s.implements,p,i):[],...s.parent?Ue(s.parent,p,i):[]]}function UUe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.GlobalEvent)throw new Error("Entity must be a global event to be flattened");return[s,...(s.inputs||[]).flatMap(r=>Ue(r,p,i)),...(s.calls||[]).flatMap(r=>Ue(r,p,i)),...s.implements?Ue(s.implements,p,i):[],...s.parent?Ue(s.parent,p,i):[]]}function FUe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.InputMap)throw new Error("Entity must be an input map to be flattened");return[s,...s.readsValue?Ue(s.readsValue,p,i):[],...s.declaration?Ue(s.declaration,p,i):[],...s.defaultValue?Ue(s.defaultValue,p,i):[],...s.parent?Ue(s.parent,p,i):[]]}function KUe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.InstalledProject)throw new Error("Entity must be an installed project to be flattened");return[s,...(s.functions||[]).flatMap(r=>Ue(r,p,i)),...(s.events||[]).flatMap(r=>Ue(r,p,i)),...s.parent?Ue(s.parent,p,i):[]]}function qUe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.InternalCall)throw new Error("Entity must be an internal call to be flattened");return[s,...(s.successCalls||[]).flatMap(r=>Ue(r,p,i)),...(s.errorCalls||[]).flatMap(r=>Ue(r,p,i)),...(s.inputs||[]).flatMap(r=>Ue(r,p,i)),...(s.outputs||[]).flatMap(r=>Ue(r,p,i)),...(Fo(s)||[]).flatMap(r=>Ue(r,p,i)),...s.error?Ue(s.error,p,i):[],...(s.writesValues||[]).flatMap(r=>Ue(r,p,i)),...s.parent?Ue(s.parent,p,i):[]]}function SUe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.LiteralValue)throw new Error("Entity must be a literal value to be flattened");return[s,...s.valueAsTypeSingle?Ue(s.valueAsTypeSingle,p,i):[],...s.valueAsTypeList&&Array.isArray(s.valueAsTypeList)?s.valueAsTypeList.flatMap(r=>Ue(r,p,i)):[],...s.parent?Ue(s.parent,p,i):[]]}function ZUe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.Loop)throw new Error("Entity must be a loop to be flattened");return[s,...(s.inputs||[]).flatMap(r=>Ue(r,p,i)),...(s.outputs||[]).flatMap(r=>Ue(r,p,i)),...(s.successCalls||[]).flatMap(r=>Ue(r,p,i)),...(s.errorCalls||[]).flatMap(r=>Ue(r,p,i)),...s.error?Ue(s.error,p,i):[],...s.dataType?Ue(s.dataType,p,i):[],...s.body?Ue(s.body,p,i):[],...(Fo(s)||[]).flatMap(r=>Ue(r,p,i)),...(s.writesValues||[]).flatMap(r=>Ue(r,p,i)),...s.parent?Ue(s.parent,p,i):[]]}function HUe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.Operation)throw new Error("Entity must be an operation to be flattened");return[s,...(s.successCalls||[]).flatMap(r=>Ue(r,p,i)),...(s.errorCalls||[]).flatMap(r=>Ue(r,p,i)),...(s.inputs||[]).flatMap(r=>Ue(r,p,i)),...(s.outputs||[]).flatMap(r=>Ue(r,p,i)),...(s.writesValues||[]).flatMap(r=>Ue(r,p,i)),...s.error?Ue(s.error,p,i):[],...(Fo(s)||[]).flatMap(r=>Ue(r,p,i)),...s.parent?Ue(s.parent,p,i):[]]}function WUe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.OutputMap)throw new Error("Entity must be an output map to be flattened");return[s,...(s.writesValues||[]).flatMap(r=>Ue(r,p,i)),...s.declaration?Ue(s.declaration,p,i):[],...s.parent?Ue(s.parent,p,i):[]]}function zUe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.PrimitiveEntity)throw new Error("Entity must be a primitive entity to be flattened");return[s,...(s.properties||[]).flatMap(r=>Ue(r,p,i)),...(s.methods||[]).flatMap(r=>Ue(r,p,i)),...(s.abstractMethods||[]).flatMap(r=>Ue(r,p,i))]}function YUe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.Project)throw new Error("Entity must be a project to be flattened");return[s,...(s.entities||[]).flatMap(r=>Ue(r,p,i)),...(s.functions||[]).flatMap(r=>Ue(r,p,i)),...(s.events||[]).flatMap(r=>Ue(r,p,i)),...(s.projects||[]).flatMap(r=>Ue(r,p,i)),...(s.variableDeclarations||[]).flatMap(r=>Ue(r,p,i)),...(s.variableInstances||[]).flatMap(r=>Ue(r,p,i)),...(s.operations||[]).flatMap(r=>Ue(r,p,i)),...(s.conditions||[]).flatMap(r=>Ue(r,p,i)),...(s.functionCalls||[]).flatMap(r=>Ue(r,p,i)),...(s.projects||[]).flatMap(r=>Ue(r,p,i)),...(s.loops||[]).flatMap(r=>Ue(r,p,i)),...(s.searches||[]).flatMap(r=>Ue(r,p,i))]}function JUe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.Property)throw new Error("Entity must be a property to be flattened");return[s,...s.defaultValue?Ue(s.defaultValue,p,i):[],...s.dataType?Ue(s.dataType,p,i):[],...s.parent?Ue(s.parent,p,i):[]]}function QUe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.ReturnStatement)throw new Error("Entity must be a return statement to be flattened");return[s,...(s.outputs||[]).flatMap(r=>Ue(r,p,i)),...s.throws?Ue(s.throws,p,i):[],...s.readsValue?Ue(s.readsValue,p,i):[],...s.dataType?Ue(s.dataType,p,i):[],...(Fo(s)||[]).flatMap(r=>Ue(r,p,i)),...s.parent?Ue(s.parent,p,i):[]]}function XUe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.Search)throw new Error("Entity must be a search to be flattened");return[s,...(s.successCalls||[]).flatMap(r=>Ue(r,p,i)),...(s.errorCalls||[]).flatMap(r=>Ue(r,p,i)),...(s.inputsDeclarations||[]).flatMap(r=>Ue(r,p,i)),...(s.inputs||[]).flatMap(r=>Ue(r,p,i)),...(s.writesValues||[]).flatMap(r=>Ue(r,p,i)),...(s.outputs||[]).flatMap(r=>Ue(r,p,i)),...s.error?Ue(s.error,p,i):[],...s.dataType?Ue(s.dataType,p,i):[],...(Fo(s)||[]).flatMap(r=>Ue(r,p,i)),...s.parent?Ue(s.parent,p,i):[]]}function eFe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.ValueDescriptor)throw new Error("Entity must be a value descriptor to be flattened");return[s,...s.defaultValue?Ue(s.defaultValue,p,i):[],...s.dataType?Ue(s.dataType,p,i):[],...s.parent?Ue(s.parent,p,i):[]]}function tFe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.VariableDeclaration)throw new Error("Entity must be a variable declaration to be flattened");return[s,...(s.successCalls||[]).flatMap(r=>Ue(r,p,i)),...(s.errorCalls||[]).flatMap(r=>Ue(r,p,i)),...(s.inputs||[]).flatMap(r=>Ue(r,p,i)),...(s.outputs||[]).flatMap(r=>Ue(r,p,i)),...(s.internalCalls||[]).flatMap(r=>Ue(r,p,i)),...(s.writesValues||[]).flatMap(r=>Ue(r,p,i)),...s.readsValue?Ue(s.readsValue,p,i):[],...s.defaultValue?Ue(s.defaultValue,p,i):[],...(Fo(s)||[]).flatMap(r=>Ue(r,p,i)),...s.dataType?Ue(s.dataType,p,i):[],...s.parent?Ue(s.parent,p,i):[]]}function iFe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.VariableInstance)throw new Error("Entity must be a variable instance to be flattened");return[s,...(s.successCalls||[]).flatMap(r=>Ue(r,p,i)),...(s.errorCalls||[]).flatMap(r=>Ue(r,p,i)),...(s.inputs||[]).flatMap(r=>Ue(r,p,i)),...(s.outputs||[]).flatMap(r=>Ue(r,p,i)),...(s.internalCalls||[]).flatMap(r=>Ue(r,p,i)),...(s.writesValues||[]).flatMap(r=>Ue(r,p,i)),...s.readsValue?Ue(s.readsValue,p,i):[],...s.defaultValue?Ue(s.defaultValue,p,i):[],...(Fo(s)||[]).flatMap(r=>Ue(r,p,i)),...s.declaration?Ue(s.declaration,p,i):[],...s.parent?Ue(s.parent,p,i):[]]}function Ue(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(!s)throw new Error("Entity must be defined to be flattened");if(s.type===d.GenericReference)return[];const r=i.ignoreBuiltInBaseEntities?i.diggestedBuiltInBaseEntitiesIds??new Set(oD()):new Set;if(i.diggestedBuiltInBaseEntitiesIds=r,i.ignoreBuiltInBaseEntities&&(ma.includes(s.type)||r.has(s.id)))return[];if(p.has(s.id))return[];switch(s.type){case d.FunctionCall:return kUe(s,p,i);case d.Operation:return HUe(s,p,i);case d.Condition:return LUe(s,p,i);case d.Loop:return ZUe(s,p,i);case d.Search:return XUe(s,p,i);case d.GlobalEvent:return UUe(s,p,i);case d.ReturnStatement:return QUe(s,p,i);case d.ContinueStatement:return BUe(s,p,i);case d.BreakStatement:return xUe(s,p,i);case d.VariableDeclaration:return tFe(s,p,i);case d.DefinitionEntity:return MUe(s,p,i);case d.FunctionDeclaration:return jUe(s,p,i);case d.Project:return YUe(s,p,i);case d.ActionDescriptor:return PUe(s,p,i);case d.ArgumentDeclaration:return NUe(s,p,i);case d.ValueDescriptor:return eFe(s,p,i);case d.InputMap:return FUe(s,p,i);case d.OutputMap:return WUe(s,p,i);case d.DataType:return GUe(s,p,i);case d.InstalledProject:return KUe(s,p,i);case d.InternalCall:return qUe(s,p,i);case d.LiteralValue:return SUe(s,p,i);case d.Property:return JUe(s,p,i);case d.VariableInstance:return iFe(s,p,i);case d.BuiltInBaseEntity:return i.ignoreBuiltInBaseEntities?[]:$Ue(s,p,i);case d.PrimitiveEntity:return i.ignoreBuiltInBaseEntities?[]:zUe(s,p,i)}return[]}async function dD(s={}){const p=new Set,i=z.YieldTracker.from(s),r=new Set;for(const a of Ix){const c=await je(a,p,{ignoreBuiltInBaseEntities:!1,tracker:i});for(const e of c)r.add(e.id),await i.tick()}return r}function Ko(s){return[...s.calledByEntry||[],...s.calledByError||[],...s.calledBySuccess||[]].filter(p=>p.type!==d.GenericReference)}async function rFe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.ActionDescriptor)throw new Error("Entity must be an action descriptor to be flattened");const r=z.YieldTracker.from(i),a=[s];await r.tick();const c={...i,tracker:r};delete c.yieldEvery;for(const e of s.inputs)a.push(...await je(e,p,c));return s.dataType&&a.push(...await je(s.dataType,p,c)),s.error&&a.push(...await je(s.error,p,c)),s.parent&&a.push(...await je(s.parent,p,c)),a}async function nFe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.ArgumentDeclaration)throw new Error("Entity must be an argument declaration to be flattened");const r=z.YieldTracker.from(i),a=[s];await r.tick();const c={...i,tracker:r};delete c.yieldEvery,s.dataType&&a.push(...await je(s.dataType,p,c)),s.parent&&a.push(...await je(s.parent,p,c)),s.defaultValue&&a.push(...await je(s.defaultValue,p,c));for(const e of s.writesValues||[])a.push(...await je(e,p,c));for(const e of s.implements||[])a.push(...await je(e,p,c));return a}async function aFe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.BreakStatement)throw new Error("Entity must be a break statement to be flattened");const r=z.YieldTracker.from(i),a=[s];await r.tick();const c={...i,tracker:r};delete c.yieldEvery;for(const f of s.outputs)a.push(...await je(f,p,c));s.parent&&a.push(...await je(s.parent,p,c)),s.throws&&a.push(...await je(s.throws,p,c)),s.dataType&&a.push(...await je(s.dataType,p,c)),s.readsValue&&a.push(...await je(s.readsValue,p,c));const e=Ko(s);for(const f of e)a.push(...await je(f,p,c));return a}async function sFe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.BuiltInBaseEntity)throw new Error("Entity must be a built-in base entity to be flattened");const r=z.YieldTracker.from(i),a=[s];await r.tick();const c={...i,tracker:r};delete c.yieldEvery;for(const e of s.properties||[])a.push(...await je(e,p,c));for(const e of s.methods||[])a.push(...await je(e,p,c));for(const e of s.abstractMethods||[])a.push(...await je(e,p,c));return s.allPropertiesImplement&&a.push(...await je(s.allPropertiesImplement,p,c)),s.additionalPropertiesDataType&&a.push(...await je(s.additionalPropertiesDataType,p,c)),s.extends&&a.push(...await je(s.extends,p,c)),a}async function lFe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.Condition)throw new Error("Entity must be a condition to be flattened");const r=z.YieldTracker.from(i),a=[s];await r.tick();const c={...i,tracker:r};if(delete c.yieldEvery,s.andChildrenGroup&&Array.isArray(s.andChildrenGroup))for(const f of s.andChildrenGroup)a.push(...await je(f,p,c));if(s.orChildrenGroup&&Array.isArray(s.orChildrenGroup))for(const f of s.orChildrenGroup)a.push(...await je(f,p,c));for(const f of s.inputs)a.push(...await je(f,p,c));for(const f of s.successCalls)a.push(...await je(f,p,c));for(const f of s.errorCalls)a.push(...await je(f,p,c));const e=Ko(s);for(const f of e)a.push(...await je(f,p,c));return s.parent&&a.push(...await je(s.parent,p,c)),a}async function oFe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.ContinueStatement)throw new Error("Entity must be a continue statement to be flattened");const r=z.YieldTracker.from(i),a=[s];await r.tick();const c={...i,tracker:r};delete c.yieldEvery;for(const f of s.outputs)a.push(...await je(f,p,c));const e=Ko(s);for(const f of e)a.push(...await je(f,p,c));return s.parent&&a.push(...await je(s.parent,p,c)),s.throws&&a.push(...await je(s.throws,p,c)),s.dataType&&a.push(...await je(s.dataType,p,c)),s.readsValue&&a.push(...await je(s.readsValue,p,c)),a}async function dFe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.DefinitionEntity)throw new Error("Entity must be a definition entity to be flattened");const r=z.YieldTracker.from(i),a=[s];await r.tick();const c={...i,tracker:r};delete c.yieldEvery;for(const e of s.properties)a.push(...await je(e,p,c));for(const e of s.methods)a.push(...await je(e,p,c));for(const e of s.abstractMethods)a.push(...await je(e,p,c));for(const e of s.implements)a.push(...await je(e,p,c));return s.extends&&a.push(...await je(s.extends,p,c)),s.parent&&a.push(...await je(s.parent,p,c)),s.additionalPropertiesDataType&&a.push(...await je(s.additionalPropertiesDataType,p,c)),s.allPropertiesImplement&&a.push(...await je(s.allPropertiesImplement,p,c)),a}async function uFe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.DataType)throw new Error("Entity must be a data type to be flattened");const r=z.YieldTracker.from(i),a=[s];await r.tick();const c={...i,tracker:r};if(delete c.yieldEvery,s.parent&&a.push(...await je(s.parent,p,c)),s.foreignKeyRef&&a.push(...await je(s.foreignKeyRef,p,c)),s.entity&&a.push(...await je(s.entity,p,c)),s.orChildrenGroup)for(const e of s.orChildrenGroup)a.push(...await je(e,p,c));if(s.andChildrenGroup)for(const e of s.andChildrenGroup)a.push(...await je(e,p,c));return a}async function pFe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.FunctionCall)throw new Error("Entity must be a function call to be flattened");const r=z.YieldTracker.from(i),a=[s];await r.tick();const c={...i,tracker:r};delete c.yieldEvery;for(const f of s.inputs)a.push(...await je(f,p,c));for(const f of s.outputs)a.push(...await je(f,p,c));s.error&&a.push(...await je(s.error,p,c));const e=Ko(s);for(const f of e)a.push(...await je(f,p,c));for(const f of s.successCalls)a.push(...await je(f,p,c));for(const f of s.errorCalls)a.push(...await je(f,p,c));for(const f of s.writesValues)a.push(...await je(f,p,c));return s.parent&&a.push(...await je(s.parent,p,c)),a}async function cFe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.FunctionDeclaration)throw new Error("Entity must be a function declaration to be flattened");const r=z.YieldTracker.from(i),a=[s];await r.tick();const c={...i,tracker:r};delete c.yieldEvery,s.parent&&a.push(...await je(s.parent,p,c)),s.implements&&a.push(...await je(s.implements,p,c)),s.dataType&&a.push(...await je(s.dataType,p,c));for(const e of s.inputs)a.push(...await je(e,p,c));for(const e of s.calls)a.push(...await je(e,p,c));return a}async function fFe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.GlobalEvent)throw new Error("Entity must be a global event to be flattened");const r=z.YieldTracker.from(i),a=[s];await r.tick();const c={...i,tracker:r};delete c.yieldEvery,s.parent&&a.push(...await je(s.parent,p,c)),s.implements&&a.push(...await je(s.implements,p,c));for(const e of s.inputs)a.push(...await je(e,p,c));for(const e of s.calls)a.push(...await je(e,p,c));return a}async function yFe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.InputMap)throw new Error("Entity must be an input map to be flattened");const r=z.YieldTracker.from(i),a=[s];await r.tick();const c={...i,tracker:r};return delete c.yieldEvery,s.parent&&a.push(...await je(s.parent,p,c)),s.declaration&&a.push(...await je(s.declaration,p,c)),s.readsValue&&a.push(...await je(s.readsValue,p,c)),s.dataType&&a.push(...await je(s.dataType,p,c)),s.defaultValue&&a.push(...await je(s.defaultValue,p,c)),a}async function hFe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.InstalledProject)throw new Error("Entity must be an installed project to be flattened");const r=z.YieldTracker.from(i),a=[s];await r.tick();const c={...i,tracker:r};delete c.yieldEvery;for(const e of s.functions)a.push(...await je(e,p,c));for(const e of s.events)a.push(...await je(e,p,c));return s.parent&&a.push(...await je(s.parent,p,c)),a}async function mFe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.InternalCall)throw new Error("Entity must be an internal call to be flattened");const r=z.YieldTracker.from(i),a=[s];await r.tick();const c={...i,tracker:r};delete c.yieldEvery;for(const f of s.inputs)a.push(...await je(f,p,c));for(const f of s.outputs)a.push(...await je(f,p,c));s.error&&a.push(...await je(s.error,p,c));const e=Ko(s);for(const f of e)a.push(...await je(f,p,c));for(const f of s.successCalls)a.push(...await je(f,p,c));for(const f of s.errorCalls)a.push(...await je(f,p,c));for(const f of s.writesValues)a.push(...await je(f,p,c));return s.parent&&a.push(...await je(s.parent,p,c)),a}async function TFe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.LiteralValue)throw new Error("Entity must be a literal value to be flattened");const r=z.YieldTracker.from(i),a=[s];await r.tick();const c={...i,tracker:r};if(delete c.yieldEvery,s.valueAsTypeSingle&&a.push(...await je(s.valueAsTypeSingle,p,c)),s.valueAsTypeList&&Array.isArray(s.valueAsTypeList))for(const e of s.valueAsTypeList)a.push(...await je(e,p,c));return s.parent&&a.push(...await je(s.parent,p,c)),a}async function vFe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.Loop)throw new Error("Entity must be a loop to be flattened");const r=z.YieldTracker.from(i),a=[s];await r.tick();const c={...i,tracker:r};delete c.yieldEvery;for(const f of s.inputs)a.push(...await je(f,p,c));for(const f of s.outputs)a.push(...await je(f,p,c));s.error&&a.push(...await je(s.error,p,c));const e=Ko(s);for(const f of e)a.push(...await je(f,p,c));for(const f of s.successCalls)a.push(...await je(f,p,c));for(const f of s.errorCalls)a.push(...await je(f,p,c));for(const f of s.writesValues)a.push(...await je(f,p,c));return s.parent&&a.push(...await je(s.parent,p,c)),s.body&&a.push(...await je(s.body,p,c)),s.dataType&&a.push(...await je(s.dataType,p,c)),a}async function EFe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.Operation)throw new Error("Entity must be an operation to be flattened");const r=z.YieldTracker.from(i),a=[s];await r.tick();const c={...i,tracker:r};delete c.yieldEvery;for(const f of s.inputs)a.push(...await je(f,p,c));for(const f of s.outputs)a.push(...await je(f,p,c));s.error&&a.push(...await je(s.error,p,c));const e=Ko(s);for(const f of e)a.push(...await je(f,p,c));for(const f of s.successCalls)a.push(...await je(f,p,c));for(const f of s.errorCalls)a.push(...await je(f,p,c));for(const f of s.writesValues)a.push(...await je(f,p,c));return s.parent&&a.push(...await je(s.parent,p,c)),a}async function bFe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.OutputMap)throw new Error("Entity must be an output map to be flattened");const r=z.YieldTracker.from(i),a=[s];await r.tick();const c={...i,tracker:r};delete c.yieldEvery;for(const e of s.writesValues)a.push(...await je(e,p,c));return s.declaration&&a.push(...await je(s.declaration,p,c)),s.dataType&&a.push(...await je(s.dataType,p,c)),s.parent&&a.push(...await je(s.parent,p,c)),a}async function AFe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.PrimitiveEntity)throw new Error("Entity must be a primitive entity to be flattened");const r=z.YieldTracker.from(i),a=[s];await r.tick();const c={...i,tracker:r};delete c.yieldEvery;for(const e of s.properties)a.push(...await je(e,p,c));for(const e of s.methods)a.push(...await je(e,p,c));for(const e of s.abstractMethods)a.push(...await je(e,p,c));return a}async function gFe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.Project)throw new Error("Entity must be a project to be flattened");const r=z.YieldTracker.from(i),a=[s];await r.tick();const c={...i,tracker:r};delete c.yieldEvery;for(const e of s.entities)a.push(...await je(e,p,c));for(const e of s.functions)a.push(...await je(e,p,c));for(const e of s.events)a.push(...await je(e,p,c));for(const e of s.projects)a.push(...await je(e,p,c));for(const e of s.variableDeclarations)a.push(...await je(e,p,c));for(const e of s.variableInstances)a.push(...await je(e,p,c));for(const e of s.operations)a.push(...await je(e,p,c));for(const e of s.conditions)a.push(...await je(e,p,c));for(const e of s.functionCalls)a.push(...await je(e,p,c));for(const e of s.projects)a.push(...await je(e,p,c));for(const e of s.loops)a.push(...await je(e,p,c));for(const e of s.searches)a.push(...await je(e,p,c));return a}async function IFe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.Property)throw new Error("Entity must be a property to be flattened");const r=z.YieldTracker.from(i),a=[s];await r.tick();const c={...i,tracker:r};return delete c.yieldEvery,s.defaultValue&&a.push(...await je(s.defaultValue,p,c)),s.dataType&&a.push(...await je(s.dataType,p,c)),s.parent&&a.push(...await je(s.parent,p,c)),a}async function RFe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.ReturnStatement)throw new Error("Entity must be a return statement to be flattened");const r=z.YieldTracker.from(i),a=[s];await r.tick();const c={...i,tracker:r};delete c.yieldEvery;for(const f of s.outputs)a.push(...await je(f,p,c));for(const f of s.outputs)a.push(...await je(f,p,c));s.throws&&a.push(...await je(s.throws,p,c)),s.readsValue&&a.push(...await je(s.readsValue,p,c)),s.dataType&&a.push(...await je(s.dataType,p,c));const e=Ko(s);for(const f of e)a.push(...await je(f,p,c));return s.parent&&a.push(...await je(s.parent,p,c)),a}async function DFe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.Search)throw new Error("Entity must be a search to be flattened");const r=z.YieldTracker.from(i),a=[s];await r.tick();const c={...i,tracker:r};delete c.yieldEvery;for(const f of s.inputs)a.push(...await je(f,p,c));for(const f of s.outputs)a.push(...await je(f,p,c));s.error&&a.push(...await je(s.error,p,c)),s.dataType&&a.push(...await je(s.dataType,p,c));for(const f of s.inputsDeclarations)a.push(...await je(f,p,c));const e=Ko(s);for(const f of e)a.push(...await je(f,p,c));for(const f of s.successCalls)a.push(...await je(f,p,c));for(const f of s.errorCalls)a.push(...await je(f,p,c));for(const f of s.writesValues)a.push(...await je(f,p,c));return s.parent&&a.push(...await je(s.parent,p,c)),a}async function wFe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.ValueDescriptor)throw new Error("Entity must be a value descriptor to be flattened");const r=z.YieldTracker.from(i),a=[s];await r.tick();const c={...i,tracker:r};return delete c.yieldEvery,s.defaultValue&&a.push(...await je(s.defaultValue,p,c)),s.dataType&&a.push(...await je(s.dataType,p,c)),s.parent&&a.push(...await je(s.parent,p,c)),a}async function CFe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.VariableDeclaration)throw new Error("Entity must be a variable declaration to be flattened");const r=z.YieldTracker.from(i),a=[s];await r.tick();const c={...i,tracker:r};delete c.yieldEvery;for(const f of s.inputs)a.push(...await je(f,p,c));for(const f of s.outputs)a.push(...await je(f,p,c));s.error&&a.push(...await je(s.error,p,c)),s.dataType&&a.push(...await je(s.dataType,p,c)),s.readsValue&&a.push(...await je(s.readsValue,p,c)),s.defaultValue&&a.push(...await je(s.defaultValue,p,c));const e=Ko(s);for(const f of e)a.push(...await je(f,p,c));for(const f of s.successCalls)a.push(...await je(f,p,c));for(const f of s.errorCalls)a.push(...await je(f,p,c));for(const f of s.writesValues)a.push(...await je(f,p,c));for(const f of s.internalCalls)a.push(...await je(f,p,c));return s.parent&&a.push(...await je(s.parent,p,c)),a}async function OFe(s,p=new Set,i={ignoreBuiltInBaseEntities:!1}){if(p.has(s.id))return[];if(p.add(s.id),s.type!==d.VariableInstance)throw new Error("Entity must be a variable instance to be flattened");const r=z.YieldTracker.from(i),a=[s];await r.tick();const c={...i,tracker:r};delete c.yieldEvery;for(const f of s.inputs)a.push(...await je(f,p,c));for(const f of s.outputs)a.push(...await je(f,p,c));s.error&&a.push(...await je(s.error,p,c)),s.readsValue&&a.push(...await je(s.readsValue,p,c)),s.defaultValue&&a.push(...await je(s.defaultValue,p,c));const e=Ko(s);for(const f of e)a.push(...await je(f,p,c));for(const f of s.successCalls)a.push(...await je(f,p,c));for(const f of s.errorCalls)a.push(...await je(f,p,c));for(const f of s.writesValues)a.push(...await je(f,p,c));for(const f of s.internalCalls)a.push(...await je(f,p,c));return s.parent&&a.push(...await je(s.parent,p,c)),s.declaration&&a.push(...await je(s.declaration,p,c)),a}async function je(s,p=new Set,i={ignoreBuiltInBaseEntities:!1,yieldEvery:100}){const r={...i,ignoreBuiltInBaseEntities:i.ignoreBuiltInBaseEntities??!1};if(!s)throw new Error("Entity must be defined to be flattened");if(s.type===d.GenericReference)return[];const a=z.YieldTracker.from(r);r.tracker=a,r.yieldEvery!==void 0&&delete r.yieldEvery;const c=r.ignoreBuiltInBaseEntities?r.diggestedBuiltInBaseEntitiesIds??new Set(await dD(r)):new Set;if(r.diggestedBuiltInBaseEntitiesIds=c,r.ignoreBuiltInBaseEntities&&(ma.includes(s.type)||c.has(s.id)))return[];if(p.has(s.id))return[];switch(s.type){case d.FunctionCall:return pFe(s,p,r);case d.Operation:return EFe(s,p,r);case d.Condition:return lFe(s,p,r);case d.Loop:return vFe(s,p,r);case d.Search:return DFe(s,p,r);case d.GlobalEvent:return fFe(s,p,r);case d.ReturnStatement:return RFe(s,p,r);case d.ContinueStatement:return oFe(s,p,r);case d.BreakStatement:return aFe(s,p,r);case d.VariableDeclaration:return CFe(s,p,r);case d.DefinitionEntity:return dFe(s,p,r);case d.FunctionDeclaration:return cFe(s,p,r);case d.Project:return gFe(s,p,r);case d.ActionDescriptor:return rFe(s,p,r);case d.ArgumentDeclaration:return nFe(s,p,r);case d.ValueDescriptor:return wFe(s,p,r);case d.InputMap:return yFe(s,p,r);case d.OutputMap:return bFe(s,p,r);case d.DataType:return uFe(s,p,r);case d.InstalledProject:return hFe(s,p,r);case d.InternalCall:return mFe(s,p,r);case d.LiteralValue:return TFe(s,p,r);case d.Property:return IFe(s,p,r);case d.VariableInstance:return OFe(s,p,r);case d.BuiltInBaseEntity:return r.ignoreBuiltInBaseEntities?[]:sFe(s,p,r);case d.PrimitiveEntity:return r.ignoreBuiltInBaseEntities?[]:AFe(s,p,r)}return[]}function _Fe(s){return s==null||s===""}function IPi(s){return s===null}function Vn(s){return s!=null&&s.valueAsType?!1:_Fe(s==null?void 0:s.value)}function co(s){return s?s.valueAsType===null&&s.value===null:!1}function VFe(s,p){if(s===p||!s&&!p)return!0;if(!s||!p||s.name===fe.EntityTemplate&&p.name!==fe.EntityTemplate||p.name===fe.EntityTemplate&&s.name!==fe.EntityTemplate)return!1;if(s.name===fe.ActionDescriptor&&p.name!==fe.ActionDescriptor||p.name===fe.ActionDescriptor&&s.name!==fe.ActionDescriptor)return!1;if(s.valueAsTypeSingle&&!p.valueAsTypeSingle||p.valueAsTypeSingle&&!s.valueAsTypeSingle)return!1;if(s.valueAsTypeList&&!p.valueAsTypeList||p.valueAsTypeList&&!s.valueAsTypeList)return!1;if(s.valueAsTypeSingle&&p.valueAsTypeSingle){if(s.valueAsTypeSingle.id!==p.valueAsTypeSingle.id)return!1}else if(s.valueAsTypeList&&p.valueAsTypeList){if(s.valueAsTypeList.length!==p.valueAsTypeList.length)return!1;for(let i=0;i<s.valueAsTypeList.length;i++)if(s.valueAsTypeList[i].id!==p.valueAsTypeList[i].id)return!1}else if(!s.valueAsType&&!p.valueAsType&&s.value!==p.value)return!1;return!0}function PFe(s,p,i){if(!i)throw new Error("[checkIsRowTransformerUpToDate] 'lastPublishedEntityVersion' argument is required");if(!p)throw new Error("[checkIsRowTransformerUpToDate] 'entity' argument is required");if(!s)throw new Error("[checkIsRowTransformerUpToDate] 'newestOpenRowTransformer' argument is required");let r=!0;const a=s.methods.find(c=>{var e;return((e=c.implements)==null?void 0:e.id)===re["built-in-base-entity"].BUILT_IN_SQL_ROW_TRANSFORMER_ENTITY.methods.up.id});if(a?(fn(i).forEach(c=>{const e=a.inputs.find(f=>f.name===c.name);e&&ni(e.getDataType(null),c.getDataType(null)).compatible||(r=!1)}),a.returnStatements.forEach(c=>{!c.dataType||!c.dataType.entity||c.dataType.entity.type!==d.DefinitionEntity?r=!1:XT(c.dataType.entity,p)||(r=!1)})):r=!1,r===null||r){const c=s.methods.find(e=>{var f;return((f=e.implements)==null?void 0:f.id)===re["built-in-base-entity"].BUILT_IN_SQL_ROW_TRANSFORMER_ENTITY.methods.down.id});c?(fn(p).forEach(e=>{const f=c.inputs.find(h=>h.name===e.name);f&&ni(f.getDataType(null),e.getDataType(null)).compatible||(r=!1)}),c.returnStatements.forEach(e=>{!e.dataType||!e.dataType.entity||e.dataType.entity.type!==d.DefinitionEntity?r=!1:XT(e.dataType.entity,i)||(r=!1)})):r=!1}return{isPreexistingRowTransformerUpToDate:r}}function NFe(s,p,i){const r={changesSinceLastPublication:!1,rowTransformerNeeded:!1,newRowTransformerNeeded:!1,newestOpenRowTransformer:null,newRequiredProperties:[],newNonRequiredProperties:[],deletedProperties:[],lastPublishedEntityVersion:null,updatedEntityVersion:i,propChanges:new Map,isPreexistingRowTransformerUpToDate:null,extendedEntities:[]},c=s.entities.filter(M=>{var ne;if(M.id===i.id)return!1;let k=!1,K=M;for(;K;){if(((ne=K.extends)==null?void 0:ne.id)===i.id){k=!0;break}if(K.extends&&K.extends.type===d.DefinitionEntity)K=K.extends;else break}return k}).map(M=>NFe(s,p,M));if(!p)return{...r,changesSinceLastPublication:!0,extendedEntities:c};const e=p.get(i.id);if(!e)return{...r,changesSinceLastPublication:!0,extendedEntities:c};const f=p.entities.filter(M=>oi(M,ge.SQL_ROW_TRANSFORMER)),m=s.entities.filter(M=>{var X;if(!oi(M,ge.SQL_ROW_TRANSFORMER)||f.find(de=>de.id===M.id))return!1;const K=M.properties.find(de=>!!de.implements.find(ie=>re["built-in-base-entity"].BUILT_IN_SQL_ROW_TRANSFORMER_ENTITY.properties.definition.id===ie.id));if(!K)return!1;const ne=(X=K.defaultValue)==null?void 0:X.valueAsType;return ne?ne.id===i.id:!1}).sort((M,k)=>B(M.createdAt).isAfter(B(k.createdAt))?-1:1)[0]||null,E=new Map;let b=!1;const A=fn(i).filter(M=>{var ne;return fn(e).find(X=>X.id===M.id)?(console.log('Skipping "'+M.name+'" as required because it was not in the last published version'),!1):(console.log(`"${M.name}" of "${(ne=M.parent)==null?void 0:ne.name}": ${wp(M.getDataType(null))}`),Ka(M.getDataType(null))?!1:(console.log('"'+M.name+'" as required is nullable'),!0))}),_=fn(i).filter(M=>{var ne;return fn(e).find(X=>X.id===M.id)?(console.log('Skipping "'+M.name+'" as non-required because it was not in the last published version'),!1):(console.log(`"${M.name}" of "${(ne=M.parent)==null?void 0:ne.name}": ${wp(M.getDataType(null))}`),Ka(M.getDataType(null))?(console.log('"'+M.name+'" as non-required is nullable'),!0):!1)}),P=fn(e).filter(M=>!fn(i).find(K=>K.id===M.id));fn(i).filter(M=>{var Y,ee,pe,se,he,ue,be,Ie,_e,Ge,Se;const k=fn(e).find(Ye=>Ye.id===M.id);let K=!1;if(!k)return!1;const ne=Sa(M.dataType,!0,`[resolveSQLMigrationsDiffs] Unsupported data-type structure on current property '${M.name}' (${M.id}). 'andChildrenGroup' with more than one child is not supported for SQL column properties.`),X=Sa(k.dataType,!0,`[resolveSQLMigrationsDiffs] Unsupported data-type structure on last published property '${M.name}' (${M.id}). 'andChildrenGroup' with more than one child is not supported for SQL column properties.`),de=Vg(ne,!0,`[resolveSQLMigrationsDiffs] Unsupported data-type structure on current property '${M.name}' (${M.id}). 'orChildrenGroup' with multiple non-null children is not supported for SQL column properties.`),ie=Vg(X,!0,`[resolveSQLMigrationsDiffs] Unsupported data-type structure on last published property '${M.name}' (${M.id}). 'orChildrenGroup' with multiple non-null children is not supported for SQL column properties.`);if(((Y=de==null?void 0:de.foreignKeyRef)==null?void 0:Y.id)!==((ee=ie==null?void 0:ie.foreignKeyRef)==null?void 0:ee.id)){const Ye=de==null?void 0:de.foreignKeyRef,Ze=ie==null?void 0:ie.foreignKeyRef;E.set(M.id,{...E.get(M.id)||{},newForeignKeyRef:Ye||void 0,oldForeignKeyRef:Ze||void 0,property:M,oldProperty:k}),K=!0,b=!0}else((pe=de==null?void 0:de.entity)==null?void 0:pe.id)!==((se=ie==null?void 0:ie.entity)==null?void 0:se.id)&&(((he=de==null?void 0:de.entity)==null?void 0:he.id)===re["primitive-entity"].string.id||((ue=ie==null?void 0:ie.entity)==null?void 0:ue.id)===re["primitive-entity"].date.id&&((be=de==null?void 0:de.entity)==null?void 0:be.id)===re["primitive-entity"].number.id?E.set(M.id,{...E.get(M.id)||{},castableDataTypeEntity:{fromId:((Ie=ie==null?void 0:ie.entity)==null?void 0:Ie.id)||"",toId:((_e=de==null?void 0:de.entity)==null?void 0:_e.id)||""},property:M,oldProperty:k}):(E.set(M.id,{...E.get(M.id)||{property:M},nonCastableDataTypeEntity:{fromId:((Ge=ie==null?void 0:ie.entity)==null?void 0:Ge.id)||"",toId:((Se=de==null?void 0:de.entity)==null?void 0:Se.id)||""},property:M,oldProperty:k}),b=!0),K=!0);M.name!==(k==null?void 0:k.name)&&(E.set(M.id,{...E.get(M.id)||{},nameChange:{from:(k==null?void 0:k.name)||"",to:M.name},property:M,oldProperty:k}),K=!0);const le=Ka(k.getDataType(null)),ye=Ka(M.getDataType(null));return ye!==le&&(E.set(M.id,{...E.get(M.id)||{},requiredChange:{from:!le,to:!ye},property:M,oldProperty:k}),ye||(b=!0),K=!0),K}),A.length>0&&(b=!0);let V=null;m&&b&&(V=PFe(m,i,e).isPreexistingRowTransformerUpToDate);const G=i.name!==e.name?{from:e.name,to:i.name}:void 0;return{...r,changesSinceLastPublication:E.size>0||!!P.length||!!A.length||!!_.length||b,rowTransformerNeeded:b,newestOpenRowTransformer:m,nameChange:G,newRequiredProperties:A,newNonRequiredProperties:_,deletedProperties:P,lastPublishedEntityVersion:e,propChanges:E,newRowTransformerNeeded:b&&!m,isPreexistingRowTransformerUpToDate:V,extendedEntities:c}}function DL(s,p,i,r,a){if(!s)throw new Error("[addDifferencesToRowTransformer] 'project' argument is required");if(!p)throw new Error("[addDifferencesToRowTransformer] 'transformer' argument is required");if(!i)throw new Error("[addDifferencesToRowTransformer] 'newEntityState' argument is required");if(!r)throw new Error("[addDifferencesToRowTransformer] 'oldEntityState' argument is required");const c=fn(i),e=fn(r);p.afterAllChildrenInitialized(a);const f=p.methods.find(m=>{var E;return((E=m.implements)==null?void 0:E.id)===re["built-in-base-entity"].BUILT_IN_SQL_ROW_TRANSFORMER_ENTITY.methods.up.id}),h=p.methods.find(m=>{var E;return((E=m.implements)==null?void 0:E.id)===re["built-in-base-entity"].BUILT_IN_SQL_ROW_TRANSFORMER_ENTITY.methods.down.id});if(!f)throw new Error("[addDifferencesToRowTransformer] The 'up' transformer trigger is missing from the parent");if(!h)throw new Error("[addDifferencesToRowTransformer] The 'down' transformer trigger is missing from the parent");e.forEach(m=>{const E=f.inputs.find(P=>P.name===m.name),b=m.getDataType(null);let A=E,_;if(E)A.editable=!0;else{const P=Za.new(a);P.parent=f.toReference(),P.name=m.name,P.index=m.index,P.implements=[...m.implements.map(G=>G.toJSON())];const V=Re(P,s);V.hydrateAncestors(),a.add(V,W.Added),V.addSelfToProject(a),V.initChildren(a),A=V}if(!A.dataType||A.dataType&&s.diggestedBuiltInBaseEntitiesIds.has(A.dataType.id)){const P=vr.new(a);P.parent=A.toReference();const V=Re(P,s);V.hydrateAncestors(),a.add(V,W.Added),V.addSelfToProject(a),V.initChildren(a),_=V}else _=A.dataType,_.editable=!0;b&&_.merge(b,a),_.metaSync({editable:!1,deletable:!1},a),A.metaSync({editable:!1,deletable:!1},a)}),[...f.inputs].forEach(m=>{e.find(b=>b.name===m.name)||(m.editable=!0,m.remove({ignoreUpstream:!1},a),m.editable=!1)}),[...f.returnStatements].forEach(m=>{var b,A,_,P;if(!m.dataType||m.dataType&&s.diggestedBuiltInBaseEntitiesIds.has(m.dataType.id)){const V=vr.new(a);V.entity=i.toReference(),V.parent=m.toReference();const G=Re(V,s);G.hydrateAncestors(),a.add(G,W.Added),G.addSelfToProject(a),G.initChildren(a)}const E=((A=(b=m.dataType)==null?void 0:b.entity)==null?void 0:A.name)||Cp((i==null?void 0:i.name)+" new format",s.getDefinitionEntities());(!((_=m.dataType)!=null&&_.entity)||m.dataType.entity.type!==d.DefinitionEntity||m.dataType.entity.parent.id!==m.dataType.id)&&(i.clone(a,m.dataType),i.metaSync({name:E},a)),_g((P=m.dataType)==null?void 0:P.entity,i,a),i.metaSync({name:E},a),m.afterAllChildrenInitialized(a),m.outputs.forEach(V=>{var M;if(V.defaultValue||V.readsValue)return;const G=h.inputs.find(k=>oe(V,s)===oe(k,s));(M=ni((G==null?void 0:G.getDataType(null))||null,V.getDataType(null)||null))!=null&&M.compatible})}),c.forEach(m=>{var V;const E=(V=m.knownVersions)==null?void 0:V.get(m.previousVersion),b=h.inputs.find(G=>G.name===m.name||!!E&&E.name===G.name),A=m.getDataType(null);let _=b,P;if(b)_.editable=!0,_.metaSync({name:m.name,codeName:m.codeName,description:m.description},a);else{const G=Za.new(a);G.parent=h.toReference(),G.name=m.name,G.codeName=m.codeName,G.description=m.description,G.index=m.index,G.implements=[...m.implements.map(k=>k.toJSON())];const M=Re(G,s);M.hydrateAncestors(),a.add(M,W.Added),M.addSelfToProject(a),M.initChildren(a),_=M}if(_.dataType)P=_.dataType,P.editable=!0,P.merge(_.dataType,a);else{const G=vr.new(a);G.parent=_.toReference();const M=Re(G,s);M.hydrateAncestors(),a.add(M,W.Added),M.addSelfToProject(a),M.initChildren(a),P=M}A&&P.merge(A,a),P.metaSync({editable:!1,deletable:!1},a),_.metaSync({editable:!1,deletable:!1},a)}),[...h.inputs].forEach(m=>{c.find(b=>{var _;if(b.name===m.name)return!0;const A=(_=b.knownVersions)==null?void 0:_.get(b.previousVersion);if(A&&A.name===m.name)return!0})||(m.editable=!0,m.remove({ignoreUpstream:!1},a),m.editable=!1)}),[...h.returnStatements].forEach(m=>{var b;if(!m.dataType||m.dataType&&s.diggestedBuiltInBaseEntitiesIds.has(m.dataType.id)){const A=vr.new(a);A.parent=m.toReference();const _=Re(A,s);_.hydrateAncestors(),a.add(_,W.Added),_.addSelfToProject(a),_.initChildren(a)}let E=(b=m.dataType)==null?void 0:b.entity;(!E||(E==null?void 0:E.id)===re["built-in-base-entity"].BUILT_IN_PERSISTED_ENTITY_ENTITY.id)&&(E=r.clone(a,m.dataType)),_g(E,r,a),E.setExtension(null,a),E.addImplementation(s.getBuiltIn(re["built-in-base-entity"].BUILT_IN_PERSISTED_ENTITY_ENTITY.id),a),E.properties.forEach(A=>A.setExtends(null,a)),m.dataType.setEntity(E,a),m.afterAllChildrenInitialized(a),m.outputs.forEach(A=>{var P;if(A.defaultValue||A.readsValue)return;const _=h.inputs.find(V=>oe(A,s)===oe(V,s));(P=ni((_==null?void 0:_.getDataType(null))||null,A.getDataType(null)||null))!=null&&P.compatible&&(A.setValueWriter(_,a),_==null||_.addValueReader(A,a))})})}function xFe(s,p,i,r,a={}){var M;const c=s.getBuiltIn(ge.SQL_ROW_TRANSFORMER),e=Cp(oe(p,s)+" row transformer",s.entities),f=c.implement(e,r),h=f.ownDeclaredProperties.find(k=>{var K;return(K=k.implements)==null?void 0:K.find(ne=>ne.id===re["built-in-base-entity"].BUILT_IN_SQL_ROW_TRANSFORMER_ENTITY.properties.definition.id)}),m=f.methods.find(k=>{var K;return((K=k.implements)==null?void 0:K.id)===re["built-in-base-entity"].BUILT_IN_SQL_ROW_TRANSFORMER_ENTITY.methods.up.id}),E=f.methods.find(k=>{var K;return((K=k.implements)==null?void 0:K.id)===re["built-in-base-entity"].BUILT_IN_SQL_ROW_TRANSFORMER_ENTITY.methods.down.id});if(!h||!m||!E)throw new Error("Cannot find definition property on the new row transformer entity");if(h.defaultValue)h.defaultValue.setValueAsTypeSingle(p,r);else{const k=Lr.new(r);k.name=fe.EntityTemplate,k.valueAsTypeSingle=p.toJSON(),k.parent=h.toReference();const K=Re(k,s);K.hydrateAncestors(),r.add(K,W.Added),K.addSelfToProject(r),K.initChildren(r)}DL(s,f,p,i,r),z.Logger.log("BEFORE - changeSet.listAdded",r.listAdded.map(k=>{var ne,X,de,ie,le,ye,Y;const K=s.get(k.id);return K?oe(K,s):k.type===d.InputMap?"(not found) "+k.type+" "+k.id+" - declaration: "+((ne=k.declaration)==null?void 0:ne.type)+" "+((X=k.declaration)==null?void 0:X.id)+' "'+((de=k.declaration)==null?void 0:de.name)+`"
|
|
607
607
|
parent: `+((le=(ie=k.parent)==null?void 0:ie.parent)==null?void 0:le.id)+" - "+((Y=(ye=k.parent)==null?void 0:ye.parent)==null?void 0:Y.name):"(not found) "+k.type+" "+k.id})),z.Logger.log("AFTER - changeSet.listAdded",r.listAdded.map(k=>{var ne,X,de,ie,le,ye,Y;const K=s.get(k.id);return K?K.type+' "'+oe(K,s)+'" ('+K.id+")":k.type===d.InputMap?"(not found) "+k.type+" ("+k.id+") - declaration: "+((ne=k.declaration)==null?void 0:ne.type)+" ("+((X=k.declaration)==null?void 0:X.id)+') "'+((de=k.declaration)==null?void 0:de.name)+`"
|
|
608
608
|
parent: "`+((le=(ie=k.parent)==null?void 0:ie.parent)==null?void 0:le.name)+'" ('+((Y=(ye=k.parent)==null?void 0:ye.parent)==null?void 0:Y.id)+")":"(not found) "+k.type+" "+k.id})),z.Logger.log("-----------------"),z.Logger.log("Old properties: ",fn(i).map(k=>k.name+" ("+k.id+")")),z.Logger.log("New properties: ",fn(p).map(k=>k.name+" ("+k.id+")"));const b=f.methods.find(k=>{var K;return((K=k.implements)==null?void 0:K.id)===re["built-in-base-entity"].BUILT_IN_SQL_ROW_TRANSFORMER_ENTITY.methods.up.id}),A=f.methods.find(k=>{var K;return((K=k.implements)==null?void 0:K.id)===re["built-in-base-entity"].BUILT_IN_SQL_ROW_TRANSFORMER_ENTITY.methods.down.id});z.Logger.log(`
|