@memberjunction/graphql-dataprovider 2.128.0 → 2.129.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var fe=Object.defineProperty;var S=(E,e)=>fe(E,"name",{value:e,configurable:!0});var h,g=require("graphql-request"),u=require("@memberjunction/core"),ge=require("@memberjunction/core-entities"),Re=require("@tempfix/idb"),$=require("rxjs"),Ie=require("graphql-ws"),Ee=require("uuid"),w=require("@memberjunction/global");const j=class j{constructor(){this._fieldMap={__mj_CreatedAt:"_mj__CreatedAt",__mj_UpdatedAt:"_mj__UpdatedAt",__mj_DeletedAt:"_mj__DeletedAt"}}MapFields(e){if(e)for(const t in e)t in this._fieldMap&&(e[this._fieldMap[t]]=e[t],delete e[t]);return e}MapFieldName(e){return this._fieldMap[e]??e}ReverseMapFieldName(e){return Object.entries(this._fieldMap).find(([t,r])=>r===e)?.[0]??e}ReverseMapFields(e){const t=Object.fromEntries(Object.entries(this._fieldMap).map(([r,s])=>[s,r]));for(const r in e)r in t&&(e[t[r]]=e[r],delete e[r]);return e}};S(j,"FieldMapper");let v=j;const W=class W extends u.TransactionGroupBase{constructor(e){super(),this._provider=e}async HandleSubmit(){const e=g.gql`
1
+ "use strict";var Re=Object.defineProperty;var S=(E,e)=>Re(E,"name",{value:e,configurable:!0});var m=require("graphql-request"),u=require("@memberjunction/core"),pe=require("@memberjunction/core-entities"),$=require("rxjs"),Ie=require("graphql-ws"),Ee=require("uuid"),w=require("@memberjunction/global"),De=require("@tempfix/idb");const W=class W{constructor(){this._fieldMap={__mj_CreatedAt:"_mj__CreatedAt",__mj_UpdatedAt:"_mj__UpdatedAt",__mj_DeletedAt:"_mj__DeletedAt"}}MapFields(e){if(e)for(const t in e)t in this._fieldMap&&(e[this._fieldMap[t]]=e[t],delete e[t]);return e}MapFieldName(e){return this._fieldMap[e]??e}ReverseMapFieldName(e){return Object.entries(this._fieldMap).find(([t,r])=>r===e)?.[0]??e}ReverseMapFields(e){const t=Object.fromEntries(Object.entries(this._fieldMap).map(([r,s])=>[s,r]));for(const r in e)r in t&&(e[t[r]]=e[r],delete e[r]);return e}};S(W,"FieldMapper");let C=W;const z=class z extends u.TransactionGroupBase{constructor(e){super(),this._provider=e}async HandleSubmit(){const e=m.gql`
2
2
  mutation ExecuteTransactionGroup($group: TransactionInputType!) {
3
3
  ExecuteTransactionGroup(group: $group) {
4
4
  Success
@@ -6,7 +6,7 @@
6
6
  ResultsJSON
7
7
  }
8
8
  }
9
- `,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const r={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const n=s.ExecuteTransactionGroup,o=[];for(let a=0;a<this.PendingTransactions.length;a++){const i=n.ResultsJSON[a],c=w.SafeJSONParse(i),p=this.PendingTransactions[a];o.push(new u.TransactionResult(p,c,c!==null))}return o}else throw new Error("Failed to execute transaction group")}};S(W,"GraphQLTransactionGroup");let N=W;const z=class z{constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=g.gql`
9
+ `,t=[];for(const a of this.PendingTransactions)t.push({EntityName:a.BaseEntity.EntityInfo.Name,EntityObjectJSON:await a.BaseEntity.GetDataObjectJSON(),OperationType:a.OperationType});const r={group:{Items:t,Variables:this.Variables.map(a=>({Name:a.Name,ItemIndex:this.MapVariableEntityObjectToPosition(a),FieldName:a.FieldName,Type:a.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const a=s.ExecuteTransactionGroup,o=[];for(let i=0;i<this.PendingTransactions.length;i++){const n=a.ResultsJSON[i],c=w.SafeJSONParse(n),p=this.PendingTransactions[i];o.push(new u.TransactionResult(p,c,c!==null))}return o}else throw new Error("Failed to execute transaction group")}};S(z,"GraphQLTransactionGroup");let v=z;const X=class X{constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=m.gql`
10
10
  mutation RunAIPrompt(
11
11
  $promptId: String!,
12
12
  $data: String,
@@ -65,7 +65,7 @@
65
65
  chatResult
66
66
  }
67
67
  }
68
- `,r=this.preparePromptVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(s)}catch(t){return this.handlePromptError(t)}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,n;try{t.parsedResult&&(r=JSON.parse(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(n=JSON.parse(t.chatResult))}catch{n=t.chatResult}return{success:t.success,output:t.output,parsedResult:r,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:s,chatResult:n}}handlePromptError(e){const t=e;return u.LogError(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){let s;try{e.onProgress&&(s=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(i=>{try{u.LogStatusEx({message:"[GraphQLAIClient] Received statusUpdate message",verboseOnly:!0,additionalArgs:[i]});const c=JSON.parse(i);if(u.LogStatusEx({message:"[GraphQLAIClient] Parsed message",verboseOnly:!0,additionalArgs:[c]}),c.resolver==="RunAIAgentResolver"&&c.type==="ExecutionProgress"&&c.status==="ok"&&c.data?.progress){u.LogStatusEx({message:"[GraphQLAIClient] Forwarding progress to callback",verboseOnly:!0,additionalArgs:[c.data.progress]});const p={...c.data.progress,metadata:{...c.data.progress.metadata||{},agentRunId:c.data.agentRunId}};e.onProgress(p)}else u.LogStatusEx({message:"[GraphQLAIClient] Message does not match filter criteria",verboseOnly:!0,additionalArgs:[{resolver:c.resolver,type:c.type,status:c.status,hasProgress:!!c.data?.progress}]})}catch(c){console.error("[GraphQLAIClient] Failed to parse progress message:",c,"Raw message:",i)}}));const n=g.gql`
68
+ `,r=this.preparePromptVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(s)}catch(t){return this.handlePromptError(t)}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,a;try{t.parsedResult&&(r=JSON.parse(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(a=JSON.parse(t.chatResult))}catch{a=t.chatResult}return{success:t.success,output:t.output,parsedResult:r,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:s,chatResult:a}}handlePromptError(e){const t=e;return u.LogError(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){let s;try{e.onProgress&&(s=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(n=>{try{u.LogStatusEx({message:"[GraphQLAIClient] Received statusUpdate message",verboseOnly:!0,additionalArgs:[n]});const c=JSON.parse(n);if(u.LogStatusEx({message:"[GraphQLAIClient] Parsed message",verboseOnly:!0,additionalArgs:[c]}),c.resolver==="RunAIAgentResolver"&&c.type==="ExecutionProgress"&&c.status==="ok"&&c.data?.progress){u.LogStatusEx({message:"[GraphQLAIClient] Forwarding progress to callback",verboseOnly:!0,additionalArgs:[c.data.progress]});const p={...c.data.progress,metadata:{...c.data.progress.metadata||{},agentRunId:c.data.agentRunId}};e.onProgress(p)}else u.LogStatusEx({message:"[GraphQLAIClient] Message does not match filter criteria",verboseOnly:!0,additionalArgs:[{resolver:c.resolver,type:c.type,status:c.status,hasProgress:!!c.data?.progress}]})}catch(c){console.error("[GraphQLAIClient] Failed to parse progress message:",c,"Raw message:",n)}}));const a=m.gql`
69
69
  mutation RunAIAgent(
70
70
  $agentId: String!,
71
71
  $messages: String!,
@@ -104,7 +104,7 @@
104
104
  result
105
105
  }
106
106
  }
107
- `,o=this.prepareAgentVariables(e,t,r),a=await this._dataProvider.ExecuteGQL(n,o);return this.processAgentResult(a.RunAIAgent?.result)}catch(n){return this.handleAgentError(n)}finally{s&&s.unsubscribe()}}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),t!==void 0&&(s.sourceArtifactId=t),r!==void 0&&(s.sourceArtifactVersionId=r),s}processAgentResult(e){return w.SafeJSONParse(e)}handleAgentError(e){const t=e;return u.LogError(`Error running AI agent: ${t}`),{success:!1,agentRun:void 0}}async ExecuteSimplePrompt(e){try{const t=g.gql`
107
+ `,o=this.prepareAgentVariables(e,t,r),i=await this._dataProvider.ExecuteGQL(a,o);return this.processAgentResult(i.RunAIAgent?.result)}catch(a){return this.handleAgentError(a)}finally{s&&s.unsubscribe()}}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),t!==void 0&&(s.sourceArtifactId=t),r!==void 0&&(s.sourceArtifactVersionId=r),s}processAgentResult(e){return w.SafeJSONParse(e)}handleAgentError(e){const t=e;return u.LogError(`Error running AI agent: ${t}`),{success:!1,agentRun:void 0}}async ExecuteSimplePrompt(e){try{const t=m.gql`
108
108
  mutation ExecuteSimplePrompt(
109
109
  $systemPrompt: String!,
110
110
  $messages: String,
@@ -127,7 +127,7 @@
127
127
  executionTimeMs
128
128
  }
129
129
  }
130
- `,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.ExecuteSimplePrompt)throw new Error("Invalid response from server");const n=s.ExecuteSimplePrompt;let o;if(n.resultObject)try{o=JSON.parse(n.resultObject)}catch{o=n.resultObject}return{success:n.success,result:n.result,resultObject:o,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){const r=t;return u.LogError(`Error executing simple prompt: ${r}`),{success:!1,modelName:"Unknown",error:r.message||"Unknown error occurred"}}}async EmbedText(e){try{const t=g.gql`
130
+ `,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.ExecuteSimplePrompt)throw new Error("Invalid response from server");const a=s.ExecuteSimplePrompt;let o;if(a.resultObject)try{o=JSON.parse(a.resultObject)}catch{o=a.resultObject}return{success:a.success,result:a.result,resultObject:o,modelName:a.modelName,error:a.error,executionTimeMs:a.executionTimeMs}}catch(t){const r=t;return u.LogError(`Error executing simple prompt: ${r}`),{success:!1,modelName:"Unknown",error:r.message||"Unknown error occurred"}}}async EmbedText(e){try{const t=m.gql`
131
131
  mutation EmbedText(
132
132
  $textToEmbed: [String!]!,
133
133
  $modelSize: String!
@@ -142,15 +142,15 @@
142
142
  error
143
143
  }
144
144
  }
145
- `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this._dataProvider.ExecuteGQL(t,s);if(!n?.EmbedText)throw new Error("Invalid response from server");const o=n.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?o.embeddings:o.embeddings[0],modelName:o.modelName,vectorDimensions:o.vectorDimensions,error:o.error}}catch(t){const r=t;return u.LogError(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}};S(z,"GraphQLAIClient");let C=z;const X=class X extends u.ProviderConfigDataBase{get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get MJAPIKey(){return this.Data.MJAPIKey}set MJAPIKey(e){this.Data.MJAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}constructor(e,t,r,s,n,o,a,i){super({Token:e,URL:t,WSURL:r,MJAPIKey:i,RefreshTokenFunction:s},n,o,a)}};S(X,"GraphQLProviderConfigData");let b=X;const pe=(h=class extends u.ProviderBase{constructor(){super(),this._refreshPromise=null,this._innerCurrentUserQueryString=`CurrentUser {
145
+ `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this._dataProvider.ExecuteGQL(t,s);if(!a?.EmbedText)throw new Error("Invalid response from server");const o=a.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?o.embeddings:o.embeddings[0],modelName:o.modelName,vectorDimensions:o.vectorDimensions,error:o.error}}catch(t){const r=t;return u.LogError(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}};S(X,"GraphQLAIClient");let N=X;const P="default",H=class H{constructor(){this._storage=new Map}getCategoryMap(e){const t=e||P;let r=this._storage.get(t);return r||(r=new Map,this._storage.set(t,r)),r}async GetItem(e,t){return this.getCategoryMap(t||P).get(e)??null}async SetItem(e,t,r){this.getCategoryMap(r||P).set(e,t)}async Remove(e,t){this.getCategoryMap(t||P).delete(e)}async ClearCategory(e){const t=e||P;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||P);return t?Array.from(t.keys()):[]}};S(H,"BrowserStorageProviderBase");let b=H;const we="MJ_Metadata",Pe=3,he=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"],Se="Metadata_KVPairs",Y=class Y extends b{constructor(){super(),this._dbReady=!1,this.dbPromise=De.openDB(we,Pe,{upgrade(e){try{e.objectStoreNames.contains(Se)&&e.deleteObjectStore(Se);for(const t of he)e.objectStoreNames.contains(t)||e.createObjectStore(t)}catch(t){u.LogErrorEx({error:t,message:t?.message})}}}),this.dbPromise.then(()=>{this._dbReady=!0}).catch(e=>{u.LogErrorEx({error:e,message:"IndexedDB initialization failed: "+e?.message})})}isKnownCategory(e){const t=`mj:${e}`;return he.includes(t)}getStoreName(e){const t=e||P;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||P;return this.isKnownCategory(r)?e:`[${r}]:${e}`}async SetItem(e,t,r){try{const s=await this.dbPromise,a=this.getStoreName(r),o=this.getStoreKey(e,r),i=s.transaction(a,"readwrite");await i.objectStore(a).put(t,o),await i.done}catch(s){u.LogErrorEx({error:s,message:s?.message}),await super.SetItem(e,t,r)}}async GetItem(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),a=this.getStoreKey(e,t);return await r.transaction(s).objectStore(s).get(a)??null}catch(r){return u.LogErrorEx({error:r,message:r?.message}),await super.GetItem(e,t)}}async Remove(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),a=this.getStoreKey(e,t),o=r.transaction(s,"readwrite");await o.objectStore(s).delete(a),await o.done}catch(r){u.LogErrorEx({error:r,message:r?.message}),await super.Remove(e,t)}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||P,s=this.getStoreName(e);if(this.isKnownCategory(r)){const a=t.transaction(s,"readwrite");await a.objectStore(s).clear(),await a.done}else{const a=`[${r}]:`,o=t.transaction("mj:default","readwrite"),i=o.objectStore("mj:default"),n=await i.getAllKeys();for(const c of n)typeof c=="string"&&c.startsWith(a)&&await i.delete(c);await o.done}}catch(t){u.LogErrorEx({error:t,message:t?.message}),await super.ClearCategory(e)}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||P,s=this.getStoreName(e),i=await t.transaction(s,"readonly").objectStore(s).getAllKeys();if(this.isKnownCategory(r))return i.map(c=>String(c));const n=`[${r}]:`;return i.map(c=>String(c)).filter(c=>c.startsWith(n)).map(c=>c.slice(n.length))}catch(t){return u.LogErrorEx({error:t,message:t?.message}),await super.GetCategoryKeys(e)}}};S(Y,"BrowserIndexedDBStorageProvider");let x=Y;const Z=class Z extends u.ProviderConfigDataBase{get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get MJAPIKey(){return this.Data.MJAPIKey}set MJAPIKey(e){this.Data.MJAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}constructor(e,t,r,s,a,o,i,n){super({Token:e,URL:t,WSURL:r,MJAPIKey:n,RefreshTokenFunction:s},a,o,i)}};S(Z,"GraphQLProviderConfigData");let T=Z;const h=class h extends u.ProviderBase{constructor(){super(),this._refreshPromise=null,this._innerCurrentUserQueryString=`CurrentUser {
146
146
  ${this.userInfoString()}
147
147
  UserRoles_UserIDArray {
148
148
  ${this.userRoleInfoString()}
149
149
  }
150
150
  }
151
- `,this._currentUserQuery=g.gql`query CurrentUserAndRoles {
151
+ `,this._currentUserQuery=m.gql`query CurrentUserAndRoles {
152
152
  ${this._innerCurrentUserQueryString}
153
- }`,this._wsClient=null,this._wsClientCreatedAt=null,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=30*60*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=5*60*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=10*60*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,h._instance||(h._instance=this)}static get Instance(){return h._instance}get ConfigData(){return this._configData}sanitizeGraphQLName(e){if(!e||e.length===0)return"";let t=e.replace(/[^A-Za-z0-9_]/g,"");return t.startsWith("__")&&(t=t.substring(2)),t=t.replace(/_/g,""),t.length===0||/^[0-9]/.test(t)?"_"+t:t}getGraphQLTypeNameBase(e){const t=e.SchemaName.trim().toLowerCase()===h.MJ_CORE_SCHEMA.trim().toLowerCase()?"MJ":this.sanitizeGraphQLName(e.SchemaName),r=this.sanitizeGraphQLName(e.BaseTable);return`${t}${r}`}get AI(){return this._aiClient||(this._aiClient=new C(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return Ee.v4()}get LocalStoragePrefix(){if(this._configData===void 0||this._configData.URL===void 0)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const r=this.LocalStoragePrefix+"sessionId";await t.SetItem(r,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,r,s){try{const n=e.Token?`${e.Token.substring(0,20)}...${e.Token.substring(e.Token.length-10)}`:"NO TOKEN";return console.log("[GraphQL] Config called with token:",{tokenPreview:n,tokenLength:e.Token?.length,separateConnection:r,hasRefreshFunction:!!e.Data?.RefreshTokenFunction}),this._configData=e,r?(this._sessionId=await this.GetPreferredUUID(s),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey),await this.SaveStoredSessionID(this._sessionId)):(h.Instance._configData=e,h.Instance._sessionId===void 0&&(h.Instance._sessionId=await this.GetPreferredUUID(s)),h.Instance._client||(h.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,h.Instance._sessionId,e.MJAPIKey)),await h.Instance.SaveStoredSessionID(h.Instance._sessionId),this._sessionId=h.Instance._sessionId,this._client=h.Instance._client),super.Config(e)}catch(n){throw u.LogError(n),n}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),r=t.UserRoles_UserIDArray.map(s=>this.ConvertBackToMJFields(s));return t.UserRoles_UserIDArray=r,new u.UserInfo(this,{...t,UserRoles:r})}}async RunReport(e,t){const r=g.gql`
153
+ }`,this._wsClient=null,this._wsClientCreatedAt=null,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=30*60*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=5*60*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=10*60*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,h._instance||(h._instance=this)}static get Instance(){return h._instance}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new N(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return Ee.v4()}get LocalStoragePrefix(){if(this._configData===void 0||this._configData.URL===void 0)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const r=this.LocalStoragePrefix+"sessionId";await t.SetItem(r,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,r,s){try{return this._configData=e,r?(this._sessionId=await this.GetPreferredUUID(s),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey),await this.SaveStoredSessionID(this._sessionId)):(h.Instance._configData=e,h.Instance._sessionId===void 0&&(h.Instance._sessionId=await this.GetPreferredUUID(s)),h.Instance._client||(h.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,h.Instance._sessionId,e.MJAPIKey)),await h.Instance.SaveStoredSessionID(h.Instance._sessionId),this._sessionId=h.Instance._sessionId,this._client=h.Instance._client),super.Config(e)}catch(a){throw u.LogError(a),a}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),r=t.UserRoles_UserIDArray.map(s=>this.ConvertBackToMJFields(s));return t.UserRoles_UserIDArray=r,new u.UserInfo(this,{...t,UserRoles:r})}}async RunReport(e,t){const r=m.gql`
154
154
  query GetReportDataQuery ($ReportID: String!) {
155
155
  GetReportData(ReportID: $ReportID) {
156
156
  Success
@@ -159,19 +159,25 @@
159
159
  ExecutionTime
160
160
  ErrorMessage
161
161
  }
162
- }`,s=await this.ExecuteGQL(r,{ReportID:e.ReportID});if(s&&s.GetReportData)return{ReportID:e.ReportID,Success:s.GetReportData.Success,Results:JSON.parse(s.GetReportData.Results),RowCount:s.GetReportData.RowCount,ExecutionTime:s.GetReportData.ExecutionTime,ErrorMessage:s.GetReportData.ErrorMessage}}async RunQuery(e,t){if(e.QueryID)return this.RunQueryByID(e.QueryID,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);throw new Error("No QueryID or QueryName provided to RunQuery")}async RunQueryByID(e,t,r,s,n,o,a){const i=g.gql`
162
+ }`,s=await this.ExecuteGQL(r,{ReportID:e.ReportID});if(s&&s.GetReportData)return{ReportID:e.ReportID,Success:s.GetReportData.Success,Results:JSON.parse(s.GetReportData.Results),RowCount:s.GetReportData.RowCount,ExecutionTime:s.GetReportData.ExecutionTime,ErrorMessage:s.GetReportData.ErrorMessage}}async InternalRunQuery(e,t){if(e.QueryID)return this.RunQueryByID(e.QueryID,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);throw new Error("No QueryID or QueryName provided to RunQuery")}async InternalRunQueries(e,t){const r=m.gql`
163
+ query RunQueriesBatch($input: [RunQueryInput!]!) {
164
+ RunQueries(input: $input) {
165
+ ${this.QueryReturnFieldList}
166
+ }
167
+ }
168
+ `,s=e.map(o=>({QueryID:o.QueryID,QueryName:o.QueryName,CategoryID:o.CategoryID,CategoryPath:o.CategoryPath,Parameters:o.Parameters,MaxRows:o.MaxRows,StartRow:o.StartRow,ForceAuditLog:o.ForceAuditLog,AuditLogDescription:o.AuditLogDescription})),a=await this.ExecuteGQL(r,{input:s});return a&&a.RunQueries?a.RunQueries.map(o=>this.TransformQueryPayload(o)):[]}async RunQueryByID(e,t,r,s,a,o,i){const n=m.gql`
163
169
  query GetQueryDataQuery($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
164
170
  GetQueryData(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
165
171
  ${this.QueryReturnFieldList}
166
172
  }
167
173
  }
168
- `,c={QueryID:e};t!==void 0&&(c.CategoryID=t),r!==void 0&&(c.CategoryPath=r),n!==void 0&&(c.Parameters=n),o!==void 0&&(c.MaxRows=o),a!==void 0&&(c.StartRow=a);const p=await this.ExecuteGQL(i,c);if(p&&p.GetQueryData)return this.TransformQueryPayload(p.GetQueryData)}async RunQueryByName(e,t,r,s,n,o,a){const i=g.gql`
174
+ `,c={QueryID:e};t!==void 0&&(c.CategoryID=t),r!==void 0&&(c.CategoryPath=r),a!==void 0&&(c.Parameters=a),o!==void 0&&(c.MaxRows=o),i!==void 0&&(c.StartRow=i);const p=await this.ExecuteGQL(n,c);if(p&&p.GetQueryData)return this.TransformQueryPayload(p.GetQueryData)}async RunQueryByName(e,t,r,s,a,o,i){const n=m.gql`
169
175
  query GetQueryDataByNameQuery($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
170
176
  GetQueryDataByName(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
171
177
  ${this.QueryReturnFieldList}
172
178
  }
173
179
  }
174
- `,c={QueryName:e};t!==void 0&&(c.CategoryID=t),r!==void 0&&(c.CategoryPath=r),n!==void 0&&(c.Parameters=n),o!==void 0&&(c.MaxRows=o),a!==void 0&&(c.StartRow=a);const p=await this.ExecuteGQL(i,c);if(p&&p.GetQueryDataByName)return this.TransformQueryPayload(p.GetQueryDataByName)}get QueryReturnFieldList(){return`
180
+ `,c={QueryName:e};t!==void 0&&(c.CategoryID=t),r!==void 0&&(c.CategoryPath=r),a!==void 0&&(c.Parameters=a),o!==void 0&&(c.MaxRows=o),i!==void 0&&(c.StartRow=i);const p=await this.ExecuteGQL(n,c);if(p&&p.GetQueryDataByName)return this.TransformQueryPayload(p.GetQueryDataByName)}get QueryReturnFieldList(){return`
175
181
  Success
176
182
  QueryID
177
183
  QueryName
@@ -180,11 +186,27 @@
180
186
  TotalRowCount
181
187
  ExecutionTime
182
188
  ErrorMessage
183
- AppliedParameters`}TransformQueryPayload(e){try{return{QueryID:e.QueryID,QueryName:e.QueryName,Success:e.Success,Results:JSON.parse(e.Results),RowCount:e.RowCount,TotalRowCount:e.TotalRowCount,ExecutionTime:e.ExecutionTime,ErrorMessage:e.ErrorMessage,AppliedParameters:e.AppliedParameters?JSON.parse(e.AppliedParameters):void 0}}catch(t){return u.LogError(`Error transforming query payload: ${t}`),null}}async RunView(e,t){await this.PreProcessRunView(e,t);try{let r="",s="";if(e){const n={};let o,a;if(e.ViewEntity)a=e.ViewEntity,o=a.Entity;else{const{entityName:l,v:d}=await this.getEntityNameAndUserView(e,t);a=d,o=l}const i=this.Entities.find(l=>l.Name===o);if(!i)throw new Error(`Entity ${o} not found in metadata`);let c=!1;const p=this.getGraphQLTypeNameBase(i);e.ViewID?(r=`Run${p}ViewByID`,s="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(r=`Run${p}ViewByName`,s="RunViewByNameInput",n.ViewName=e.ViewName):(c=!0,r=`Run${p}DynamicView`,s="RunDynamicViewInput",n.EntityName=e.EntityName),n.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",n.OrderBy=e.OrderBy?e.OrderBy:"",n.UserSearchString=e.UserSearchString?e.UserSearchString:"",n.Fields=e.Fields,n.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,e.MaxRows!==void 0&&(n.MaxRows=e.MaxRows),e.StartRow!==void 0&&(n.StartRow=e.StartRow),n.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,n.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(n.AuditLogDescription=e.AuditLogDescription),c||(n.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",n.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,n.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",n.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1);const m=this.getViewRunTimeFieldList(i,a,e,c),R=g.gql`
189
+ AppliedParameters`}TransformQueryPayload(e){try{return{QueryID:e.QueryID,QueryName:e.QueryName,Success:e.Success,Results:JSON.parse(e.Results),RowCount:e.RowCount,TotalRowCount:e.TotalRowCount,ExecutionTime:e.ExecutionTime,ErrorMessage:e.ErrorMessage,AppliedParameters:e.AppliedParameters?JSON.parse(e.AppliedParameters):void 0}}catch(t){return u.LogError(`Error transforming query payload: ${t}`),null}}async RunQueriesWithCacheCheck(e,t){try{const r=e.map(n=>({params:{QueryID:n.params.QueryID||null,QueryName:n.params.QueryName||null,CategoryID:n.params.CategoryID||null,CategoryPath:n.params.CategoryPath||null,Parameters:n.params.Parameters||null,MaxRows:n.params.MaxRows??null,StartRow:n.params.StartRow??null,ForceAuditLog:n.params.ForceAuditLog||!1,AuditLogDescription:n.params.AuditLogDescription||null},cacheStatus:n.cacheStatus?{maxUpdatedAt:n.cacheStatus.maxUpdatedAt,rowCount:n.cacheStatus.rowCount}:null})),s=m.gql`
190
+ query RunQueriesWithCacheCheckQuery($input: [RunQueryWithCacheCheckInput!]!) {
191
+ RunQueriesWithCacheCheck(input: $input) {
192
+ success
193
+ errorMessage
194
+ results {
195
+ queryIndex
196
+ queryId
197
+ status
198
+ Results
199
+ maxUpdatedAt
200
+ rowCount
201
+ errorMessage
202
+ }
203
+ }
204
+ }
205
+ `,o=(await this.ExecuteGQL(s,{input:r}))?.RunQueriesWithCacheCheck;if(!o)return{success:!1,results:[],errorMessage:"No response from server"};const i=o.results.map(n=>{if((n.status==="stale"||n.status==="no_validation")&&n.Results){const c=JSON.parse(n.Results);return{queryIndex:n.queryIndex,queryId:n.queryId,status:n.status,results:c,maxUpdatedAt:n.maxUpdatedAt,rowCount:n.rowCount,errorMessage:n.errorMessage}}return{queryIndex:n.queryIndex,queryId:n.queryId,status:n.status,maxUpdatedAt:n.maxUpdatedAt,rowCount:n.rowCount,errorMessage:n.errorMessage}});return{success:o.success,results:i,errorMessage:o.errorMessage}}catch(r){return u.LogError(`Error in RunQueriesWithCacheCheck: ${r}`),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async InternalRunView(e,t){try{let r="",s="";if(e){const a={};let o,i;if(e.ViewEntity)i=e.ViewEntity,o=i.Entity;else{const{entityName:l,v:d}=await this.getEntityNameAndUserView(e,t);i=d,o=l}const n=this.Entities.find(l=>l.Name===o);if(!n)throw new Error(`Entity ${o} not found in metadata`);let c=!1;const p=u.getGraphQLTypeNameBase(n);e.ViewID?(r=`Run${p}ViewByID`,s="RunViewByIDInput",a.ViewID=e.ViewID):e.ViewName?(r=`Run${p}ViewByName`,s="RunViewByNameInput",a.ViewName=e.ViewName):(c=!0,r=`Run${p}DynamicView`,s="RunDynamicViewInput",a.EntityName=e.EntityName),a.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",a.OrderBy=e.OrderBy?e.OrderBy:"",a.UserSearchString=e.UserSearchString?e.UserSearchString:"",a.Fields=e.Fields,a.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,e.MaxRows!==void 0&&(a.MaxRows=e.MaxRows),e.StartRow!==void 0&&(a.StartRow=e.StartRow),a.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,a.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(a.AuditLogDescription=e.AuditLogDescription),c||(a.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",a.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,a.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",a.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1);const g=this.getViewRunTimeFieldList(n,i,e,c),R=m.gql`
184
206
  query RunViewQuery ($input: ${s}!) {
185
207
  ${r}(input: $input) {
186
208
  Results {
187
- ${m.join(`
209
+ ${g.join(`
188
210
  `)}
189
211
  }
190
212
  UserViewRunID
@@ -194,7 +216,7 @@
194
216
  Success
195
217
  ErrorMessage
196
218
  }
197
- }`,y=await this.ExecuteGQL(R,{input:n});if(y&&y[r]){const l=y[r].Results;if(l&&l.length>0){const I=i.Fields.filter(f=>f.CodeName!==f.Name&&f.CodeName!==void 0);l.forEach(f=>{this.ConvertBackToMJFields(f),I.forEach(D=>{f[D.Name]=f[D.CodeName]})})}const d=y[r];return await this.PostProcessRunView(d,e,t),d}}else throw"No parameters passed to RunView";return null}catch(r){throw u.LogError(r),r}}async RunViews(e,t){await this.PreProcessRunViews(e,t);try{let r=[],s=[],n=[];for(const i of e){let c="",p="";const m={};let R=null,y=null;if(i.ViewEntity)y=i.ViewEntity,R=y.Get("Entity");else{const{entityName:f,v:D}=await this.getEntityNameAndUserView(i,t);y=D,R=f}const l=this.Entities.find(f=>f.Name===R);if(!l)throw new Error(`Entity ${R} not found in metadata`);s.push(l);let d=!1;const I=this.getGraphQLTypeNameBase(l);i.ViewID?(c=`Run${I}ViewByID`,p="RunViewByIDInput",m.ViewID=i.ViewID):i.ViewName?(c=`Run${I}ViewByName`,p="RunViewByNameInput",m.ViewName=i.ViewName):(d=!0,c=`Run${I}DynamicView`,p="RunDynamicViewInput",m.EntityName=i.EntityName),m.ExtraFilter=i.ExtraFilter||"",m.OrderBy=i.OrderBy||"",m.UserSearchString=i.UserSearchString||"",m.Fields=i.Fields,m.IgnoreMaxRows=i.IgnoreMaxRows||!1,i.MaxRows!==void 0&&(m.MaxRows=i.MaxRows),i.StartRow!==void 0&&(m.StartRow=i.StartRow),m.ForceAuditLog=i.ForceAuditLog||!1,m.ResultType=i.ResultType||"simple",i.AuditLogDescription&&i.AuditLogDescription.length>0&&(m.AuditLogDescription=i.AuditLogDescription),d||(m.ExcludeUserViewRunID=i.ExcludeUserViewRunID||"",m.ExcludeDataFromAllPriorViewRuns=i.ExcludeDataFromAllPriorViewRuns||!1,m.OverrideExcludeFilter=i.OverrideExcludeFilter||"",m.SaveViewResults=i.SaveViewResults||!1),r.push(m),n.push(...this.getViewRunTimeFieldList(l,y,i,d))}const o=g.gql`
219
+ }`,y=await this.ExecuteGQL(R,{input:a});if(y&&y[r]){const l=y[r].Results;if(l&&l.length>0){const I=n.Fields.filter(f=>f.CodeName!==f.Name&&f.CodeName!==void 0);l.forEach(f=>{this.ConvertBackToMJFields(f),I.forEach(D=>{f[D.Name]=f[D.CodeName]})})}return y[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw u.LogError(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],a=[];for(const n of e){let c="",p="";const g={};let R=null,y=null;if(n.ViewEntity)y=n.ViewEntity,R=y.Get("Entity");else{const{entityName:f,v:D}=await this.getEntityNameAndUserView(n,t);y=D,R=f}const l=this.Entities.find(f=>f.Name===R);if(!l)throw new Error(`Entity ${R} not found in metadata`);s.push(l);let d=!1;const I=u.getGraphQLTypeNameBase(l);n.ViewID?(c=`Run${I}ViewByID`,p="RunViewByIDInput",g.ViewID=n.ViewID):n.ViewName?(c=`Run${I}ViewByName`,p="RunViewByNameInput",g.ViewName=n.ViewName):(d=!0,c=`Run${I}DynamicView`,p="RunDynamicViewInput",g.EntityName=n.EntityName),g.ExtraFilter=n.ExtraFilter||"",g.OrderBy=n.OrderBy||"",g.UserSearchString=n.UserSearchString||"",g.Fields=n.Fields,g.IgnoreMaxRows=n.IgnoreMaxRows||!1,n.MaxRows!==void 0&&(g.MaxRows=n.MaxRows),n.StartRow!==void 0&&(g.StartRow=n.StartRow),g.ForceAuditLog=n.ForceAuditLog||!1,g.ResultType=n.ResultType||"simple",n.AuditLogDescription&&n.AuditLogDescription.length>0&&(g.AuditLogDescription=n.AuditLogDescription),d||(g.ExcludeUserViewRunID=n.ExcludeUserViewRunID||"",g.ExcludeDataFromAllPriorViewRuns=n.ExcludeDataFromAllPriorViewRuns||!1,g.OverrideExcludeFilter=n.OverrideExcludeFilter||"",g.SaveViewResults=n.SaveViewResults||!1),r.push(g),a.push(...this.getViewRunTimeFieldList(l,y,n,d))}const o=m.gql`
198
220
  query RunViewsQuery ($input: [RunViewGenericInput!]!) {
199
221
  RunViews(input: $input) {
200
222
  Results {
@@ -212,7 +234,29 @@
212
234
  Success
213
235
  ErrorMessage
214
236
  }
215
- }`,a=await this.ExecuteGQL(o,{input:r});if(a&&a.RunViews){const i=a.RunViews;for(const[c,p]of i.entries())p.Results=p.Results.map(m=>{let R=JSON.parse(m.Data);return this.ConvertBackToMJFields(R),R});return await this.PostProcessRunViews(i,e,t),i}return null}catch(r){throw u.LogError(r),r}}async getEntityNameAndUserView(e,t){let r,s;if(e.EntityName)r=e.EntityName;else if(e.ViewID)s=await ge.ViewInfo.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await ge.ViewInfo.GetViewEntityByName(e.ViewName,t),r=s.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:r,v:s}}getViewRunTimeFieldList(e,t,r,s){const n=[],o=new v;if(r.Fields){for(const a of e.PrimaryKeys)r.Fields.find(i=>i.trim().toLowerCase()===a.Name.toLowerCase())===void 0&&n.push(a.Name);r.Fields.forEach(a=>{n.push(o.MapFieldName(a))})}else if(s)e.Fields.forEach(a=>{a.IsBinaryFieldType||n.push(o.MapFieldName(a.CodeName))});else{for(const a of e.PrimaryKeys)n.find(i=>i.trim().toLowerCase()===a.Name.toLowerCase())===void 0&&n.push(a.Name);t.Columns.forEach(a=>{a.hidden===!1&&!n.find(i=>i.trim().toLowerCase()===a.EntityField?.Name.trim().toLowerCase())&&a.EntityField&&n.push(o.MapFieldName(a.EntityField.CodeName))})}return n}get ProviderType(){return u.ProviderType.Network}async GetRecordChanges(e,t){try{const r={EntityName:"Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},s=await this.RunView(r);return s?s.Results.sort((n,o)=>n.ChangedAt>o.ChangedAt?-1:1):null}catch(r){throw u.LogError(r),r}}async GetRecordDependencies(e,t){try{const r=g.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
237
+ }`,i=await this.ExecuteGQL(o,{input:r});if(i&&i.RunViews){const n=i.RunViews;for(const[c,p]of n.entries())p.Results=p.Results.map(g=>{let R=JSON.parse(g.Data);return this.ConvertBackToMJFields(R),R});return n}return null}catch(r){throw u.LogError(r),r}}async RunViewsWithCacheCheck(e,t){try{const r=e.map(n=>({params:{EntityName:n.params.EntityName||"",ExtraFilter:n.params.ExtraFilter||"",OrderBy:n.params.OrderBy||"",Fields:n.params.Fields,UserSearchString:n.params.UserSearchString||"",IgnoreMaxRows:n.params.IgnoreMaxRows||!1,MaxRows:n.params.MaxRows,StartRow:n.params.StartRow,ForceAuditLog:n.params.ForceAuditLog||!1,AuditLogDescription:n.params.AuditLogDescription||"",ResultType:n.params.ResultType||"simple"},cacheStatus:n.cacheStatus?{maxUpdatedAt:n.cacheStatus.maxUpdatedAt,rowCount:n.cacheStatus.rowCount}:null})),s=m.gql`
238
+ query RunViewsWithCacheCheckQuery($input: [RunViewWithCacheCheckInput!]!) {
239
+ RunViewsWithCacheCheck(input: $input) {
240
+ success
241
+ errorMessage
242
+ results {
243
+ viewIndex
244
+ status
245
+ maxUpdatedAt
246
+ rowCount
247
+ errorMessage
248
+ Results {
249
+ PrimaryKey {
250
+ FieldName
251
+ Value
252
+ }
253
+ EntityID
254
+ Data
255
+ }
256
+ }
257
+ }
258
+ }
259
+ `,o=(await this.ExecuteGQL(s,{input:r}))?.RunViewsWithCacheCheck;if(!o)return{success:!1,results:[],errorMessage:"No response from server"};const i=o.results.map((n,c)=>{const p=e[c];if(n.status==="stale"&&n.Results){const g=p.params.EntityName,R=this.Entities.find(l=>l.Name===g),y=n.Results.map(l=>{const d=JSON.parse(l.Data);return this.ConvertBackToMJFields(d),d});return{viewIndex:n.viewIndex,status:n.status,results:y,maxUpdatedAt:n.maxUpdatedAt,rowCount:n.rowCount,errorMessage:n.errorMessage}}return{viewIndex:n.viewIndex,status:n.status,results:void 0,maxUpdatedAt:n.maxUpdatedAt,rowCount:n.rowCount,errorMessage:n.errorMessage}});return{success:o.success,results:i,errorMessage:o.errorMessage}}catch(r){return u.LogError(r),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async getEntityNameAndUserView(e,t){let r,s;if(e.EntityName)r=e.EntityName;else if(e.ViewID)s=await pe.ViewInfo.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await pe.ViewInfo.GetViewEntityByName(e.ViewName,t),r=s.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:r,v:s}}getViewRunTimeFieldList(e,t,r,s){const a=[],o=new C;if(r.Fields){for(const i of e.PrimaryKeys)r.Fields.find(n=>n.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&a.push(i.Name);r.Fields.forEach(i=>{a.push(o.MapFieldName(i))})}else if(s)e.Fields.forEach(i=>{i.IsBinaryFieldType||a.push(o.MapFieldName(i.CodeName))});else{for(const i of e.PrimaryKeys)a.find(n=>n.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&a.push(i.Name);t.Columns.forEach(i=>{i.hidden===!1&&!a.find(n=>n.trim().toLowerCase()===i.EntityField?.Name.trim().toLowerCase())&&i.EntityField&&a.push(o.MapFieldName(i.EntityField.CodeName))})}return a}get ProviderType(){return u.ProviderType.Network}async GetRecordChanges(e,t){try{const r={EntityName:"Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},s=await this.RunView(r);return s?s.Results.sort((a,o)=>a.ChangedAt>o.ChangedAt?-1:1):null}catch(r){throw u.LogError(r),r}}async GetRecordDependencies(e,t){try{const r=m.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
216
260
  GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
217
261
  EntityName
218
262
  RelatedEntityName
@@ -224,7 +268,7 @@
224
268
  }
225
269
  }
226
270
  }
227
- }`,s={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}};return(await this.ExecuteGQL(r,s))?.GetRecordDependencies}catch(r){throw u.LogError(r),r}}ensureKeyValuePairValueIsString(e){return e.map(t=>({FieldName:t.FieldName,Value:t.Value.toString()}))}async GetRecordDuplicates(e,t){if(!e)return null;const r=g.gql`query GetRecordDuplicatesQuery ($params: PotentialDuplicateRequestType!) {
271
+ }`,s={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}};return(await this.ExecuteGQL(r,s))?.GetRecordDependencies}catch(r){throw u.LogError(r),r}}ensureKeyValuePairValueIsString(e){return e.map(t=>({FieldName:t.FieldName,Value:t.Value.toString()}))}async GetRecordDuplicates(e,t){if(!e)return null;const r=m.gql`query GetRecordDuplicatesQuery ($params: PotentialDuplicateRequestType!) {
228
272
  GetRecordDuplicates(params: $params) {
229
273
  Status
230
274
  ErrorMessage
@@ -246,7 +290,7 @@
246
290
  }
247
291
  }
248
292
  }
249
- }`;let s={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(o=>o.Copy())};const n=await this.ExecuteGQL(r,{params:s});if(n&&n.GetRecordDuplicates)return n.GetRecordDuplicates}async MergeRecords(e,t,r){const s=this.Entities.find(n=>n.Name.trim().toLowerCase()===e.EntityName.trim().toLowerCase());if(!s||!s.AllowRecordMerge)throw new Error(`Entity ${e.EntityName} does not allow record merging, check the AllowRecordMerge property in the entity metadata`);try{const n=g.gql`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
293
+ }`;let s={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(o=>o.Copy())};const a=await this.ExecuteGQL(r,{params:s});if(a&&a.GetRecordDuplicates)return a.GetRecordDuplicates}async MergeRecords(e,t,r){const s=this.Entities.find(a=>a.Name.trim().toLowerCase()===e.EntityName.trim().toLowerCase());if(!s||!s.AllowRecordMerge)throw new Error(`Entity ${e.EntityName} does not allow record merging, check the AllowRecordMerge property in the entity metadata`);try{const a=m.gql`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
250
294
  MergeRecords(request: $request) {
251
295
  Success
252
296
  OverallStatus
@@ -263,32 +307,32 @@
263
307
  Message
264
308
  }
265
309
  }
266
- }`,o={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(i=>({FieldName:i.FieldName,Value:i.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(i=>i.Copy())};return(await this.ExecuteGQL(n,{request:o}))?.MergeRecords}catch(n){return u.LogError(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){const s=new u.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const n={input:{}},o=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(y=>({FieldName:y.CodeName,Value:y.Value})),e.ResultHistory.push(s);const a=this.getGraphQLTypeNameBase(e.EntityInfo),i=`${o}${a}`,c=e.Fields.filter(y=>!y.ReadOnly||y.IsPrimaryKey&&e.IsSaved),p=new v,m=` ${i}(input: $input) {
310
+ }`,o={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(n=>({FieldName:n.FieldName,Value:n.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(n=>n.Copy())};return(await this.ExecuteGQL(a,{request:o}))?.MergeRecords}catch(a){return u.LogError(a),{Success:!1,OverallStatus:a&&a.message?a.message:a,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){const s=new u.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const a={input:{}},o=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(y=>({FieldName:y.CodeName,Value:y.Value})),e.ResultHistory.push(s);const i=u.getGraphQLTypeNameBase(e.EntityInfo),n=`${o}${i}`,c=e.Fields.filter(y=>!y.ReadOnly||y.IsPrimaryKey&&e.IsSaved),p=new C,g=` ${n}(input: $input) {
267
311
  ${e.Fields.map(y=>p.MapFieldName(y.CodeName)).join(`
268
312
  `)}
269
- }`,R=g.gql`mutation ${o}${a} ($input: ${i}Input!) {
270
- ${m}
313
+ }`,R=m.gql`mutation ${o}${i} ($input: ${n}Input!) {
314
+ ${g}
271
315
  }
272
- `;for(let y=0;y<c.length;y++){const l=c[y];let d=l.Value;if(d)switch(l.EntityFieldInfo.TSType){case u.EntityFieldTSType.Date:d=d.getTime();break;case u.EntityFieldTSType.Boolean:typeof d!="boolean"&&(d=parseInt(d)!==0);break;case u.EntityFieldTSType.Number:if(typeof d!="number"){const I=Number(d);isNaN(I)||(d=I)}break}d===null&&l.EntityFieldInfo.AllowsNull===!1&&(l.EntityFieldInfo.DefaultValue!==null?d=l.EntityFieldInfo.DefaultValue:l.FieldType===u.EntityFieldTSType.Number||l.FieldType===u.EntityFieldTSType.Boolean?d=0:d=""),n.input[l.CodeName]=d}if(o.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const y=[];e.Fields.forEach(l=>{let d=null;l.OldValue!==null&&l.OldValue!==void 0&&(l.EntityFieldInfo.TSType===u.EntityFieldTSType.Date?d=l.OldValue.getTime().toString():l.EntityFieldInfo.TSType===u.EntityFieldTSType.Boolean?d=l.OldValue===!0?"1":"0":typeof l.OldValue!="string"?d=l.OldValue.toString():d=l.OldValue),y.push({Key:l.CodeName,Value:d})}),n.input.OldValues___=y}if(e.TransactionGroup){const y=[{varName:"input",inputType:i+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,s.Type==="create"?"Create":"Update",m,n,{mutationName:i,mutationInputTypes:y},(l,d)=>{s.EndedAt=new Date,d&&l?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(l)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const y=await this.ExecuteGQL(R,n);if(y&&y[i])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(y[i]),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(n){return s.Success=!1,s.EndedAt=new Date,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,u.LogError(n),null}}async Load(e,t,r=null,s){try{const n={};let o="",a="";for(let y=0;y<t.KeyValuePairs.length;y++){const l=e.Fields.find(f=>f.Name.trim().toLowerCase()===t.KeyValuePairs[y].FieldName.trim().toLowerCase()).EntityFieldInfo,d=t.GetValueByIndex(y),I=l.GraphQLType;if(a.length>0&&(a+=", "),a+=`$${l.CodeName}: ${I}!`,o.length>0&&(o+=", "),o+=`${l.CodeName}: $${l.CodeName}`,l.TSType===u.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(y)))throw new Error(`Primary Key value ${d} (${l.Name}) is not a valid number`);n[l.CodeName]=parseInt(d)}else n[l.CodeName]=d}const i=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",c=this.getGraphQLTypeNameBase(e.EntityInfo),p=new v,m=g.gql`query Single${c}${i.length>0?"Full":""} (${a}) {
316
+ `;for(let y=0;y<c.length;y++){const l=c[y];let d=l.Value;if(d)switch(l.EntityFieldInfo.TSType){case u.EntityFieldTSType.Date:d=d.getTime();break;case u.EntityFieldTSType.Boolean:typeof d!="boolean"&&(d=parseInt(d)!==0);break;case u.EntityFieldTSType.Number:if(typeof d!="number"){const I=Number(d);isNaN(I)||(d=I)}break}d===null&&l.EntityFieldInfo.AllowsNull===!1&&(l.EntityFieldInfo.DefaultValue!==null?d=l.EntityFieldInfo.DefaultValue:l.FieldType===u.EntityFieldTSType.Number||l.FieldType===u.EntityFieldTSType.Boolean?d=0:d=""),a.input[l.CodeName]=d}if(o.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const y=[];e.Fields.forEach(l=>{let d=null;l.OldValue!==null&&l.OldValue!==void 0&&(l.EntityFieldInfo.TSType===u.EntityFieldTSType.Date?d=l.OldValue.getTime().toString():l.EntityFieldInfo.TSType===u.EntityFieldTSType.Boolean?d=l.OldValue===!0?"1":"0":typeof l.OldValue!="string"?d=l.OldValue.toString():d=l.OldValue),y.push({Key:l.CodeName,Value:d})}),a.input.OldValues___=y}if(e.TransactionGroup){const y=[{varName:"input",inputType:n+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,s.Type==="create"?"Create":"Update",g,a,{mutationName:n,mutationInputTypes:y},(l,d)=>{s.EndedAt=new Date,d&&l?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(l)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const y=await this.ExecuteGQL(R,a);if(y&&y[n])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(y[n]),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(a){return s.Success=!1,s.EndedAt=new Date,s.Message=a.response?.errors?.length>0?a.response.errors[0].message:a.message,u.LogError(a),null}}async Load(e,t,r=null,s){try{const a={};let o="",i="";for(let y=0;y<t.KeyValuePairs.length;y++){const l=e.Fields.find(f=>f.Name.trim().toLowerCase()===t.KeyValuePairs[y].FieldName.trim().toLowerCase()).EntityFieldInfo,d=t.GetValueByIndex(y),I=l.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${l.CodeName}: ${I}!`,o.length>0&&(o+=", "),o+=`${l.CodeName}: $${l.CodeName}`,l.TSType===u.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(y)))throw new Error(`Primary Key value ${d} (${l.Name}) is not a valid number`);a[l.CodeName]=parseInt(d)}else a[l.CodeName]=d}const n=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",c=u.getGraphQLTypeNameBase(e.EntityInfo),p=new C,g=m.gql`query Single${c}${n.length>0?"Full":""} (${i}) {
273
317
  ${c}(${o}) {
274
318
  ${e.Fields.filter(y=>!y.EntityFieldInfo.IsBinaryFieldType).map(y=>y.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?y.CodeName.replace("__mj_","_mj__"):y.CodeName).join(`
275
319
  `)}
276
- ${i}
320
+ ${n}
277
321
  }
278
322
  }
279
- `,R=await this.ExecuteGQL(m,n);return R&&R[c]?this.ConvertBackToMJFields(R[c]):null}catch(n){return u.LogError(n),null}}ConvertBackToMJFields(e){return new v().ReverseMapFields(e),e}getRelatedEntityString(e,t){let r="";for(let s=0;s<e.RelatedEntities.length;s++)if(t.indexOf(e.RelatedEntities[s].RelatedEntity)>=0){const n=e.RelatedEntities[s],o=this.Entities.find(i=>i.ID===n.RelatedEntityID);let a="";n.Type.toLowerCase().trim()==="many to many"?a=`${n.RelatedEntityCodeName}_${n.JoinEntityJoinField.replace(/\s/g,"")}`:a=`${n.RelatedEntityCodeName}_${n.RelatedEntityJoinField.replace(/\s/g,"")}`,r+=`
280
- ${a} {
281
- ${o.Fields.map(i=>i.CodeName).join(`
323
+ `,R=await this.ExecuteGQL(g,a);return R&&R[c]?this.ConvertBackToMJFields(R[c]):null}catch(a){return u.LogError(a),null}}ConvertBackToMJFields(e){return new C().ReverseMapFields(e),e}getRelatedEntityString(e,t){let r="";for(let s=0;s<e.RelatedEntities.length;s++)if(t.indexOf(e.RelatedEntities[s].RelatedEntity)>=0){const a=e.RelatedEntities[s],o=this.Entities.find(n=>n.ID===a.RelatedEntityID);let i="";a.Type.toLowerCase().trim()==="many to many"?i=`${a.RelatedEntityCodeName}_${a.JoinEntityJoinField.replace(/\s/g,"")}`:i=`${a.RelatedEntityCodeName}_${a.RelatedEntityJoinField.replace(/\s/g,"")}`,r+=`
324
+ ${i} {
325
+ ${o.Fields.map(n=>n.CodeName).join(`
282
326
  `)}
283
327
  }
284
- `}return r}async Delete(e,t,r){const s=new u.BaseEntityResult;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(l=>({FieldName:l.CodeName,Value:l.Value})),e.ResultHistory.push(s);const n={},o=[];let a="",i="",c="";for(let l of e.PrimaryKey.KeyValuePairs){const d=e.Fields.find(I=>I.Name.trim().toLowerCase()===l.FieldName.trim().toLowerCase());n[d.CodeName]=d.Value,o.push({varName:d.CodeName,inputType:d.EntityFieldInfo.GraphQLType+"!"}),a.length>0&&(a+=", "),a+=`${d.CodeName}: $${d.CodeName}`,i.length>0&&(i+=", "),i+=`$${d.CodeName}: ${d.EntityFieldInfo.GraphQLType}!`,c.length>0&&(c+=`
285
- `),c+=`${d.CodeName}`}o.push({varName:"options___",inputType:"DeleteOptionsInput!"}),n.options___=t||{SkipEntityAIActions:!1,SkipEntityActions:!1};const m="Delete"+this.getGraphQLTypeNameBase(e.EntityInfo),R=g.gql`${m}(${a}, options___: $options___) {
328
+ `}return r}async Delete(e,t,r){const s=new u.BaseEntityResult;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(l=>({FieldName:l.CodeName,Value:l.Value})),e.ResultHistory.push(s);const a={},o=[];let i="",n="",c="";for(let l of e.PrimaryKey.KeyValuePairs){const d=e.Fields.find(I=>I.Name.trim().toLowerCase()===l.FieldName.trim().toLowerCase());a[d.CodeName]=d.Value,o.push({varName:d.CodeName,inputType:d.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${d.CodeName}: $${d.CodeName}`,n.length>0&&(n+=", "),n+=`$${d.CodeName}: ${d.EntityFieldInfo.GraphQLType}!`,c.length>0&&(c+=`
329
+ `),c+=`${d.CodeName}`}o.push({varName:"options___",inputType:"DeleteOptionsInput!"}),a.options___=t||{SkipEntityAIActions:!1,SkipEntityActions:!1};const g="Delete"+u.getGraphQLTypeNameBase(e.EntityInfo),R=m.gql`${g}(${i}, options___: $options___) {
286
330
  ${c}
287
331
  }
288
- `,y=g.gql`mutation ${m} (${i}, $options___: DeleteOptionsInput!) {
332
+ `,y=m.gql`mutation ${g} (${n}, $options___: DeleteOptionsInput!) {
289
333
  ${R}
290
334
  }
291
- `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,"Delete",R,n,{mutationName:m,mutationInputTypes:o},(l,d)=>{if(s.EndedAt=new Date,d&&l){let I=!0;for(const f of e.PrimaryKey.KeyValuePairs)f.Value!==l[f.FieldName]&&(I=!1);I?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const l=await this.ExecuteGQL(y,n);if(l&&l[m]){const d=l[m];for(let I of e.PrimaryKey.KeyValuePairs){let f=d[I.FieldName],D=I.Value;if(typeof D=="number"&&(D=D.toString()),typeof f=="number"&&(f=f.toString()),D!==f)throw new Error(`Primary key value mismatch in server Delete response. Field: ${I.FieldName}, Original: ${D}, Returned: ${f}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(n){return s.EndedAt=new Date,s.Success=!1,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,u.LogError(n),!1}}async GetDatasetByName(e,t){const r=g.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
335
+ `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,"Delete",R,a,{mutationName:g,mutationInputTypes:o},(l,d)=>{if(s.EndedAt=new Date,d&&l){let I=!0;for(const f of e.PrimaryKey.KeyValuePairs)f.Value!==l[f.FieldName]&&(I=!1);I?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const l=await this.ExecuteGQL(y,a);if(l&&l[g]){const d=l[g];for(let I of e.PrimaryKey.KeyValuePairs){let f=d[I.FieldName],D=I.Value;if(typeof D=="number"&&(D=D.toString()),typeof f=="number"&&(f=f.toString()),D!==f)throw new Error(`Primary key value mismatch in server Delete response. Field: ${I.FieldName}, Original: ${D}, Returned: ${f}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(a){return s.EndedAt=new Date,s.Success=!1,s.Message=a.response?.errors?.length>0?a.response.errors[0].message:a.message,u.LogError(a),!1}}async GetDatasetByName(e,t){const r=m.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
292
336
  GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
293
337
  DatasetID
294
338
  DatasetName
@@ -297,7 +341,7 @@
297
341
  LatestUpdateDate
298
342
  Results
299
343
  }
300
- }`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetByName&&s.GetDatasetByName.Success?{DatasetID:s.GetDatasetByName.DatasetID,DatasetName:s.GetDatasetByName.DatasetName,Success:s.GetDatasetByName.Success,Status:s.GetDatasetByName.Status,LatestUpdateDate:new Date(s.GetDatasetByName.LatestUpdateDate),Results:JSON.parse(s.GetDatasetByName.Results)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,Results:null}}async GetDatasetStatusByName(e,t){const r=g.gql`query GetDatasetStatusByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
344
+ }`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetByName&&s.GetDatasetByName.Success?{DatasetID:s.GetDatasetByName.DatasetID,DatasetName:s.GetDatasetByName.DatasetName,Success:s.GetDatasetByName.Success,Status:s.GetDatasetByName.Status,LatestUpdateDate:new Date(s.GetDatasetByName.LatestUpdateDate),Results:JSON.parse(s.GetDatasetByName.Results)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,Results:null}}async GetDatasetStatusByName(e,t){const r=m.gql`query GetDatasetStatusByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
301
345
  GetDatasetStatusByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
302
346
  DatasetID
303
347
  DatasetName
@@ -306,22 +350,22 @@
306
350
  LatestUpdateDate
307
351
  EntityUpdateDates
308
352
  }
309
- }`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetStatusByName&&s.GetDatasetStatusByName.Success?{DatasetID:s.GetDatasetStatusByName.DatasetID,DatasetName:s.GetDatasetStatusByName.DatasetName,Success:s.GetDatasetStatusByName.Success,Status:s.GetDatasetStatusByName.Status,LatestUpdateDate:new Date(s.GetDatasetStatusByName.LatestUpdateDate),EntityUpdateDates:JSON.parse(s.GetDatasetStatusByName.EntityUpdateDates)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,EntityUpdateDates:null}}async CreateTransactionGroup(){return new N(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const n=this.Entities.find(i=>i.Name===t);if(!n)throw new Error(`Entity ${t} not found in metadata`);const o=g.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
353
+ }`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetStatusByName&&s.GetDatasetStatusByName.Success?{DatasetID:s.GetDatasetStatusByName.DatasetID,DatasetName:s.GetDatasetStatusByName.DatasetName,Success:s.GetDatasetStatusByName.Success,Status:s.GetDatasetStatusByName.Status,LatestUpdateDate:new Date(s.GetDatasetStatusByName.LatestUpdateDate),EntityUpdateDates:JSON.parse(s.GetDatasetStatusByName.EntityUpdateDates)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,EntityUpdateDates:null}}async CreateTransactionGroup(){return new v(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const a=this.Entities.find(n=>n.Name===t);if(!a)throw new Error(`Entity ${t} not found in metadata`);const o=m.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
310
354
  GetRecordFavoriteStatus(params: $params) {
311
355
  Success
312
356
  IsFavorite
313
357
  }
314
- }`,a=await this.ExecuteGQL(o,{params:{UserID:e,EntityID:n.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)}}});if(a&&a.GetRecordFavoriteStatus&&a.GetRecordFavoriteStatus.Success)return a.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,t,r,s,n){const o=this.Entities.find(c=>c.Name===t);if(!o)throw new Error(`Entity ${t} not found in metadata`);const a=g.gql`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
358
+ }`,i=await this.ExecuteGQL(o,{params:{UserID:e,EntityID:a.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)}}});if(i&&i.GetRecordFavoriteStatus&&i.GetRecordFavoriteStatus.Success)return i.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,t,r,s,a){const o=this.Entities.find(c=>c.Name===t);if(!o)throw new Error(`Entity ${t} not found in metadata`);const i=m.gql`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
315
359
  SetRecordFavoriteStatus(params: $params){
316
360
  Success
317
361
  }
318
- }`,i=await this.ExecuteGQL(a,{params:{UserID:e,EntityID:o.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)},IsFavorite:s}});if(i&&i.SetRecordFavoriteStatus!==null)return i.SetRecordFavoriteStatus.Success}async GetEntityRecordName(e,t){if(!e||!t||t.KeyValuePairs?.length===0)return null;const r=g.gql`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
362
+ }`,n=await this.ExecuteGQL(i,{params:{UserID:e,EntityID:o.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)},IsFavorite:s}});if(n&&n.SetRecordFavoriteStatus!==null)return n.SetRecordFavoriteStatus.Success}async GetEntityRecordName(e,t){if(!e||!t||t.KeyValuePairs?.length===0)return null;const r=m.gql`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
319
363
  GetEntityRecordName(EntityName: $EntityName, CompositeKey: $CompositeKey) {
320
364
  Success
321
365
  Status
322
366
  RecordName
323
367
  }
324
- }`,s=await this.ExecuteGQL(r,{EntityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}});if(s&&s.GetEntityRecordName&&s.GetEntityRecordName.Success)return s.GetEntityRecordName.RecordName}async GetEntityRecordNames(e){if(!e)return null;const t=g.gql`query GetEntityRecordNamesQuery ($info: [EntityRecordNameInput!]!) {
368
+ }`,s=await this.ExecuteGQL(r,{EntityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}});if(s&&s.GetEntityRecordName&&s.GetEntityRecordName.Success)return s.GetEntityRecordName.RecordName}async GetEntityRecordNames(e){if(!e)return null;const t=m.gql`query GetEntityRecordNamesQuery ($info: [EntityRecordNameInput!]!) {
325
369
  GetEntityRecordNames(info: $info) {
326
370
  Success
327
371
  Status
@@ -334,35 +378,35 @@
334
378
  EntityName
335
379
  RecordName
336
380
  }
337
- }`,r=await this.ExecuteGQL(t,{info:e.map(s=>({EntityName:s.EntityName,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.CompositeKey.KeyValuePairs)}}))});if(r&&r.GetEntityRecordNames)return r.GetEntityRecordNames}async GetDataContextData(e){try{const t=g.gql`query GetDataContextData ($DataContextID: String!) {
381
+ }`,r=await this.ExecuteGQL(t,{info:e.map(s=>({EntityName:s.EntityName,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.CompositeKey.KeyValuePairs)}}))});if(r&&r.GetEntityRecordNames)return r.GetEntityRecordNames}async GetDataContextData(e){try{const t=m.gql`query GetDataContextData ($DataContextID: String!) {
338
382
  GetDataContextData(DataContextID: $DataContextID) {
339
383
  Success
340
384
  ErrorMessages
341
385
  Results
342
386
  }
343
- }`,r=await this.ExecuteGQL(t,{DataContextID:e});if(r&&r.GetDataContextData){if(r.GetDataContextData.Success)return r.GetDataContextData.Results.map(s=>JSON.parse(s));throw new Error(r.GetDataContextData.ErrorMessages.join(", "))}else throw new Error("GraphQL query failed")}catch(t){throw u.LogError(t),t}}async GetDataContextItemData(e){try{const t=g.gql`query GetDataContextItemData ($DataContextItemID: String!) {
387
+ }`,r=await this.ExecuteGQL(t,{DataContextID:e});if(r&&r.GetDataContextData){if(r.GetDataContextData.Success)return r.GetDataContextData.Results.map(s=>JSON.parse(s));throw new Error(r.GetDataContextData.ErrorMessages.join(", "))}else throw new Error("GraphQL query failed")}catch(t){throw u.LogError(t),t}}async GetDataContextItemData(e){try{const t=m.gql`query GetDataContextItemData ($DataContextItemID: String!) {
344
388
  GetDataContextItemData(DataContextItemID: $DataContextItemID) {
345
389
  Success
346
390
  ErrorMessage
347
391
  Result
348
392
  }
349
- }`,r=await this.ExecuteGQL(t,{DataContextItemID:e});if(r&&r.GetDataContextItemData){if(r.GetDataContextItemData.Success)return JSON.parse(r.GetDataContextItemData.Result);throw new Error(r.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw u.LogError(t),t}}static async ExecuteGQL(e,t,r=!0){return h.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(console.log("[GraphQL] ExecuteGQL error caught:",{hasResponse:!!s?.response,hasErrors:!!s?.response?.errors,errorCount:s?.response?.errors?.length,firstError:s?.response?.errors?.[0],errorCode:s?.response?.errors?.[0]?.extensions?.code,errorMessage:s?.response?.errors?.[0]?.message,fullError:s}),s&&s.response&&s.response.errors?.length>0){const o=s.response.errors[0]?.extensions?.code?.toUpperCase().trim();if(console.log("[GraphQL] Error code detected:",o),o==="JWT_EXPIRED"){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw u.LogError("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s}else throw u.LogError(s),s}}async RefreshToken(){const e=h.Instance&&h.Instance._configData===this._configData;if(e&&h.Instance._refreshPromise)return console.log("[GraphQL] Token refresh already in progress (singleton), waiting..."),h.Instance._refreshPromise;if(this._refreshPromise)return console.log("[GraphQL] Token refresh already in progress (instance), waiting..."),this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(h.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&h.Instance&&(h.Instance._refreshPromise=null)}}async performTokenRefresh(){if(this._configData.Data.RefreshTokenFunction){const e=await this._configData.Data.RefreshTokenFunction();if(e){this._configData.Token=e;const t=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey);this._client=t,h.Instance&&h.Instance._configData===this._configData&&(h.Instance._client=t)}else throw new Error("Refresh token function returned null or undefined token")}else throw new Error("No refresh token function provided")}static async RefreshToken(){return h.Instance.RefreshToken()}CreateNewGraphQLClient(e,t,r,s){const n=t?`${t.substring(0,20)}...${t.substring(t.length-10)}`:"NO TOKEN";console.log("[GraphQL] Creating new client:",{url:e,tokenPreview:n,tokenLength:t?.length,sessionId:r,hasMJAPIKey:!!s});const o={"x-session-id":r};return t&&(o.authorization="Bearer "+t),s&&(o["x-mj-api-key"]=s),new g.GraphQLClient(e,{headers:o})}userInfoString(){return this.infoString(new u.UserInfo(null,null))}userRoleInfoString(){return this.infoString(new u.UserRoleInfo(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
393
+ }`,r=await this.ExecuteGQL(t,{DataContextItemID:e});if(r&&r.GetDataContextItemData){if(r.GetDataContextItemData.Success)return JSON.parse(r.GetDataContextItemData.Result);throw new Error(r.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw u.LogError(t),t}}static async ExecuteGQL(e,t,r=!0){return h.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(console.error("[GraphQL] ExecuteGQL error caught:",{hasResponse:!!s?.response,hasErrors:!!s?.response?.errors,errorCount:s?.response?.errors?.length,firstError:s?.response?.errors?.[0],errorCode:s?.response?.errors?.[0]?.extensions?.code,errorMessage:s?.response?.errors?.[0]?.message,fullError:s}),s&&s.response&&s.response.errors?.length>0)if(s.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw u.LogError("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw u.LogError(s),s}}async RefreshToken(){const e=h.Instance&&h.Instance._configData===this._configData;if(e&&h.Instance._refreshPromise)return h.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(h.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&h.Instance&&(h.Instance._refreshPromise=null)}}async performTokenRefresh(){if(this._configData.Data.RefreshTokenFunction){const e=await this._configData.Data.RefreshTokenFunction();if(e){this._configData.Token=e;const t=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey);this._client=t,h.Instance&&h.Instance._configData===this._configData&&(h.Instance._client=t)}else throw new Error("Refresh token function returned null or undefined token")}else throw new Error("No refresh token function provided")}static async RefreshToken(){return h.Instance.RefreshToken()}CreateNewGraphQLClient(e,t,r,s){const a={"x-session-id":r};return t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),new m.GraphQLClient(e,{headers:a})}userInfoString(){return this.infoString(new u.UserInfo(null,null))}userRoleInfoString(){return this.infoString(new u.UserRoleInfo(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
350
394
  `:s.startsWith("_")||(t+=s+`
351
- `);return t}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new L),this._localStorageProvider}get Metadata(){return this}getOrCreateWSClient(){const e=Date.now();return this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&this._activeSubscriptionCount===0&&this.disposeWSClient(),this._wsClient||(this._wsClient=Ie.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token},keepAlive:3e4,retryAttempts:3,shouldRetry:()=>!0}),this._wsClientCreatedAt=e,this._subscriptionCleanupTimer||(this._subscriptionCleanupTimer=setInterval(()=>{this.cleanupStaleSubscriptions()},this.SUBSCRIPTION_CLEANUP_INTERVAL_MS))),this._wsClient}disposeWSClient(){if(this._wsClient){try{this._wsClient.dispose()}catch(e){console.error("[GraphQLDataProvider] Error disposing WebSocket client:",e)}this._wsClient=null,this._wsClientCreatedAt=null}}completeAllSubjects(){this._pushStatusSubjects.forEach((e,t)=>{try{e.subject.complete(),e.subscription.unsubscribe()}catch(r){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,r)}}),this._pushStatusSubjects.clear()}cleanupStaleSubscriptions(){if(!this._isCleaningUp){this._isCleaningUp=!0;try{const e=Date.now(),t=this._pushStatusSubjects.size,r=Array.from(this._pushStatusSubjects.entries()),s=[];r.forEach(([n,o])=>{const a=e-o.lastRequestedAt,i=e-o.lastEmissionAt;o.activeSubscribers===0&&a>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&i>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${n} for cleanup: activeSubscribers=${o.activeSubscribers}, timeSinceRequested=${Math.round(a/1e3)}s, timeSinceEmission=${Math.round(i/1e3)}s`),s.push(n))}),s.forEach(n=>{const o=this._pushStatusSubjects.get(n);if(o)try{o.subject.complete(),o.subscription.unsubscribe(),this._pushStatusSubjects.delete(n),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${n}`)}catch(a){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${n}:`,a)}}),s.length>0&&console.log(`[GraphQLDataProvider] Cleaned up ${s.length} stale subscription(s)`),this._pushStatusSubjects.size===0&&this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&(console.log("[GraphQLDataProvider] Disposing of idle WebSocket client"),this.disposeWSClient())}finally{this._isCleaningUp=!1}}}subscribe(e,t){return new $.Observable(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=s.subscribe({query:e,variables:t},{next:o=>{r.next(o.data)},error:async o=>{const a=o;if(a?.extensions?.code==="JWT_EXPIRED"||a?.message?.includes("token has expired")||a?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] WebSocket JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),r.complete()}catch(c){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",c),r.error(c)}}else r.error(o)},complete:()=>{r.complete()}});return()=>{this._activeSubscriptionCount--,n()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),r=this._pushStatusSubjects.get(e);if(r)return r.lastRequestedAt=t,new $.Observable(i=>{r.activeSubscribers++;const c=r.subject.subscribe(i);return()=>{const p=this._pushStatusSubjects.get(e);p&&p.activeSubscribers>0&&p.activeSubscribers--,c.unsubscribe()}});const s=g.gql`subscription StatusUpdates($sessionId: String!) {
395
+ `);return t}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new x),this._localStorageProvider}get Metadata(){return this}getOrCreateWSClient(){const e=Date.now();return this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&this._activeSubscriptionCount===0&&this.disposeWSClient(),this._wsClient||(this._wsClient=Ie.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token},keepAlive:3e4,retryAttempts:3,shouldRetry:()=>!0}),this._wsClientCreatedAt=e,this._subscriptionCleanupTimer||(this._subscriptionCleanupTimer=setInterval(()=>{this.cleanupStaleSubscriptions()},this.SUBSCRIPTION_CLEANUP_INTERVAL_MS))),this._wsClient}disposeWSClient(){if(this._wsClient){try{this._wsClient.dispose()}catch(e){console.error("[GraphQLDataProvider] Error disposing WebSocket client:",e)}this._wsClient=null,this._wsClientCreatedAt=null}}completeAllSubjects(){this._pushStatusSubjects.forEach((e,t)=>{try{e.subject.complete(),e.subscription.unsubscribe()}catch(r){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,r)}}),this._pushStatusSubjects.clear()}cleanupStaleSubscriptions(){if(!this._isCleaningUp){this._isCleaningUp=!0;try{const e=Date.now(),t=this._pushStatusSubjects.size,r=Array.from(this._pushStatusSubjects.entries()),s=[];r.forEach(([a,o])=>{const i=e-o.lastRequestedAt,n=e-o.lastEmissionAt;o.activeSubscribers===0&&i>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&n>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${a} for cleanup: activeSubscribers=${o.activeSubscribers}, timeSinceRequested=${Math.round(i/1e3)}s, timeSinceEmission=${Math.round(n/1e3)}s`),s.push(a))}),s.forEach(a=>{const o=this._pushStatusSubjects.get(a);if(o)try{o.subject.complete(),o.subscription.unsubscribe(),this._pushStatusSubjects.delete(a),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${a}`)}catch(i){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${a}:`,i)}}),s.length>0&&console.log(`[GraphQLDataProvider] Cleaned up ${s.length} stale subscription(s)`),this._pushStatusSubjects.size===0&&this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&(console.log("[GraphQLDataProvider] Disposing of idle WebSocket client"),this.disposeWSClient())}finally{this._isCleaningUp=!1}}}subscribe(e,t){return new $.Observable(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const a=s.subscribe({query:e,variables:t},{next:o=>{r.next(o.data)},error:async o=>{const i=o;if(i?.extensions?.code==="JWT_EXPIRED"||i?.message?.includes("token has expired")||i?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] WebSocket JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),r.complete()}catch(c){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",c),r.error(c)}}else r.error(o)},complete:()=>{r.complete()}});return()=>{this._activeSubscriptionCount--,a()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),r=this._pushStatusSubjects.get(e);if(r)return r.lastRequestedAt=t,new $.Observable(n=>{r.activeSubscribers++;const c=r.subject.subscribe(n);return()=>{const p=this._pushStatusSubjects.get(e);p&&p.activeSubscribers>0&&p.activeSubscribers--,c.unsubscribe()}});const s=m.gql`subscription StatusUpdates($sessionId: String!) {
352
396
  statusUpdates(sessionId: $sessionId) {
353
397
  date
354
398
  message
355
399
  sessionId
356
400
  }
357
401
  }
358
- `,n=new $.Subject,o=this.getOrCreateWSClient(),a=new $.Subscription;return a.add(new $.Observable(i=>{const c=o.subscribe({query:s,variables:{sessionId:e}},{next:p=>{const m=this._pushStatusSubjects.get(e);m&&(m.lastEmissionAt=Date.now()),i.next(p.data.statusUpdates.message)},error:async p=>{const m=p;if(m?.extensions?.code==="JWT_EXPIRED"||m?.message?.includes("token has expired")||m?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),i.complete()}catch(y){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",y),i.error(y)}}else i.error(p)},complete:()=>{i.complete()}});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,c()}}).subscribe({next:i=>n.next(i),error:i=>{n.error(i),this._pushStatusSubjects.delete(e)},complete:()=>{n.complete(),this._pushStatusSubjects.delete(e)}})),this._pushStatusSubjects.set(e,{subject:n,subscription:a,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new $.Observable(i=>{const c=this._pushStatusSubjects.get(e);c&&c.activeSubscribers++;const p=n.subscribe(i);return()=>{const m=this._pushStatusSubjects.get(e);m&&m.activeSubscribers>0&&m.activeSubscribers--,p.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}},S(h,"_GraphQLDataProvider"),h);pe.MJ_CORE_SCHEMA="__mj";let he=pe;const H=class H{constructor(){this._localStorage={}}async GetItem(e){return new Promise(t=>{this._localStorage.hasOwnProperty(e)?t(this._localStorage[e]):t(null)})}async SetItem(e,t){return new Promise(r=>{this._localStorage[e]=t,r()})}async Remove(e){return new Promise(t=>{this._localStorage.hasOwnProperty(e)&&delete this._localStorage[e],t()})}};S(H,"BrowserStorageProviderBase");let T=H;const De="MJ_Metadata",P="Metadata_KVPairs",Z=class Z extends T{constructor(){super(),this.dbPromise=Re.openDB(De,1,{upgrade(e){e.objectStoreNames.contains(P)||e.createObjectStore(P)}})}async setItem(e,t){const s=(await this.dbPromise).transaction(P,"readwrite");await s.objectStore(P).put(t,e),await s.done}async getItem(e){return await(await this.dbPromise).transaction(P).objectStore(P).get(e)}async remove(e){const r=(await this.dbPromise).transaction(P,"readwrite");await r.objectStore(P).delete(e),await r.done}};S(Z,"BrowserIndexedDBStorageProvider");let L=Z;async function we(E){const e=new he;return u.SetProvider(e),await e.Config(E),w.MJGlobal.Instance.RaiseEvent({event:w.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),e}S(we,"setupGraphQLClient");const Y=class Y{};S(Y,"SyncRolesAndUsersResult");let V=Y;const ee=class ee{};S(ee,"RoleInput");let G=ee;const te=class te{};S(te,"UserInput");let x=te;const re=class re{};S(re,"RolesAndUsersInput");let Q=re;var Se=(E=>(E.Create="Create",E.Update="Update",E.CreateOrUpdate="CreateOrUpdate",E.Delete="Delete",E.DeleteWithFilter="DeleteWithFilter",E))(Se||{});const se=class se{};S(se,"ActionItemInput");let M=se;const ne=class ne{constructor(){this.Results=[]}};S(ne,"SyncDataResult");let F=ne;const oe=class oe{};S(oe,"ActionItemOutput");let A=oe;const ie=class ie{get Client(){return this._client}constructor(e,t,r,s){const n={"x-session-id":r};this._sessionId=r,t&&(n.authorization="Bearer "+t),s&&(n["x-mj-api-key"]=s),this._client=new g.GraphQLClient(e,{headers:n})}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
402
+ `,a=new $.Subject,o=this.getOrCreateWSClient(),i=new $.Subscription;return i.add(new $.Observable(n=>{const c=o.subscribe({query:s,variables:{sessionId:e}},{next:p=>{const g=this._pushStatusSubjects.get(e);g&&(g.lastEmissionAt=Date.now()),n.next(p.data.statusUpdates.message)},error:async p=>{const g=p;if(g?.extensions?.code==="JWT_EXPIRED"||g?.message?.includes("token has expired")||g?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),n.complete()}catch(y){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",y),n.error(y)}}else n.error(p)},complete:()=>{n.complete()}});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,c()}}).subscribe({next:n=>a.next(n),error:n=>{a.error(n),this._pushStatusSubjects.delete(e)},complete:()=>{a.complete(),this._pushStatusSubjects.delete(e)}})),this._pushStatusSubjects.set(e,{subject:a,subscription:i,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new $.Observable(n=>{const c=this._pushStatusSubjects.get(e);c&&c.activeSubscribers++;const p=a.subscribe(n);return()=>{const g=this._pushStatusSubjects.get(e);g&&g.activeSubscribers>0&&g.activeSubscribers--,p.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}};S(h,"GraphQLDataProvider");let L=h;async function Ce(E){const e=new L;return u.SetProvider(e),await e.Config(E),await u.StartupManager.Instance.Startup(),w.MJGlobal.Instance.RaiseEvent({event:w.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),e}S(Ce,"setupGraphQLClient");const ee=class ee{};S(ee,"SyncRolesAndUsersResult");let M=ee;const te=class te{};S(te,"RoleInput");let V=te;const re=class re{};S(re,"UserInput");let A=re;const se=class se{};S(se,"RolesAndUsersInput");let Q=se;var fe=(E=>(E.Create="Create",E.Update="Update",E.CreateOrUpdate="CreateOrUpdate",E.Delete="Delete",E.DeleteWithFilter="DeleteWithFilter",E))(fe||{});const ae=class ae{};S(ae,"ActionItemInput");let G=ae;const ne=class ne{constructor(){this.Results=[]}};S(ne,"SyncDataResult");let F=ne;const oe=class oe{};S(oe,"ActionItemOutput");let U=oe;const ie=class ie{get Client(){return this._client}constructor(e,t,r,s){const a={"x-session-id":r};this._sessionId=r,t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),this._client=new m.GraphQLClient(e,{headers:a})}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
359
403
  GetData(input: $input) {
360
404
  Success
361
405
  ErrorMessages
362
406
  Queries
363
407
  Results
364
408
  }
365
- }`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(n=>n?w.SafeJSONParse(n):null),ErrorMessages:s.GetData.ErrorMessages,Queries:s.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:s.GetData?.ErrorMessages??["Unknown error"],Queries:s.GetData?.Queries??e}}catch(r){let s=r instanceof Error?r.message:String(r);const n=s.match(/Error: ([^:]+)\./);if(n&&(s=n[1]+"."),u.IsVerboseLoggingEnabled()){const o=`GraphQLSystemUserClient::GetData - Error getting data - ${r}`;u.LogError(o)}return{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
409
+ }`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(a=>a?w.SafeJSONParse(a):null),ErrorMessages:s.GetData.ErrorMessages,Queries:s.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:s.GetData?.ErrorMessages??["Unknown error"],Queries:s.GetData?.Queries??e}}catch(r){let s=r instanceof Error?r.message:String(r);const a=s.match(/Error: ([^:]+)\./);if(a&&(s=a[1]+"."),u.IsVerboseLoggingEnabled()){const o=`GraphQLSystemUserClient::GetData - Error getting data - ${r}`;u.LogError(o)}return{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
366
410
  GetAllEntities {
367
411
  Success
368
412
  ErrorMessage
@@ -622,7 +666,7 @@
622
666
  ID
623
667
  Name
624
668
  }
625
- }`,s={ID:e};t!==void 0&&(s.options=t);const n=await this.Client.request(r,s);return n&&n.DeleteQuerySystemResolver?n.DeleteQuerySystemResolver:{Success:!1,ErrorMessage:"Failed to delete query"}}catch(r){return u.LogError(`GraphQLSystemUserClient::DeleteQuery - Error deleting query - ${r}`),{Success:!1,ErrorMessage:r.toString()}}}async RunAIPrompt(e){try{const t=g.gql`
669
+ }`,s={ID:e};t!==void 0&&(s.options=t);const a=await this.Client.request(r,s);return a&&a.DeleteQuerySystemResolver?a.DeleteQuerySystemResolver:{Success:!1,ErrorMessage:"Failed to delete query"}}catch(r){return u.LogError(`GraphQLSystemUserClient::DeleteQuery - Error deleting query - ${r}`),{Success:!1,ErrorMessage:r.toString()}}}async RunAIPrompt(e){try{const t=m.gql`
626
670
  query RunAIPromptSystemUser(
627
671
  $promptId: String!,
628
672
  $data: String,
@@ -681,7 +725,7 @@
681
725
  chatResult
682
726
  }
683
727
  }
684
- `,r=this.preparePromptVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIPromptSystemUser?this.processPromptResult(s.RunAIPromptSystemUser):{success:!1,error:"Failed to execute AI prompt as system user"}}catch(t){return u.LogError(`GraphQLSystemUserClient::RunAIPrompt - Error running AI prompt - ${t}`),{success:!1,error:t.toString()}}}async RunAIAgent(e){try{const t=g.gql`
728
+ `,r=this.preparePromptVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIPromptSystemUser?this.processPromptResult(s.RunAIPromptSystemUser):{success:!1,error:"Failed to execute AI prompt as system user"}}catch(t){return u.LogError(`GraphQLSystemUserClient::RunAIPrompt - Error running AI prompt - ${t}`),{success:!1,error:t.toString()}}}async RunAIAgent(e){try{const t=m.gql`
685
729
  query RunAIAgentSystemUser(
686
730
  $agentId: String!,
687
731
  $messages: String!,
@@ -708,7 +752,7 @@
708
752
  result
709
753
  }
710
754
  }
711
- `,r=this.prepareAgentVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIAgentSystemUser?this.processAgentResult(s.RunAIAgentSystemUser.result):{success:!1,agentRun:void 0}}catch(t){return u.LogError(`GraphQLSystemUserClient::RunAIAgent - Error running AI agent - ${t}`),{success:!1,agentRun:void 0}}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}prepareAgentVariables(e){const t={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._sessionId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),t}processPromptResult(e){let t,r,s;try{e.parsedResult&&(t=JSON.parse(e.parsedResult))}catch{t=e.parsedResult}try{e.validationResult&&(r=JSON.parse(e.validationResult))}catch{r=e.validationResult}try{e.chatResult&&(s=JSON.parse(e.chatResult))}catch{s=e.chatResult}return{success:e.success,output:e.output,parsedResult:t,error:e.error,executionTimeMs:e.executionTimeMs,tokensUsed:e.tokensUsed,promptRunId:e.promptRunId,rawResult:e.rawResult,validationResult:r,chatResult:s}}processAgentResult(e){return w.SafeJSONParse(e)}async ExecuteSimplePrompt(e){try{const t=g.gql`
755
+ `,r=this.prepareAgentVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIAgentSystemUser?this.processAgentResult(s.RunAIAgentSystemUser.result):{success:!1,agentRun:void 0}}catch(t){return u.LogError(`GraphQLSystemUserClient::RunAIAgent - Error running AI agent - ${t}`),{success:!1,agentRun:void 0}}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}prepareAgentVariables(e){const t={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._sessionId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),t}processPromptResult(e){let t,r,s;try{e.parsedResult&&(t=JSON.parse(e.parsedResult))}catch{t=e.parsedResult}try{e.validationResult&&(r=JSON.parse(e.validationResult))}catch{r=e.validationResult}try{e.chatResult&&(s=JSON.parse(e.chatResult))}catch{s=e.chatResult}return{success:e.success,output:e.output,parsedResult:t,error:e.error,executionTimeMs:e.executionTimeMs,tokensUsed:e.tokensUsed,promptRunId:e.promptRunId,rawResult:e.rawResult,validationResult:r,chatResult:s}}processAgentResult(e){return w.SafeJSONParse(e)}async ExecuteSimplePrompt(e){try{const t=m.gql`
712
756
  query ExecuteSimplePromptSystemUser(
713
757
  $systemPrompt: String!,
714
758
  $messages: String,
@@ -731,7 +775,7 @@
731
775
  executionTimeMs
732
776
  }
733
777
  }
734
- `,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this.Client.request(t,r);if(!s?.ExecuteSimplePromptSystemUser)return{success:!1,modelName:"Unknown",error:"Failed to execute simple prompt as system user"};const n=s.ExecuteSimplePromptSystemUser;let o;if(n.resultObject)try{o=JSON.parse(n.resultObject)}catch{o=n.resultObject}return{success:n.success,result:n.result,resultObject:o,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){return u.LogError(`GraphQLSystemUserClient::ExecuteSimplePrompt - Error executing simple prompt - ${t}`),{success:!1,modelName:"Unknown",error:t.toString()}}}async EmbedText(e){try{const t=g.gql`
778
+ `,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this.Client.request(t,r);if(!s?.ExecuteSimplePromptSystemUser)return{success:!1,modelName:"Unknown",error:"Failed to execute simple prompt as system user"};const a=s.ExecuteSimplePromptSystemUser;let o;if(a.resultObject)try{o=JSON.parse(a.resultObject)}catch{o=a.resultObject}return{success:a.success,result:a.result,resultObject:o,modelName:a.modelName,error:a.error,executionTimeMs:a.executionTimeMs}}catch(t){return u.LogError(`GraphQLSystemUserClient::ExecuteSimplePrompt - Error executing simple prompt - ${t}`),{success:!1,modelName:"Unknown",error:t.toString()}}}async EmbedText(e){try{const t=m.gql`
735
779
  query EmbedTextSystemUser(
736
780
  $textToEmbed: [String!]!,
737
781
  $modelSize: String!
@@ -746,7 +790,7 @@
746
790
  error
747
791
  }
748
792
  }
749
- `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this.Client.request(t,s);if(!n?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const o=n.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?o.embeddings:o.embeddings[0],modelName:o.modelName,vectorDimensions:o.vectorDimensions,error:o.error}}catch(t){return u.LogError(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}};S(ie,"GraphQLSystemUserClient");let U=ie;const ae=class ae{};S(ae,"GetDataOutput");let _=ae;const ue=class ue{};S(ue,"SimpleRemoteEntityOutput");let q=ue;const ce=class ce{};S(ce,"SimpleRemoteEntity");let O=ce;const le=class le{};S(le,"SimpleRemoteEntityField");let k=le;const de=class de{constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),n=this.createActionVariables(e,s,r),o=await this.executeActionMutation(n);return this.processActionResult(o,t)}catch(s){return this.handleActionError(s,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{...t,Value:r}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=g.gql`
793
+ `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this.Client.request(t,s);if(!a?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const o=a.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?o.embeddings:o.embeddings[0],modelName:o.modelName,vectorDimensions:o.vectorDimensions,error:o.error}}catch(t){return u.LogError(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}};S(ie,"GraphQLSystemUserClient");let q=ie;const ue=class ue{};S(ue,"GetDataOutput");let _=ue;const ce=class ce{};S(ce,"SimpleRemoteEntityOutput");let O=ce;const le=class le{};S(le,"SimpleRemoteEntity");let k=le;const de=class de{};S(de,"SimpleRemoteEntityField");let B=de;const ye=class ye{constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),a=this.createActionVariables(e,s,r),o=await this.executeActionMutation(a);return this.processActionResult(o,t)}catch(s){return this.handleActionError(s,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{...t,Value:r}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=m.gql`
750
794
  mutation RunAction($input: RunActionInput!) {
751
795
  RunAction(input: $input) {
752
796
  Success
@@ -755,7 +799,7 @@
755
799
  ResultData
756
800
  }
757
801
  }
758
- `;return await this._dataProvider.ExecuteGQL(t,e)}processActionResult(e,t){if(!e?.RunAction)throw new Error("Invalid response from server");let r;try{e.RunAction.ResultData&&(r=JSON.parse(e.RunAction.ResultData))}catch(s){u.LogError(`Failed to parse action result data: ${s}`)}return{Success:e.RunAction.Success,Message:e.RunAction.Message,Result:r,LogEntry:null,Params:t||[],RunParams:null}}handleActionError(e,t){const r=e;return u.LogError(`Error running action: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Result:null,LogEntry:null,Params:t||[],RunParams:null}}async RunEntityAction(e){try{const t=this.createEntityActionInput(e),r=await this.executeEntityActionMutation(t);return this.processEntityActionResult(r)}catch(t){return this.handleEntityActionError(t)}}createEntityActionInput(e){const t={EntityActionID:e.EntityAction.ID,InvocationType:e.InvocationType.Name,ListID:e.ListID,ViewID:e.ViewID};return e.Params&&(t.Params=this.convertActionParams(e.Params)),e.EntityObject&&this.addEntityInformation(t,e.EntityObject),t}convertActionParams(e){return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{Name:t.Name,Value:r,Type:t.Type}})}addEntityInformation(e,t){e.EntityName=t.EntityInfo?.Name,t.PrimaryKey&&(e.PrimaryKey=this.convertPrimaryKey(t.PrimaryKey))}convertPrimaryKey(e){return{KeyValuePairs:e.KeyValuePairs.map(t=>this.convertKeyValuePair(t))}}convertKeyValuePair(e){return{FieldName:e.FieldName,Value:e.Value!==null&&e.Value!==void 0?typeof e.Value=="object"?JSON.stringify(e.Value):e.Value.toString():null}}async executeEntityActionMutation(e){const t=g.gql`
802
+ `;return await this._dataProvider.ExecuteGQL(t,e)}processActionResult(e,t){if(!e?.RunAction)throw new Error("Invalid response from server");let r;try{e.RunAction.ResultData&&(r=JSON.parse(e.RunAction.ResultData))}catch(s){u.LogError(`Failed to parse action result data: ${s}`)}return{Success:e.RunAction.Success,Message:e.RunAction.Message,Result:r,LogEntry:null,Params:t||[],RunParams:null}}handleActionError(e,t){const r=e;return u.LogError(`Error running action: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Result:null,LogEntry:null,Params:t||[],RunParams:null}}async RunEntityAction(e){try{const t=this.createEntityActionInput(e),r=await this.executeEntityActionMutation(t);return this.processEntityActionResult(r)}catch(t){return this.handleEntityActionError(t)}}createEntityActionInput(e){const t={EntityActionID:e.EntityAction.ID,InvocationType:e.InvocationType.Name,ListID:e.ListID,ViewID:e.ViewID};return e.Params&&(t.Params=this.convertActionParams(e.Params)),e.EntityObject&&this.addEntityInformation(t,e.EntityObject),t}convertActionParams(e){return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{Name:t.Name,Value:r,Type:t.Type}})}addEntityInformation(e,t){e.EntityName=t.EntityInfo?.Name,t.PrimaryKey&&(e.PrimaryKey=this.convertPrimaryKey(t.PrimaryKey))}convertPrimaryKey(e){return{KeyValuePairs:e.KeyValuePairs.map(t=>this.convertKeyValuePair(t))}}convertKeyValuePair(e){return{FieldName:e.FieldName,Value:e.Value!==null&&e.Value!==void 0?typeof e.Value=="object"?JSON.stringify(e.Value):e.Value.toString():null}}async executeEntityActionMutation(e){const t=m.gql`
759
803
  mutation RunEntityAction($input: EntityActionInput!) {
760
804
  RunEntityAction(input: $input) {
761
805
  Success
@@ -763,7 +807,7 @@
763
807
  ResultData
764
808
  }
765
809
  }
766
- `;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(r){u.LogError(`Failed to parse entity action result data: ${r}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return u.LogError(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}};S(de,"GraphQLActionClient");let B=de;const ye=class ye{constructor(e){this._dataProvider=e}async RunTest(e){let t;try{e.onProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(o=>{try{const a=JSON.parse(o);a.resolver==="RunTestResolver"&&a.type==="TestExecutionProgress"&&a.status==="ok"&&a.data?.progress&&e.onProgress(a.data.progress)}catch(a){console.error("[GraphQLTestingClient] Failed to parse progress message:",a)}}));const r=g.gql`
810
+ `;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(r){u.LogError(`Failed to parse entity action result data: ${r}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return u.LogError(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}};S(ye,"GraphQLActionClient");let K=ye;const me=class me{constructor(e){this._dataProvider=e}async RunTest(e){let t;try{e.onProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(o=>{try{const i=JSON.parse(o);i.resolver==="RunTestResolver"&&i.type==="TestExecutionProgress"&&i.status==="ok"&&i.data?.progress&&e.onProgress(i.data.progress)}catch(i){console.error("[GraphQLTestingClient] Failed to parse progress message:",i)}}));const r=m.gql`
767
811
  mutation RunTest(
768
812
  $testId: String!,
769
813
  $verbose: Boolean,
@@ -780,7 +824,7 @@
780
824
  result
781
825
  }
782
826
  }
783
- `,s={testId:e.testId,verbose:e.verbose,environment:e.environment},n=await this._dataProvider.ExecuteGQL(r,s);return this.processTestResult(n.RunTest)}catch(r){return this.handleError(r,"RunTest")}finally{t&&t.unsubscribe()}}async RunTestSuite(e){let t;try{e.onProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(o=>{try{const a=JSON.parse(o);a.resolver==="RunTestResolver"&&a.type==="TestExecutionProgress"&&a.status==="ok"&&a.data?.progress&&e.onProgress(a.data.progress)}catch(a){console.error("[GraphQLTestingClient] Failed to parse progress message:",a)}}));const r=g.gql`
827
+ `,s={testId:e.testId,verbose:e.verbose,environment:e.environment},a=await this._dataProvider.ExecuteGQL(r,s);return this.processTestResult(a.RunTest)}catch(r){return this.handleError(r,"RunTest")}finally{t&&t.unsubscribe()}}async RunTestSuite(e){let t;try{e.onProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(o=>{try{const i=JSON.parse(o);i.resolver==="RunTestResolver"&&i.type==="TestExecutionProgress"&&i.status==="ok"&&i.data?.progress&&e.onProgress(i.data.progress)}catch(i){console.error("[GraphQLTestingClient] Failed to parse progress message:",i)}}));const r=m.gql`
784
828
  mutation RunTestSuite(
785
829
  $suiteId: String!,
786
830
  $verbose: Boolean,
@@ -799,11 +843,11 @@
799
843
  result
800
844
  }
801
845
  }
802
- `,s={suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel},n=await this._dataProvider.ExecuteGQL(r,s);return this.processSuiteResult(n.RunTestSuite)}catch(r){return this.handleError(r,"RunTestSuite")}finally{t&&t.unsubscribe()}}async IsTestRunning(e){try{const t=g.gql`
846
+ `,s={suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel},a=await this._dataProvider.ExecuteGQL(r,s);return this.processSuiteResult(a.RunTestSuite)}catch(r){return this.handleError(r,"RunTestSuite")}finally{t&&t.unsubscribe()}}async IsTestRunning(e){try{const t=m.gql`
803
847
  query IsTestRunning($testId: String!) {
804
848
  IsTestRunning(testId: $testId)
805
849
  }
806
- `;return(await this._dataProvider.ExecuteGQL(t,{testId:e})).IsTestRunning}catch(t){return u.LogError(`Error checking test running status: ${t.message}`),!1}}processTestResult(e){if(!e)throw new Error("Invalid response from server");let t;try{t=w.SafeJSONParse(e.result)}catch{t=e.result}return{success:e.success,errorMessage:e.errorMessage,executionTimeMs:e.executionTimeMs,result:t}}processSuiteResult(e){if(!e)throw new Error("Invalid response from server");let t;try{t=w.SafeJSONParse(e.result)}catch{t=e.result}return{success:e.success,errorMessage:e.errorMessage,executionTimeMs:e.executionTimeMs,result:t}}handleError(e,t){const r=e.message;return u.LogError(`${t} failed: ${r}`),{success:!1,errorMessage:r,result:null}}};S(ye,"GraphQLTestingClient");let J=ye;const me=class me{constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=g.gql`
850
+ `;return(await this._dataProvider.ExecuteGQL(t,{testId:e})).IsTestRunning}catch(t){return u.LogError(`Error checking test running status: ${t.message}`),!1}}processTestResult(e){if(!e)throw new Error("Invalid response from server");let t;try{t=w.SafeJSONParse(e.result)}catch{t=e.result}return{success:e.success,errorMessage:e.errorMessage,executionTimeMs:e.executionTimeMs,result:t}}processSuiteResult(e){if(!e)throw new Error("Invalid response from server");let t;try{t=w.SafeJSONParse(e.result)}catch{t=e.result}return{success:e.success,errorMessage:e.errorMessage,executionTimeMs:e.executionTimeMs,result:t}}handleError(e,t){const r=e.message;return u.LogError(`${t} failed: ${r}`),{success:!1,errorMessage:r,result:null}}};S(me,"GraphQLTestingClient");let J=me;const ge=class ge{constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=m.gql`
807
851
  query GetRegistryComponent(
808
852
  $registryName: String!,
809
853
  $namespace: String!,
@@ -824,7 +868,7 @@
824
868
  specification
825
869
  }
826
870
  }
827
- `,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const n=s.GetRegistryComponent;if(n.notModified&&!n.specification)return null;if(n.specification){if(typeof n.specification=="object")return n.specification;try{return JSON.parse(n.specification)}catch(o){return u.LogError(`Failed to parse component specification: ${o}`),null}}return null}return null}catch(t){throw u.LogError(t),new Error(`Failed to get registry component: ${t instanceof Error?t.message:"Unknown error"}`)}}async GetRegistryComponentWithHash(e){try{const t=g.gql`
871
+ `,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const a=s.GetRegistryComponent;if(a.notModified&&!a.specification)return null;if(a.specification){if(typeof a.specification=="object")return a.specification;try{return JSON.parse(a.specification)}catch(o){return u.LogError(`Failed to parse component specification: ${o}`),null}}return null}return null}catch(t){throw u.LogError(t),new Error(`Failed to get registry component: ${t instanceof Error?t.message:"Unknown error"}`)}}async GetRegistryComponentWithHash(e){try{const t=m.gql`
828
872
  query GetRegistryComponent(
829
873
  $registryName: String!,
830
874
  $namespace: String!,
@@ -845,7 +889,7 @@
845
889
  specification
846
890
  }
847
891
  }
848
- `,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const n=s.GetRegistryComponent;let o;if(n.specification)try{o=JSON.parse(n.specification)}catch(a){u.LogError(`Failed to parse component specification in GetRegistryComponentWithHash: ${a}`),o=void 0}return{specification:o,hash:n.hash,notModified:n.notModified,message:n.message}}return{specification:void 0,hash:"",notModified:!1,message:"Component not found"}}catch(t){throw u.LogError(t),new Error(`Failed to get registry component with hash: ${t instanceof Error?t.message:"Unknown error"}`)}}async SearchRegistryComponents(e){try{const t=g.gql`
892
+ `,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const a=s.GetRegistryComponent;let o;if(a.specification)try{o=JSON.parse(a.specification)}catch(i){u.LogError(`Failed to parse component specification in GetRegistryComponentWithHash: ${i}`),o=void 0}return{specification:o,hash:a.hash,notModified:a.notModified,message:a.message}}return{specification:void 0,hash:"",notModified:!1,message:"Component not found"}}catch(t){throw u.LogError(t),new Error(`Failed to get registry component with hash: ${t instanceof Error?t.message:"Unknown error"}`)}}async SearchRegistryComponents(e){try{const t=m.gql`
849
893
  query SearchRegistryComponents($params: SearchRegistryComponentsInput!) {
850
894
  SearchRegistryComponents(params: $params) {
851
895
  components
@@ -854,7 +898,7 @@
854
898
  limit
855
899
  }
856
900
  }
857
- `,r=await this._dataProvider.ExecuteGQL(t,{params:e});if(r&&r.SearchRegistryComponents){const s=r.SearchRegistryComponents;return{components:s.components.map(n=>JSON.parse(n)),total:s.total,offset:s.offset,limit:s.limit}}return{components:[],total:0,offset:0,limit:e.limit||10}}catch(t){throw u.LogError(t),new Error(`Failed to search registry components: ${t instanceof Error?t.message:"Unknown error"}`)}}async ResolveComponentDependencies(e,t){try{const r=g.gql`
901
+ `,r=await this._dataProvider.ExecuteGQL(t,{params:e});if(r&&r.SearchRegistryComponents){const s=r.SearchRegistryComponents;return{components:s.components.map(a=>JSON.parse(a)),total:s.total,offset:s.offset,limit:s.limit}}return{components:[],total:0,offset:0,limit:e.limit||10}}catch(t){throw u.LogError(t),new Error(`Failed to search registry components: ${t instanceof Error?t.message:"Unknown error"}`)}}async ResolveComponentDependencies(e,t){try{const r=m.gql`
858
902
  query ResolveComponentDependencies(
859
903
  $registryId: String!,
860
904
  $componentId: String!
@@ -879,7 +923,7 @@
879
923
  }
880
924
  }
881
925
  }
882
- `,s=await this._dataProvider.ExecuteGQL(r,{registryId:e,componentId:t});return s&&s.ResolveComponentDependencies?s.ResolveComponentDependencies:null}catch(r){throw u.LogError(r),new Error(`Failed to resolve component dependencies: ${r instanceof Error?r.message:"Unknown error"}`)}}async ComponentExists(e){try{return await this.GetRegistryComponent(e)!==null}catch{return!1}}async GetLatestVersion(e,t,r){try{return(await this.GetRegistryComponent({registryName:e,namespace:t,name:r,version:"latest"}))?.version||null}catch(s){return u.LogError(s),null}}async SendComponentFeedback(e){try{const t=g.gql`
926
+ `,s=await this._dataProvider.ExecuteGQL(r,{registryId:e,componentId:t});return s&&s.ResolveComponentDependencies?s.ResolveComponentDependencies:null}catch(r){throw u.LogError(r),new Error(`Failed to resolve component dependencies: ${r instanceof Error?r.message:"Unknown error"}`)}}async ComponentExists(e){try{return await this.GetRegistryComponent(e)!==null}catch{return!1}}async GetLatestVersion(e,t,r){try{return(await this.GetRegistryComponent({registryName:e,namespace:t,name:r,version:"latest"}))?.version||null}catch(s){return u.LogError(s),null}}async SendComponentFeedback(e){try{const t=m.gql`
883
927
  mutation SendComponentFeedback($feedback: ComponentFeedbackInput!) {
884
928
  SendComponentFeedback(feedback: $feedback) {
885
929
  success
@@ -887,5 +931,5 @@
887
931
  error
888
932
  }
889
933
  }
890
- `,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return u.LogError(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}};S(me,"GraphQLComponentRegistryClient");let K=me;Object.defineProperty(exports,"gql",{enumerable:!0,get:function(){return g.gql}}),exports.ActionItemInput=M,exports.ActionItemOutput=A,exports.FieldMapper=v,exports.GetDataOutput=_,exports.GraphQLAIClient=C,exports.GraphQLActionClient=B,exports.GraphQLComponentRegistryClient=K,exports.GraphQLDataProvider=he,exports.GraphQLProviderConfigData=b,exports.GraphQLSystemUserClient=U,exports.GraphQLTestingClient=J,exports.GraphQLTransactionGroup=N,exports.RoleInput=G,exports.RolesAndUsersInput=Q,exports.SimpleRemoteEntity=O,exports.SimpleRemoteEntityField=k,exports.SimpleRemoteEntityOutput=q,exports.SyncDataAction=Se,exports.SyncDataResult=F,exports.SyncRolesAndUsersResult=V,exports.UserInput=x,exports.setupGraphQLClient=we;
934
+ `,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return u.LogError(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}};S(ge,"GraphQLComponentRegistryClient");let j=ge;Object.defineProperty(exports,"gql",{enumerable:!0,get:function(){return m.gql}}),exports.ActionItemInput=G,exports.ActionItemOutput=U,exports.BrowserIndexedDBStorageProvider=x,exports.BrowserStorageProviderBase=b,exports.FieldMapper=C,exports.GetDataOutput=_,exports.GraphQLAIClient=N,exports.GraphQLActionClient=K,exports.GraphQLComponentRegistryClient=j,exports.GraphQLDataProvider=L,exports.GraphQLProviderConfigData=T,exports.GraphQLSystemUserClient=q,exports.GraphQLTestingClient=J,exports.GraphQLTransactionGroup=v,exports.RoleInput=V,exports.RolesAndUsersInput=Q,exports.SimpleRemoteEntity=k,exports.SimpleRemoteEntityField=B,exports.SimpleRemoteEntityOutput=O,exports.SyncDataAction=fe,exports.SyncDataResult=F,exports.SyncRolesAndUsersResult=M,exports.UserInput=A,exports.setupGraphQLClient=Ce;
891
935
  //# sourceMappingURL=index.cjs.map