@memberjunction/graphql-dataprovider 3.3.0 → 4.0.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.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0});import{gql as m,GraphQLClient as ve}from"graphql-request";import{gql as dt}from"graphql-request";import{TransactionGroupBase as Ue,TransactionResult as Ve,LogError as d,LogStatusEx as x,LogErrorEx as C,ProviderConfigDataBase as Le,ProviderBase as Qe,UserInfo as $e,getGraphQLTypeNameBase as A,ProviderType as Fe,BaseEntityResult as Ce,EntityFieldTSType as v,TransactionItem as Ne,UserRoleInfo as Ge,InMemoryLocalStorageProvider as _e,SetProvider as Oe,StartupManager as qe,IsVerboseLoggingEnabled as ke}from"@memberjunction/core";import{ViewInfo as Ae}from"@memberjunction/core-entities";import{Observable as M,Subject as Ke,Subscription as je}from"rxjs";import{createClient as Be}from"graphql-ws";import{v4 as Je}from"uuid";import{SafeJSONParse as $,MJGlobal as We,MJEventType as ze}from"@memberjunction/global";import{openDB as He}from"@tempfix/idb";const re=class re{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}};f(re,"FieldMapper");let N=re;const se=class se extends Ue{constructor(e){super(),this._provider=e}async HandleSubmit(){const e=m`
1
+ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});import{gql as m,GraphQLClient as T}from"graphql-request";import{gql as qe}from"graphql-request";import{TransactionGroupBase as j,TransactionResult as J,LogError as d,LogStatusEx as x,LogErrorEx as $,ProviderBase as W,UserInfo as U,getGraphQLTypeNameBase as N,ProviderType as z,BaseEntityResult as V,EntityFieldTSType as C,TransactionItem as L,UserRoleInfo as H,InMemoryLocalStorageProvider as X,ProviderConfigDataBase as Y,SetProvider as Z,StartupManager as ee,IsVerboseLoggingEnabled as te}from"@memberjunction/core";import{ViewInfo as Q}from"@memberjunction/core-entities";import{Observable as M,Subject as re,Subscription as se}from"rxjs";import{createClient as ne}from"graphql-ws";import{v4 as ae}from"uuid";import{SafeJSONParse as v,MJGlobal as oe,MJEventType as ie}from"@memberjunction/global";import{openDB as ue}from"@tempfix/idb";class A{static{p(this,"FieldMapper")}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}}class G extends j{static{p(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=m`
2
2
  mutation ExecuteTransactionGroup($group: TransactionInputType!) {
3
3
  ExecuteTransactionGroup(group: $group) {
4
4
  Success
@@ -6,7 +6,7 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
6
6
  ResultsJSON
7
7
  }
8
8
  }
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,n=[];for(let i=0;i<this.PendingTransactions.length;i++){const o=a.ResultsJSON[i],u=$(o),c=this.PendingTransactions[i];n.push(new Ve(c,u,u!==null))}return n}else throw new Error("Failed to execute transaction group")}};f(se,"GraphQLTransactionGroup");let T=se;const ae=class ae{constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=m`
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,a=[];for(let i=0;i<this.PendingTransactions.length;i++){const o=n.ResultsJSON[i],u=v(o),c=this.PendingTransactions[i];a.push(new J(c,u,u!==null))}return a}else throw new Error("Failed to execute transaction group")}}class F{static{p(this,"GraphQLAIClient")}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=m`
10
10
  mutation RunAIPrompt(
11
11
  $promptId: String!,
12
12
  $data: String,
@@ -65,7 +65,7 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
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,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 d(`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(o=>{try{x({message:"[GraphQLAIClient] Received statusUpdate message",verboseOnly:!0,additionalArgs:[o]});const u=JSON.parse(o);if(x({message:"[GraphQLAIClient] Parsed message",verboseOnly:!0,additionalArgs:[u]}),u.resolver==="RunAIAgentResolver"&&u.type==="ExecutionProgress"&&u.status==="ok"&&u.data?.progress){x({message:"[GraphQLAIClient] Forwarding progress to callback",verboseOnly:!0,additionalArgs:[u.data.progress]});const c={...u.data.progress,metadata:{...u.data.progress.metadata||{},agentRunId:u.data.agentRunId}};e.onProgress(c)}else x({message:"[GraphQLAIClient] Message does not match filter criteria",verboseOnly:!0,additionalArgs:[{resolver:u.resolver,type:u.type,status:u.status,hasProgress:!!u.data?.progress}]})}catch(u){console.error("[GraphQLAIClient] Failed to parse progress message:",u,"Raw message:",o)}}));const a=m`
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 d(`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(o=>{try{x({message:"[GraphQLAIClient] Received statusUpdate message",verboseOnly:!0,additionalArgs:[o]});const u=JSON.parse(o);if(x({message:"[GraphQLAIClient] Parsed message",verboseOnly:!0,additionalArgs:[u]}),u.resolver==="RunAIAgentResolver"&&u.type==="ExecutionProgress"&&u.status==="ok"&&u.data?.progress){x({message:"[GraphQLAIClient] Forwarding progress to callback",verboseOnly:!0,additionalArgs:[u.data.progress]});const c={...u.data.progress,metadata:{...u.data.progress.metadata||{},agentRunId:u.data.agentRunId}};e.onProgress(c)}else x({message:"[GraphQLAIClient] Message does not match filter criteria",verboseOnly:!0,additionalArgs:[{resolver:u.resolver,type:u.type,status:u.status,hasProgress:!!u.data?.progress}]})}catch(u){console.error("[GraphQLAIClient] Failed to parse progress message:",u,"Raw message:",o)}}));const n=m`
69
69
  mutation RunAIAgent(
70
70
  $agentId: String!,
71
71
  $messages: String!,
@@ -104,7 +104,7 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
104
104
  result
105
105
  }
106
106
  }
107
- `,n=this.prepareAgentVariables(e,t,r),i=await this._dataProvider.ExecuteGQL(a,n);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 $(e)}handleAgentError(e){return d(`Error running AI agent: ${e}`),{success:!1,agentRun:void 0}}async RunAIAgentFromConversationDetail(e){let t;try{e.onProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(n=>{try{const i=JSON.parse(n);if(i.resolver==="RunAIAgentResolver"&&i.type==="ExecutionProgress"&&i.status==="ok"&&i.data?.progress){const o={...i.data.progress,metadata:{...i.data.progress.metadata||{},agentRunId:i.data.agentRunId}};e.onProgress(o)}}catch(i){console.error("[GraphQLAIClient] Failed to parse progress message:",i)}}));const r=m`
107
+ `,a=this.prepareAgentVariables(e,t,r),i=await this._dataProvider.ExecuteGQL(n,a);return this.processAgentResult(i.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 v(e)}handleAgentError(e){return d(`Error running AI agent: ${e}`),{success:!1,agentRun:void 0}}async RunAIAgentFromConversationDetail(e){let t;try{e.onProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(a=>{try{const i=JSON.parse(a);if(i.resolver==="RunAIAgentResolver"&&i.type==="ExecutionProgress"&&i.status==="ok"&&i.data?.progress){const o={...i.data.progress,metadata:{...i.data.progress.metadata||{},agentRunId:i.data.agentRunId}};e.onProgress(o)}}catch(i){console.error("[GraphQLAIClient] Failed to parse progress message:",i)}}));const r=m`
108
108
  mutation RunAIAgentFromConversationDetail(
109
109
  $conversationDetailId: String!,
110
110
  $agentId: String!,
@@ -141,7 +141,7 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
141
141
  result
142
142
  }
143
143
  }
144
- `,s={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId};e.maxHistoryMessages!==void 0&&(s.maxHistoryMessages=e.maxHistoryMessages),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.createArtifacts!==void 0&&(s.createArtifacts=e.createArtifacts),e.createNotification!==void 0&&(s.createNotification=e.createNotification),e.sourceArtifactId!==void 0&&(s.sourceArtifactId=e.sourceArtifactId),e.sourceArtifactVersionId!==void 0&&(s.sourceArtifactVersionId=e.sourceArtifactVersionId);const a=await this._dataProvider.ExecuteGQL(r,s);return this.processAgentResult(a.RunAIAgentFromConversationDetail?.result)}catch(r){return this.handleAgentError(r)}finally{t&&t.unsubscribe()}}async ExecuteSimplePrompt(e){try{const t=m`
144
+ `,s={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId};e.maxHistoryMessages!==void 0&&(s.maxHistoryMessages=e.maxHistoryMessages),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.createArtifacts!==void 0&&(s.createArtifacts=e.createArtifacts),e.createNotification!==void 0&&(s.createNotification=e.createNotification),e.sourceArtifactId!==void 0&&(s.sourceArtifactId=e.sourceArtifactId),e.sourceArtifactVersionId!==void 0&&(s.sourceArtifactVersionId=e.sourceArtifactVersionId);const n=await this._dataProvider.ExecuteGQL(r,s);return this.processAgentResult(n.RunAIAgentFromConversationDetail?.result)}catch(r){return this.handleAgentError(r)}finally{t&&t.unsubscribe()}}async ExecuteSimplePrompt(e){try{const t=m`
145
145
  mutation ExecuteSimplePrompt(
146
146
  $systemPrompt: String!,
147
147
  $messages: String,
@@ -164,7 +164,7 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
164
164
  executionTimeMs
165
165
  }
166
166
  }
167
- `,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 n;if(a.resultObject)try{n=JSON.parse(a.resultObject)}catch{n=a.resultObject}return{success:a.success,result:a.result,resultObject:n,modelName:a.modelName,error:a.error,executionTimeMs:a.executionTimeMs}}catch(t){const r=t;return d(`Error executing simple prompt: ${r}`),{success:!1,modelName:"Unknown",error:r.message||"Unknown error occurred"}}}async EmbedText(e){try{const t=m`
167
+ `,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 a;if(n.resultObject)try{a=JSON.parse(n.resultObject)}catch{a=n.resultObject}return{success:n.success,result:n.result,resultObject:a,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){const r=t;return d(`Error executing simple prompt: ${r}`),{success:!1,modelName:"Unknown",error:r.message||"Unknown error occurred"}}}async EmbedText(e){try{const t=m`
168
168
  mutation EmbedText(
169
169
  $textToEmbed: [String!]!,
170
170
  $modelSize: String!
@@ -179,7 +179,7 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
179
179
  error
180
180
  }
181
181
  }
182
- `,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 n=a.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?n.embeddings:n.embeddings[0],modelName:n.modelName,vectorDimensions:n.vectorDimensions,error:n.error}}catch(t){const r=t;return d(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}};f(ae,"GraphQLAIClient");let U=ae;const P="default",ne=class ne{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()):[]}};f(ne,"BrowserStorageProviderBase");let V=ne;const Xe="MJ_Metadata",Ye=3,be=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"],xe="Metadata_KVPairs",oe=class oe extends V{constructor(){super(),this._dbReady=!1,this.dbPromise=He(Xe,Ye,{upgrade(e){try{e.objectStoreNames.contains(xe)&&e.deleteObjectStore(xe);for(const t of be)e.objectStoreNames.contains(t)||e.createObjectStore(t)}catch(t){C({error:t,message:t?.message})}}}),this.dbPromise.then(()=>{this._dbReady=!0}).catch(e=>{C({error:e,message:"IndexedDB initialization failed: "+e?.message})})}isKnownCategory(e){const t=`mj:${e}`;return be.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),n=this.getStoreKey(e,r),i=s.transaction(a,"readwrite");await i.objectStore(a).put(t,n),await i.done}catch(s){C({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 C({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),n=r.transaction(s,"readwrite");await n.objectStore(s).delete(a),await n.done}catch(r){C({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}]:`,n=t.transaction("mj:default","readwrite"),i=n.objectStore("mj:default"),o=await i.getAllKeys();for(const u of o)typeof u=="string"&&u.startsWith(a)&&await i.delete(u);await n.done}}catch(t){C({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(u=>String(u));const o=`[${r}]:`;return i.map(u=>String(u)).filter(u=>u.startsWith(o)).map(u=>u.slice(o.length))}catch(t){return C({error:t,message:t?.message}),await super.GetCategoryKeys(e)}}};f(oe,"BrowserIndexedDBStorageProvider");let L=oe;const ie=class ie extends Le{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 UserAPIKey(){return this.Data.UserAPIKey}set UserAPIKey(e){this.Data.UserAPIKey=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,n,i,o,u){super({Token:e,URL:t,WSURL:r,MJAPIKey:o,UserAPIKey:u,RefreshTokenFunction:s},a,n,i)}};f(ie,"GraphQLProviderConfigData");let F=ie;const h=class h extends Qe{constructor(){super(),this._refreshPromise=null,this._innerCurrentUserQueryString=`CurrentUser {
182
+ `,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 a=n.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?a.embeddings:a.embeddings[0],modelName:a.modelName,vectorDimensions:a.vectorDimensions,error:a.error}}catch(t){const r=t;return d(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}}const P="default";class _{static{p(this,"BrowserStorageProviderBase")}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()):[]}}const ce="MJ_Metadata",le=3,O=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"],q="Metadata_KVPairs";class K extends _{static{p(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=ue(ce,le,{upgrade(e){try{e.objectStoreNames.contains(q)&&e.deleteObjectStore(q);for(const t of O)e.objectStoreNames.contains(t)||e.createObjectStore(t)}catch(t){$({error:t,message:t?.message})}}}),this.dbPromise.then(()=>{this._dbReady=!0}).catch(e=>{$({error:e,message:"IndexedDB initialization failed: "+e?.message})})}isKnownCategory(e){const t=`mj:${e}`;return O.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,n=this.getStoreName(r),a=this.getStoreKey(e,r),i=s.transaction(n,"readwrite");await i.objectStore(n).put(t,a),await i.done}catch(s){$({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),n=this.getStoreKey(e,t);return await r.transaction(s).objectStore(s).get(n)??null}catch(r){return $({error:r,message:r?.message}),await super.GetItem(e,t)}}async Remove(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t),a=r.transaction(s,"readwrite");await a.objectStore(s).delete(n),await a.done}catch(r){$({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 n=t.transaction(s,"readwrite");await n.objectStore(s).clear(),await n.done}else{const n=`[${r}]:`,a=t.transaction("mj:default","readwrite"),i=a.objectStore("mj:default"),o=await i.getAllKeys();for(const u of o)typeof u=="string"&&u.startsWith(n)&&await i.delete(u);await a.done}}catch(t){$({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(u=>String(u));const o=`[${r}]:`;return i.map(u=>String(u)).filter(u=>u.startsWith(o)).map(u=>u.slice(o.length))}catch(t){return $({error:t,message:t?.message}),await super.GetCategoryKeys(e)}}}class de extends Y{static{p(this,"GraphQLProviderConfigData")}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 UserAPIKey(){return this.Data.UserAPIKey}set UserAPIKey(e){this.Data.UserAPIKey=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,a,i,o,u){super({Token:e,URL:t,WSURL:r,MJAPIKey:o,UserAPIKey:u,RefreshTokenFunction:s},n,a,i)}}class S extends W{static{p(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._innerCurrentUserQueryString=`CurrentUser {
183
183
  ${this.userInfoString()}
184
184
  UserRoles_UserIDArray {
185
185
  ${this.userRoleInfoString()}
@@ -187,7 +187,7 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
187
187
  }
188
188
  `,this._currentUserQuery=m`query CurrentUserAndRoles {
189
189
  ${this._innerCurrentUserQueryString}
190
- }`,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 U(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return Je()}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,e.UserAPIKey),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,e.UserAPIKey)),await h.Instance.SaveStoredSessionID(h.Instance._sessionId),this._sessionId=h.Instance._sessionId,this._client=h.Instance._client),super.Config(e)}catch(a){throw d(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 $e(this,{...t,UserRoles:r})}}async RunReport(e,t){const r=m`
190
+ }`,this._wsClient=null,this._wsClientCreatedAt=null,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=1800*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=300*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=600*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,S._instance||(S._instance=this)}static get Instance(){return S._instance}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new F(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return ae()}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,e.UserAPIKey),await this.SaveStoredSessionID(this._sessionId)):(S.Instance._configData=e,S.Instance._sessionId===void 0&&(S.Instance._sessionId=await this.GetPreferredUUID(s)),S.Instance._client||(S.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,S.Instance._sessionId,e.MJAPIKey,e.UserAPIKey)),await S.Instance.SaveStoredSessionID(S.Instance._sessionId),this._sessionId=S.Instance._sessionId,this._client=S.Instance._client),super.Config(e)}catch(n){throw d(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(this,{...t,UserRoles:r})}}async RunReport(e,t){const r=m`
191
191
  query GetReportDataQuery ($ReportID: String!) {
192
192
  GetReportData(ReportID: $ReportID) {
193
193
  Success
@@ -202,19 +202,19 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
202
202
  ${this.QueryReturnFieldList}
203
203
  }
204
204
  }
205
- `,s=e.map(n=>({QueryID:n.QueryID,QueryName:n.QueryName,CategoryID:n.CategoryID,CategoryPath:n.CategoryPath,Parameters:n.Parameters,MaxRows:n.MaxRows,StartRow:n.StartRow,ForceAuditLog:n.ForceAuditLog,AuditLogDescription:n.AuditLogDescription})),a=await this.ExecuteGQL(r,{input:s});return a&&a.RunQueries?a.RunQueries.map(n=>this.TransformQueryPayload(n)):[]}async RunQueryByID(e,t,r,s,a,n,i){const o=m`
205
+ `,s=e.map(a=>({QueryID:a.QueryID,QueryName:a.QueryName,CategoryID:a.CategoryID,CategoryPath:a.CategoryPath,Parameters:a.Parameters,MaxRows:a.MaxRows,StartRow:a.StartRow,ForceAuditLog:a.ForceAuditLog,AuditLogDescription:a.AuditLogDescription})),n=await this.ExecuteGQL(r,{input:s});return n&&n.RunQueries?n.RunQueries.map(a=>this.TransformQueryPayload(a)):[]}async RunQueryByID(e,t,r,s,n,a,i){const o=m`
206
206
  query GetQueryDataQuery($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
207
207
  GetQueryData(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
208
208
  ${this.QueryReturnFieldList}
209
209
  }
210
210
  }
211
- `,u={QueryID:e};t!==void 0&&(u.CategoryID=t),r!==void 0&&(u.CategoryPath=r),a!==void 0&&(u.Parameters=a),n!==void 0&&(u.MaxRows=n),i!==void 0&&(u.StartRow=i);const c=await this.ExecuteGQL(o,u);if(c&&c.GetQueryData)return this.TransformQueryPayload(c.GetQueryData)}async RunQueryByName(e,t,r,s,a,n,i){const o=m`
211
+ `,u={QueryID:e};t!==void 0&&(u.CategoryID=t),r!==void 0&&(u.CategoryPath=r),n!==void 0&&(u.Parameters=n),a!==void 0&&(u.MaxRows=a),i!==void 0&&(u.StartRow=i);const c=await this.ExecuteGQL(o,u);if(c&&c.GetQueryData)return this.TransformQueryPayload(c.GetQueryData)}async RunQueryByName(e,t,r,s,n,a,i){const o=m`
212
212
  query GetQueryDataByNameQuery($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
213
213
  GetQueryDataByName(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
214
214
  ${this.QueryReturnFieldList}
215
215
  }
216
216
  }
217
- `,u={QueryName:e};t!==void 0&&(u.CategoryID=t),r!==void 0&&(u.CategoryPath=r),a!==void 0&&(u.Parameters=a),n!==void 0&&(u.MaxRows=n),i!==void 0&&(u.StartRow=i);const c=await this.ExecuteGQL(o,u);if(c&&c.GetQueryDataByName)return this.TransformQueryPayload(c.GetQueryDataByName)}get QueryReturnFieldList(){return`
217
+ `,u={QueryName:e};t!==void 0&&(u.CategoryID=t),r!==void 0&&(u.CategoryPath=r),n!==void 0&&(u.Parameters=n),a!==void 0&&(u.MaxRows=a),i!==void 0&&(u.StartRow=i);const c=await this.ExecuteGQL(o,u);if(c&&c.GetQueryDataByName)return this.TransformQueryPayload(c.GetQueryDataByName)}get QueryReturnFieldList(){return`
218
218
  Success
219
219
  QueryID
220
220
  QueryName
@@ -239,7 +239,7 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
239
239
  }
240
240
  }
241
241
  }
242
- `,n=(await this.ExecuteGQL(s,{input:r}))?.RunQueriesWithCacheCheck;if(!n)return{success:!1,results:[],errorMessage:"No response from server"};const i=n.results.map(o=>{if((o.status==="stale"||o.status==="no_validation")&&o.Results){const u=JSON.parse(o.Results);return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,results:u,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}});return{success:n.success,results:i,errorMessage:n.errorMessage}}catch(r){return d(`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 n,i;if(e.ViewEntity)i=e.ViewEntity,n=i.Entity;else{const{entityName:g,v:S}=await this.getEntityNameAndUserView(e,t);i=S,n=g}const o=this.Entities.find(g=>g.Name===n);if(!o)throw new Error(`Entity ${n} not found in metadata`);let u=!1;const c=A(o);e.ViewID?(r=`Run${c}ViewByID`,s="RunViewByIDInput",a.ViewID=e.ViewID):e.ViewName?(r=`Run${c}ViewByName`,s="RunViewByNameInput",a.ViewName=e.ViewName):(u=!0,r=`Run${c}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),u||(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),e.Aggregates&&e.Aggregates.length>0&&(a.Aggregates=e.Aggregates.map(g=>({expression:g.expression,alias:g.alias})));const p=this.getViewRunTimeFieldList(o,i,e,u),I=e.Aggregates&&e.Aggregates.length>0?`
242
+ `,a=(await this.ExecuteGQL(s,{input:r}))?.RunQueriesWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map(o=>{if((o.status==="stale"||o.status==="no_validation")&&o.Results){const u=JSON.parse(o.Results);return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,results:u,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}});return{success:a.success,results:i,errorMessage:a.errorMessage}}catch(r){return d(`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 n={};let a,i;if(e.ViewEntity)i=e.ViewEntity,a=i.Entity;else{const{entityName:g,v:I}=await this.getEntityNameAndUserView(e,t);i=I,a=g}const o=this.Entities.find(g=>g.Name===a);if(!o)throw new Error(`Entity ${a} not found in metadata`);let u=!1;const c=N(o);e.ViewID?(r=`Run${c}ViewByID`,s="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(r=`Run${c}ViewByName`,s="RunViewByNameInput",n.ViewName=e.ViewName):(u=!0,r=`Run${c}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),u||(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),e.Aggregates&&e.Aggregates.length>0&&(n.Aggregates=e.Aggregates.map(g=>({expression:g.expression,alias:g.alias})));const f=this.getViewRunTimeFieldList(o,i,e,u),R=e.Aggregates&&e.Aggregates.length>0?`
243
243
  AggregateResults {
244
244
  alias
245
245
  expression
@@ -250,7 +250,7 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
250
250
  query RunViewQuery ($input: ${s}!) {
251
251
  ${r}(input: $input) {
252
252
  Results {
253
- ${p.join(`
253
+ ${f.join(`
254
254
  `)}
255
255
  }
256
256
  UserViewRunID
@@ -258,9 +258,9 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
258
258
  TotalRowCount
259
259
  ExecutionTime
260
260
  Success
261
- ErrorMessage${I}
261
+ ErrorMessage${R}
262
262
  }
263
- }`;a.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:n,queryName:r,aggregateCount:a.Aggregates.length,aggregates:a.Aggregates});const y=await this.ExecuteGQL(l,{input:a});if(y&&y[r]){const g=y[r].AggregateResults;a.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:n,aggregateResultCount:g?.length||0,aggregateResults:g,aggregateExecutionTime:y[r].AggregateExecutionTime});const S=y[r].Results;if(S&&S.length>0){const w=o.Fields.filter(D=>D.CodeName!==D.Name&&D.CodeName!==void 0);S.forEach(D=>{this.ConvertBackToMJFields(D),w.forEach(b=>{D[b.Name]=D[b.CodeName]})})}return y[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw d(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],a=[];for(const c of e){let p="",I="";const l={};let y=null,g=null;if(c.ViewEntity)g=c.ViewEntity,y=g.Get("Entity");else{const{entityName:D,v:b}=await this.getEntityNameAndUserView(c,t);g=b,y=D}const S=this.Entities.find(D=>D.Name===y);if(!S)throw new Error(`Entity ${y} not found in metadata`);s.push(S);let R=!1;const w=A(S);c.ViewID?(p=`Run${w}ViewByID`,I="RunViewByIDInput",l.ViewID=c.ViewID):c.ViewName?(p=`Run${w}ViewByName`,I="RunViewByNameInput",l.ViewName=c.ViewName):(R=!0,p=`Run${w}DynamicView`,I="RunDynamicViewInput",l.EntityName=c.EntityName),l.ExtraFilter=c.ExtraFilter||"",l.OrderBy=c.OrderBy||"",l.UserSearchString=c.UserSearchString||"",l.Fields=c.Fields,l.IgnoreMaxRows=c.IgnoreMaxRows||!1,c.MaxRows!==void 0&&(l.MaxRows=c.MaxRows),c.StartRow!==void 0&&(l.StartRow=c.StartRow),l.ForceAuditLog=c.ForceAuditLog||!1,l.ResultType=c.ResultType||"simple",c.AuditLogDescription&&c.AuditLogDescription.length>0&&(l.AuditLogDescription=c.AuditLogDescription),R||(l.ExcludeUserViewRunID=c.ExcludeUserViewRunID||"",l.ExcludeDataFromAllPriorViewRuns=c.ExcludeDataFromAllPriorViewRuns||!1,l.OverrideExcludeFilter=c.OverrideExcludeFilter||"",l.SaveViewResults=c.SaveViewResults||!1),c.Aggregates&&c.Aggregates.length>0&&(l.Aggregates=c.Aggregates.map(D=>({expression:D.expression,alias:D.alias}))),r.push(l),a.push(...this.getViewRunTimeFieldList(S,g,c,R))}const i=e.some(c=>c.Aggregates&&c.Aggregates.length>0)?`
263
+ }`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:a,queryName:r,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const y=await this.ExecuteGQL(l,{input:n});if(y&&y[r]){const g=y[r].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:a,aggregateResultCount:g?.length||0,aggregateResults:g,aggregateExecutionTime:y[r].AggregateExecutionTime});const I=y[r].Results;if(I&&I.length>0){const E=o.Fields.filter(w=>w.CodeName!==w.Name&&w.CodeName!==void 0);I.forEach(w=>{this.ConvertBackToMJFields(w),E.forEach(b=>{w[b.Name]=w[b.CodeName]})})}return y[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw d(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],n=[];for(const c of e){let f="",R="";const l={};let y=null,g=null;if(c.ViewEntity)g=c.ViewEntity,y=g.Get("Entity");else{const{entityName:w,v:b}=await this.getEntityNameAndUserView(c,t);g=b,y=w}const I=this.Entities.find(w=>w.Name===y);if(!I)throw new Error(`Entity ${y} not found in metadata`);s.push(I);let D=!1;const E=N(I);c.ViewID?(f=`Run${E}ViewByID`,R="RunViewByIDInput",l.ViewID=c.ViewID):c.ViewName?(f=`Run${E}ViewByName`,R="RunViewByNameInput",l.ViewName=c.ViewName):(D=!0,f=`Run${E}DynamicView`,R="RunDynamicViewInput",l.EntityName=c.EntityName),l.ExtraFilter=c.ExtraFilter||"",l.OrderBy=c.OrderBy||"",l.UserSearchString=c.UserSearchString||"",l.Fields=c.Fields,l.IgnoreMaxRows=c.IgnoreMaxRows||!1,c.MaxRows!==void 0&&(l.MaxRows=c.MaxRows),c.StartRow!==void 0&&(l.StartRow=c.StartRow),l.ForceAuditLog=c.ForceAuditLog||!1,l.ResultType=c.ResultType||"simple",c.AuditLogDescription&&c.AuditLogDescription.length>0&&(l.AuditLogDescription=c.AuditLogDescription),D||(l.ExcludeUserViewRunID=c.ExcludeUserViewRunID||"",l.ExcludeDataFromAllPriorViewRuns=c.ExcludeDataFromAllPriorViewRuns||!1,l.OverrideExcludeFilter=c.OverrideExcludeFilter||"",l.SaveViewResults=c.SaveViewResults||!1),c.Aggregates&&c.Aggregates.length>0&&(l.Aggregates=c.Aggregates.map(w=>({expression:w.expression,alias:w.alias}))),r.push(l),n.push(...this.getViewRunTimeFieldList(I,g,c,D))}const i=e.some(c=>c.Aggregates&&c.Aggregates.length>0)?`
264
264
  AggregateResults {
265
265
  alias
266
266
  expression
@@ -285,7 +285,7 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
285
285
  Success
286
286
  ErrorMessage${i}
287
287
  }
288
- }`,u=await this.ExecuteGQL(o,{input:r});if(u&&u.RunViews){const c=u.RunViews;for(const[p,I]of c.entries())I.Results=I.Results.map(l=>{let y=JSON.parse(l.Data);return this.ConvertBackToMJFields(y),y});return c}return null}catch(r){throw d(r),r}}async RunViewsWithCacheCheck(e,t){try{const r=e.map(o=>({params:{EntityName:o.params.EntityName||"",ExtraFilter:o.params.ExtraFilter||"",OrderBy:o.params.OrderBy||"",Fields:o.params.Fields,UserSearchString:o.params.UserSearchString||"",IgnoreMaxRows:o.params.IgnoreMaxRows||!1,MaxRows:o.params.MaxRows,StartRow:o.params.StartRow,ForceAuditLog:o.params.ForceAuditLog||!1,AuditLogDescription:o.params.AuditLogDescription||"",ResultType:o.params.ResultType||"simple"},cacheStatus:o.cacheStatus?{maxUpdatedAt:o.cacheStatus.maxUpdatedAt,rowCount:o.cacheStatus.rowCount}:null})),s=m`
288
+ }`,u=await this.ExecuteGQL(o,{input:r});if(u&&u.RunViews){const c=u.RunViews;for(const[f,R]of c.entries())R.Results=R.Results.map(l=>{let y=JSON.parse(l.Data);return this.ConvertBackToMJFields(y),y});return c}return null}catch(r){throw d(r),r}}async RunViewsWithCacheCheck(e,t){try{const r=e.map(o=>({params:{EntityName:o.params.EntityName||"",ExtraFilter:o.params.ExtraFilter||"",OrderBy:o.params.OrderBy||"",Fields:o.params.Fields,UserSearchString:o.params.UserSearchString||"",IgnoreMaxRows:o.params.IgnoreMaxRows||!1,MaxRows:o.params.MaxRows,StartRow:o.params.StartRow,ForceAuditLog:o.params.ForceAuditLog||!1,AuditLogDescription:o.params.AuditLogDescription||"",ResultType:o.params.ResultType||"simple"},cacheStatus:o.cacheStatus?{maxUpdatedAt:o.cacheStatus.maxUpdatedAt,rowCount:o.cacheStatus.rowCount}:null})),s=m`
289
289
  query RunViewsWithCacheCheckQuery($input: [RunViewWithCacheCheckInput!]!) {
290
290
  RunViewsWithCacheCheck(input: $input) {
291
291
  success
@@ -318,7 +318,7 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
318
318
  }
319
319
  }
320
320
  }
321
- `,n=(await this.ExecuteGQL(s,{input:r}))?.RunViewsWithCacheCheck;if(!n)return{success:!1,results:[],errorMessage:"No response from server"};const i=n.results.map((o,u)=>{const c=e[u];if(o.status==="differential"&&o.differentialData){const p=o.differentialData.updatedRows.map(I=>{const l=JSON.parse(I.Data);return this.ConvertBackToMJFields(l),l});return{viewIndex:o.viewIndex,status:o.status,results:void 0,differentialData:{updatedRows:p,deletedRecordIDs:o.differentialData.deletedRecordIDs},maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}if(o.status==="stale"&&o.Results){const p=o.Results.map(I=>{const l=JSON.parse(I.Data);return this.ConvertBackToMJFields(l),l});return{viewIndex:o.viewIndex,status:o.status,results:p,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}return{viewIndex:o.viewIndex,status:o.status,results:void 0,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}});return{success:n.success,results:i,errorMessage:n.errorMessage}}catch(r){return d(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 Ae.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await Ae.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=[],n=new N;if(r.Fields){for(const i of e.PrimaryKeys)r.Fields.find(o=>o.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&a.push(i.Name);r.Fields.forEach(i=>{a.push(n.MapFieldName(i))})}else if(s)e.Fields.forEach(i=>{i.IsBinaryFieldType||a.push(n.MapFieldName(i.CodeName))});else{for(const i of e.PrimaryKeys)a.find(o=>o.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&a.push(i.Name);t.Columns.forEach(i=>{i.hidden===!1&&!a.find(o=>o.trim().toLowerCase()===i.EntityField?.Name.trim().toLowerCase())&&i.EntityField&&a.push(n.MapFieldName(i.EntityField.CodeName))})}return a}get ProviderType(){return Fe.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,n)=>a.ChangedAt>n.ChangedAt?-1:1):null}catch(r){throw d(r),r}}async GetRecordDependencies(e,t){try{const r=m`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
321
+ `,a=(await this.ExecuteGQL(s,{input:r}))?.RunViewsWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map((o,u)=>{const c=e[u];if(o.status==="differential"&&o.differentialData){const f=o.differentialData.updatedRows.map(R=>{const l=JSON.parse(R.Data);return this.ConvertBackToMJFields(l),l});return{viewIndex:o.viewIndex,status:o.status,results:void 0,differentialData:{updatedRows:f,deletedRecordIDs:o.differentialData.deletedRecordIDs},maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}if(o.status==="stale"&&o.Results){const f=o.Results.map(R=>{const l=JSON.parse(R.Data);return this.ConvertBackToMJFields(l),l});return{viewIndex:o.viewIndex,status:o.status,results:f,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}return{viewIndex:o.viewIndex,status:o.status,results:void 0,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}});return{success:a.success,results:i,errorMessage:a.errorMessage}}catch(r){return d(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 Q.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await Q.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=[],a=new A;if(r.Fields){for(const i of e.PrimaryKeys)r.Fields.find(o=>o.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);r.Fields.forEach(i=>{n.push(a.MapFieldName(i))})}else if(s)e.Fields.forEach(i=>{i.IsBinaryFieldType||n.push(a.MapFieldName(i.CodeName))});else{for(const i of e.PrimaryKeys)n.find(o=>o.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);t.Columns.forEach(i=>{i.hidden===!1&&!n.find(o=>o.trim().toLowerCase()===i.EntityField?.Name.trim().toLowerCase())&&i.EntityField&&n.push(a.MapFieldName(i.EntityField.CodeName))})}return n}get ProviderType(){return z.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,a)=>n.ChangedAt>a.ChangedAt?-1:1):null}catch(r){throw d(r),r}}async GetRecordDependencies(e,t){try{const r=m`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
322
322
  GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
323
323
  EntityName
324
324
  RelatedEntityName
@@ -352,7 +352,7 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
352
352
  }
353
353
  }
354
354
  }
355
- }`;let s={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(n=>n.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`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
355
+ }`;let s={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(a=>a.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=m`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
356
356
  MergeRecords(request: $request) {
357
357
  Success
358
358
  OverallStatus
@@ -369,32 +369,32 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
369
369
  Message
370
370
  }
371
371
  }
372
- }`,n={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(o=>({FieldName:o.FieldName,Value:o.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(o=>o.Copy())};return(await this.ExecuteGQL(a,{request:n}))?.MergeRecords}catch(a){return d(a),{Success:!1,OverallStatus:a&&a.message?a.message:a,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){const s=new Ce;try{e.RegisterTransactionPreprocessing();const a={input:{}},n=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(l=>({FieldName:l.CodeName,Value:l.Value})),e.ResultHistory.push(s);const i=A(e.EntityInfo),o=`${n}${i}`,u=e.Fields.filter(l=>!l.ReadOnly||l.IsPrimaryKey&&e.IsSaved),c=new N,p=` ${o}(input: $input) {
372
+ }`,a={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(o=>({FieldName:o.FieldName,Value:o.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(o=>o.Copy())};return(await this.ExecuteGQL(n,{request:a}))?.MergeRecords}catch(n){return d(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){const s=new V;try{e.RegisterTransactionPreprocessing();const n={input:{}},a=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(l=>({FieldName:l.CodeName,Value:l.Value})),e.ResultHistory.push(s);const i=N(e.EntityInfo),o=`${a}${i}`,u=e.Fields.filter(l=>!l.ReadOnly||l.IsPrimaryKey&&e.IsSaved),c=new A,f=` ${o}(input: $input) {
373
373
  ${e.Fields.map(l=>c.MapFieldName(l.CodeName)).join(`
374
374
  `)}
375
- }`,I=m`mutation ${n}${i} ($input: ${o}Input!) {
376
- ${p}
375
+ }`,R=m`mutation ${a}${i} ($input: ${o}Input!) {
376
+ ${f}
377
377
  }
378
- `;for(let l=0;l<u.length;l++){const y=u[l];let g=y.Value;if(g)switch(y.EntityFieldInfo.TSType){case v.Date:g=g.getTime();break;case v.Boolean:typeof g!="boolean"&&(g=parseInt(g)!==0);break;case v.Number:if(typeof g!="number"){const S=Number(g);isNaN(S)||(g=S)}break}g===null&&y.EntityFieldInfo.AllowsNull===!1&&(y.EntityFieldInfo.DefaultValue!==null?g=y.EntityFieldInfo.DefaultValue:y.FieldType===v.Number||y.FieldType===v.Boolean?g=0:g=""),a.input[y.CodeName]=g}if(n.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const l=[];e.Fields.forEach(y=>{let g=null;y.OldValue!==null&&y.OldValue!==void 0&&(y.EntityFieldInfo.TSType===v.Date?g=y.OldValue.getTime().toString():y.EntityFieldInfo.TSType===v.Boolean?g=y.OldValue===!0?"1":"0":typeof y.OldValue!="string"?g=y.OldValue.toString():g=y.OldValue),l.push({Key:y.CodeName,Value:g})}),a.input.OldValues___=l}if(e.TransactionGroup){const l=[{varName:"input",inputType:o+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new Ne(e,s.Type==="create"?"Create":"Update",p,a,{mutationName:o,mutationInputTypes:l},(y,g)=>{s.EndedAt=new Date,g&&y?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(y)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const l=await this.ExecuteGQL(I,a);if(l&&l[o])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(l[o]),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,d(a),null}}async Load(e,t,r=null,s){try{const a={};let n="",i="";for(let l=0;l<t.KeyValuePairs.length;l++){const y=e.Fields.find(R=>R.Name.trim().toLowerCase()===t.KeyValuePairs[l].FieldName.trim().toLowerCase()).EntityFieldInfo,g=t.GetValueByIndex(l),S=y.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${y.CodeName}: ${S}!`,n.length>0&&(n+=", "),n+=`${y.CodeName}: $${y.CodeName}`,y.TSType===v.Number){if(isNaN(t.GetValueByIndex(l)))throw new Error(`Primary Key value ${g} (${y.Name}) is not a valid number`);a[y.CodeName]=parseInt(g)}else a[y.CodeName]=g}const o=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",u=A(e.EntityInfo),c=new N,p=m`query Single${u}${o.length>0?"Full":""} (${i}) {
379
- ${u}(${n}) {
378
+ `;for(let l=0;l<u.length;l++){const y=u[l];let g=y.Value;if(g)switch(y.EntityFieldInfo.TSType){case C.Date:g=g.getTime();break;case C.Boolean:typeof g!="boolean"&&(g=parseInt(g)!==0);break;case C.Number:if(typeof g!="number"){const I=Number(g);isNaN(I)||(g=I)}break}g===null&&y.EntityFieldInfo.AllowsNull===!1&&(y.EntityFieldInfo.DefaultValue!==null?g=y.EntityFieldInfo.DefaultValue:y.FieldType===C.Number||y.FieldType===C.Boolean?g=0:g=""),n.input[y.CodeName]=g}if(a.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const l=[];e.Fields.forEach(y=>{let g=null;y.OldValue!==null&&y.OldValue!==void 0&&(y.EntityFieldInfo.TSType===C.Date?g=y.OldValue.getTime().toString():y.EntityFieldInfo.TSType===C.Boolean?g=y.OldValue===!0?"1":"0":typeof y.OldValue!="string"?g=y.OldValue.toString():g=y.OldValue),l.push({Key:y.CodeName,Value:g})}),n.input.OldValues___=l}if(e.TransactionGroup){const l=[{varName:"input",inputType:o+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new L(e,s.Type==="create"?"Create":"Update",f,n,{mutationName:o,mutationInputTypes:l},(y,g)=>{s.EndedAt=new Date,g&&y?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(y)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const l=await this.ExecuteGQL(R,n);if(l&&l[o])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(l[o]),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,d(n),null}}async Load(e,t,r=null,s){try{const n={};let a="",i="";for(let l=0;l<t.KeyValuePairs.length;l++){const y=e.Fields.find(D=>D.Name.trim().toLowerCase()===t.KeyValuePairs[l].FieldName.trim().toLowerCase()).EntityFieldInfo,g=t.GetValueByIndex(l),I=y.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${y.CodeName}: ${I}!`,a.length>0&&(a+=", "),a+=`${y.CodeName}: $${y.CodeName}`,y.TSType===C.Number){if(isNaN(t.GetValueByIndex(l)))throw new Error(`Primary Key value ${g} (${y.Name}) is not a valid number`);n[y.CodeName]=parseInt(g)}else n[y.CodeName]=g}const o=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",u=N(e.EntityInfo),c=new A,f=m`query Single${u}${o.length>0?"Full":""} (${i}) {
379
+ ${u}(${a}) {
380
380
  ${e.Fields.filter(l=>!l.EntityFieldInfo.IsBinaryFieldType).map(l=>l.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?l.CodeName.replace("__mj_","_mj__"):l.CodeName).join(`
381
381
  `)}
382
382
  ${o}
383
383
  }
384
384
  }
385
- `,I=await this.ExecuteGQL(p,a);return I&&I[u]?this.ConvertBackToMJFields(I[u]):null}catch(a){return d(a),null}}ConvertBackToMJFields(e){return new N().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],n=this.Entities.find(o=>o.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+=`
385
+ `,R=await this.ExecuteGQL(f,n);return R&&R[u]?this.ConvertBackToMJFields(R[u]):null}catch(n){return d(n),null}}ConvertBackToMJFields(e){return new A().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],a=this.Entities.find(o=>o.ID===n.RelatedEntityID);let i="";n.Type.toLowerCase().trim()==="many to many"?i=`${n.RelatedEntityCodeName}_${n.JoinEntityJoinField.replace(/\s/g,"")}`:i=`${n.RelatedEntityCodeName}_${n.RelatedEntityJoinField.replace(/\s/g,"")}`,r+=`
386
386
  ${i} {
387
- ${n.Fields.map(o=>o.CodeName).join(`
387
+ ${a.Fields.map(o=>o.CodeName).join(`
388
388
  `)}
389
389
  }
390
- `}return r}async Delete(e,t,r){const s=new Ce;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(y=>({FieldName:y.CodeName,Value:y.Value})),e.ResultHistory.push(s);const a={},n=[];let i="",o="",u="";for(let y of e.PrimaryKey.KeyValuePairs){const g=e.Fields.find(S=>S.Name.trim().toLowerCase()===y.FieldName.trim().toLowerCase());a[g.CodeName]=g.Value,n.push({varName:g.CodeName,inputType:g.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${g.CodeName}: $${g.CodeName}`,o.length>0&&(o+=", "),o+=`$${g.CodeName}: ${g.EntityFieldInfo.GraphQLType}!`,u.length>0&&(u+=`
391
- `),u+=`${g.CodeName}`}n.push({varName:"options___",inputType:"DeleteOptionsInput!"}),a.options___=t||{SkipEntityAIActions:!1,SkipEntityActions:!1};const p="Delete"+A(e.EntityInfo),I=m`${p}(${i}, options___: $options___) {
390
+ `}return r}async Delete(e,t,r){const s=new V;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(y=>({FieldName:y.CodeName,Value:y.Value})),e.ResultHistory.push(s);const n={},a=[];let i="",o="",u="";for(let y of e.PrimaryKey.KeyValuePairs){const g=e.Fields.find(I=>I.Name.trim().toLowerCase()===y.FieldName.trim().toLowerCase());n[g.CodeName]=g.Value,a.push({varName:g.CodeName,inputType:g.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${g.CodeName}: $${g.CodeName}`,o.length>0&&(o+=", "),o+=`$${g.CodeName}: ${g.EntityFieldInfo.GraphQLType}!`,u.length>0&&(u+=`
391
+ `),u+=`${g.CodeName}`}a.push({varName:"options___",inputType:"DeleteOptionsInput!"}),n.options___=t||{SkipEntityAIActions:!1,SkipEntityActions:!1};const f="Delete"+N(e.EntityInfo),R=m`${f}(${i}, options___: $options___) {
392
392
  ${u}
393
393
  }
394
- `,l=m`mutation ${p} (${o}, $options___: DeleteOptionsInput!) {
395
- ${I}
394
+ `,l=m`mutation ${f} (${o}, $options___: DeleteOptionsInput!) {
395
+ ${R}
396
396
  }
397
- `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new Ne(e,"Delete",I,a,{mutationName:p,mutationInputTypes:n},(y,g)=>{if(s.EndedAt=new Date,g&&y){let S=!0;for(const R of e.PrimaryKey.KeyValuePairs)R.Value!==y[R.FieldName]&&(S=!1);S?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const y=await this.ExecuteGQL(l,a);if(y&&y[p]){const g=y[p];for(let S of e.PrimaryKey.KeyValuePairs){let R=g[S.FieldName],w=S.Value;if(typeof w=="number"&&(w=w.toString()),typeof R=="number"&&(R=R.toString()),w!==R)throw new Error(`Primary key value mismatch in server Delete response. Field: ${S.FieldName}, Original: ${w}, Returned: ${R}`)}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,d(a),!1}}async GetDatasetByName(e,t){const r=m`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
397
+ `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new L(e,"Delete",R,n,{mutationName:f,mutationInputTypes:a},(y,g)=>{if(s.EndedAt=new Date,g&&y){let I=!0;for(const D of e.PrimaryKey.KeyValuePairs)D.Value!==y[D.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 y=await this.ExecuteGQL(l,n);if(y&&y[f]){const g=y[f];for(let I of e.PrimaryKey.KeyValuePairs){let D=g[I.FieldName],E=I.Value;if(typeof E=="number"&&(E=E.toString()),typeof D=="number"&&(D=D.toString()),E!==D)throw new Error(`Primary key value mismatch in server Delete response. Field: ${I.FieldName}, Original: ${E}, Returned: ${D}`)}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,d(n),!1}}async GetDatasetByName(e,t){const r=m`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
398
398
  GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
399
399
  DatasetID
400
400
  DatasetName
@@ -412,16 +412,16 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
412
412
  LatestUpdateDate
413
413
  EntityUpdateDates
414
414
  }
415
- }`,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 T(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const a=this.Entities.find(o=>o.Name===t);if(!a)throw new Error(`Entity ${t} not found in metadata`);const n=m`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
415
+ }`,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 G(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const n=this.Entities.find(o=>o.Name===t);if(!n)throw new Error(`Entity ${t} not found in metadata`);const a=m`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
416
416
  GetRecordFavoriteStatus(params: $params) {
417
417
  Success
418
418
  IsFavorite
419
419
  }
420
- }`,i=await this.ExecuteGQL(n,{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 n=this.Entities.find(u=>u.Name===t);if(!n)throw new Error(`Entity ${t} not found in metadata`);const i=m`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
420
+ }`,i=await this.ExecuteGQL(a,{params:{UserID:e,EntityID:n.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)}}});if(i&&i.GetRecordFavoriteStatus&&i.GetRecordFavoriteStatus.Success)return i.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,t,r,s,n){const a=this.Entities.find(u=>u.Name===t);if(!a)throw new Error(`Entity ${t} not found in metadata`);const i=m`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
421
421
  SetRecordFavoriteStatus(params: $params){
422
422
  Success
423
423
  }
424
- }`,o=await this.ExecuteGQL(i,{params:{UserID:e,EntityID:n.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)},IsFavorite:s}});if(o&&o.SetRecordFavoriteStatus!==null)return o.SetRecordFavoriteStatus.Success}async GetEntityRecordName(e,t){if(!e||!t||t.KeyValuePairs?.length===0)return null;const r=m`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
424
+ }`,o=await this.ExecuteGQL(i,{params:{UserID:e,EntityID:a.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)},IsFavorite:s}});if(o&&o.SetRecordFavoriteStatus!==null)return o.SetRecordFavoriteStatus.Success}async GetEntityRecordName(e,t){if(!e||!t||t.KeyValuePairs?.length===0)return null;const r=m`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
425
425
  GetEntityRecordName(EntityName: $EntityName, CompositeKey: $CompositeKey) {
426
426
  Success
427
427
  Status
@@ -452,23 +452,23 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
452
452
  ErrorMessage
453
453
  Result
454
454
  }
455
- }`,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 d(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 d("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw d(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._configData.UserAPIKey);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,a){const n={"x-session-id":r};return t&&(n.authorization="Bearer "+t),s&&(n["x-mj-api-key"]=s),a&&(n["x-api-key"]=a),new ve(e,{headers:n})}userInfoString(){return this.infoString(new $e(null,null))}userRoleInfoString(){return this.infoString(new Ge(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
455
+ }`,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 d(t),t}}static async ExecuteGQL(e,t,r=!0){return S.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 d("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw d(s),s}}async RefreshToken(){const e=S.Instance&&S.Instance._configData===this._configData;if(e&&S.Instance._refreshPromise)return S.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(S.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&S.Instance&&(S.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._configData.UserAPIKey);this._client=t,S.Instance&&S.Instance._configData===this._configData&&(S.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 S.Instance.RefreshToken()}CreateNewGraphQLClient(e,t,r,s,n){const a={"x-session-id":r};return t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),n&&(a["x-api-key"]=n),new T(e,{headers:a})}userInfoString(){return this.infoString(new U(null,null))}userRoleInfoString(){return this.infoString(new H(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
456
456
  `:s.startsWith("_")||(t+=s+`
457
- `);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new L:this._localStorageProvider=new _e),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=Be({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,n])=>{const i=e-n.lastRequestedAt,o=e-n.lastEmissionAt;n.activeSubscribers===0&&i>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&o>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${a} for cleanup: activeSubscribers=${n.activeSubscribers}, timeSinceRequested=${Math.round(i/1e3)}s, timeSinceEmission=${Math.round(o/1e3)}s`),s.push(a))}),s.forEach(a=>{const n=this._pushStatusSubjects.get(a);if(n)try{n.subject.complete(),n.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 M(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const a=s.subscribe({query:e,variables:t},{next:n=>{r.next(n.data)},error:async n=>{const i=n;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(u){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",u),r.error(u)}}else r.error(n)},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 M(o=>{r.activeSubscribers++;const u=r.subject.subscribe(o);return()=>{const c=this._pushStatusSubjects.get(e);c&&c.activeSubscribers>0&&c.activeSubscribers--,u.unsubscribe()}});const s=m`subscription StatusUpdates($sessionId: String!) {
457
+ `);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new K: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=ne({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token},keepAlive:3e4,retryAttempts:3,shouldRetry:p(()=>!0,"shouldRetry")}),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,a])=>{const i=e-a.lastRequestedAt,o=e-a.lastEmissionAt;a.activeSubscribers===0&&i>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&o>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${n} for cleanup: activeSubscribers=${a.activeSubscribers}, timeSinceRequested=${Math.round(i/1e3)}s, timeSinceEmission=${Math.round(o/1e3)}s`),s.push(n))}),s.forEach(n=>{const a=this._pushStatusSubjects.get(n);if(a)try{a.subject.complete(),a.subscription.unsubscribe(),this._pushStatusSubjects.delete(n),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${n}`)}catch(i){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${n}:`,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 M(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=s.subscribe({query:e,variables:t},{next:p(a=>{r.next(a.data)},"next"),error:p(async a=>{const i=a;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(u){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",u),r.error(u)}}else r.error(a)},"error"),complete:p(()=>{r.complete()},"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 M(o=>{r.activeSubscribers++;const u=r.subject.subscribe(o);return()=>{const c=this._pushStatusSubjects.get(e);c&&c.activeSubscribers>0&&c.activeSubscribers--,u.unsubscribe()}});const s=m`subscription StatusUpdates($sessionId: String!) {
458
458
  statusUpdates(sessionId: $sessionId) {
459
459
  date
460
460
  message
461
461
  sessionId
462
462
  }
463
463
  }
464
- `,a=new Ke,n=this.getOrCreateWSClient(),i=new je;return i.add(new M(o=>{const u=n.subscribe({query:s,variables:{sessionId:e}},{next:c=>{const p=this._pushStatusSubjects.get(e);p&&(p.lastEmissionAt=Date.now()),o.next(c.data.statusUpdates.message)},error:async c=>{const p=c;if(p?.extensions?.code==="JWT_EXPIRED"||p?.message?.includes("token has expired")||p?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),o.complete()}catch(l){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",l),o.error(l)}}else o.error(c)},complete:()=>{o.complete()}});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,u()}}).subscribe({next:o=>a.next(o),error:o=>{a.error(o),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 M(o=>{const u=this._pushStatusSubjects.get(e);u&&u.activeSubscribers++;const c=a.subscribe(o);return()=>{const p=this._pushStatusSubjects.get(e);p&&p.activeSubscribers>0&&p.activeSubscribers--,c.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}};f(h,"GraphQLDataProvider");let Q=h;async function Ze(E){const e=new Q;return Oe(e),await e.Config(E),await qe.Instance.Startup(),We.Instance.RaiseEvent({event:ze.LoggedIn,eventCode:null,component:this,args:null}),e}f(Ze,"setupGraphQLClient");const ue=class ue{};f(ue,"SyncRolesAndUsersResult");let G=ue;const ce=class ce{};f(ce,"RoleInput");let _=ce;const le=class le{};f(le,"UserInput");let O=le;const de=class de{};f(de,"RolesAndUsersInput");let q=de;var Me=(E=>(E.Create="Create",E.Update="Update",E.CreateOrUpdate="CreateOrUpdate",E.Delete="Delete",E.DeleteWithFilter="DeleteWithFilter",E))(Me||{});const ye=class ye{};f(ye,"ActionItemInput");let k=ye;const me=class me{constructor(){this.Results=[]}};f(me,"SyncDataResult");let K=me;const ge=class ge{};f(ge,"ActionItemOutput");let j=ge;const pe=class pe{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 ve(e,{headers:a})}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
464
+ `,n=new re,a=this.getOrCreateWSClient(),i=new se;return i.add(new M(o=>{const u=a.subscribe({query:s,variables:{sessionId:e}},{next:p(c=>{const f=this._pushStatusSubjects.get(e);f&&(f.lastEmissionAt=Date.now()),o.next(c.data.statusUpdates.message)},"next"),error:p(async c=>{const f=c;if(f?.extensions?.code==="JWT_EXPIRED"||f?.message?.includes("token has expired")||f?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),o.complete()}catch(l){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",l),o.error(l)}}else o.error(c)},"error"),complete:p(()=>{o.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,u()}}).subscribe({next:p(o=>n.next(o),"next"),error:p(o=>{n.error(o),this._pushStatusSubjects.delete(e)},"error"),complete:p(()=>{n.complete(),this._pushStatusSubjects.delete(e)},"complete")})),this._pushStatusSubjects.set(e,{subject:n,subscription:i,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new M(o=>{const u=this._pushStatusSubjects.get(e);u&&u.activeSubscribers++;const c=n.subscribe(o);return()=>{const f=this._pushStatusSubjects.get(e);f&&f.activeSubscribers>0&&f.activeSubscribers--,c.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}}async function ye(h){const e=new S;return Z(e),await e.Config(h),await ee.Instance.Startup(),oe.Instance.RaiseEvent({event:ie.LoggedIn,eventCode:null,component:this,args:null}),e}p(ye,"setupGraphQLClient");class me{static{p(this,"SyncRolesAndUsersResult")}}class ge{static{p(this,"RoleInput")}}class pe{static{p(this,"UserInput")}}class he{static{p(this,"RolesAndUsersInput")}}var k=(h=>(h.Create="Create",h.Update="Update",h.CreateOrUpdate="CreateOrUpdate",h.Delete="Delete",h.DeleteWithFilter="DeleteWithFilter",h))(k||{});class fe{static{p(this,"ActionItemInput")}}class Se{static{p(this,"SyncDataResult")}constructor(){this.Results=[]}}class Ie{static{p(this,"ActionItemOutput")}}class Re{static{p(this,"GraphQLSystemUserClient")}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 T(e,{headers:n})}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
465
465
  GetData(input: $input) {
466
466
  Success
467
467
  ErrorMessages
468
468
  Queries
469
469
  Results
470
470
  }
471
- }`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(a=>a?$(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]+"."),ke()){const n=`GraphQLSystemUserClient::GetData - Error getting data - ${r}`;d(n)}return{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
471
+ }`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(n=>n?v(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]+"."),te()){const a=`GraphQLSystemUserClient::GetData - Error getting data - ${r}`;d(a)}return{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
472
472
  GetAllEntities {
473
473
  Success
474
474
  ErrorMessage
@@ -599,7 +599,7 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
599
599
  ErrorMessage
600
600
  AppliedParameters
601
601
  }
602
- }`,r={QueryID:e.QueryID};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataSystemUser?{...s.GetQueryDataSystemUser,Results:s.GetQueryDataSystemUser.Results?$(s.GetQueryDataSystemUser.Results):null}:{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return d(`GraphQLSystemUserClient::GetQueryDataSystemUser - Error executing query - ${t}`),{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async GetQueryDataByName(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataByNameSystemUser($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
602
+ }`,r={QueryID:e.QueryID};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataSystemUser?{...s.GetQueryDataSystemUser,Results:s.GetQueryDataSystemUser.Results?v(s.GetQueryDataSystemUser.Results):null}:{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return d(`GraphQLSystemUserClient::GetQueryDataSystemUser - Error executing query - ${t}`),{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async GetQueryDataByName(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataByNameSystemUser($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
603
603
  GetQueryDataByNameSystemUser(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
604
604
  QueryID
605
605
  QueryName
@@ -611,7 +611,7 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
611
611
  ErrorMessage
612
612
  AppliedParameters
613
613
  }
614
- }`,r={QueryName:e.QueryName};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataByNameSystemUser?{...s.GetQueryDataByNameSystemUser,Results:s.GetQueryDataByNameSystemUser.Results?$(s.GetQueryDataByNameSystemUser.Results):null}:{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return d(`GraphQLSystemUserClient::GetQueryDataByNameSystemUser - Error executing query - ${t}`),{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async CreateQuery(e){try{const r=await this.Client.request(`mutation CreateQuerySystemUser($input: CreateQuerySystemUserInput!) {
614
+ }`,r={QueryName:e.QueryName};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataByNameSystemUser?{...s.GetQueryDataByNameSystemUser,Results:s.GetQueryDataByNameSystemUser.Results?v(s.GetQueryDataByNameSystemUser.Results):null}:{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return d(`GraphQLSystemUserClient::GetQueryDataByNameSystemUser - Error executing query - ${t}`),{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async CreateQuery(e){try{const r=await this.Client.request(`mutation CreateQuerySystemUser($input: CreateQuerySystemUserInput!) {
615
615
  CreateQuerySystemUser(input: $input) {
616
616
  Success
617
617
  ErrorMessage
@@ -728,7 +728,7 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
728
728
  ID
729
729
  Name
730
730
  }
731
- }`,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 d(`GraphQLSystemUserClient::DeleteQuery - Error deleting query - ${r}`),{Success:!1,ErrorMessage:r.toString()}}}async RunAIPrompt(e){try{const t=m`
731
+ }`,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 d(`GraphQLSystemUserClient::DeleteQuery - Error deleting query - ${r}`),{Success:!1,ErrorMessage:r.toString()}}}async RunAIPrompt(e){try{const t=m`
732
732
  query RunAIPromptSystemUser(
733
733
  $promptId: String!,
734
734
  $data: String,
@@ -814,7 +814,7 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
814
814
  result
815
815
  }
816
816
  }
817
- `,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 d(`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 $(e)}async ExecuteSimplePrompt(e){try{const t=m`
817
+ `,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 d(`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 v(e)}async ExecuteSimplePrompt(e){try{const t=m`
818
818
  query ExecuteSimplePromptSystemUser(
819
819
  $systemPrompt: String!,
820
820
  $messages: String,
@@ -837,7 +837,7 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
837
837
  executionTimeMs
838
838
  }
839
839
  }
840
- `,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 n;if(a.resultObject)try{n=JSON.parse(a.resultObject)}catch{n=a.resultObject}return{success:a.success,result:a.result,resultObject:n,modelName:a.modelName,error:a.error,executionTimeMs:a.executionTimeMs}}catch(t){return d(`GraphQLSystemUserClient::ExecuteSimplePrompt - Error executing simple prompt - ${t}`),{success:!1,modelName:"Unknown",error:t.toString()}}}async EmbedText(e){try{const t=m`
840
+ `,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 a;if(n.resultObject)try{a=JSON.parse(n.resultObject)}catch{a=n.resultObject}return{success:n.success,result:n.result,resultObject:a,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){return d(`GraphQLSystemUserClient::ExecuteSimplePrompt - Error executing simple prompt - ${t}`),{success:!1,modelName:"Unknown",error:t.toString()}}}async EmbedText(e){try{const t=m`
841
841
  query EmbedTextSystemUser(
842
842
  $textToEmbed: [String!]!,
843
843
  $modelSize: String!
@@ -852,7 +852,7 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
852
852
  error
853
853
  }
854
854
  }
855
- `,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 n=a.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?n.embeddings:n.embeddings[0],modelName:n.modelName,vectorDimensions:n.vectorDimensions,error:n.error}}catch(t){return d(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}};f(pe,"GraphQLSystemUserClient");let B=pe;const he=class he{};f(he,"GetDataOutput");let J=he;const fe=class fe{};f(fe,"SimpleRemoteEntityOutput");let W=fe;const Se=class Se{};f(Se,"SimpleRemoteEntity");let z=Se;const Ie=class Ie{};f(Ie,"SimpleRemoteEntityField");let H=Ie;const Re=class Re{constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),a=this.createActionVariables(e,s,r),n=await this.executeActionMutation(a);return this.processActionResult(n,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`
855
+ `,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 a=n.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?a.embeddings:a.embeddings[0],modelName:a.modelName,vectorDimensions:a.vectorDimensions,error:a.error}}catch(t){return d(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}}class De{static{p(this,"GetDataOutput")}}class we{static{p(this,"SimpleRemoteEntityOutput")}}class Ee{static{p(this,"SimpleRemoteEntity")}}class Pe{static{p(this,"SimpleRemoteEntityField")}}class Ce{static{p(this,"GraphQLActionClient")}constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),n=this.createActionVariables(e,s,r),a=await this.executeActionMutation(n);return this.processActionResult(a,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`
856
856
  mutation RunAction($input: RunActionInput!) {
857
857
  RunAction(input: $input) {
858
858
  Success
@@ -869,7 +869,7 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
869
869
  ResultData
870
870
  }
871
871
  }
872
- `;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){d(`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 d(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}};f(Re,"GraphQLActionClient");let X=Re;const De=class De{constructor(e){this._dataProvider=e}async CreateAPIKey(e){try{const t=this.createAPIKeyVariables(e),r=await this.executeCreateAPIKeyMutation(t);return this.processCreateAPIKeyResult(r)}catch(t){return this.handleCreateAPIKeyError(t)}}createAPIKeyVariables(e){return{input:{Label:e.Label,Description:e.Description,ExpiresAt:e.ExpiresAt?.toISOString(),ScopeIDs:e.ScopeIDs}}}async executeCreateAPIKeyMutation(e){const t=m`
872
+ `;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){d(`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 d(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}}class ve{static{p(this,"GraphQLEncryptionClient")}constructor(e){this._dataProvider=e}async CreateAPIKey(e){try{const t=this.createAPIKeyVariables(e),r=await this.executeCreateAPIKeyMutation(t);return this.processCreateAPIKeyResult(r)}catch(t){return this.handleCreateAPIKeyError(t)}}createAPIKeyVariables(e){return{input:{Label:e.Label,Description:e.Description,ExpiresAt:e.ExpiresAt?.toISOString(),ScopeIDs:e.ScopeIDs}}}async executeCreateAPIKeyMutation(e){const t=m`
873
873
  mutation CreateAPIKey($input: CreateAPIKeyInput!) {
874
874
  CreateAPIKey(input: $input) {
875
875
  Success
@@ -885,7 +885,7 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
885
885
  Error
886
886
  }
887
887
  }
888
- `,s=await this._dataProvider.ExecuteGQL(t,{apiKeyId:e});return s?.RevokeAPIKey?{Success:s.RevokeAPIKey.Success,Error:s.RevokeAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}catch(t){const r=t;return d(`Error revoking API key: ${r.message}`),{Success:!1,Error:`Error: ${r.message}`}}}};f(De,"GraphQLEncryptionClient");let Y=De;const we=class we{constructor(e){this._dataProvider=e}async RunTest(e){let t;try{e.onProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(o=>{try{const u=JSON.parse(o);u.resolver==="RunTestResolver"&&u.type==="TestExecutionProgress"&&u.status==="ok"&&u.data?.progress&&e.onProgress(u.data.progress)}catch(u){console.error("[GraphQLTestingClient] Failed to parse progress message:",u)}}));const r=m`
888
+ `,s=await this._dataProvider.ExecuteGQL(t,{apiKeyId:e});return s?.RevokeAPIKey?{Success:s.RevokeAPIKey.Success,Error:s.RevokeAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}catch(t){const r=t;return d(`Error revoking API key: ${r.message}`),{Success:!1,Error:`Error: ${r.message}`}}}}class $e{static{p(this,"GraphQLTestingClient")}constructor(e){this._dataProvider=e}async RunTest(e){let t;try{e.onProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(o=>{try{const u=JSON.parse(o);u.resolver==="RunTestResolver"&&u.type==="TestExecutionProgress"&&u.status==="ok"&&u.data?.progress&&e.onProgress(u.data.progress)}catch(u){console.error("[GraphQLTestingClient] Failed to parse progress message:",u)}}));const r=m`
889
889
  mutation RunTest(
890
890
  $testId: String!,
891
891
  $verbose: Boolean,
@@ -906,7 +906,7 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
906
906
  result
907
907
  }
908
908
  }
909
- `,s=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,a=e.variables?JSON.stringify(e.variables):void 0,n={testId:e.testId,verbose:e.verbose,environment:e.environment,tags:s,variables:a},i=await this._dataProvider.ExecuteGQL(r,n);return this.processTestResult(i.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(u=>{try{const c=JSON.parse(u);c.resolver==="RunTestResolver"&&c.type==="TestExecutionProgress"&&c.status==="ok"&&c.data?.progress&&e.onProgress(c.data.progress)}catch(c){console.error("[GraphQLTestingClient] Failed to parse progress message:",c)}}));const r=m`
909
+ `,s=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,n=e.variables?JSON.stringify(e.variables):void 0,a={testId:e.testId,verbose:e.verbose,environment:e.environment,tags:s,variables:n},i=await this._dataProvider.ExecuteGQL(r,a);return this.processTestResult(i.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(u=>{try{const c=JSON.parse(u);c.resolver==="RunTestResolver"&&c.type==="TestExecutionProgress"&&c.status==="ok"&&c.data?.progress&&e.onProgress(c.data.progress)}catch(c){console.error("[GraphQLTestingClient] Failed to parse progress message:",c)}}));const r=m`
910
910
  mutation RunTestSuite(
911
911
  $suiteId: String!,
912
912
  $verbose: Boolean,
@@ -935,11 +935,11 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
935
935
  result
936
936
  }
937
937
  }
938
- `,s=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,a=e.variables?JSON.stringify(e.variables):void 0,n=e.selectedTestIds&&e.selectedTestIds.length>0?JSON.stringify(e.selectedTestIds):void 0,i={suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel,tags:s,variables:a,selectedTestIds:n,sequenceStart:e.sequenceStart,sequenceEnd:e.sequenceEnd},o=await this._dataProvider.ExecuteGQL(r,i);return this.processSuiteResult(o.RunTestSuite)}catch(r){return this.handleError(r,"RunTestSuite")}finally{t&&t.unsubscribe()}}async IsTestRunning(e){try{const t=m`
938
+ `,s=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,n=e.variables?JSON.stringify(e.variables):void 0,a=e.selectedTestIds&&e.selectedTestIds.length>0?JSON.stringify(e.selectedTestIds):void 0,i={suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel,tags:s,variables:n,selectedTestIds:a,sequenceStart:e.sequenceStart,sequenceEnd:e.sequenceEnd},o=await this._dataProvider.ExecuteGQL(r,i);return this.processSuiteResult(o.RunTestSuite)}catch(r){return this.handleError(r,"RunTestSuite")}finally{t&&t.unsubscribe()}}async IsTestRunning(e){try{const t=m`
939
939
  query IsTestRunning($testId: String!) {
940
940
  IsTestRunning(testId: $testId)
941
941
  }
942
- `;return(await this._dataProvider.ExecuteGQL(t,{testId:e})).IsTestRunning}catch(t){return d(`Error checking test running status: ${t.message}`),!1}}processTestResult(e){if(!e)throw new Error("Invalid response from server");let t;try{t=$(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=$(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 d(`${t} failed: ${r}`),{success:!1,errorMessage:r,result:null}}};f(we,"GraphQLTestingClient");let Z=we;const Ee=class Ee{constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=m`
942
+ `;return(await this._dataProvider.ExecuteGQL(t,{testId:e})).IsTestRunning}catch(t){return d(`Error checking test running status: ${t.message}`),!1}}processTestResult(e){if(!e)throw new Error("Invalid response from server");let t;try{t=v(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=v(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 d(`${t} failed: ${r}`),{success:!1,errorMessage:r,result:null}}}class Ne{static{p(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=m`
943
943
  query GetRegistryComponent(
944
944
  $registryName: String!,
945
945
  $namespace: String!,
@@ -960,7 +960,7 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
960
960
  specification
961
961
  }
962
962
  }
963
- `,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(n){return d(`Failed to parse component specification: ${n}`),null}}return null}return null}catch(t){throw d(t),new Error(`Failed to get registry component: ${t instanceof Error?t.message:"Unknown error"}`)}}async GetRegistryComponentWithHash(e){try{const t=m`
963
+ `,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(a){return d(`Failed to parse component specification: ${a}`),null}}return null}return null}catch(t){throw d(t),new Error(`Failed to get registry component: ${t instanceof Error?t.message:"Unknown error"}`)}}async GetRegistryComponentWithHash(e){try{const t=m`
964
964
  query GetRegistryComponent(
965
965
  $registryName: String!,
966
966
  $namespace: String!,
@@ -981,7 +981,7 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
981
981
  specification
982
982
  }
983
983
  }
984
- `,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 n;if(a.specification)try{n=JSON.parse(a.specification)}catch(i){d(`Failed to parse component specification in GetRegistryComponentWithHash: ${i}`),n=void 0}return{specification:n,hash:a.hash,notModified:a.notModified,message:a.message}}return{specification:void 0,hash:"",notModified:!1,message:"Component not found"}}catch(t){throw d(t),new Error(`Failed to get registry component with hash: ${t instanceof Error?t.message:"Unknown error"}`)}}async SearchRegistryComponents(e){try{const t=m`
984
+ `,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 a;if(n.specification)try{a=JSON.parse(n.specification)}catch(i){d(`Failed to parse component specification in GetRegistryComponentWithHash: ${i}`),a=void 0}return{specification:a,hash:n.hash,notModified:n.notModified,message:n.message}}return{specification:void 0,hash:"",notModified:!1,message:"Component not found"}}catch(t){throw d(t),new Error(`Failed to get registry component with hash: ${t instanceof Error?t.message:"Unknown error"}`)}}async SearchRegistryComponents(e){try{const t=m`
985
985
  query SearchRegistryComponents($params: SearchRegistryComponentsInput!) {
986
986
  SearchRegistryComponents(params: $params) {
987
987
  components
@@ -990,7 +990,7 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
990
990
  limit
991
991
  }
992
992
  }
993
- `,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 d(t),new Error(`Failed to search registry components: ${t instanceof Error?t.message:"Unknown error"}`)}}async ResolveComponentDependencies(e,t){try{const r=m`
993
+ `,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 d(t),new Error(`Failed to search registry components: ${t instanceof Error?t.message:"Unknown error"}`)}}async ResolveComponentDependencies(e,t){try{const r=m`
994
994
  query ResolveComponentDependencies(
995
995
  $registryId: String!,
996
996
  $componentId: String!
@@ -1023,7 +1023,23 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
1023
1023
  error
1024
1024
  }
1025
1025
  }
1026
- `,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return d(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}};f(Ee,"GraphQLComponentRegistryClient");let ee=Ee;const Pe=class Pe{constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const s=m`
1026
+ `,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return d(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}}class Ae{static{p(this,"GraphQLVersionHistoryClient")}constructor(e){this._dataProvider=e}async CreateLabel(e){let t;try{e.OnProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(a=>{try{const i=JSON.parse(a);i.resolver==="VersionHistoryResolver"&&i.type==="CreateLabelProgress"&&i.status==="ok"&&i.data&&e.OnProgress(i.data)}catch{}}));const r=m`
1027
+ mutation CreateVersionLabel($input: CreateVersionLabelInput!, $sessionId: String) {
1028
+ CreateVersionLabel(input: $input, sessionId: $sessionId) {
1029
+ Success
1030
+ LabelID
1031
+ LabelName
1032
+ ItemsCaptured
1033
+ SyntheticSnapshotsCreated
1034
+ Error
1035
+ CaptureErrors {
1036
+ EntityName
1037
+ RecordID
1038
+ ErrorMessage
1039
+ }
1040
+ }
1041
+ }
1042
+ `,s={input:this.buildInput(e),sessionId:this._dataProvider.sessionId},n=await this._dataProvider.ExecuteGQL(r,s);return this.processResult(n)}catch(r){const s=r instanceof Error?r.message:String(r);return d(`GraphQLVersionHistoryClient.CreateLabel error: ${s}`),{Success:!1,Error:s}}finally{t&&t.unsubscribe()}}buildInput(e){const t={Name:e.Name};return e.Description!=null&&(t.Description=e.Description),e.Scope!=null&&(t.Scope=e.Scope),e.EntityName!=null&&(t.EntityName=e.EntityName),e.ParentID!=null&&(t.ParentID=e.ParentID),e.ExternalSystemID!=null&&(t.ExternalSystemID=e.ExternalSystemID),e.IncludeDependencies!=null&&(t.IncludeDependencies=e.IncludeDependencies),e.MaxDepth!=null&&(t.MaxDepth=e.MaxDepth),e.ExcludeEntities!=null&&(t.ExcludeEntities=e.ExcludeEntities),e.RecordKeys&&e.RecordKeys.length>0&&(t.RecordKeys=e.RecordKeys.map(r=>({Key:r.Key,Value:r.Value}))),t}processResult(e){const t=e?.CreateVersionLabel;if(!t)return{Success:!1,Error:"Invalid response from server."};const r=Array.isArray(t.CaptureErrors)?t.CaptureErrors.map(s=>({EntityName:s.EntityName??"",RecordID:s.RecordID??"",ErrorMessage:s.ErrorMessage??""})):void 0;return{Success:t.Success,LabelID:t.LabelID,LabelName:t.LabelName,ItemsCaptured:t.ItemsCaptured,SyntheticSnapshotsCreated:t.SyntheticSnapshotsCreated,Error:t.Error,CaptureErrors:r}}}class be{static{p(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const s=m`
1027
1043
  query ListStorageObjects($input: ListStorageObjectsInput!) {
1028
1044
  ListStorageObjects(input: $input) {
1029
1045
  objects {
@@ -1040,22 +1056,22 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
1040
1056
  prefixes
1041
1057
  }
1042
1058
  }
1043
- `,a={input:{AccountID:e,Prefix:t,Delimiter:r||"/"}},n=await this._dataProvider.ExecuteGQL(s,a);if(!n?.ListStorageObjects)throw new Error("Invalid response from server");return{objects:n.ListStorageObjects.objects.map(i=>({...i,lastModified:new Date(i.lastModified)})),prefixes:n.ListStorageObjects.prefixes}}catch(s){const a=s;throw d(`Error listing storage objects: ${a}`),a}}async DirectoryExists(e,t){try{const r=await this.ListObjects(e,t.endsWith("/")?t:`${t}/`,"/");return r.objects.length>0||r.prefixes.length>0}catch(r){return d(`Error checking directory existence: ${r}`),!1}}async CreateDirectory(e,t){try{const r=m`
1059
+ `,n={input:{AccountID:e,Prefix:t,Delimiter:r||"/"}},a=await this._dataProvider.ExecuteGQL(s,n);if(!a?.ListStorageObjects)throw new Error("Invalid response from server");return{objects:a.ListStorageObjects.objects.map(i=>({...i,lastModified:new Date(i.lastModified)})),prefixes:a.ListStorageObjects.prefixes}}catch(s){const n=s;throw d(`Error listing storage objects: ${n}`),n}}async DirectoryExists(e,t){try{const r=await this.ListObjects(e,t.endsWith("/")?t:`${t}/`,"/");return r.objects.length>0||r.prefixes.length>0}catch(r){return d(`Error checking directory existence: ${r}`),!1}}async CreateDirectory(e,t){try{const r=m`
1044
1060
  mutation CreateDirectory($input: CreateDirectoryInput!) {
1045
1061
  CreateDirectory(input: $input)
1046
1062
  }
1047
- `,s={input:{AccountID:e,Path:t}};return(await this._dataProvider.ExecuteGQL(r,s))?.CreateDirectory??!1}catch(r){return d(`Error creating directory: ${r}`),!1}}async ObjectExists(e,t){try{const r=t.substring(0,t.lastIndexOf("/")+1),s=t.substring(t.lastIndexOf("/")+1);return(await this.ListObjects(e,r,"/")).objects.some(n=>n.name===s||n.fullPath===t)}catch(r){return d(`Error checking object existence: ${r}`),!1}}async CreatePreAuthUploadUrl(e,t,r){try{const s=m`
1063
+ `,s={input:{AccountID:e,Path:t}};return(await this._dataProvider.ExecuteGQL(r,s))?.CreateDirectory??!1}catch(r){return d(`Error creating directory: ${r}`),!1}}async ObjectExists(e,t){try{const r=t.substring(0,t.lastIndexOf("/")+1),s=t.substring(t.lastIndexOf("/")+1);return(await this.ListObjects(e,r,"/")).objects.some(a=>a.name===s||a.fullPath===t)}catch(r){return d(`Error checking object existence: ${r}`),!1}}async CreatePreAuthUploadUrl(e,t,r){try{const s=m`
1048
1064
  mutation CreatePreAuthUploadUrl($input: CreatePreAuthUploadUrlInput!) {
1049
1065
  CreatePreAuthUploadUrl(input: $input) {
1050
1066
  UploadUrl
1051
1067
  ProviderKey
1052
1068
  }
1053
1069
  }
1054
- `,a={input:{AccountID:e,ObjectName:t,ContentType:r}},n=await this._dataProvider.ExecuteGQL(s,a);if(!n?.CreatePreAuthUploadUrl)throw new Error("Invalid response from server");return{uploadUrl:n.CreatePreAuthUploadUrl.UploadUrl,providerKey:n.CreatePreAuthUploadUrl.ProviderKey}}catch(s){const a=s;throw d(`Error creating pre-auth upload URL: ${a}`),a}}async CreatePreAuthDownloadUrl(e,t){try{const r=m`
1070
+ `,n={input:{AccountID:e,ObjectName:t,ContentType:r}},a=await this._dataProvider.ExecuteGQL(s,n);if(!a?.CreatePreAuthUploadUrl)throw new Error("Invalid response from server");return{uploadUrl:a.CreatePreAuthUploadUrl.UploadUrl,providerKey:a.CreatePreAuthUploadUrl.ProviderKey}}catch(s){const n=s;throw d(`Error creating pre-auth upload URL: ${n}`),n}}async CreatePreAuthDownloadUrl(e,t){try{const r=m`
1055
1071
  query CreatePreAuthDownloadUrl($input: CreatePreAuthDownloadUrlInput!) {
1056
1072
  CreatePreAuthDownloadUrl(input: $input)
1057
1073
  }
1058
- `,s={input:{AccountID:e,ObjectName:t}},a=await this._dataProvider.ExecuteGQL(r,s);if(a?.CreatePreAuthDownloadUrl===void 0)throw new Error("Invalid response from server");return a.CreatePreAuthDownloadUrl}catch(r){const s=r;throw d(`Error creating pre-auth download URL: ${s}`),s}}async DeleteObject(e,t){try{const r=m`
1074
+ `,s={input:{AccountID:e,ObjectName:t}},n=await this._dataProvider.ExecuteGQL(r,s);if(n?.CreatePreAuthDownloadUrl===void 0)throw new Error("Invalid response from server");return n.CreatePreAuthDownloadUrl}catch(r){const s=r;throw d(`Error creating pre-auth download URL: ${s}`),s}}async DeleteObject(e,t){try{const r=m`
1059
1075
  mutation DeleteStorageObject($input: DeleteStorageObjectInput!) {
1060
1076
  DeleteStorageObject(input: $input)
1061
1077
  }
@@ -1063,11 +1079,11 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
1063
1079
  mutation MoveStorageObject($input: MoveStorageObjectInput!) {
1064
1080
  MoveStorageObject(input: $input)
1065
1081
  }
1066
- `,a={input:{AccountID:e,OldName:t,NewName:r}};return(await this._dataProvider.ExecuteGQL(s,a))?.MoveStorageObject??!1}catch(s){return d(`Error moving storage object: ${s}`),!1}}async CopyObject(e,t,r){try{const s=m`
1082
+ `,n={input:{AccountID:e,OldName:t,NewName:r}};return(await this._dataProvider.ExecuteGQL(s,n))?.MoveStorageObject??!1}catch(s){return d(`Error moving storage object: ${s}`),!1}}async CopyObject(e,t,r){try{const s=m`
1067
1083
  mutation CopyStorageObject($input: CopyStorageObjectInput!) {
1068
1084
  CopyStorageObject(input: $input)
1069
1085
  }
1070
- `,a={input:{AccountID:e,SourceName:t,DestinationName:r}};return(await this._dataProvider.ExecuteGQL(s,a))?.CopyStorageObject??!1}catch(s){return d(`Error copying storage object: ${s}`),!1}}async CopyObjectBetweenAccounts(e,t,r,s){try{const a=m`
1086
+ `,n={input:{AccountID:e,SourceName:t,DestinationName:r}};return(await this._dataProvider.ExecuteGQL(s,n))?.CopyStorageObject??!1}catch(s){return d(`Error copying storage object: ${s}`),!1}}async CopyObjectBetweenAccounts(e,t,r,s){try{const n=m`
1071
1087
  mutation CopyObjectBetweenAccounts($input: CopyObjectBetweenAccountsInput!) {
1072
1088
  CopyObjectBetweenAccounts(input: $input) {
1073
1089
  success
@@ -1079,7 +1095,7 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
1079
1095
  destinationPath
1080
1096
  }
1081
1097
  }
1082
- `,n={input:{SourceAccountID:e,DestinationAccountID:t,SourcePath:r,DestinationPath:s}},i=await this._dataProvider.ExecuteGQL(a,n);if(!i?.CopyObjectBetweenAccounts)throw new Error("Invalid response from server");return{success:i.CopyObjectBetweenAccounts.success,message:i.CopyObjectBetweenAccounts.message,bytesTransferred:i.CopyObjectBetweenAccounts.bytesTransferred,sourceAccount:i.CopyObjectBetweenAccounts.sourceAccount,destinationAccount:i.CopyObjectBetweenAccounts.destinationAccount,sourcePath:i.CopyObjectBetweenAccounts.sourcePath,destinationPath:i.CopyObjectBetweenAccounts.destinationPath}}catch(a){const n=a;return d(`Error copying object between accounts: ${n}`),{success:!1,message:n.message,sourceAccount:"",destinationAccount:"",sourcePath:r,destinationPath:s}}}async SearchFiles(e,t,r){try{const s=m`
1098
+ `,a={input:{SourceAccountID:e,DestinationAccountID:t,SourcePath:r,DestinationPath:s}},i=await this._dataProvider.ExecuteGQL(n,a);if(!i?.CopyObjectBetweenAccounts)throw new Error("Invalid response from server");return{success:i.CopyObjectBetweenAccounts.success,message:i.CopyObjectBetweenAccounts.message,bytesTransferred:i.CopyObjectBetweenAccounts.bytesTransferred,sourceAccount:i.CopyObjectBetweenAccounts.sourceAccount,destinationAccount:i.CopyObjectBetweenAccounts.destinationAccount,sourcePath:i.CopyObjectBetweenAccounts.sourcePath,destinationPath:i.CopyObjectBetweenAccounts.destinationPath}}catch(n){const a=n;return d(`Error copying object between accounts: ${a}`),{success:!1,message:a.message,sourceAccount:"",destinationAccount:"",sourcePath:r,destinationPath:s}}}async SearchFiles(e,t,r){try{const s=m`
1083
1099
  query SearchAcrossAccounts($input: SearchAcrossAccountsInput!) {
1084
1100
  SearchAcrossAccounts(input: $input) {
1085
1101
  accountResults {
@@ -1107,5 +1123,5 @@ var Te=Object.defineProperty;var f=(E,e)=>Te(E,"name",{value:e,configurable:!0})
1107
1123
  failedAccounts
1108
1124
  }
1109
1125
  }
1110
- `,a={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:r?.maxResultsPerAccount,FileTypes:r?.fileTypes,SearchContent:r?.searchContent}},n=await this._dataProvider.ExecuteGQL(s,a);if(!n?.SearchAcrossAccounts)throw new Error("Invalid response from server");const i=n.SearchAcrossAccounts;return{accountResults:i.accountResults.map(o=>({accountId:o.accountID,accountName:o.accountName,success:o.success,errorMessage:o.errorMessage,results:o.results.map(u=>({path:u.path,name:u.name,size:u.size,contentType:u.contentType,lastModified:new Date(u.lastModified),relevance:u.relevance,excerpt:u.excerpt,matchInFilename:u.matchInFilename,objectId:u.objectId})),totalMatches:o.totalMatches,hasMore:o.hasMore,nextPageToken:o.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(s){return d(`Error searching across accounts: ${s}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}};f(Pe,"GraphQLFileStorageClient");let te=Pe;export{k as ActionItemInput,j as ActionItemOutput,L as BrowserIndexedDBStorageProvider,V as BrowserStorageProviderBase,N as FieldMapper,J as GetDataOutput,U as GraphQLAIClient,X as GraphQLActionClient,ee as GraphQLComponentRegistryClient,Q as GraphQLDataProvider,Y as GraphQLEncryptionClient,te as GraphQLFileStorageClient,F as GraphQLProviderConfigData,B as GraphQLSystemUserClient,Z as GraphQLTestingClient,T as GraphQLTransactionGroup,_ as RoleInput,q as RolesAndUsersInput,z as SimpleRemoteEntity,H as SimpleRemoteEntityField,W as SimpleRemoteEntityOutput,Me as SyncDataAction,K as SyncDataResult,G as SyncRolesAndUsersResult,O as UserInput,dt as gql,Ze as setupGraphQLClient};
1126
+ `,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:r?.maxResultsPerAccount,FileTypes:r?.fileTypes,SearchContent:r?.searchContent}},a=await this._dataProvider.ExecuteGQL(s,n);if(!a?.SearchAcrossAccounts)throw new Error("Invalid response from server");const i=a.SearchAcrossAccounts;return{accountResults:i.accountResults.map(o=>({accountId:o.accountID,accountName:o.accountName,success:o.success,errorMessage:o.errorMessage,results:o.results.map(u=>({path:u.path,name:u.name,size:u.size,contentType:u.contentType,lastModified:new Date(u.lastModified),relevance:u.relevance,excerpt:u.excerpt,matchInFilename:u.matchInFilename,objectId:u.objectId})),totalMatches:o.totalMatches,hasMore:o.hasMore,nextPageToken:o.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(s){return d(`Error searching across accounts: ${s}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}export{fe as ActionItemInput,Ie as ActionItemOutput,K as BrowserIndexedDBStorageProvider,_ as BrowserStorageProviderBase,A as FieldMapper,De as GetDataOutput,F as GraphQLAIClient,Ce as GraphQLActionClient,Ne as GraphQLComponentRegistryClient,S as GraphQLDataProvider,ve as GraphQLEncryptionClient,be as GraphQLFileStorageClient,de as GraphQLProviderConfigData,Re as GraphQLSystemUserClient,$e as GraphQLTestingClient,G as GraphQLTransactionGroup,Ae as GraphQLVersionHistoryClient,ge as RoleInput,he as RolesAndUsersInput,Ee as SimpleRemoteEntity,Pe as SimpleRemoteEntityField,we as SimpleRemoteEntityOutput,k as SyncDataAction,Se as SyncDataResult,me as SyncRolesAndUsersResult,pe as UserInput,qe as gql,ye as setupGraphQLClient};
1111
1127
  //# sourceMappingURL=index.mjs.map