@elyx-code/project-logic-tree 0.0.6746 → 0.0.6747

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 CHANGED
@@ -3,7 +3,7 @@ Please provide a unique 'name' string.`,severity:ce.Error,code:Ie.NameNotUniqueI
3
3
  Please provide a unique 'name' string.`,severity:ce.Error,code:Ie.NameNotUniqueInScope})),i}function CP(o,p){const i=[];o.name||i.push(new De({id:`${o.id}--${Ie.EmptyName}`,message:`Entity with id "${o.id}" and type "${o.type}" has an empty name. Please provide a 'name' string.`,severity:ce.Error,code:Ie.EmptyName}));const n=o.parent&&ra(o.parent,p)||p;if(!n)i.push(new De({id:`${o.id}--parent-reference--${ae.ReferencedEntityNotFound}`,message:`The entity with id '${o.parent}' that isn't yet found in the project. Perhaps it should be created first. Or perhaps the ID is incorrect.`,severity:ce.Error,code:ae.ReferencedEntityNotFound}));else{const c=RP(n).filter(e=>e.name===o.name);c.length&&i.push(new De({id:`${o.id}--${Ie.NameNotUniqueInScope}`,message:`Entity with id "${o.id}" and type "${o.type}" has a name "${o.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:ce.Error,code:Ie.NameNotUniqueInScope}))}return i}function _P(o,p){const i=[];o.name||i.push(new De({id:`${o.id}--${Ie.EmptyName}`,message:`Entity with id "${o.id}" and type "${o.type}" has an empty name. Please provide a 'name' string.`,severity:ce.Error,code:Ie.EmptyName}));const n=ne(o.parent);if(!n)i.push(new De({id:`${o.id}--parent-reference--${ae.InvalidReferenceObjectStructure}`,message:`Reference object at 'parent' property for entity with id "${o.id}" and type "${o.type}" is not a valid reference. A reference needs to be a 'id' string of an existing entity in the project.`,severity:ce.Error,code:ae.InvalidReferenceObjectStructure}));else{const s=p.get(n);if(!s)i.push(new De({id:`${o.id}--parent-reference--${ae.ReferencedEntityNotFound}`,message:`The entity with id '${n}' that isn't yet found in the project. Perhaps it should be created first. Or perhaps the ID is incorrect.`,severity:ce.Error,code:ae.ReferencedEntityNotFound}));else{const e=s.properties.filter(y=>y.name===o.name);e.length&&i.push(new De({id:`${o.id}--${Ie.NameNotUniqueInScope}`,message:`Entity with id "${o.id}" and type "${o.type}" has a name "${o.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:ce.Error,code:Ie.NameNotUniqueInScope}))}}return i}function VP(o,p){const i=[];o.name||i.push(new De({id:`${o.id}--${Ie.EmptyName}`,message:`Entity with id "${o.id}" and type "${o.type}" has an empty name. Please provide a 'name' string.`,severity:ce.Error,code:Ie.EmptyName}));const n=ne(o.parent);if(!n)i.push(new De({id:`${o.id}--parent-reference--${ae.InvalidReferenceObjectStructure}`,message:`Reference object at 'parent' property for entity with id "${o.id}" and type "${o.type}" is not a valid reference. A reference needs to be a 'id' string of an existing entity in the project.`,severity:ce.Error,code:ae.InvalidReferenceObjectStructure}));else{const s=p.get(n);if(!s)i.push(new De({id:`${o.id}--parent-reference--${ae.ReferencedEntityNotFound}`,message:`The entity with id '${n}' that isn't yet found in the project. Perhaps it should be created first. Or perhaps the ID is incorrect.`,severity:ce.Error,code:ae.ReferencedEntityNotFound}));else{const e=nx(s).filter(y=>y.name===o.name);e.length&&i.push(new De({id:`${o.id}--${Ie.NameNotUniqueInScope}`,message:`Entity with id "${o.id}" and type "${o.type}" has a name "${o.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:ce.Error,code:Ie.NameNotUniqueInScope}))}}return i}function sTi(o,p){switch(o.type){case d.DefinitionEntity:return wP(o,p);case d.FunctionDeclaration:return OP(o,p);case d.VariableDeclaration:return CP(o,p);case d.Property:return _P(o,p);case d.ArgumentDeclaration:return VP(o,p);default:return[]}}function Ic(o,p){var n;const i=o;switch(o.type){case d.FunctionCall:case d.InternalCall:return ra(o.declaration,p).codeName;case d.ActionDescriptor:case d.DefinitionEntity:case d.VariableDeclaration:case d.ValueDescriptor:case d.FunctionDeclaration:return o.codeName||null;case d.Property:case d.ArgumentDeclaration:{if(o.codeName)return o.codeName;if((n=o.implements)!=null&&n.length){const s=o.implements.find(c=>{const e=ra(c,p);return!!(e!=null&&e.codeName)});if(s)return ra(s,p).codeName||null}break}case d.InputMap:case d.OutputMap:case d.VariableInstance:{if(o.declaration){const s=ra(o.declaration,p);return Ic(s,p)||""}break}}return i.codeName||null}function PP(o,p){let i=o;if(!!p.some(s=>s.name===i)){const s=o.split(" "),c=s.pop()||"",e=parseInt(c);return!isNaN(e)?s.push(`${e+1}`):(s.push(c),s.push("1")),i=s.join(" "),PP(i,p)}return i}function xwe(o,p,i){const s=`${uA(o)}-${p}-id`;return i.instances[s]?x.UUID.uuid():s}function KO(o,p){let i="",n=null;if(o.parent){const c=p.get(o.parent);c&&(n=c)}let s="";return n&&(s=`${uA(se(n,p))}-`),i=`${s}${uA(se(o,p))}-id`,p.instances[i]?x.UUID.uuid():i}function jr(o,p,i="uuid"){return i==="semantic"?xwe(se(o,p),o.type,p):x.UUID.uuid()}const lTi=/^[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 NP(o){return typeof o=="string"&&lTi.test(o)}function oTi(o){return o instanceof Error&&o.name==="ZodError"&&"issues"in o&&Array.isArray(o.issues)}var dTi=class extends Error{constructor(p,i){super(p,i);I(this,"name");I(this,"details");this.name="ZodValidationError",this.details=uTi(i)}toString(){return this.message}};function uTi(o){if(o){const p=o.cause;if(oTi(p))return p.issues}return[]}function pTi(o){return o.length!==0}function E4(o){return o.description??""}var cTi=/[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*/u;function fTi(o){if(o.length===1){let p=o[0];return typeof p=="symbol"&&(p=E4(p)),p.toString()||'""'}return o.reduce((p,i)=>{if(typeof i=="number")return p+"["+i.toString()+"]";if(typeof i=="symbol"&&(i=E4(i)),i.includes('"'))return p+'["'+yTi(i)+'"]';if(!cTi.test(i))return p+'["'+i+'"]';const n=p.length===0?"":".";return p+n+i},"")}function yTi(o){return o.replace(/"/g,'\\"')}var hTi="; ",mTi=99,$we="Validation error",TTi=": ",vTi=", or ";function ETi(o={}){const{issueSeparator:p=hTi,unionSeparator:i=vTi,prefixSeparator:n=TTi,prefix:s=$we,includePath:c=!0,maxIssuesInMessage:e=mTi}=o;return y=>{const m=y.slice(0,e).map(v=>kb({issue:v,issueSeparator:p,unionSeparator:i,includePath:c})).join(p);return bTi(m,s,n)}}function kb(o){const{issue:p,issueSeparator:i,unionSeparator:n,includePath:s}=o;if(p.code===rt.invalid_union)return p.unionErrors.reduce((c,e)=>{const y=e.issues.map(m=>kb({issue:m,issueSeparator:i,unionSeparator:n,includePath:s})).join(i);return c.includes(y)||c.push(y),c},[]).join(n);if(p.code===rt.invalid_arguments)return[p.message,...p.argumentsError.issues.map(c=>kb({issue:c,issueSeparator:i,unionSeparator:n,includePath:s}))].join(i);if(p.code===rt.invalid_return_type)return[p.message,...p.returnTypeError.issues.map(c=>kb({issue:c,issueSeparator:i,unionSeparator:n,includePath:s}))].join(i);if(s&&pTi(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 "${fTi(p.path)}"`}return p.message}function bTi(o,p,i){return p!==null?o.length>0?[p,o].join(i):p:o.length>0?o:$we}function ATi(o,p={}){const n=gTi(p)([o]);return new dTi(n,{cause:new _o([o])})}function gTi(o){return"messageBuilder"in o?o.messageBuilder:ETi(o)}async function Lwe(o,p={}){var c;const i=J.YieldTracker.from(p),n=[...Rs(o)];await i.tick();const s=Mt(o.errors,n);return await((c=o.dataType)==null?void 0:c.validateAsync({tracker:i})),s}function Mwe(o){var i;(i=o.dataType)==null||i.validate();const p=[...Rs(o)];return Mt(o.errors,p)}const ITi=Object.freeze(Object.defineProperty({__proto__:null,validate:Mwe,validateAsync:Lwe},Symbol.toStringTag,{value:"Module"}));function Bwe(o){return o.listAdded.forEach(p=>{const i=o.project.get(p.id);(i==null?void 0:i.type)===d.DefinitionEntity&&i.parent.type!==d.DataType&&(o.project.emit(zt.EXPLICIT_DEFINITION_ENTITY_ADDED,i,o),Wi(i,Re.PERSISTED_ENTITY)?o.project.emit(zt.PERSISTED_DEFINITION_ENTITY_ADDED,i,o):Wi(i,Re.RELATIONAL_DATABASE)&&o.project.emit(zt.RELATIONAL_DATABASE_DEFINITION_ENTITY_ADDED,i,o))}),o.listUpdated.forEach(p=>{const i=o.project.get(p.id);(i==null?void 0:i.type)===d.DefinitionEntity&&i.parent.type!==d.DataType&&(o.project.emit(zt.EXPLICIT_DEFINITION_ENTITY_UPDATED,i,o),Wi(i,Re.PERSISTED_ENTITY)?o.project.emit(zt.PERSISTED_DEFINITION_ENTITY_UPDATED,i,o):Wi(i,Re.RELATIONAL_DATABASE)&&o.project.emit(zt.RELATIONAL_DATABASE_DEFINITION_ENTITY_UPDATED,i,o))}),o.listRemoved.forEach(p=>{const i=o.project.get(p.id)||o.project.getDeleted(p.id);(i==null?void 0:i.type)===d.DefinitionEntity&&i.parent.type!==d.DataType&&(o.project.emit(zt.EXPLICIT_DEFINITION_ENTITY_REMOVED,i,o),Wi(i,Re.PERSISTED_ENTITY)?o.project.emit(zt.PERSISTED_DEFINITION_ENTITY_REMOVED,i,o):Wi(i,Re.RELATIONAL_DATABASE)&&o.project.emit(zt.RELATIONAL_DATABASE_DEFINITION_ENTITY_REMOVED,i,o))}),o}async function Gwe(o,p={}){const i=J.YieldTracker.from(p),n=[];for(const s of o.listAdded){const c=o.project.get(s.id);(c==null?void 0:c.type)===d.DefinitionEntity&&c.parent.type!==d.DataType&&(n.push(o.project.emitAsync(zt.EXPLICIT_DEFINITION_ENTITY_ADDED,c,o)),Wi(c,Re.PERSISTED_ENTITY)?n.push(o.project.emitAsync(zt.PERSISTED_DEFINITION_ENTITY_ADDED,c,o)):Wi(c,Re.RELATIONAL_DATABASE)&&n.push(o.project.emitAsync(zt.RELATIONAL_DATABASE_DEFINITION_ENTITY_ADDED,c,o))),await i.tick()}for(const s of o.listUpdated){const c=o.project.get(s.id);(c==null?void 0:c.type)===d.DefinitionEntity&&c.parent.type!==d.DataType&&(n.push(o.project.emitAsync(zt.EXPLICIT_DEFINITION_ENTITY_UPDATED,c,o)),Wi(c,Re.PERSISTED_ENTITY)?n.push(o.project.emitAsync(zt.PERSISTED_DEFINITION_ENTITY_UPDATED,c,o)):Wi(c,Re.RELATIONAL_DATABASE)&&n.push(o.project.emitAsync(zt.RELATIONAL_DATABASE_DEFINITION_ENTITY_UPDATED,c,o))),await i.tick()}for(const s of o.listRemoved){const c=o.project.get(s.id)||o.project.getDeleted(s.id);(c==null?void 0:c.type)===d.DefinitionEntity&&c.parent.type!==d.DataType&&(n.push(o.project.emitAsync(zt.EXPLICIT_DEFINITION_ENTITY_REMOVED,c,o)),Wi(c,Re.PERSISTED_ENTITY)?n.push(o.project.emitAsync(zt.PERSISTED_DEFINITION_ENTITY_REMOVED,c,o)):Wi(c,Re.RELATIONAL_DATABASE)&&n.push(o.project.emitAsync(zt.RELATIONAL_DATABASE_DEFINITION_ENTITY_REMOVED,c,o))),await i.tick()}return await Promise.all(n),o}var UI=(o=>(o.Manual="manual",o.Automatic="automatic",o))(UI||{}),H=(o=>(o.Added="added",o.Updated="updated",o.Removed="removed",o.Affected="affected",o))(H||{}),_=(o=>(o.AddSuccessCall="add-success-call",o.AddErrorCall="add-error-call",o.AddCall="add-call",o.SetParent="set-parent",o.SetStandaloneParent="set-standalone-parent",o.AfterAllChildrenInitialized="after-all-children-initialized",o.UpdateWithShallowTransfer="update-with-shallow-transfer",o.RemoveFromParent="remove-from-parent",o.RemoveEntity="remove-entity",o.RestoreEntity="restore-entity",o.CloneEntity="clone-entity",o.AddInput="add-input",o.RemoveInput="remove-input",o.SetDataType="set-data-type",o.RemoveDataType="remove-data-type",o.SetAdditionalPropertiesDataType="set-additional-properties-data-type",o.RemoveAdditionalPropertiesDataType="remove-additional-properties-data-type",o.SetAllPropertiesImplement="set-all-properties-implement",o.RemoveAllPropertiesImplement="remove-all-properties-implement",o.RemoveValueReader="remove-value-reader",o.AddValueReader="add-value-reader",o.RemoveValueWriter="remove-value-writer",o.SetValueWriter="set-value-writer",o.AddEntryCaller="add-entry-caller",o.AddSuccessCaller="add-success-caller",o.AddErrorCaller="add-error-caller",o.RemoveCall="remove-call",o.RemoveCaller="remove-caller",o.RemoveChildGroup="remove-child-group",o.AddToAndGroup="add-to-and-group",o.AddToOrGroup="add-to-or-group",o.RemoveUnrecognizedInputs="remove-unrecognized-inputs",o.RemoveUnrecognizedOutputs="remove-unrecognized-outputs",o.SyncInputs="sync-inputs",o.SyncOutputs="sync-outputs",o.SetImplements="set-implements",o.SetExtends="set-extends",o.SetExtension="set-extension",o.AddImplementation="add-implementation",o.RemoveImplementation="remove-implementation",o.AddProperty="add-property",o.RemoveProperty="remove-property",o.AddMethod="add-method",o.RemoveMethod="remove-method",o.AddAbstractMethod="add-abstract-method",o.RemoveAbstractMethod="remove-abstract-method",o.SetValueAsTypeSingle="set-value-as-type-single",o.SetValueAsTypeList="set-value-as-type-list",o.SetValueAsType="set-value-as-type",o.RemoveErrorCatching="remove-error-catching",o.RemoveAllErrorCallers="remove-all-error-callers",o.RemoveAllSuccessCallers="remove-all-success-callers",o.RemoveAllCallers="remove-all-callers",o.RemoveAllErrorCalls="remove-all-error-calls",o.SetDataTypeEntityValue="set-data-type-entity-value",o.MergeDataTypes="merge-data-types",o.SetDataTypeForeignKeyRef="set-data-type-foreign-key-ref",o.SetErrorEntity="set-error-entity",o.AddValueAsTypeToList="add-value-as-type-to-list",o.RemoveValueAsTypeFromList="remove-value-as-type-from-list",o))(_||{}),Ii=(o=>(o.ActionOwnerEntityNotEditable="action-owner-entity-not-editable",o.ActionCounterpartEntityNotEditable="action-counterpart-entity-not-editable",o.ActionOwnerEntityNonDeletable="action-owner-entity-non-deletable",o.GlobalVariableDeclarationCannnotCatchError="global-variable-declaration-cannot-catch-error",o.GlobalVariableDeclarationCannotReadValue="global-variable-declaration-cannot-read-value",o.GlobalVariableDeclarationCannotBeCalled="global-variable-declaration-cannot-be-called",o.GlobalVariableDeclarationCannotCallFromError="global-variable-declaration-cannot-call-from-error",o.ValueReadingOverridesConstantProperty="value-reading-overrides-constant-property",o.DefaultValueOverridesConstantProperty="default-value-overrides-constant-property",o.ValueReadingOverridesConstantVariable="value-reading-overrides-constant-variable",o.DefaultValueOverridesConstantVariable="default-value-overrides-constant-variable",o))(Ii||{});class kwe{constructor({id:p,action:i,errorReason:n,owner:s,counterpart:c,rootAction:e},y){I(this,"id");I(this,"action");I(this,"errorReason");I(this,"owner",null);I(this,"counterpart",null);I(this,"rootAction",!1);I(this,"parent");this.id=p,this.action=i,this.errorReason=n||null,this.owner=s||null,this.counterpart=c||null,this.rootAction=e||!1,this.parent=y}}class Z extends J.Events{constructor(i,n,s,c,e=!1,y=""){super(y?y+"-cs-events":"anonymous-cs-events");I(this,"id",x.UUID.uuid());I(this,"seenEntities",[]);I(this,"added",{});I(this,"updated",{});I(this,"removed",{});I(this,"affected",{});I(this,"self",null);I(this,"author");I(this,"timestamp");I(this,"open",!0);I(this,"startedClose",!1);I(this,"dirty",!0);I(this,"submitting",!1);I(this,"lockedVersions",!1);I(this,"type","manual");I(this,"autoclose",!1);I(this,"autoCloseActionName","");I(this,"project");I(this,"events",new Map);I(this,"ignoreNonEditable",!1);I(this,"ignoreNonDeletable",!1);I(this,"logger");if(this.project=i,this.author=n||x.sessionAuthor||"",this.timestamp=s,this.self=c,this.autoclose=e,this.autoCloseActionName=y,this.logger=J.Logger.module("cs:"+(this.autoCloseActionName?this.autoCloseActionName+":":"")+this.id),this.autoclose&&!this.autoCloseActionName)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 n=new kwe(i,this);this.events.set(i.id,n),this.emit("change-set-event",n)}discardOrphans(){this.added[this.project.id]&&(this.updatedIds.forEach(e=>{const y=this.updated[e];this.added[e]=y,delete this.updated[e]}),this.removedIds.forEach(e=>{this.remove(e)}));const i=[...this.addedIds,...this.updatedIds],s=this.project.toFlatIds().filter(e=>!this.project.diggestedBuiltInBaseEntitiesIds.has(e));if(i.filter(e=>!s.includes(e)).forEach(e=>{const y=this.get(e);this.logger.warn(`[discardOrphans] Entity ${y==null?void 0:y.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 n=J.YieldTracker.from(i),s=this.project.toFlatIds();if(this.added[this.project.id]){for(const m of this.updatedIds){const v=this.updated[m];this.added[m]=v,delete this.updated[m],await n.tick()}for(const m of this.removedIds)this.remove(m),await n.tick()}const c=[...this.addedIds,...this.updatedIds],e=s.filter(m=>!this.project.diggestedBuiltInBaseEntitiesIds.has(m)),y=c.filter(m=>!e.includes(m));for(const m of y){const v=this.get(m);this.logger.warn(`[discardOrphansAsync] Entity ${v==null?void 0:v.type} with id "${m}" present in change-set but not in project. Removing from change-set.`),this.remove(m),await n.tick()}if(this.added[this.project.id]){const m=[...this.addedIds,...this.updatedIds],E=s.filter(b=>!this.project.diggestedBuiltInBaseEntitiesIds.has(b)).filter(b=>!m.includes(b));for(const b of E){const w=this.project.get(b);this.add(w,"added"),await n.tick()}}}captureAllChangesInVersionInstances(){[...this.addedIds,...this.updatedIds].forEach(n=>{const s=this.project.get(n);if(!s){const e=this.added[n],y=this.updated[n],m=e||y;throw new Error(`Entity ${(m==null?void 0:m.type)||"of unknown type"} with id "${n}" was ${e?"added":"updated"} but isn't found in the project state when capturing version for change-set.`)}const c=this.get(n);s.version===c.version&&s.captureVersion()}),this.removedIds.forEach(n=>{const s=this.project.getDeleted(n);if(!s){const e=this.removed[n];throw new Error(`Entity ${(e==null?void 0:e.type)||"of unknown type"} with id "${n}" was removed but isn't found in the project state when capturing version for change-set.`)}const c=this.get(n);s.version===c.version&&s.captureVersion()})}async captureAllChangesInVersionInstancesAsync(i={}){const n=J.YieldTracker.from(i),s=[...this.addedIds,...this.updatedIds];for(const c of s){const e=this.project.get(c);if(!e)throw new Error(`Entity with id "${c}" not found in the project state when capturing version for change-set.`);const y=this.get(c);e.version===y.version&&e.captureVersion(),await n.tick()}for(const c of this.removedIds){const e=this.project.getDeleted(c);if(!e)throw new Error(`Entity with id "${c}" not found in the project state when capturing version for change-set.`);const y=this.get(c);e.version===y.version&&e.captureVersion(),await n.tick()}}async attemptAutocloseAsync(i,n){var s;return this.autoclose&&this.autoCloseActionName&&this.autoCloseActionName===i&&(this.self&&n===((s=this.self)==null?void 0:s.id)||!this.self)&&await this.closeAsync(),this}async closeAsync(i={}){const n=J.YieldTracker.from(i),s={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:n}):this.beforeCloseAsync({tracker:n})),!this.isValid&&this.self&&!this.added[this.self.id]&&!this.updated[this.self.id]&&this.removed[this.self.id],await this.discardOrphansAsync({tracker:n}),await this.sanitizeAsync({tracker:n}),await this.recursiveCaptureUpstreamVersionsAsync({tracker:n}),this.lockedVersions||(await this.captureAllChangesInVersionInstancesAsync({tracker:n}),await this.recursiveCaptureUpstreamVersionsAsync({tracker:n})),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(zt.CHANGE_SET_CLOSED_BEFORE_PERSIST,this),e?s.persistType==="parallel"?await this.project.persistChangeSetInParallel(this):await this.project.persistChangeSetSequentially(this):s.persistType==="parallel"?this.project.persistChangeSetInParallel(this):this.project.persistChangeSetSequentially(this),this.destroy(),this)}attemptAutoclose(i,n){var s;return this.autoclose&&this.autoCloseActionName&&this.autoCloseActionName===i&&(this.self&&n===((s=this.self)==null?void 0:s.id)||!this.self)&&this.close(),this}recursiveCaptureUpstreamVersions(){if(this.lockedVersions)return;[...this.addedIds,...this.updatedIds,...this.removedIds].forEach(n=>{const s=this.get(n),{added:c,updated:e,removed:y,affected:m}=s.recursiveCaptureUpstreamVersions(this.timestamp);for(const v of c)this.add(v,"added");for(const v of e)this.add(v,"updated");for(const v of y)this.add(v,"removed");for(const v of m)this.add(v,"affected")})}async recursiveCaptureUpstreamVersionsAsync(i={}){if(this.lockedVersions)return;const n=J.YieldTracker.from(i),s=[...this.addedIds,...this.updatedIds,...this.removedIds];for await(const c of s){const e=this.get(c),{added:y,updated:m,removed:v,affected:E}=e.recursiveCaptureUpstreamVersions(this.timestamp);for(const b of y)this.add(b,"added");for(const b of m)this.add(b,"updated");for(const b of v)this.add(b,"removed");for(const b of E)this.add(b,"affected");await n.tick()}}sanitize(){this.listAdded.forEach(i=>{i.previousVersion=null})}async sanitizeAsync(i={}){const n=J.YieldTracker.from(i);for(const s of this.listAdded)s.previousVersion=null,await n.tick()}syncDependents(){return[...this.list,...this.listAffected].forEach(i=>{const n=this.project.get(i.id);!n||n.deleted||rA(n,this.project)||n==null||n.syncDependents(this)}),this}async syncDependentsAsync(i={}){const n=J.YieldTracker.from(i);for(const s of[...this.list,...this.listAffected]){const c=this.project.get(s.id);!c||c.deleted||rA(c,this.project)||(c==null||c.syncDependents(this),await n.tick())}return this}async beforeCloseAsync(i={}){const n=J.YieldTracker.from(i);await this.project.emitAsync(zt.BEFORE_CHANGE_SET_CLOSE_BEFORE_SIDE_EFFECTS,this),await this.syncDependentsAsync({tracker:n}),await this.emitAsyncProjectSideEffects({tracker:n}),await this.project.emitAsync(zt.BEFORE_CHANGE_SET_CLOSE_AFTER_SIDE_EFFECTS,this),this.teardown()}beforeClose(){this.project.emit(zt.BEFORE_CHANGE_SET_CLOSE_BEFORE_SIDE_EFFECTS,this),this.syncDependents(),this.emitProjectSideEffects(),this.project.emit(zt.BEFORE_CHANGE_SET_CLOSE_AFTER_SIDE_EFFECTS,this),this.teardown()}teardown(){this.destroy()}emitProjectSideEffects(){return Bwe(this)}async emitAsyncProjectSideEffects(i={}){return Gwe(this,i)}close(i={}){const n={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(zt.CHANGE_SET_CLOSED_BEFORE_PERSIST,this),n.persistType==="parallel"?this.project.persistChangeSetInParallel(this):this.project.persistChangeSetSequentially(this),this.destroy(),this}addDependentsToAffected(i){Object.values(i.detachedDependents).forEach(n=>{const{entity:s,field:c}=n;this.has(s.id)||this.add(s,"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(n=>n!==i)),this}add(i,n,s={preventRecursion:!1}){var e,y,m;if(!this.open||!this.dirty)return this;if(rA(i,this.project))return this;if(this.seenEntities.indexOf(i.id)===-1&&this.seenEntities.push(i.id),n==="removed"){if(this.added[i.id])return delete this.added[i.id],this.seenEntities=this.seenEntities.filter(E=>E!==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),!s.preventRecursion)){const{added:E,updated:b,removed:w,affected:V}=i.recursiveCaptureUpstreamVersions(this.timestamp);for(const $ of E)this.add($,"added");for(const $ of b)this.add($,"updated");for(const $ of w)this.add($,"removed");for(const $ of V)this.add($,"affected")}i.captureVersion();const v=(e=i.knownVersions)==null?void 0:e.get(i.version);if(!v)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]=v,this}if(n==="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&&!s.preventRecursion){const{added:E,updated:b,removed:w,affected:V}=i.recursiveCaptureUpstreamVersions(this.timestamp);for(const $ of E)this.add($,"added");for(const $ of b)this.add($,"updated");for(const $ of w)this.add($,"removed");for(const $ of V)this.add($,"affected")}i.previousVersion=null,i.captureVersion();const v=(y=i.knownVersions)==null?void 0:y.get(i.version);if(!v)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]=v,delete this.affected[i.id],this.addDependentsToAffected(i),this}if(n==="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),!s.preventRecursion)){const{added:E,updated:b,removed:w,affected:V}=i.recursiveCaptureUpstreamVersions(this.timestamp);for(const $ of E)this.add($,"added");for(const $ of b)this.add($,"updated");for(const $ of w)this.add($,"removed");for(const $ of V)this.add($,"affected")}i.captureVersion();const v=(m=i.knownVersions)==null?void 0:m.get(i.version);if(!v)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]=v,this.addDependentsToAffected(i),this}if(n==="affected"){if(this.removed[i.id])return this;if(this.added[i.id])return this;if(this.updated[i.id])return this;this.affected[i.id]=i}return this}toJSON(){var y;const i={},n={},s={},c=new Set;for(const m of Object.values(this.added))i[m.id]=m.toShallowJSON();for(const m of Object.values(this.updated))n[m.id]=m.toShallowJSON();for(const m of Object.values(this.removed))s[m.id]=m.toShallowJSON();for(const m of Object.values(this.affected))c.add(m.id);const e=this.get(((y=this.self)==null?void 0:y.id)||"");return{added:i,updated:n,removed:s,affected:Array.from(c),self:e?e.toShallowJSON():null,seenEntities:this.seenEntities}}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 RTi(o){return new Set([...Object.keys(o.added),...Object.keys(o.updated),...Object.keys(o.removed),...Array.from(o.affected)])}function FO(o,p,i){var y;const n=new Date().toISOString(),s=new Z(i,x.sessionAuthor,n,i);if(s.lockedVersions=!0,o===p)throw J.Logger.error("From: ",o),J.Logger.error("To: ",p),new Error("Cannot generate transitional change set between the same two versions or change-sets");let c;if(o==="initial"?c=!0:p==="initial"?c=!1:M(o.timestamp).isBefore(M(p.timestamp))?c=!0:c=!1,J.Logger.log("Transitioning from ",o==="initial"?"initial":o.index),J.Logger.log("Transitioning to ",p==="initial"?"initial":p.index),J.Logger.log("Is forward: ",c),c){const v=p.index,E=o==="initial"?0:o.index;J.Logger.log("ownIndex: ",v),J.Logger.log("startIndex: ",E);const b=v===E?[i.history[v]]:i.history.slice(E+1,v+1);if(b.sort((w,V)=>M(w.timestamp).isAfter(M(V.timestamp))?1:-1),!b.length)throw new Error("No change sets in the history between the history indexes provided");J.Logger.log("REDO change-set: ",b[0].id," ",b[0].timestamp),b.forEach(w=>{SO(w,V=>{const $=i.instances[V.id]||i.deletedInstances[V.id];let L="";try{L=se(V,i)}catch{}if(!$)throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" doesn't have an 'activeVersion' set.`);if(!$.knownVersions)throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" has an active version instance missing the 'knownVersions' property value.`);if(!$.knownVersions.get(V.version))throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" has an active version instance missing the 'knownVersions' property value for version "${V.version}".`);$.restoreVersion(V.version),s.timestamp=$.createdAt,s.add($,H.Added,{preventRecursion:!0})},V=>{const $=i.instances[V.id]||i.deletedInstances[V.id];let L="";try{L=se(V,i)}catch{}if(!$)throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" doesn't have an 'activeVersion' set.`);if(!$.knownVersions)throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" has an active version instance missing the 'knownVersions' property value.`);if(!$.knownVersions.get(V.version))throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" has an active version instance missing the 'knownVersions' property value for version "${V.version}".`);$.restoreVersion(V.version),s.timestamp=$.createdAt,s.add($,H.Updated,{preventRecursion:!0})},V=>{const $=i.instances[V.id]||i.deletedInstances[V.id];let L="";try{L=se(V,i)}catch{}if(!$)throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" doesn't have an 'activeVersion' set.`);if(!$.knownVersions)throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" has an active version instance missing the 'knownVersions' property value.`);if(!$.knownVersions.get(V.version))throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" has an active version instance missing the 'knownVersions' property value for version "${V.version}".`);$.restoreVersion(V.version),s.timestamp=$.createdAt,s.add($,H.Removed,{preventRecursion:!0})})})}else{const v=o.index,E=p==="initial"?0:p.index,b=v===E?[i.history[v]]:i.history.slice(E+1,v+1);if(b.sort((w,V)=>M(V.timestamp).isAfter(M(w.timestamp))?1:-1),!b.length)throw new Error("No change sets in the history between the history indexes provided");J.Logger.log("UNDO change-set: ",b[0].id," ",b[0].timestamp),b.forEach(w=>{SO(w,V=>{const $=i.instances[V.id]||i.deletedInstances[V.id];let L="";try{L=se(V,i)}catch{}if(!$)throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" doesn't have an 'activeVersion' set.`);if(!$.knownVersions)throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" has an active version instance missing the 'knownVersions' property value.`);if(!$.knownVersions.get(V.version))throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" has an active version instance missing the 'knownVersions' property value for version "${V.version}".`);V.previousVersion&&$.restoreVersion(V.previousVersion),s.timestamp=$.createdAt,s.add($,H.Removed,{preventRecursion:!0})},V=>{const $=i.instances[V.id]||i.deletedInstances[V.id];let L="";try{L=se(V,i)}catch{}if(!$)throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" doesn't have an 'activeVersion' set.`);if(!$.knownVersions)throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" has an active version instance missing the 'knownVersions' property value.`);if(!$.knownVersions.get(V.version))throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" has an active version instance missing the 'knownVersions' property value for version "${V.version}".`);$.restoreVersion(V.previousVersion),s.timestamp=$.createdAt,s.add($,H.Updated,{preventRecursion:!0})},V=>{const $=i.instances[V.id]||i.deletedInstances[V.id];let L="";try{L=se(V,i)}catch{}if(!$)throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" doesn't have an 'activeVersion' set.`);if(!$.knownVersions)throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" has an active version instance missing the 'knownVersions' property value.`);if(!$.knownVersions.get(V.version))throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" has an active version instance missing the 'knownVersions' property value for version "${V.version}".`);$.restoreVersion(V.previousVersion),s.timestamp=$.createdAt,s.add($,H.Added,{preventRecursion:!0})})})}let e;if(p==="initial"){const m=Array.from(((y=i.knownVersions)==null?void 0:y.values())||[]).reduce((v,E)=>!v||M(E.createdAt).isBefore(M(v.createdAt))?E:v,null);if(!m)throw new Error("No oldest version found");e=m.createdAt}else e=p.timestamp;return s.open=!1,{transitionalChangeSet:s,transitionTime:n,timeOfOriginalTargetChanges:e}}function SO(o,p,i,n){var y;if(!(o!=null&&o.self))throw new Error("Change set must have a valid `self` entity state to be traversed");const s=((y=o.self)==null?void 0:y.type)===d.Project?o.self:o.self.project,c=new Nn(o.self,{allBuiltInEntityIds:s.diggestedBuiltInBaseEntitiesIds});J.Logger.log("changeSet.added: ",Object.keys(o.added).length),J.Logger.log("changeSet.updated: ",Object.keys(o.updated).length),J.Logger.log("changeSet.removed: ",Object.keys(o.removed).length);const e={...o.added,...o.updated,...o.removed};c.order=Object.keys(e),c.flatRecord=e,c.orderEntities(),J.Logger.log("All entities: ",c.order.map((m,v)=>`${v+1}: ${e[m].type} - ${m}`).join(`,
6
+ Please provide a unique 'name' string.`,severity:ce.Error,code:Ie.NameNotUniqueInScope}))}}return i}function sTi(o,p){switch(o.type){case d.DefinitionEntity:return wP(o,p);case d.FunctionDeclaration:return OP(o,p);case d.VariableDeclaration:return CP(o,p);case d.Property:return _P(o,p);case d.ArgumentDeclaration:return VP(o,p);default:return[]}}function Ic(o,p){var n;const i=o;switch(o.type){case d.FunctionCall:case d.InternalCall:return ra(o.declaration,p).codeName;case d.ActionDescriptor:case d.DefinitionEntity:case d.VariableDeclaration:case d.ValueDescriptor:case d.FunctionDeclaration:return o.codeName||null;case d.Property:case d.ArgumentDeclaration:{if(o.codeName)return o.codeName;if((n=o.implements)!=null&&n.length){const s=o.implements.find(c=>{const e=ra(c,p);return!!(e!=null&&e.codeName)});if(s)return ra(s,p).codeName||null}break}case d.InputMap:case d.OutputMap:case d.VariableInstance:{if(o.declaration){const s=ra(o.declaration,p);return Ic(s,p)||""}break}}return i.codeName||null}function PP(o,p){let i=o;if(!!p.some(s=>s.name===i)){const s=o.split(" "),c=s.pop()||"",e=parseInt(c);return!isNaN(e)?s.push(`${e+1}`):(s.push(c),s.push("1")),i=s.join(" "),PP(i,p)}return i}function xwe(o,p,i){const s=`${uA(o)}-${p}-id`;return i.instances[s]?x.UUID.uuid():s}function KO(o,p){let i="",n=null;if(o.parent){const c=p.get(o.parent);c&&(n=c)}let s="";return n&&(s=`${uA(se(n,p))}-`),i=`${s}${uA(se(o,p))}-id`,p.instances[i]?x.UUID.uuid():i}function jr(o,p,i="uuid"){return i==="semantic"?xwe(se(o,p),o.type,p):x.UUID.uuid()}const lTi=/^[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 NP(o){return typeof o=="string"&&lTi.test(o)}function oTi(o){return o instanceof Error&&o.name==="ZodError"&&"issues"in o&&Array.isArray(o.issues)}var dTi=class extends Error{constructor(p,i){super(p,i);I(this,"name");I(this,"details");this.name="ZodValidationError",this.details=uTi(i)}toString(){return this.message}};function uTi(o){if(o){const p=o.cause;if(oTi(p))return p.issues}return[]}function pTi(o){return o.length!==0}function E4(o){return o.description??""}var cTi=/[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*/u;function fTi(o){if(o.length===1){let p=o[0];return typeof p=="symbol"&&(p=E4(p)),p.toString()||'""'}return o.reduce((p,i)=>{if(typeof i=="number")return p+"["+i.toString()+"]";if(typeof i=="symbol"&&(i=E4(i)),i.includes('"'))return p+'["'+yTi(i)+'"]';if(!cTi.test(i))return p+'["'+i+'"]';const n=p.length===0?"":".";return p+n+i},"")}function yTi(o){return o.replace(/"/g,'\\"')}var hTi="; ",mTi=99,$we="Validation error",TTi=": ",vTi=", or ";function ETi(o={}){const{issueSeparator:p=hTi,unionSeparator:i=vTi,prefixSeparator:n=TTi,prefix:s=$we,includePath:c=!0,maxIssuesInMessage:e=mTi}=o;return y=>{const m=y.slice(0,e).map(v=>kb({issue:v,issueSeparator:p,unionSeparator:i,includePath:c})).join(p);return bTi(m,s,n)}}function kb(o){const{issue:p,issueSeparator:i,unionSeparator:n,includePath:s}=o;if(p.code===rt.invalid_union)return p.unionErrors.reduce((c,e)=>{const y=e.issues.map(m=>kb({issue:m,issueSeparator:i,unionSeparator:n,includePath:s})).join(i);return c.includes(y)||c.push(y),c},[]).join(n);if(p.code===rt.invalid_arguments)return[p.message,...p.argumentsError.issues.map(c=>kb({issue:c,issueSeparator:i,unionSeparator:n,includePath:s}))].join(i);if(p.code===rt.invalid_return_type)return[p.message,...p.returnTypeError.issues.map(c=>kb({issue:c,issueSeparator:i,unionSeparator:n,includePath:s}))].join(i);if(s&&pTi(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 "${fTi(p.path)}"`}return p.message}function bTi(o,p,i){return p!==null?o.length>0?[p,o].join(i):p:o.length>0?o:$we}function ATi(o,p={}){const n=gTi(p)([o]);return new dTi(n,{cause:new _o([o])})}function gTi(o){return"messageBuilder"in o?o.messageBuilder:ETi(o)}async function Lwe(o,p={}){var c;const i=J.YieldTracker.from(p),n=[...Rs(o)];await i.tick();const s=Mt(o.errors,n);return await((c=o.dataType)==null?void 0:c.validateAsync({tracker:i})),s}function Mwe(o){var i;(i=o.dataType)==null||i.validate();const p=[...Rs(o)];return Mt(o.errors,p)}const ITi=Object.freeze(Object.defineProperty({__proto__:null,validate:Mwe,validateAsync:Lwe},Symbol.toStringTag,{value:"Module"}));function Bwe(o){return o.listAdded.forEach(p=>{const i=o.project.get(p.id);(i==null?void 0:i.type)===d.DefinitionEntity&&i.parent.type!==d.DataType&&(o.project.emit(zt.EXPLICIT_DEFINITION_ENTITY_ADDED,i,o),Wi(i,Re.PERSISTED_ENTITY)?o.project.emit(zt.PERSISTED_DEFINITION_ENTITY_ADDED,i,o):Wi(i,Re.RELATIONAL_DATABASE)&&o.project.emit(zt.RELATIONAL_DATABASE_DEFINITION_ENTITY_ADDED,i,o))}),o.listUpdated.forEach(p=>{const i=o.project.get(p.id);(i==null?void 0:i.type)===d.DefinitionEntity&&i.parent.type!==d.DataType&&(o.project.emit(zt.EXPLICIT_DEFINITION_ENTITY_UPDATED,i,o),Wi(i,Re.PERSISTED_ENTITY)?o.project.emit(zt.PERSISTED_DEFINITION_ENTITY_UPDATED,i,o):Wi(i,Re.RELATIONAL_DATABASE)&&o.project.emit(zt.RELATIONAL_DATABASE_DEFINITION_ENTITY_UPDATED,i,o))}),o.listRemoved.forEach(p=>{const i=o.project.get(p.id)||o.project.getDeleted(p.id);(i==null?void 0:i.type)===d.DefinitionEntity&&i.parent.type!==d.DataType&&(o.project.emit(zt.EXPLICIT_DEFINITION_ENTITY_REMOVED,i,o),Wi(i,Re.PERSISTED_ENTITY)?o.project.emit(zt.PERSISTED_DEFINITION_ENTITY_REMOVED,i,o):Wi(i,Re.RELATIONAL_DATABASE)&&o.project.emit(zt.RELATIONAL_DATABASE_DEFINITION_ENTITY_REMOVED,i,o))}),o}async function Gwe(o,p={}){const i=J.YieldTracker.from(p),n=[];for(const s of o.listAdded){const c=o.project.get(s.id);(c==null?void 0:c.type)===d.DefinitionEntity&&c.parent.type!==d.DataType&&(n.push(o.project.emitAsync(zt.EXPLICIT_DEFINITION_ENTITY_ADDED,c,o)),Wi(c,Re.PERSISTED_ENTITY)?n.push(o.project.emitAsync(zt.PERSISTED_DEFINITION_ENTITY_ADDED,c,o)):Wi(c,Re.RELATIONAL_DATABASE)&&n.push(o.project.emitAsync(zt.RELATIONAL_DATABASE_DEFINITION_ENTITY_ADDED,c,o))),await i.tick()}for(const s of o.listUpdated){const c=o.project.get(s.id);(c==null?void 0:c.type)===d.DefinitionEntity&&c.parent.type!==d.DataType&&(n.push(o.project.emitAsync(zt.EXPLICIT_DEFINITION_ENTITY_UPDATED,c,o)),Wi(c,Re.PERSISTED_ENTITY)?n.push(o.project.emitAsync(zt.PERSISTED_DEFINITION_ENTITY_UPDATED,c,o)):Wi(c,Re.RELATIONAL_DATABASE)&&n.push(o.project.emitAsync(zt.RELATIONAL_DATABASE_DEFINITION_ENTITY_UPDATED,c,o))),await i.tick()}for(const s of o.listRemoved){const c=o.project.get(s.id)||o.project.getDeleted(s.id);(c==null?void 0:c.type)===d.DefinitionEntity&&c.parent.type!==d.DataType&&(n.push(o.project.emitAsync(zt.EXPLICIT_DEFINITION_ENTITY_REMOVED,c,o)),Wi(c,Re.PERSISTED_ENTITY)?n.push(o.project.emitAsync(zt.PERSISTED_DEFINITION_ENTITY_REMOVED,c,o)):Wi(c,Re.RELATIONAL_DATABASE)&&n.push(o.project.emitAsync(zt.RELATIONAL_DATABASE_DEFINITION_ENTITY_REMOVED,c,o))),await i.tick()}return await Promise.all(n),o}var UI=(o=>(o.Manual="manual",o.Automatic="automatic",o))(UI||{}),H=(o=>(o.Added="added",o.Updated="updated",o.Removed="removed",o.Affected="affected",o))(H||{}),_=(o=>(o.AddSuccessCall="add-success-call",o.AddErrorCall="add-error-call",o.AddCall="add-call",o.SetParent="set-parent",o.SetStandaloneParent="set-standalone-parent",o.AfterAllChildrenInitialized="after-all-children-initialized",o.UpdateWithShallowTransfer="update-with-shallow-transfer",o.RemoveFromParent="remove-from-parent",o.RemoveEntity="remove-entity",o.RestoreEntity="restore-entity",o.CloneEntity="clone-entity",o.AddInput="add-input",o.RemoveInput="remove-input",o.SetDataType="set-data-type",o.RemoveDataType="remove-data-type",o.SetAdditionalPropertiesDataType="set-additional-properties-data-type",o.RemoveAdditionalPropertiesDataType="remove-additional-properties-data-type",o.SetAllPropertiesImplement="set-all-properties-implement",o.RemoveAllPropertiesImplement="remove-all-properties-implement",o.RemoveValueReader="remove-value-reader",o.AddValueReader="add-value-reader",o.RemoveValueWriter="remove-value-writer",o.SetValueWriter="set-value-writer",o.AddEntryCaller="add-entry-caller",o.AddSuccessCaller="add-success-caller",o.AddErrorCaller="add-error-caller",o.RemoveCall="remove-call",o.RemoveCaller="remove-caller",o.RemoveChildGroup="remove-child-group",o.AddToAndGroup="add-to-and-group",o.AddToOrGroup="add-to-or-group",o.RemoveUnrecognizedInputs="remove-unrecognized-inputs",o.RemoveUnrecognizedOutputs="remove-unrecognized-outputs",o.SyncInputs="sync-inputs",o.SyncOutputs="sync-outputs",o.SetImplements="set-implements",o.SetExtends="set-extends",o.SetExtension="set-extension",o.AddImplementation="add-implementation",o.RemoveImplementation="remove-implementation",o.AddProperty="add-property",o.RemoveProperty="remove-property",o.AddMethod="add-method",o.RemoveMethod="remove-method",o.AddAbstractMethod="add-abstract-method",o.RemoveAbstractMethod="remove-abstract-method",o.SetValueAsTypeSingle="set-value-as-type-single",o.SetValueAsTypeList="set-value-as-type-list",o.SetValueAsType="set-value-as-type",o.RemoveErrorCatching="remove-error-catching",o.RemoveAllErrorCallers="remove-all-error-callers",o.RemoveAllSuccessCallers="remove-all-success-callers",o.RemoveAllCallers="remove-all-callers",o.RemoveAllErrorCalls="remove-all-error-calls",o.SetDataTypeEntityValue="set-data-type-entity-value",o.MergeDataTypes="merge-data-types",o.SetDataTypeForeignKeyRef="set-data-type-foreign-key-ref",o.SetErrorEntity="set-error-entity",o.AddValueAsTypeToList="add-value-as-type-to-list",o.RemoveValueAsTypeFromList="remove-value-as-type-from-list",o))(_||{}),Ii=(o=>(o.ActionOwnerEntityNotEditable="action-owner-entity-not-editable",o.ActionCounterpartEntityNotEditable="action-counterpart-entity-not-editable",o.ActionOwnerEntityNonDeletable="action-owner-entity-non-deletable",o.GlobalVariableDeclarationCannnotCatchError="global-variable-declaration-cannot-catch-error",o.GlobalVariableDeclarationCannotReadValue="global-variable-declaration-cannot-read-value",o.GlobalVariableDeclarationCannotBeCalled="global-variable-declaration-cannot-be-called",o.GlobalVariableDeclarationCannotCallFromError="global-variable-declaration-cannot-call-from-error",o.ValueReadingOverridesConstantProperty="value-reading-overrides-constant-property",o.DefaultValueOverridesConstantProperty="default-value-overrides-constant-property",o.ValueReadingOverridesConstantVariable="value-reading-overrides-constant-variable",o.DefaultValueOverridesConstantVariable="default-value-overrides-constant-variable",o))(Ii||{});class kwe{constructor({id:p,action:i,errorReason:n,owner:s,counterpart:c,rootAction:e},y){I(this,"id");I(this,"action");I(this,"errorReason");I(this,"owner",null);I(this,"counterpart",null);I(this,"rootAction",!1);I(this,"parent");this.id=p,this.action=i,this.errorReason=n||null,this.owner=s||null,this.counterpart=c||null,this.rootAction=e||!1,this.parent=y}}class Z extends J.Events{constructor(i,n,s,c,e=!1,y=""){super(y?y+"-cs-events":"anonymous-cs-events");I(this,"id",x.UUID.uuid());I(this,"seenEntities",[]);I(this,"added",{});I(this,"updated",{});I(this,"removed",{});I(this,"affected",{});I(this,"self",null);I(this,"author");I(this,"timestamp");I(this,"open",!0);I(this,"startedClose",!1);I(this,"dirty",!0);I(this,"submitting",!1);I(this,"lockedVersions",!1);I(this,"type","manual");I(this,"autoclose",!1);I(this,"autoCloseActionName","");I(this,"project");I(this,"events",new Map);I(this,"ignoreNonEditable",!1);I(this,"ignoreNonDeletable",!1);I(this,"logger");if(this.project=i,this.author=n||x.sessionAuthor||"",this.timestamp=s,this.self=c,this.autoclose=e,this.autoCloseActionName=y,this.logger=J.Logger.module("cs:"+(this.autoCloseActionName?this.autoCloseActionName+":":"")+this.id),this.autoclose&&!this.autoCloseActionName)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 n=new kwe(i,this);this.events.set(i.id,n),this.emit("change-set-event",n)}discardOrphans(){this.added[this.project.id]&&(this.updatedIds.forEach(e=>{const y=this.updated[e];this.added[e]=y,delete this.updated[e]}),this.removedIds.forEach(e=>{this.remove(e)}));const i=[...this.addedIds,...this.updatedIds],s=this.project.toFlatIds().filter(e=>!this.project.diggestedBuiltInBaseEntitiesIds.has(e));if(i.filter(e=>!s.includes(e)).forEach(e=>{const y=this.get(e);this.logger.warn(`[discardOrphans] Entity ${y==null?void 0:y.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 n=J.YieldTracker.from(i),s=this.project.toFlatIds();if(this.added[this.project.id]){for(const m of this.updatedIds){const v=this.updated[m];this.added[m]=v,delete this.updated[m],await n.tick()}for(const m of this.removedIds)this.remove(m),await n.tick()}const c=[...this.addedIds,...this.updatedIds],e=s.filter(m=>!this.project.diggestedBuiltInBaseEntitiesIds.has(m)),y=c.filter(m=>!e.includes(m));for(const m of y){const v=this.get(m);this.logger.warn(`[discardOrphansAsync] Entity ${v==null?void 0:v.type} with id "${m}" present in change-set but not in project. Removing from change-set.`),this.remove(m),await n.tick()}if(this.added[this.project.id]){const m=[...this.addedIds,...this.updatedIds],E=s.filter(b=>!this.project.diggestedBuiltInBaseEntitiesIds.has(b)).filter(b=>!m.includes(b));for(const b of E){const w=this.project.get(b);this.add(w,"added"),await n.tick()}}}captureAllChangesInVersionInstances(){[...this.addedIds,...this.updatedIds].forEach(n=>{const s=this.project.get(n);if(!s){const e=this.added[n],y=this.updated[n],m=e||y;throw new Error(`Entity ${(m==null?void 0:m.type)||"of unknown type"} with id "${n}" was ${e?"added":"updated"} but isn't found in the project state when capturing version for change-set.`)}const c=this.get(n);s.version===c.version&&s.captureVersion()}),this.removedIds.forEach(n=>{const s=this.project.getDeleted(n);if(!s){const e=this.removed[n];throw new Error(`Entity ${(e==null?void 0:e.type)||"of unknown type"} with id "${n}" was removed but isn't found in the project state when capturing version for change-set.`)}const c=this.get(n);s.version===c.version&&s.captureVersion()})}async captureAllChangesInVersionInstancesAsync(i={}){const n=J.YieldTracker.from(i),s=[...this.addedIds,...this.updatedIds];for(const c of s){const e=this.project.get(c);if(!e){const m=this.added[c],v=this.updated[c],E=m||v;throw new Error(`Entity ${(E==null?void 0:E.type)||"of unknown type"} with id "${c}" was ${m?"added":"updated"} but isn't found in the project state when capturing version for change-set.`)}const y=this.get(c);e.version===y.version&&e.captureVersion(),await n.tick()}for(const c of this.removedIds){const e=this.project.getDeleted(c);if(!e){const m=this.removed[c];throw new Error(`Entity ${(m==null?void 0:m.type)||"of unknown type"} with id "${c}" was removed but isn't found in the project state when capturing version for change-set.`)}const y=this.get(c);e.version===y.version&&e.captureVersion(),await n.tick()}}async attemptAutocloseAsync(i,n){var s;return this.autoclose&&this.autoCloseActionName&&this.autoCloseActionName===i&&(this.self&&n===((s=this.self)==null?void 0:s.id)||!this.self)&&await this.closeAsync(),this}async closeAsync(i={}){const n=J.YieldTracker.from(i),s={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:n}):this.beforeCloseAsync({tracker:n})),!this.isValid&&this.self&&!this.added[this.self.id]&&!this.updated[this.self.id]&&this.removed[this.self.id],await this.discardOrphansAsync({tracker:n}),await this.sanitizeAsync({tracker:n}),await this.recursiveCaptureUpstreamVersionsAsync({tracker:n}),this.lockedVersions||(await this.captureAllChangesInVersionInstancesAsync({tracker:n}),await this.recursiveCaptureUpstreamVersionsAsync({tracker:n})),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(zt.CHANGE_SET_CLOSED_BEFORE_PERSIST,this),e?s.persistType==="parallel"?await this.project.persistChangeSetInParallel(this):await this.project.persistChangeSetSequentially(this):s.persistType==="parallel"?this.project.persistChangeSetInParallel(this):this.project.persistChangeSetSequentially(this),this.destroy(),this)}attemptAutoclose(i,n){var s;return this.autoclose&&this.autoCloseActionName&&this.autoCloseActionName===i&&(this.self&&n===((s=this.self)==null?void 0:s.id)||!this.self)&&this.close(),this}recursiveCaptureUpstreamVersions(){if(this.lockedVersions)return;[...this.addedIds,...this.updatedIds,...this.removedIds].forEach(n=>{const s=this.get(n),{added:c,updated:e,removed:y,affected:m}=s.recursiveCaptureUpstreamVersions(this.timestamp);for(const v of c)this.add(v,"added");for(const v of e)this.add(v,"updated");for(const v of y)this.add(v,"removed");for(const v of m)this.add(v,"affected")})}async recursiveCaptureUpstreamVersionsAsync(i={}){if(this.lockedVersions)return;const n=J.YieldTracker.from(i),s=[...this.addedIds,...this.updatedIds,...this.removedIds];for await(const c of s){const e=this.get(c),{added:y,updated:m,removed:v,affected:E}=e.recursiveCaptureUpstreamVersions(this.timestamp);for(const b of y)this.add(b,"added");for(const b of m)this.add(b,"updated");for(const b of v)this.add(b,"removed");for(const b of E)this.add(b,"affected");await n.tick()}}sanitize(){this.listAdded.forEach(i=>{i.previousVersion=null})}async sanitizeAsync(i={}){const n=J.YieldTracker.from(i);for(const s of this.listAdded)s.previousVersion=null,await n.tick()}syncDependents(){return[...this.list,...this.listAffected].forEach(i=>{const n=this.project.get(i.id);!n||n.deleted||rA(n,this.project)||n==null||n.syncDependents(this)}),this}async syncDependentsAsync(i={}){const n=J.YieldTracker.from(i);for(const s of[...this.list,...this.listAffected]){const c=this.project.get(s.id);!c||c.deleted||rA(c,this.project)||(c==null||c.syncDependents(this),await n.tick())}return this}async beforeCloseAsync(i={}){const n=J.YieldTracker.from(i);await this.project.emitAsync(zt.BEFORE_CHANGE_SET_CLOSE_BEFORE_SIDE_EFFECTS,this),await this.syncDependentsAsync({tracker:n}),await this.emitAsyncProjectSideEffects({tracker:n}),await this.project.emitAsync(zt.BEFORE_CHANGE_SET_CLOSE_AFTER_SIDE_EFFECTS,this),this.teardown()}beforeClose(){this.project.emit(zt.BEFORE_CHANGE_SET_CLOSE_BEFORE_SIDE_EFFECTS,this),this.syncDependents(),this.emitProjectSideEffects(),this.project.emit(zt.BEFORE_CHANGE_SET_CLOSE_AFTER_SIDE_EFFECTS,this),this.teardown()}teardown(){this.destroy()}emitProjectSideEffects(){return Bwe(this)}async emitAsyncProjectSideEffects(i={}){return Gwe(this,i)}close(i={}){const n={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(zt.CHANGE_SET_CLOSED_BEFORE_PERSIST,this),n.persistType==="parallel"?this.project.persistChangeSetInParallel(this):this.project.persistChangeSetSequentially(this),this.destroy(),this}addDependentsToAffected(i){Object.values(i.detachedDependents).forEach(n=>{const{entity:s,field:c}=n;this.has(s.id)||this.add(s,"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(n=>n!==i)),this}add(i,n,s={preventRecursion:!1}){var e,y,m;if(!this.open||!this.dirty)return this;if(rA(i,this.project))return this;if(this.seenEntities.indexOf(i.id)===-1&&this.seenEntities.push(i.id),n==="removed"){if(this.added[i.id])return delete this.added[i.id],this.seenEntities=this.seenEntities.filter(E=>E!==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),!s.preventRecursion)){const{added:E,updated:b,removed:w,affected:V}=i.recursiveCaptureUpstreamVersions(this.timestamp);for(const $ of E)this.add($,"added");for(const $ of b)this.add($,"updated");for(const $ of w)this.add($,"removed");for(const $ of V)this.add($,"affected")}i.captureVersion();const v=(e=i.knownVersions)==null?void 0:e.get(i.version);if(!v)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]=v,this}if(n==="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&&!s.preventRecursion){const{added:E,updated:b,removed:w,affected:V}=i.recursiveCaptureUpstreamVersions(this.timestamp);for(const $ of E)this.add($,"added");for(const $ of b)this.add($,"updated");for(const $ of w)this.add($,"removed");for(const $ of V)this.add($,"affected")}i.previousVersion=null,i.captureVersion();const v=(y=i.knownVersions)==null?void 0:y.get(i.version);if(!v)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]=v,delete this.affected[i.id],this.addDependentsToAffected(i),this}if(n==="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),!s.preventRecursion)){const{added:E,updated:b,removed:w,affected:V}=i.recursiveCaptureUpstreamVersions(this.timestamp);for(const $ of E)this.add($,"added");for(const $ of b)this.add($,"updated");for(const $ of w)this.add($,"removed");for(const $ of V)this.add($,"affected")}i.captureVersion();const v=(m=i.knownVersions)==null?void 0:m.get(i.version);if(!v)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]=v,this.addDependentsToAffected(i),this}if(n==="affected"){if(this.removed[i.id])return this;if(this.added[i.id])return this;if(this.updated[i.id])return this;this.affected[i.id]=i}return this}toJSON(){var y;const i={},n={},s={},c=new Set;for(const m of Object.values(this.added))i[m.id]=m.toShallowJSON();for(const m of Object.values(this.updated))n[m.id]=m.toShallowJSON();for(const m of Object.values(this.removed))s[m.id]=m.toShallowJSON();for(const m of Object.values(this.affected))c.add(m.id);const e=this.get(((y=this.self)==null?void 0:y.id)||"");return{added:i,updated:n,removed:s,affected:Array.from(c),self:e?e.toShallowJSON():null,seenEntities:this.seenEntities}}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 RTi(o){return new Set([...Object.keys(o.added),...Object.keys(o.updated),...Object.keys(o.removed),...Array.from(o.affected)])}function FO(o,p,i){var y;const n=new Date().toISOString(),s=new Z(i,x.sessionAuthor,n,i);if(s.lockedVersions=!0,o===p)throw J.Logger.error("From: ",o),J.Logger.error("To: ",p),new Error("Cannot generate transitional change set between the same two versions or change-sets");let c;if(o==="initial"?c=!0:p==="initial"?c=!1:M(o.timestamp).isBefore(M(p.timestamp))?c=!0:c=!1,J.Logger.log("Transitioning from ",o==="initial"?"initial":o.index),J.Logger.log("Transitioning to ",p==="initial"?"initial":p.index),J.Logger.log("Is forward: ",c),c){const v=p.index,E=o==="initial"?0:o.index;J.Logger.log("ownIndex: ",v),J.Logger.log("startIndex: ",E);const b=v===E?[i.history[v]]:i.history.slice(E+1,v+1);if(b.sort((w,V)=>M(w.timestamp).isAfter(M(V.timestamp))?1:-1),!b.length)throw new Error("No change sets in the history between the history indexes provided");J.Logger.log("REDO change-set: ",b[0].id," ",b[0].timestamp),b.forEach(w=>{SO(w,V=>{const $=i.instances[V.id]||i.deletedInstances[V.id];let L="";try{L=se(V,i)}catch{}if(!$)throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" doesn't have an 'activeVersion' set.`);if(!$.knownVersions)throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" has an active version instance missing the 'knownVersions' property value.`);if(!$.knownVersions.get(V.version))throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" has an active version instance missing the 'knownVersions' property value for version "${V.version}".`);$.restoreVersion(V.version),s.timestamp=$.createdAt,s.add($,H.Added,{preventRecursion:!0})},V=>{const $=i.instances[V.id]||i.deletedInstances[V.id];let L="";try{L=se(V,i)}catch{}if(!$)throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" doesn't have an 'activeVersion' set.`);if(!$.knownVersions)throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" has an active version instance missing the 'knownVersions' property value.`);if(!$.knownVersions.get(V.version))throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" has an active version instance missing the 'knownVersions' property value for version "${V.version}".`);$.restoreVersion(V.version),s.timestamp=$.createdAt,s.add($,H.Updated,{preventRecursion:!0})},V=>{const $=i.instances[V.id]||i.deletedInstances[V.id];let L="";try{L=se(V,i)}catch{}if(!$)throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" doesn't have an 'activeVersion' set.`);if(!$.knownVersions)throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" has an active version instance missing the 'knownVersions' property value.`);if(!$.knownVersions.get(V.version))throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" has an active version instance missing the 'knownVersions' property value for version "${V.version}".`);$.restoreVersion(V.version),s.timestamp=$.createdAt,s.add($,H.Removed,{preventRecursion:!0})})})}else{const v=o.index,E=p==="initial"?0:p.index,b=v===E?[i.history[v]]:i.history.slice(E+1,v+1);if(b.sort((w,V)=>M(V.timestamp).isAfter(M(w.timestamp))?1:-1),!b.length)throw new Error("No change sets in the history between the history indexes provided");J.Logger.log("UNDO change-set: ",b[0].id," ",b[0].timestamp),b.forEach(w=>{SO(w,V=>{const $=i.instances[V.id]||i.deletedInstances[V.id];let L="";try{L=se(V,i)}catch{}if(!$)throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" doesn't have an 'activeVersion' set.`);if(!$.knownVersions)throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" has an active version instance missing the 'knownVersions' property value.`);if(!$.knownVersions.get(V.version))throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" has an active version instance missing the 'knownVersions' property value for version "${V.version}".`);V.previousVersion&&$.restoreVersion(V.previousVersion),s.timestamp=$.createdAt,s.add($,H.Removed,{preventRecursion:!0})},V=>{const $=i.instances[V.id]||i.deletedInstances[V.id];let L="";try{L=se(V,i)}catch{}if(!$)throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" doesn't have an 'activeVersion' set.`);if(!$.knownVersions)throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" has an active version instance missing the 'knownVersions' property value.`);if(!$.knownVersions.get(V.version))throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" has an active version instance missing the 'knownVersions' property value for version "${V.version}".`);$.restoreVersion(V.previousVersion),s.timestamp=$.createdAt,s.add($,H.Updated,{preventRecursion:!0})},V=>{const $=i.instances[V.id]||i.deletedInstances[V.id];let L="";try{L=se(V,i)}catch{}if(!$)throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" doesn't have an 'activeVersion' set.`);if(!$.knownVersions)throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" has an active version instance missing the 'knownVersions' property value.`);if(!$.knownVersions.get(V.version))throw new Error(`Entity ${V.type} ${L?`"${L}" `:""}with id "${V.id}" has an active version instance missing the 'knownVersions' property value for version "${V.version}".`);$.restoreVersion(V.previousVersion),s.timestamp=$.createdAt,s.add($,H.Added,{preventRecursion:!0})})})}let e;if(p==="initial"){const m=Array.from(((y=i.knownVersions)==null?void 0:y.values())||[]).reduce((v,E)=>!v||M(E.createdAt).isBefore(M(v.createdAt))?E:v,null);if(!m)throw new Error("No oldest version found");e=m.createdAt}else e=p.timestamp;return s.open=!1,{transitionalChangeSet:s,transitionTime:n,timeOfOriginalTargetChanges:e}}function SO(o,p,i,n){var y;if(!(o!=null&&o.self))throw new Error("Change set must have a valid `self` entity state to be traversed");const s=((y=o.self)==null?void 0:y.type)===d.Project?o.self:o.self.project,c=new Nn(o.self,{allBuiltInEntityIds:s.diggestedBuiltInBaseEntitiesIds});J.Logger.log("changeSet.added: ",Object.keys(o.added).length),J.Logger.log("changeSet.updated: ",Object.keys(o.updated).length),J.Logger.log("changeSet.removed: ",Object.keys(o.removed).length);const e={...o.added,...o.updated,...o.removed};c.order=Object.keys(e),c.flatRecord=e,c.orderEntities(),J.Logger.log("All entities: ",c.order.map((m,v)=>`${v+1}: ${e[m].type} - ${m}`).join(`,
7
7
  `)),J.Logger.log("Traversing new additions"),c.visit(async m=>{if(o.added[m.id])try{J.Logger.log("Adding: ",m.id),p(m)}catch(v){J.Logger.error("Error: ",v),J.Logger.error("Errored entity: ",m)}}),J.Logger.log("Traversing updates"),c.visit(async m=>{if(o.updated[m.id])try{J.Logger.log("Updating: ",m.id),i(m)}catch(v){J.Logger.error("Error: ",v),J.Logger.error("Errored entity: ",m)}}),J.Logger.log("Traversing removals"),c.visit(async(m,v)=>{if(o.removed[m.id])try{J.Logger.log("Removing: ",m.id),n(m)}catch(E){J.Logger.error("Error: ",E),J.Logger.error("Errored entity: ",m)}})}function qO(o,p,i){const n=o+1;return p.splice(n,p.length-n,i),p.length-1}function DTi(o){[...o.listUpdated,...o.listAdded].forEach(p=>{const i=o.project.get(p.id);i.editable=!0})}function wTi(o){[...o.listUpdated,...o.listAdded].forEach(p=>{const i=o.project.get(p.id);i.deletable=!0})}function OTi(o){[...o.listUpdated,...o.listAdded].forEach(p=>{const i=o.project.get(p.id);i.editable=!0,i.deletable=!0})}function CTi(o){[...o.listUpdated,...o.listAdded].forEach(p=>{const i=o.project.get(p.id);i.editable=!1})}function _Ti(o){[...o.listUpdated,...o.listAdded].forEach(p=>{const i=o.project.get(p.id);i.deletable=!1})}function VTi(o){[...o.listUpdated,...o.listAdded].forEach(p=>{const i=o.project.get(p.id);i.editable=!1,i.deletable=!1})}function PTi(o,p){p?o.metaSync({editable:!1,deletable:!1},p):(o.editable=!1,o.deletable=!1),Me(o,new Set,{ignoreBuiltInBaseEntities:!0}).forEach(n=>{p?n.metaSync({editable:!1,deletable:!1},p):(n.editable=!1,n.deletable=!1)})}function NTi(o,p){p?o.metaSync({editable:!0,deletable:!0},p):(o.editable=!0,o.deletable=!0),Me(o,new Set,{ignoreBuiltInBaseEntities:!0}).forEach(n=>{p?n.metaSync({editable:!0,deletable:!0},p):(n.editable=!0,n.deletable=!0)})}function xTi(o){const{projectRecord:p,chain:i,projectId:n,sort:s,order:c}=o,e=s?(i||[]).sort((E,b)=>{const w=E.updated[n],V=b.updated[n];return M(w.createdAt).valueOf()-M(V.createdAt).valueOf()}):i||[],y={...p};e.forEach(E=>{Object.values(E.removed).forEach(w=>{delete y[w.id]}),Object.values(E.added).forEach(w=>{y[w.id]=w}),Object.values(E.updated).forEach(w=>{y[w.id]=w});const b=E.updated[n];y[n]=b});let m=null;if(c){const E=new Nn;E.flatRecord=y,E.orderEntities(),m=E.order}return{project:y[n],record:y,order:m}}class xP{constructor(p){I(this,"version");I(this,"previousVersion");I(this,"createdAt");I(this,"deleted",!1);I(this,"author");this.version=p.version,this.previousVersion=p.previousVersion,this.createdAt=M(p.createdAt).toISOString(),this.deleted=p.deleted,this.author=p.author}baseMetaSync(p,i,n){this.deleted=p.deleted!==void 0?p.deleted:this.deleted}}class Ur extends xP{constructor(i){super(i);I(this,"deletable",!0);I(this,"editable",!0);this.deletable=i.deletable,this.editable=i.editable}checkCanEditWithCounterpartAndSideEffects(i,n,s,c){var e,y;return!this.checkCanEdit(i,c)||!this.checkCanEdit(n,c)?(this.checkCanEdit(n,c)?(J.Logger.warn(`[${s}] User is not allowed to edit this ${i.type} entity with id: ${i.id}`),c==null||c.event({id:`${s}-${i.id}--${n.id}`,action:s,owner:i,counterpart:n,errorReason:Ii.ActionOwnerEntityNotEditable,rootAction:((y=c==null?void 0:c.self)==null?void 0:y.id)===i.id&&(c==null?void 0:c.autoCloseActionName)===s})):(J.Logger.warn(`[${s}] User is not allowed to edit this ${i.type} entity with id: ${i.id} because its counterpart ${n.type} with id: ${n.id} is not editable`),c==null||c.event({id:`${s}-${i.id}--${n.id}`,action:s,owner:i,counterpart:n,errorReason:Ii.ActionCounterpartEntityNotEditable,rootAction:((e=c==null?void 0:c.self)==null?void 0:e.id)===i.id&&(c==null?void 0:c.autoCloseActionName)===s})),c==null||c.attemptAutoclose(s,i.id),!1):!0}checkCanEditFromScopeOwner(i,n){const s=cn(i,i.project);return s?this.checkCanEdit(s,n):!0}checkCanEditFromScopeOwnerWithSideEffects(i,n,s){var e;const c=this.checkCanEditFromScopeOwner(i,s);return!c&&!(s!=null&&s.ignoreNonEditable)&&(J.Logger.warn(`[${n}] User is not allowed to edit this ${i.type} entity with id: ${i.id}`),s==null||s.event({id:`${n}-${i.id}`,action:n,owner:i,errorReason:Ii.ActionOwnerEntityNotEditable,rootAction:((e=s==null?void 0:s.self)==null?void 0:e.id)===i.id&&(s==null?void 0:s.autoCloseActionName)===n}),s==null||s.attemptAutoclose(n,i.id)),c}checkCanEdit(i,n){var s;return(s=i.project)!=null&&s.initialized?i.type===d.BuiltInBaseEntity||i.type===d.PrimitiveEntity?!1:i.initialized?!(i.project.diggestedBuiltInBaseEntitiesIds.has(i.id)||i.parent&&!(this.checkCanEdit(i.parent,n)&&i.editable)&&!(n!=null&&n.ignoreNonEditable)||!i.editable&&!(n!=null&&n.ignoreNonEditable)):!0:!0}checkCanDelete(i,n){var s;return i.type!==d.Project&&i.project.diggestedBuiltInBaseEntitiesIds.has(i.id)?!1:i.type===d.Project||(s=i.parent)!=null&&s.deleted?!0:!(!i.deletable&&!(n!=null&&n.ignoreNonDeletable))}baseMetaSync(i,n,s){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(n,s)?i.deleted:!1};super.baseMetaSync(c,n,s)}}var jwe=(o=>(o.ArgumentDataTypeEntityField="data-type-entity-field",o.ArgumentDataTypeField="data-type-field",o.ArgumentImplementsField="argument-implements-field",o))(jwe||{});const di=class di extends Ur{constructor(i,n){super(i);I(this,"initialData");I(this,"id");I(this,"name");I(this,"codeName",null);I(this,"description",null);I(this,"index");I(this,"required");I(this,"constant",!0);I(this,"type",d.ArgumentDeclaration);I(this,"defaultValue",null);I(this,"dataType",null);I(this,"writesValues",[]);I(this,"implements",[]);I(this,"project");I(this,"errors",[]);I(this,"parent");I(this,"detachedDependents",{});I(this,"knownVersions",null);I(this,"activeVersion",!1);I(this,"initialized",!1);I(this,"startedInitialization",!1);I(this,"suggestion",!1);I(this,"_codeNativeValueValidation",null);this.initialData=i,this.project=n,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)||M().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,n){const s=ne(i.parent),c=n.get(s),e={id:i.id,version:x.UUID.uuid(),createdAt:M().toISOString(),author:x.sessionAuthor,previousVersion:null,deleted:!1,name:i.name,deletable:!0,editable:!0,type:d.ArgumentDeclaration,index:c.inputs.length,defaultValue:null,codeName:i.codeName||null,description:i.description||null,required:i.required,constant:!0,implements:[],dataType:null,writesValues:[],parent:c},y=me(e,n);return y.setParent(c,null),y}static validateGenerationTarget(i,n){let s=JSON.parse(JSON.stringify(i));const c=[],e=bn(s,{parent:{list:!1,types:[d.FunctionDeclaration,d.Search,d.Condition]}},n);s=e.modifiedData;const y=VP(s,n);if(s.parent){const m=n.get(ne(s.parent));if(m&&Yt.includes(m.type)){const v=m.implements;if(v){const E=v.inputs.find(k=>k.name===s.name),b=v.inputs.filter(k=>!m.inputs.find(S=>S.type===d.ArgumentDeclaration&&S.name===k.name)),w=m.inputs.filter(k=>k.type===d.ArgumentDeclaration),V=w.find(k=>k.name===s.name),$=w.length?`The parent entity already implements the following arguments: ${wt(w.map(k=>`'${k.id}' (${k.name})`),", "," and ")}.`:"The parent entity does not yet have any implemented arguments.",L=b.length?`The parent entity is still missing the following arguments in the implementation: ${wt(b.map(k=>`'${k.id}' (${k.name})`),", "," and ")}.`:"The parent entity has all the arguments it needs implemented.";E?V&&c.push(new De({id:`${s.id}--${Ie.NoOverlapWithImplementedSignature}`,code:Ie.NoOverlapWithImplementedSignature,severity:ce.Error,message:`Entity of type '${d.ArgumentDeclaration}' with id '${s.id}' should not exist in a parent entity of type '${m.type}' with id '${m.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
  ${$}
package/dist/index.js CHANGED
@@ -80289,10 +80289,12 @@ class Z extends Zf {
80289
80289
  const n = Ke.from(i), s = [...this.addedIds, ...this.updatedIds];
80290
80290
  for (const c of s) {
80291
80291
  const e = this.project.get(c);
80292
- if (!e)
80292
+ if (!e) {
80293
+ const m = this.added[c], v = this.updated[c], b = m || v;
80293
80294
  throw new Error(
80294
- `Entity with id "${c}" not found in the project state when capturing version for change-set.`
80295
+ `Entity ${(b == null ? void 0 : b.type) || "of unknown type"} with id "${c}" was ${m ? "added" : "updated"} but isn't found in the project state when capturing version for change-set.`
80295
80296
  );
80297
+ }
80296
80298
  const y = this.get(c);
80297
80299
  e.version === y.version && e.captureVersion(), await n.tick();
80298
80300
  }
@@ -80300,10 +80302,12 @@ class Z extends Zf {
80300
80302
  const e = this.project.getDeleted(
80301
80303
  c
80302
80304
  );
80303
- if (!e)
80305
+ if (!e) {
80306
+ const m = this.removed[c];
80304
80307
  throw new Error(
80305
- `Entity with id "${c}" not found in the project state when capturing version for change-set.`
80308
+ `Entity ${(m == null ? void 0 : m.type) || "of unknown type"} with id "${c}" was removed but isn't found in the project state when capturing version for change-set.`
80306
80309
  );
80310
+ }
80307
80311
  const y = this.get(c);
80308
80312
  e.version === y.version && e.captureVersion(), await n.tick();
80309
80313
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@elyx-code/project-logic-tree",
3
- "version": "0.0.6746",
3
+ "version": "0.0.6747",
4
4
  "author": "Sergio Herrero",
5
5
  "license": "UNLICENSED",
6
6
  "description": "An installable module which contains the type definitions and ephemeral state management for a projects' logic tree data structure",