@memberjunction/graphql-dataprovider 5.2.0 → 5.3.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 B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});import{gql as m,GraphQLClient as U}from"graphql-request";import{gql as ke}from"graphql-request";import{TransactionGroupBase as j,TransactionResult as J,LogError as l,LogStatusEx as x,LogErrorEx as v,ProviderBase as W,UserInfo as L,getGraphQLTypeNameBase as A,ProviderType as z,BaseEntityResult as T,EntityFieldTSType as P,TransactionItem as Q,CompositeKey as H,UserRoleInfo as X,InMemoryLocalStorageProvider as Y,ProviderConfigDataBase as Z,SetProvider as ee,StartupManager as te,IsVerboseLoggingEnabled as re}from"@memberjunction/core";import{ViewInfo as V}from"@memberjunction/core-entities";import{Observable as M,Subject as se,Subscription as ne}from"rxjs";import{createClient as ae}from"graphql-ws";import{v4 as oe}from"uuid";import{SafeJSONParse as $,MJGlobal as ie,MJEventType as ue}from"@memberjunction/global";import{openDB as ce}from"@tempfix/idb";class N{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 F extends j{static{p(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=m`
1
+ var B=Object.defineProperty;var h=(S,e)=>B(S,"name",{value:e,configurable:!0});import{gql as m,GraphQLClient as L}from"graphql-request";import{gql as ke}from"graphql-request";import{TransactionGroupBase as j,TransactionResult as J,LogError as d,LogStatusEx as x,LogErrorEx as $,ProviderBase as W,UserInfo as F,getGraphQLTypeNameBase as A,ProviderType as z,BaseEntityResult as U,EntityFieldTSType as v,TransactionItem as Q,CompositeKey as H,UserRoleInfo as X,InMemoryLocalStorageProvider as Y,ProviderConfigDataBase as Z,SetProvider as ee,StartupManager as te,IsVerboseLoggingEnabled as re}from"@memberjunction/core";import{ViewInfo as V}from"@memberjunction/core-entities";import{Observable as M,Subject as se,Subscription as ne}from"rxjs";import{createClient as ae}from"graphql-ws";import{v4 as oe}from"uuid";import{SafeJSONParse as P,MJGlobal as ie,MJEventType as ue}from"@memberjunction/global";import{openDB as ce}from"@tempfix/idb";class N{static{h(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{h(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 B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
6
6
  ResultsJSON
7
7
  }
8
8
  }
9
- `,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const r={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const n=s.ExecuteTransactionGroup,a=[];for(let i=0;i<this.PendingTransactions.length;i++){const o=n.ResultsJSON[i],u=$(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 G{static{p(this,"GraphQLAIClient")}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=P(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 T{static{h(this,"GraphQLAIClient")}static{this.FIRE_AND_FORGET_TIMEOUT_MS=900*1e3}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 B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
65
65
  chatResult
66
66
  }
67
67
  }
68
- `,r=this.preparePromptVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(s)}catch(t){return this.handlePromptError(t)}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,n;try{t.parsedResult&&(r=JSON.parse(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(n=JSON.parse(t.chatResult))}catch{n=t.chatResult}return{success:t.success,output:t.output,parsedResult:r,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:s,chatResult:n}}handlePromptError(e){const t=e;return l(`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`
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 B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
104
104
  result
105
105
  }
106
106
  }
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 $(e)}handleAgentError(e){return l(`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`
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 P(e)}handleAgentError(e){const r=e?.message||String(e);d(`Error running AI agent: ${r}`);const s=r.includes("Failed to fetch")||r.includes("NetworkError"),n=r.includes("timed out")||r.includes("timeout");let a;return s?a="Lost connection to the server. The agent may still be running. Please refresh to check the latest status.":a=r,{success:!1,agentRun:void 0,errorMessage:a}}async RunAIAgentFromConversationDetail(e){let t,r;try{let s,n;const a=new Promise((f,p)=>{s=f,n=p});r=setTimeout(()=>{n(new Error("The agent may still be running on the server but the connection timed out after 15 minutes. Please refresh the page to check the latest status."))},T.FIRE_AND_FORGET_TIMEOUT_MS),t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(f=>{try{const p=JSON.parse(f);if(e.onProgress&&p.resolver==="RunAIAgentResolver"&&p.type==="ExecutionProgress"&&p.status==="ok"&&p.data?.progress){const l={...p.data.progress,metadata:{...p.data.progress.metadata||{},agentRunId:p.data.agentRunId}};e.onProgress(l)}p.resolver==="RunAIAgentResolver"&&p.type==="StreamingContent"&&p.status==="ok"&&p.data?.type==="complete"&&p.data?.conversationDetailId===e.conversationDetailId&&(r&&clearTimeout(r),p.data.result?s(P(p.data.result)):s({success:p.data.success!==!1,agentRun:void 0}))}catch(p){console.error("[GraphQLAIClient] Failed to parse progress message:",p)}});const i=m`
108
108
  mutation RunAIAgentFromConversationDetail(
109
109
  $conversationDetailId: String!,
110
110
  $agentId: String!,
@@ -118,7 +118,8 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
118
118
  $createArtifacts: Boolean,
119
119
  $createNotification: Boolean,
120
120
  $sourceArtifactId: String,
121
- $sourceArtifactVersionId: String
121
+ $sourceArtifactVersionId: String,
122
+ $fireAndForget: Boolean
122
123
  ) {
123
124
  RunAIAgentFromConversationDetail(
124
125
  conversationDetailId: $conversationDetailId,
@@ -133,7 +134,8 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
133
134
  createArtifacts: $createArtifacts,
134
135
  createNotification: $createNotification,
135
136
  sourceArtifactId: $sourceArtifactId,
136
- sourceArtifactVersionId: $sourceArtifactVersionId
137
+ sourceArtifactVersionId: $sourceArtifactVersionId,
138
+ fireAndForget: $fireAndForget
137
139
  ) {
138
140
  success
139
141
  errorMessage
@@ -141,7 +143,7 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
141
143
  result
142
144
  }
143
145
  }
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`
146
+ `,o={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId,fireAndForget:!0};e.maxHistoryMessages!==void 0&&(o.maxHistoryMessages=e.maxHistoryMessages),e.data!==void 0&&(o.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(o.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(o.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(o.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(o.configurationId=e.configurationId),e.createArtifacts!==void 0&&(o.createArtifacts=e.createArtifacts),e.createNotification!==void 0&&(o.createNotification=e.createNotification),e.sourceArtifactId!==void 0&&(o.sourceArtifactId=e.sourceArtifactId),e.sourceArtifactVersionId!==void 0&&(o.sourceArtifactVersionId=e.sourceArtifactVersionId);const c=(await this._dataProvider.ExecuteGQL(i,o)).RunAIAgentFromConversationDetail;return c?.success?await a:(r&&clearTimeout(r),{success:!1,agentRun:void 0,errorMessage:c?.errorMessage||"Server rejected the agent execution request"})}catch(s){return r&&clearTimeout(r),this.handleAgentError(s)}finally{r&&clearTimeout(r),t&&t.unsubscribe()}}async ExecuteSimplePrompt(e){try{const t=m`
145
147
  mutation ExecuteSimplePrompt(
146
148
  $systemPrompt: String!,
147
149
  $messages: String,
@@ -164,7 +166,7 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
164
166
  executionTimeMs
165
167
  }
166
168
  }
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 l(`Error executing simple prompt: ${r}`),{success:!1,modelName:"Unknown",error:r.message||"Unknown error occurred"}}}async EmbedText(e){try{const t=m`
169
+ `,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
170
  mutation EmbedText(
169
171
  $textToEmbed: [String!]!,
170
172
  $modelSize: String!
@@ -179,7 +181,7 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
179
181
  error
180
182
  }
181
183
  }
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 l(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}}const C="default";class _{static{p(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||C;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||C).get(e)??null}async SetItem(e,t,r){this.getCategoryMap(r||C).set(e,t)}async Remove(e,t){this.getCategoryMap(t||C).delete(e)}async ClearCategory(e){const t=e||C;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||C);return t?Array.from(t.keys()):[]}}const le="MJ_Metadata",de=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=ce(le,de,{upgrade(e){try{e.objectStoreNames.contains(q)&&e.deleteObjectStore(q);for(const t of O)e.objectStoreNames.contains(t)||e.createObjectStore(t)}catch(t){v({error:t,message:t?.message})}}}),this.dbPromise.then(()=>{this._dbReady=!0}).catch(e=>{v({error:e,message:"IndexedDB initialization failed: "+e?.message})})}isKnownCategory(e){const t=`mj:${e}`;return O.includes(t)}getStoreName(e){const t=e||C;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||C;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){v({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 v({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){v({error:r,message:r?.message}),await super.Remove(e,t)}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||C,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){v({error:t,message:t?.message}),await super.ClearCategory(e)}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||C,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 v({error:t,message:t?.message}),await super.GetCategoryKeys(e)}}}class ye extends Z{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 {
184
+ `,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 C="default";class _{static{h(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||C;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||C).get(e)??null}async SetItem(e,t,r){this.getCategoryMap(r||C).set(e,t)}async Remove(e,t){this.getCategoryMap(t||C).delete(e)}async ClearCategory(e){const t=e||C;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||C);return t?Array.from(t.keys()):[]}}const le="MJ_Metadata",de=3,O=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"],q="Metadata_KVPairs";class k extends _{static{h(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=ce(le,de,{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||C;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||C;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||C,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||C,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 ye extends Z{static{h(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 I extends W{static{h(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._innerCurrentUserQueryString=`CurrentUser {
183
185
  ${this.userInfoString()}
184
186
  MJUserRoles_UserIDArray {
185
187
  ${this.userRoleInfoString()}
@@ -187,7 +189,7 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
187
189
  }
188
190
  `,this._currentUserQuery=m`query CurrentUserAndRoles {
189
191
  ${this._innerCurrentUserQueryString}
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 G(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return oe()}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 l(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.MJUserRoles_UserIDArray.map(s=>this.ConvertBackToMJFields(s));return t.MJUserRoles_UserIDArray=r,new L(this,{...t,UserRoles:r})}}async RunReport(e,t){const r=m`
192
+ }`,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,I._instance||(I._instance=this)}static get Instance(){return I._instance}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new T(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return oe()}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)):(I.Instance._configData=e,I.Instance._sessionId===void 0&&(I.Instance._sessionId=await this.GetPreferredUUID(s)),I.Instance._client||(I.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,I.Instance._sessionId,e.MJAPIKey,e.UserAPIKey)),await I.Instance.SaveStoredSessionID(I.Instance._sessionId),this._sessionId=I.Instance._sessionId,this._client=I.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.MJUserRoles_UserIDArray.map(s=>this.ConvertBackToMJFields(s));return t.MJUserRoles_UserIDArray=r,new F(this,{...t,UserRoles:r})}}async RunReport(e,t){const r=m`
191
193
  query GetReportDataQuery ($ReportID: String!) {
192
194
  GetReportData(ReportID: $ReportID) {
193
195
  Success
@@ -229,7 +231,7 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
229
231
  TotalRowCount
230
232
  ExecutionTime
231
233
  ErrorMessage
232
- AppliedParameters`}TransformQueryPayload(e){try{return{QueryID:e.QueryID,QueryName:e.QueryName,Success:e.Success,Results:JSON.parse(e.Results),RowCount:e.RowCount,TotalRowCount:e.TotalRowCount,ExecutionTime:e.ExecutionTime,ErrorMessage:e.ErrorMessage,AppliedParameters:e.AppliedParameters?JSON.parse(e.AppliedParameters):void 0}}catch(t){return l(`Error transforming query payload: ${t}`),null}}async RunQueriesWithCacheCheck(e,t){try{const r=e.map(o=>({params:{QueryID:o.params.QueryID||null,QueryName:o.params.QueryName||null,CategoryID:o.params.CategoryID||null,CategoryPath:o.params.CategoryPath||null,Parameters:o.params.Parameters||null,MaxRows:o.params.MaxRows??null,StartRow:o.params.StartRow??null,ForceAuditLog:o.params.ForceAuditLog||!1,AuditLogDescription:o.params.AuditLogDescription||null},cacheStatus:o.cacheStatus?{maxUpdatedAt:o.cacheStatus.maxUpdatedAt,rowCount:o.cacheStatus.rowCount}:null})),s=m`
234
+ AppliedParameters`}TransformQueryPayload(e){try{return{QueryID:e.QueryID,QueryName:e.QueryName,Success:e.Success,Results:JSON.parse(e.Results),RowCount:e.RowCount,TotalRowCount:e.TotalRowCount,ExecutionTime:e.ExecutionTime,ErrorMessage:e.ErrorMessage,AppliedParameters:e.AppliedParameters?JSON.parse(e.AppliedParameters):void 0}}catch(t){return d(`Error transforming query payload: ${t}`),null}}async RunQueriesWithCacheCheck(e,t){try{const r=e.map(o=>({params:{QueryID:o.params.QueryID||null,QueryName:o.params.QueryName||null,CategoryID:o.params.CategoryID||null,CategoryPath:o.params.CategoryPath||null,Parameters:o.params.Parameters||null,MaxRows:o.params.MaxRows??null,StartRow:o.params.StartRow??null,ForceAuditLog:o.params.ForceAuditLog||!1,AuditLogDescription:o.params.AuditLogDescription||null},cacheStatus:o.cacheStatus?{maxUpdatedAt:o.cacheStatus.maxUpdatedAt,rowCount:o.cacheStatus.rowCount}:null})),s=m`
233
235
  query RunQueriesWithCacheCheckQuery($input: [RunQueryWithCacheCheckInput!]!) {
234
236
  RunQueriesWithCacheCheck(input: $input) {
235
237
  success
@@ -245,14 +247,14 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
245
247
  }
246
248
  }
247
249
  }
248
- `,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 l(`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=A(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?`
250
+ `,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:R}=await this.getEntityNameAndUserView(e,t);i=R,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=A(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),p=e.Aggregates&&e.Aggregates.length>0?`
249
251
  AggregateResults {
250
252
  alias
251
253
  expression
252
254
  value
253
255
  error
254
256
  }
255
- AggregateExecutionTime`:"",d=m`
257
+ AggregateExecutionTime`:"",l=m`
256
258
  query RunViewQuery ($input: ${s}!) {
257
259
  ${r}(input: $input) {
258
260
  Results {
@@ -264,9 +266,9 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
264
266
  TotalRowCount
265
267
  ExecutionTime
266
268
  Success
267
- ErrorMessage${R}
269
+ ErrorMessage${p}
268
270
  }
269
- }`;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(d,{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 w=o.Fields.filter(D=>D.CodeName!==D.Name&&D.CodeName!==void 0);I.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 l(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],n=[];for(const c of e){let f="",R="";const d={};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 I=this.Entities.find(D=>D.Name===y);if(!I)throw new Error(`Entity ${y} not found in metadata`);s.push(I);let E=!1;const w=A(I);c.ViewID?(f=`Run${w}ViewByID`,R="RunViewByIDInput",d.ViewID=c.ViewID):c.ViewName?(f=`Run${w}ViewByName`,R="RunViewByNameInput",d.ViewName=c.ViewName):(E=!0,f=`Run${w}DynamicView`,R="RunDynamicViewInput",d.EntityName=c.EntityName),d.ExtraFilter=c.ExtraFilter||"",d.OrderBy=c.OrderBy||"",d.UserSearchString=c.UserSearchString||"",d.Fields=c.Fields,d.IgnoreMaxRows=c.IgnoreMaxRows||!1,c.MaxRows!==void 0&&(d.MaxRows=c.MaxRows),c.StartRow!==void 0&&(d.StartRow=c.StartRow),d.ForceAuditLog=c.ForceAuditLog||!1,d.ResultType=c.ResultType||"simple",c.AuditLogDescription&&c.AuditLogDescription.length>0&&(d.AuditLogDescription=c.AuditLogDescription),E||(d.ExcludeUserViewRunID=c.ExcludeUserViewRunID||"",d.ExcludeDataFromAllPriorViewRuns=c.ExcludeDataFromAllPriorViewRuns||!1,d.OverrideExcludeFilter=c.OverrideExcludeFilter||"",d.SaveViewResults=c.SaveViewResults||!1),c.Aggregates&&c.Aggregates.length>0&&(d.Aggregates=c.Aggregates.map(D=>({expression:D.expression,alias:D.alias}))),r.push(d),n.push(...this.getViewRunTimeFieldList(I,g,c,E))}const i=e.some(c=>c.Aggregates&&c.Aggregates.length>0)?`
271
+ }`;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 R=y[r].Results;if(R&&R.length>0){const w=o.Fields.filter(D=>D.CodeName!==D.Name&&D.CodeName!==void 0);R.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=[],n=[];for(const c of e){let f="",p="";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 R=this.Entities.find(D=>D.Name===y);if(!R)throw new Error(`Entity ${y} not found in metadata`);s.push(R);let E=!1;const w=A(R);c.ViewID?(f=`Run${w}ViewByID`,p="RunViewByIDInput",l.ViewID=c.ViewID):c.ViewName?(f=`Run${w}ViewByName`,p="RunViewByNameInput",l.ViewName=c.ViewName):(E=!0,f=`Run${w}DynamicView`,p="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),E||(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),n.push(...this.getViewRunTimeFieldList(R,g,c,E))}const i=e.some(c=>c.Aggregates&&c.Aggregates.length>0)?`
270
272
  AggregateResults {
271
273
  alias
272
274
  expression
@@ -291,7 +293,7 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
291
293
  Success
292
294
  ErrorMessage${i}
293
295
  }
294
- }`,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(d=>{let y=JSON.parse(d.Data);return this.ConvertBackToMJFields(y),y});return c}return null}catch(r){throw l(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`
296
+ }`,u=await this.ExecuteGQL(o,{input:r});if(u&&u.RunViews){const c=u.RunViews;for(const[f,p]of c.entries())p.Results=p.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`
295
297
  query RunViewsWithCacheCheckQuery($input: [RunViewWithCacheCheckInput!]!) {
296
298
  RunViewsWithCacheCheck(input: $input) {
297
299
  success
@@ -324,7 +326,7 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
324
326
  }
325
327
  }
326
328
  }
327
- `,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 d=JSON.parse(R.Data);return this.ConvertBackToMJFields(d),d});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 d=JSON.parse(R.Data);return this.ConvertBackToMJFields(d),d});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 l(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 V.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await V.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 N;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:"MJ: 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 l(r),r}}async GetRecordDependencies(e,t){try{const r=m`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
329
+ `,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(p=>{const l=JSON.parse(p.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(p=>{const l=JSON.parse(p.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 V.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await V.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 N;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:"MJ: 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!) {
328
330
  GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
329
331
  EntityName
330
332
  RelatedEntityName
@@ -336,7 +338,7 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
336
338
  }
337
339
  }
338
340
  }
339
- }`,s={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}};return(await this.ExecuteGQL(r,s))?.GetRecordDependencies}catch(r){throw l(r),r}}ensureKeyValuePairValueIsString(e){return e.map(t=>({FieldName:t.FieldName,Value:t.Value.toString()}))}async GetRecordDuplicates(e,t){if(!e)return null;const r=m`query GetRecordDuplicatesQuery ($params: PotentialDuplicateRequestType!) {
341
+ }`,s={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}};return(await this.ExecuteGQL(r,s))?.GetRecordDependencies}catch(r){throw d(r),r}}ensureKeyValuePairValueIsString(e){return e.map(t=>({FieldName:t.FieldName,Value:t.Value.toString()}))}async GetRecordDuplicates(e,t){if(!e)return null;const r=m`query GetRecordDuplicatesQuery ($params: PotentialDuplicateRequestType!) {
340
342
  GetRecordDuplicates(params: $params) {
341
343
  Status
342
344
  ErrorMessage
@@ -375,32 +377,32 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
375
377
  Message
376
378
  }
377
379
  }
378
- }`,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 l(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){if(r?.IsParentEntitySave){const n=new T;return n.StartedAt=new Date,n.EndedAt=new Date,n.Type=e.IsSaved?"update":"create",n.Success=!0,n.NewValues=e.GetAll(),e.ResultHistory.push(n),n.NewValues}const s=new T;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(d=>({FieldName:d.CodeName,Value:d.Value})),e.ResultHistory.push(s);const i=A(e.EntityInfo),o=`${a}${i}`,u=e.Fields.filter(d=>!d.ReadOnly||d.IsPrimaryKey&&e.IsSaved),c=new N,f=` ${o}(input: $input) {
379
- ${e.Fields.map(d=>c.MapFieldName(d.CodeName)).join(`
380
+ }`,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){if(r?.IsParentEntitySave){const n=new U;return n.StartedAt=new Date,n.EndedAt=new Date,n.Type=e.IsSaved?"update":"create",n.Success=!0,n.NewValues=e.GetAll(),e.ResultHistory.push(n),n.NewValues}const s=new U;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=A(e.EntityInfo),o=`${a}${i}`,u=e.Fields.filter(l=>!l.ReadOnly||l.IsPrimaryKey&&e.IsSaved),c=new N,f=` ${o}(input: $input) {
381
+ ${e.Fields.map(l=>c.MapFieldName(l.CodeName)).join(`
380
382
  `)}
381
- }`,R=m`mutation ${a}${i} ($input: ${o}Input!) {
383
+ }`,p=m`mutation ${a}${i} ($input: ${o}Input!) {
382
384
  ${f}
383
385
  }
384
- `;for(let d=0;d<u.length;d++){const y=u[d];let g=e.Get(y.Name);if(g)switch(y.EntityFieldInfo.TSType){case P.Date:g=g.getTime();break;case P.Boolean:typeof g!="boolean"&&(g=parseInt(g)!==0);break;case P.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===P.Number||y.FieldType===P.Boolean?g=0:g=""),n.input[y.CodeName]=g}if(a.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const d=[];e.Fields.forEach(y=>{let g=null;y.OldValue!==null&&y.OldValue!==void 0&&(y.EntityFieldInfo.TSType===P.Date?g=y.OldValue.getTime().toString():y.EntityFieldInfo.TSType===P.Boolean?g=y.OldValue===!0?"1":"0":typeof y.OldValue!="string"?g=y.OldValue.toString():g=y.OldValue),d.push({Key:y.CodeName,Value:g})}),n.input.OldValues___=d}if(e.TransactionGroup){const d=[{varName:"input",inputType:o+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new Q(e,s.Type==="create"?"Create":"Update",f,n,{mutationName:o,mutationInputTypes:d},(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 d=await this.ExecuteGQL(R,n);if(d&&d[o])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(d[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,l(n),null}}async Load(e,t,r=null,s){try{const n={};let a="",i="";for(let d=0;d<t.KeyValuePairs.length;d++){const y=e.Fields.find(E=>E.Name.trim().toLowerCase()===t.KeyValuePairs[d].FieldName.trim().toLowerCase()).EntityFieldInfo,g=t.GetValueByIndex(d),I=y.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${y.CodeName}: ${I}!`,a.length>0&&(a+=", "),a+=`${y.CodeName}: $${y.CodeName}`,y.TSType===P.Number){if(isNaN(t.GetValueByIndex(d)))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=A(e.EntityInfo),c=new N,f=m`query Single${u}${o.length>0?"Full":""} (${i}) {
386
+ `;for(let l=0;l<u.length;l++){const y=u[l];let g=e.Get(y.Name);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 R=Number(g);isNaN(R)||(g=R)}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=""),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===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})}),n.input.OldValues___=l}if(e.TransactionGroup){const l=[{varName:"input",inputType:o+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new Q(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(p,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(E=>E.Name.trim().toLowerCase()===t.KeyValuePairs[l].FieldName.trim().toLowerCase()).EntityFieldInfo,g=t.GetValueByIndex(l),R=y.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${y.CodeName}: ${R}!`,a.length>0&&(a+=", "),a+=`${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`);n[y.CodeName]=parseInt(g)}else n[y.CodeName]=g}const o=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",u=A(e.EntityInfo),c=new N,f=m`query Single${u}${o.length>0?"Full":""} (${i}) {
385
387
  ${u}(${a}) {
386
- ${e.Fields.filter(d=>!d.EntityFieldInfo.IsBinaryFieldType).map(d=>d.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?d.CodeName.replace("__mj_","_mj__"):d.CodeName).join(`
388
+ ${e.Fields.filter(l=>!l.EntityFieldInfo.IsBinaryFieldType).map(l=>l.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?l.CodeName.replace("__mj_","_mj__"):l.CodeName).join(`
387
389
  `)}
388
390
  ${o}
389
391
  }
390
392
  }
391
- `,R=await this.ExecuteGQL(f,n);return R&&R[u]?this.ConvertBackToMJFields(R[u]):null}catch(n){return l(n),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 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+=`
393
+ `,p=await this.ExecuteGQL(f,n);return p&&p[u]?this.ConvertBackToMJFields(p[u]):null}catch(n){return d(n),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 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+=`
392
394
  ${i} {
393
395
  ${a.Fields.map(o=>o.CodeName).join(`
394
396
  `)}
395
397
  }
396
- `}return r}async Delete(e,t,r){const s=new T;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+=`
397
- `),u+=`${g.CodeName}`}a.push({varName:"options___",inputType:"DeleteOptionsInput!"}),n.options___={SkipEntityAIActions:t?.SkipEntityAIActions??!1,SkipEntityActions:t?.SkipEntityActions??!1,ReplayOnly:t?.ReplayOnly??!1,IsParentEntityDelete:t?.IsParentEntityDelete??!1};const f="Delete"+A(e.EntityInfo),R=m`${f}(${i}, options___: $options___) {
398
+ `}return r}async Delete(e,t,r){const s=new U;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(R=>R.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+=`
399
+ `),u+=`${g.CodeName}`}a.push({varName:"options___",inputType:"DeleteOptionsInput!"}),n.options___={SkipEntityAIActions:t?.SkipEntityAIActions??!1,SkipEntityActions:t?.SkipEntityActions??!1,ReplayOnly:t?.ReplayOnly??!1,IsParentEntityDelete:t?.IsParentEntityDelete??!1};const f="Delete"+A(e.EntityInfo),p=m`${f}(${i}, options___: $options___) {
398
400
  ${u}
399
401
  }
400
- `,d=m`mutation ${f} (${o}, $options___: DeleteOptionsInput!) {
401
- ${R}
402
+ `,l=m`mutation ${f} (${o}, $options___: DeleteOptionsInput!) {
403
+ ${p}
402
404
  }
403
- `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new Q(e,"Delete",R,n,{mutationName:f,mutationInputTypes:a},(y,g)=>{if(s.EndedAt=new Date,g&&y){let I=!0;for(const E of e.PrimaryKey.KeyValuePairs)E.Value!==y[E.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(d,n);if(y&&y[f]){const g=y[f];for(let I of e.PrimaryKey.KeyValuePairs){let E=g[I.FieldName],w=I.Value;if(typeof w=="number"&&(w=w.toString()),typeof E=="number"&&(E=E.toString()),w!==E)throw new Error(`Primary key value mismatch in server Delete response. Field: ${I.FieldName}, Original: ${w}, Returned: ${E}`)}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,l(n),!1}}async GetDatasetByName(e,t){const r=m`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
405
+ `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new Q(e,"Delete",p,n,{mutationName:f,mutationInputTypes:a},(y,g)=>{if(s.EndedAt=new Date,g&&y){let R=!0;for(const E of e.PrimaryKey.KeyValuePairs)E.Value!==y[E.FieldName]&&(R=!1);R?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 R of e.PrimaryKey.KeyValuePairs){let E=g[R.FieldName],w=R.Value;if(typeof w=="number"&&(w=w.toString()),typeof E=="number"&&(E=E.toString()),w!==E)throw new Error(`Primary key value mismatch in server Delete response. Field: ${R.FieldName}, Original: ${w}, Returned: ${E}`)}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!]) {
404
406
  GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
405
407
  DatasetID
406
408
  DatasetName
@@ -418,7 +420,7 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
418
420
  LatestUpdateDate
419
421
  EntityUpdateDates
420
422
  }
421
- }`,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 F(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!) {
423
+ }`,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!) {
422
424
  GetRecordFavoriteStatus(params: $params) {
423
425
  Success
424
426
  IsFavorite
@@ -452,41 +454,41 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
452
454
  ErrorMessages
453
455
  Results
454
456
  }
455
- }`,r=await this.ExecuteGQL(t,{DataContextID:e});if(r&&r.GetDataContextData){if(r.GetDataContextData.Success)return r.GetDataContextData.Results.map(s=>JSON.parse(s));throw new Error(r.GetDataContextData.ErrorMessages.join(", "))}else throw new Error("GraphQL query failed")}catch(t){throw l(t),t}}async GetDataContextItemData(e){try{const t=m`query GetDataContextItemData ($DataContextItemID: String!) {
457
+ }`,r=await this.ExecuteGQL(t,{DataContextID:e});if(r&&r.GetDataContextData){if(r.GetDataContextData.Success)return r.GetDataContextData.Results.map(s=>JSON.parse(s));throw new Error(r.GetDataContextData.ErrorMessages.join(", "))}else throw new Error("GraphQL query failed")}catch(t){throw d(t),t}}async GetDataContextItemData(e){try{const t=m`query GetDataContextItemData ($DataContextItemID: String!) {
456
458
  GetDataContextItemData(DataContextItemID: $DataContextItemID) {
457
459
  Success
458
460
  ErrorMessage
459
461
  Result
460
462
  }
461
- }`,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 l(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 l("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw l(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 U(e,{headers:a})}userInfoString(){return this.infoString(new L(null,null))}userRoleInfoString(){return this.infoString(new X(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
463
+ }`,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 I.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=I.Instance&&I.Instance._configData===this._configData;if(e&&I.Instance._refreshPromise)return I.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(I.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&I.Instance&&(I.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,I.Instance&&I.Instance._configData===this._configData&&(I.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 I.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 L(e,{headers:a})}userInfoString(){return this.infoString(new F(null,null))}userRoleInfoString(){return this.infoString(new X(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
462
464
  `:s.startsWith("_")||(t+=s+`
463
- `);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new k:this._localStorageProvider=new Y),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=ae({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!) {
465
+ `);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new k:this._localStorageProvider=new Y),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=ae({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token},keepAlive:3e4,retryAttempts:3,shouldRetry:h(()=>!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:h(a=>{r.next(a.data)},"next"),error:h(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:h(()=>{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!) {
464
466
  statusUpdates(sessionId: $sessionId) {
465
467
  date
466
468
  message
467
469
  sessionId
468
470
  }
469
471
  }
470
- `,n=new se,a=this.getOrCreateWSClient(),i=new ne;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(d){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",d),o.error(d)}}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 FindISAChildEntity(e,t,r){if(!e.IsParentType)return null;const s=`query FindISAChildEntity($EntityName: String!, $RecordID: String!) {
472
+ `,n=new se,a=this.getOrCreateWSClient(),i=new ne;return i.add(new M(o=>{const u=a.subscribe({query:s,variables:{sessionId:e}},{next:h(c=>{const f=this._pushStatusSubjects.get(e);f&&(f.lastEmissionAt=Date.now()),o.next(c.data.statusUpdates.message)},"next"),error:h(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:h(()=>{o.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,u()}}).subscribe({next:h(o=>n.next(o),"next"),error:h(o=>{n.error(o),this._pushStatusSubjects.delete(e)},"error"),complete:h(()=>{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 FindISAChildEntity(e,t,r){if(!e.IsParentType)return null;const s=`query FindISAChildEntity($EntityName: String!, $RecordID: String!) {
471
473
  FindISAChildEntity(EntityName: $EntityName, RecordID: $RecordID) {
472
474
  Success
473
475
  ChildEntityName
474
476
  ErrorMessage
475
477
  }
476
- }`;try{const n=await this.ExecuteGQL(s,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntity?.Success&&n.FindISAChildEntity.ChildEntityName?{ChildEntityName:n.FindISAChildEntity.ChildEntityName}:null}catch(n){return l(`FindISAChildEntity failed for ${e.Name}: ${n}`),null}}async FindISAChildEntities(e,t,r){if(!e.IsParentType)return[];const s=`query FindISAChildEntities($EntityName: String!, $RecordID: String!) {
478
+ }`;try{const n=await this.ExecuteGQL(s,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntity?.Success&&n.FindISAChildEntity.ChildEntityName?{ChildEntityName:n.FindISAChildEntity.ChildEntityName}:null}catch(n){return d(`FindISAChildEntity failed for ${e.Name}: ${n}`),null}}async FindISAChildEntities(e,t,r){if(!e.IsParentType)return[];const s=`query FindISAChildEntities($EntityName: String!, $RecordID: String!) {
477
479
  FindISAChildEntities(EntityName: $EntityName, RecordID: $RecordID) {
478
480
  Success
479
481
  ChildEntityNames
480
482
  ErrorMessage
481
483
  }
482
- }`;try{const n=await this.ExecuteGQL(s,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntities?.Success&&n.FindISAChildEntities.ChildEntityNames?n.FindISAChildEntities.ChildEntityNames.map(a=>({ChildEntityName:a})):[]}catch(n){return l(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function me(h){const e=new S;return ee(e),await e.Config(h),await te.Instance.Startup(),ie.Instance.RaiseEvent({event:ue.LoggedIn,eventCode:null,component:this,args:null}),e}p(me,"setupGraphQLClient");class ge{static{p(this,"SyncRolesAndUsersResult")}}class pe{static{p(this,"RoleInput")}}class he{static{p(this,"UserInput")}}class fe{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 Se{static{p(this,"ActionItemInput")}}class Ie{static{p(this,"SyncDataResult")}constructor(){this.Results=[]}}class Re{static{p(this,"ActionItemOutput")}}class Ee{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 U(e,{headers:n})}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
484
+ }`;try{const n=await this.ExecuteGQL(s,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntities?.Success&&n.FindISAChildEntities.ChildEntityNames?n.FindISAChildEntities.ChildEntityNames.map(a=>({ChildEntityName:a})):[]}catch(n){return d(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function me(S){const e=new I;return ee(e),await e.Config(S),await te.Instance.Startup(),ie.Instance.RaiseEvent({event:ue.LoggedIn,eventCode:null,component:this,args:null}),e}h(me,"setupGraphQLClient");class ge{static{h(this,"SyncRolesAndUsersResult")}}class pe{static{h(this,"RoleInput")}}class he{static{h(this,"UserInput")}}class fe{static{h(this,"RolesAndUsersInput")}}var K=(S=>(S.Create="Create",S.Update="Update",S.CreateOrUpdate="CreateOrUpdate",S.Delete="Delete",S.DeleteWithFilter="DeleteWithFilter",S))(K||{});class Se{static{h(this,"ActionItemInput")}}class Ie{static{h(this,"SyncDataResult")}constructor(){this.Results=[]}}class Re{static{h(this,"ActionItemOutput")}}class Ee{static{h(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 L(e,{headers:n})}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
483
485
  GetData(input: $input) {
484
486
  Success
485
487
  ErrorMessages
486
488
  Queries
487
489
  Results
488
490
  }
489
- }`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(n=>n?$(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]+"."),re()){const a=`GraphQLSystemUserClient::GetData - Error getting data - ${r}`;l(a)}return{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
491
+ }`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(n=>n?P(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]+"."),re()){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 {
490
492
  GetAllEntities {
491
493
  Success
492
494
  ErrorMessage
@@ -509,7 +511,7 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
509
511
  }
510
512
  }
511
513
  }
512
- }`);return t&&t.GetAllEntities?t.GetAllEntities:{Success:!1,Results:[],ErrorMessage:t.GetAllEntities?.ErrorMessage??"Unknown error"}}catch(e){return l(`GraphQLSystemUserClient::GetAllRemoteEntities - Error getting remote entities - ${e}`),{Success:!1,Results:[],ErrorMessage:e}}}async SyncData(e){try{const r=await this.Client.request(`mutation SyncData($items: [ActionItemInputType!]!) {
514
+ }`);return t&&t.GetAllEntities?t.GetAllEntities:{Success:!1,Results:[],ErrorMessage:t.GetAllEntities?.ErrorMessage??"Unknown error"}}catch(e){return d(`GraphQLSystemUserClient::GetAllRemoteEntities - Error getting remote entities - ${e}`),{Success:!1,Results:[],ErrorMessage:e}}}async SyncData(e){try{const r=await this.Client.request(`mutation SyncData($items: [ActionItemInputType!]!) {
513
515
  SyncData(items: $items) {
514
516
  Success
515
517
  Results {
@@ -533,11 +535,11 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
533
535
  RecordJSON
534
536
  }
535
537
  }
536
- }`,{items:e});return r&&r.SyncData?r.SyncData:{Success:!1,Results:[]}}catch(t){return l(`GraphQLSystemUserClient::SyncData - Error syncing data - ${t}`),{Success:!1,Results:[]}}}async SyncRolesAndUsers(e){try{const r=await this.Client.request(`mutation SyncRolesAndUsers($data: RolesAndUsersInputType!) {
538
+ }`,{items:e});return r&&r.SyncData?r.SyncData:{Success:!1,Results:[]}}catch(t){return d(`GraphQLSystemUserClient::SyncData - Error syncing data - ${t}`),{Success:!1,Results:[]}}}async SyncRolesAndUsers(e){try{const r=await this.Client.request(`mutation SyncRolesAndUsers($data: RolesAndUsersInputType!) {
537
539
  SyncRolesAndUsers(data: $data) {
538
540
  Success
539
541
  }
540
- }`,{data:e});return r&&r.SyncRolesAndUsers?r.SyncRolesAndUsers:{Success:!1}}catch(t){return l(`GraphQLSystemUserClient::SyncRolesAndUsers - Error syncing roles and users - ${t}`),{Success:!1}}}async RunViewByName(e){try{const r=await this.Client.request(`query RunViewByNameSystemUser($input: RunViewByNameInput!) {
542
+ }`,{data:e});return r&&r.SyncRolesAndUsers?r.SyncRolesAndUsers:{Success:!1}}catch(t){return d(`GraphQLSystemUserClient::SyncRolesAndUsers - Error syncing roles and users - ${t}`),{Success:!1}}}async RunViewByName(e){try{const r=await this.Client.request(`query RunViewByNameSystemUser($input: RunViewByNameInput!) {
541
543
  RunViewByNameSystemUser(input: $input) {
542
544
  Results {
543
545
  PrimaryKey {
@@ -554,7 +556,7 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
554
556
  ErrorMessage
555
557
  Success
556
558
  }
557
- }`,{input:e});return r&&r.RunViewByNameSystemUser?r.RunViewByNameSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by name"}}catch(t){return l(`GraphQLSystemUserClient::RunViewByNameSystemUser - Error running view by name - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViewByID(e){try{const r=await this.Client.request(`query RunViewByIDSystemUser($input: RunViewByIDInput!) {
559
+ }`,{input:e});return r&&r.RunViewByNameSystemUser?r.RunViewByNameSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by name"}}catch(t){return d(`GraphQLSystemUserClient::RunViewByNameSystemUser - Error running view by name - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViewByID(e){try{const r=await this.Client.request(`query RunViewByIDSystemUser($input: RunViewByIDInput!) {
558
560
  RunViewByIDSystemUser(input: $input) {
559
561
  Results {
560
562
  PrimaryKey {
@@ -571,7 +573,7 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
571
573
  ErrorMessage
572
574
  Success
573
575
  }
574
- }`,{input:e});return r&&r.RunViewByIDSystemUser?r.RunViewByIDSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by ID"}}catch(t){return l(`GraphQLSystemUserClient::RunViewByIDSystemUser - Error running view by ID - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunDynamicView(e){try{const r=await this.Client.request(`query RunDynamicViewSystemUser($input: RunDynamicViewInput!) {
576
+ }`,{input:e});return r&&r.RunViewByIDSystemUser?r.RunViewByIDSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by ID"}}catch(t){return d(`GraphQLSystemUserClient::RunViewByIDSystemUser - Error running view by ID - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunDynamicView(e){try{const r=await this.Client.request(`query RunDynamicViewSystemUser($input: RunDynamicViewInput!) {
575
577
  RunDynamicViewSystemUser(input: $input) {
576
578
  Results {
577
579
  PrimaryKey {
@@ -588,7 +590,7 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
588
590
  ErrorMessage
589
591
  Success
590
592
  }
591
- }`,{input:e});return r&&r.RunDynamicViewSystemUser?r.RunDynamicViewSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute dynamic view"}}catch(t){return l(`GraphQLSystemUserClient::RunDynamicViewSystemUser - Error running dynamic view - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViews(e){try{const r=await this.Client.request(`query RunViewsSystemUser($input: [RunViewGenericInput!]!) {
593
+ }`,{input:e});return r&&r.RunDynamicViewSystemUser?r.RunDynamicViewSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute dynamic view"}}catch(t){return d(`GraphQLSystemUserClient::RunDynamicViewSystemUser - Error running dynamic view - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViews(e){try{const r=await this.Client.request(`query RunViewsSystemUser($input: [RunViewGenericInput!]!) {
592
594
  RunViewsSystemUser(input: $input) {
593
595
  Results {
594
596
  PrimaryKey {
@@ -605,7 +607,7 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
605
607
  ErrorMessage
606
608
  Success
607
609
  }
608
- }`,{input:e});return r&&r.RunViewsSystemUser?r.RunViewsSystemUser:[]}catch(t){return l(`GraphQLSystemUserClient::RunViewsSystemUser - Error running views - ${t}`),[]}}async GetQueryData(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 GetQueryDataSystemUser($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
610
+ }`,{input:e});return r&&r.RunViewsSystemUser?r.RunViewsSystemUser:[]}catch(t){return d(`GraphQLSystemUserClient::RunViewsSystemUser - Error running views - ${t}`),[]}}async GetQueryData(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 GetQueryDataSystemUser($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
609
611
  GetQueryDataSystemUser(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
610
612
  QueryID
611
613
  QueryName
@@ -617,7 +619,7 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
617
619
  ErrorMessage
618
620
  AppliedParameters
619
621
  }
620
- }`,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 l(`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) {
622
+ }`,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?P(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) {
621
623
  GetQueryDataByNameSystemUser(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
622
624
  QueryID
623
625
  QueryName
@@ -629,7 +631,7 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
629
631
  ErrorMessage
630
632
  AppliedParameters
631
633
  }
632
- }`,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 l(`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!) {
634
+ }`,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?P(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!) {
633
635
  CreateQuerySystemUser(input: $input) {
634
636
  Success
635
637
  ErrorMessage
@@ -684,7 +686,7 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
684
686
  Role
685
687
  }
686
688
  }
687
- }`,{input:e});return r&&r.CreateQuerySystemUser?r.CreateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to create query"}}catch(t){return l(`GraphQLSystemUserClient::CreateQuery - Error creating query - ${t}`),{Success:!1,ErrorMessage:t.toString()}}}async UpdateQuery(e){try{const r=await this.Client.request(`mutation UpdateQuerySystemUser($input: UpdateQuerySystemUserInput!) {
689
+ }`,{input:e});return r&&r.CreateQuerySystemUser?r.CreateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to create query"}}catch(t){return d(`GraphQLSystemUserClient::CreateQuery - Error creating query - ${t}`),{Success:!1,ErrorMessage:t.toString()}}}async UpdateQuery(e){try{const r=await this.Client.request(`mutation UpdateQuerySystemUser($input: UpdateQuerySystemUserInput!) {
688
690
  UpdateQuerySystemUser(input: $input) {
689
691
  Success
690
692
  ErrorMessage
@@ -739,14 +741,14 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
739
741
  Role
740
742
  }
741
743
  }
742
- }`,{input:e});return r&&r.UpdateQuerySystemUser?r.UpdateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to update query"}}catch(t){return l(`GraphQLSystemUserClient::UpdateQuery - Error updating query - ${t}`),{Success:!1,ErrorMessage:t.toString()}}}async DeleteQuery(e,t){try{if(!e||e.trim()==="")return l("GraphQLSystemUserClient::DeleteQuery - Invalid query ID: ID cannot be null or empty"),{Success:!1,ErrorMessage:"Invalid query ID: ID cannot be null or empty"};const r=`mutation DeleteQuerySystemResolver($ID: String!, $options: DeleteOptionsInput) {
744
+ }`,{input:e});return r&&r.UpdateQuerySystemUser?r.UpdateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to update query"}}catch(t){return d(`GraphQLSystemUserClient::UpdateQuery - Error updating query - ${t}`),{Success:!1,ErrorMessage:t.toString()}}}async DeleteQuery(e,t){try{if(!e||e.trim()==="")return d("GraphQLSystemUserClient::DeleteQuery - Invalid query ID: ID cannot be null or empty"),{Success:!1,ErrorMessage:"Invalid query ID: ID cannot be null or empty"};const r=`mutation DeleteQuerySystemResolver($ID: String!, $options: DeleteOptionsInput) {
743
745
  DeleteQuerySystemResolver(ID: $ID, options: $options) {
744
746
  Success
745
747
  ErrorMessage
746
748
  ID
747
749
  Name
748
750
  }
749
- }`,s={ID:e};t!==void 0&&(s.options={SkipEntityAIActions:t.SkipEntityAIActions??!1,SkipEntityActions:t.SkipEntityActions??!1,ReplayOnly:t.ReplayOnly??!1,IsParentEntityDelete:t.IsParentEntityDelete??!1});const n=await this.Client.request(r,s);return n&&n.DeleteQuerySystemResolver?n.DeleteQuerySystemResolver:{Success:!1,ErrorMessage:"Failed to delete query"}}catch(r){let s="";if(r instanceof Error){if(s=r.message,"cause"in r&&r.cause){const n=r.cause;s+=` | Cause: ${n.message||n}`,"code"in n&&(s+=` | Code: ${n.code}`)}if("response"in r){const n=r.response;n?.status&&(s+=` | HTTP Status: ${n.status}`),n?.errors&&(s+=` | GraphQL Errors: ${JSON.stringify(n.errors)}`)}r.stack&&console.error("DeleteQuery stack trace:",r.stack)}else s=String(r);return l(`GraphQLSystemUserClient::DeleteQuery - Error deleting query - ${s}`),{Success:!1,ErrorMessage:s}}}async RunAIPrompt(e){try{const t=m`
751
+ }`,s={ID:e};t!==void 0&&(s.options={SkipEntityAIActions:t.SkipEntityAIActions??!1,SkipEntityActions:t.SkipEntityActions??!1,ReplayOnly:t.ReplayOnly??!1,IsParentEntityDelete:t.IsParentEntityDelete??!1});const n=await this.Client.request(r,s);return n&&n.DeleteQuerySystemResolver?n.DeleteQuerySystemResolver:{Success:!1,ErrorMessage:"Failed to delete query"}}catch(r){let s="";if(r instanceof Error){if(s=r.message,"cause"in r&&r.cause){const n=r.cause;s+=` | Cause: ${n.message||n}`,"code"in n&&(s+=` | Code: ${n.code}`)}if("response"in r){const n=r.response;n?.status&&(s+=` | HTTP Status: ${n.status}`),n?.errors&&(s+=` | GraphQL Errors: ${JSON.stringify(n.errors)}`)}r.stack&&console.error("DeleteQuery stack trace:",r.stack)}else s=String(r);return d(`GraphQLSystemUserClient::DeleteQuery - Error deleting query - ${s}`),{Success:!1,ErrorMessage:s}}}async RunAIPrompt(e){try{const t=m`
750
752
  query RunAIPromptSystemUser(
751
753
  $promptId: String!,
752
754
  $data: String,
@@ -805,7 +807,7 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
805
807
  chatResult
806
808
  }
807
809
  }
808
- `,r=this.preparePromptVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIPromptSystemUser?this.processPromptResult(s.RunAIPromptSystemUser):{success:!1,error:"Failed to execute AI prompt as system user"}}catch(t){return l(`GraphQLSystemUserClient::RunAIPrompt - Error running AI prompt - ${t}`),{success:!1,error:t.toString()}}}async RunAIAgent(e){try{const t=m`
810
+ `,r=this.preparePromptVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIPromptSystemUser?this.processPromptResult(s.RunAIPromptSystemUser):{success:!1,error:"Failed to execute AI prompt as system user"}}catch(t){return d(`GraphQLSystemUserClient::RunAIPrompt - Error running AI prompt - ${t}`),{success:!1,error:t.toString()}}}async RunAIAgent(e){try{const t=m`
809
811
  query RunAIAgentSystemUser(
810
812
  $agentId: String!,
811
813
  $messages: String!,
@@ -832,7 +834,7 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
832
834
  result
833
835
  }
834
836
  }
835
- `,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 l(`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`
837
+ `,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 P(e)}async ExecuteSimplePrompt(e){try{const t=m`
836
838
  query ExecuteSimplePromptSystemUser(
837
839
  $systemPrompt: String!,
838
840
  $messages: String,
@@ -855,7 +857,7 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
855
857
  executionTimeMs
856
858
  }
857
859
  }
858
- `,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 l(`GraphQLSystemUserClient::ExecuteSimplePrompt - Error executing simple prompt - ${t}`),{success:!1,modelName:"Unknown",error:t.toString()}}}async EmbedText(e){try{const t=m`
860
+ `,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`
859
861
  query EmbedTextSystemUser(
860
862
  $textToEmbed: [String!]!,
861
863
  $modelSize: String!
@@ -870,7 +872,7 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
870
872
  error
871
873
  }
872
874
  }
873
- `,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 l(`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 Ce{static{p(this,"SimpleRemoteEntity")}}class Pe{static{p(this,"SimpleRemoteEntityField")}}class $e{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`
875
+ `,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{h(this,"GetDataOutput")}}class we{static{h(this,"SimpleRemoteEntityOutput")}}class Ce{static{h(this,"SimpleRemoteEntity")}}class Pe{static{h(this,"SimpleRemoteEntityField")}}class ve{static{h(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`
874
876
  mutation RunAction($input: RunActionInput!) {
875
877
  RunAction(input: $input) {
876
878
  Success
@@ -879,7 +881,7 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
879
881
  ResultData
880
882
  }
881
883
  }
882
- `;return await this._dataProvider.ExecuteGQL(t,e)}processActionResult(e,t){if(!e?.RunAction)throw new Error("Invalid response from server");let r;try{e.RunAction.ResultData&&(r=JSON.parse(e.RunAction.ResultData))}catch(s){l(`Failed to parse action result data: ${s}`)}return{Success:e.RunAction.Success,Message:e.RunAction.Message,Result:r,LogEntry:null,Params:t||[],RunParams:null}}handleActionError(e,t){const r=e;return l(`Error running action: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Result:null,LogEntry:null,Params:t||[],RunParams:null}}async RunEntityAction(e){try{const t=this.createEntityActionInput(e),r=await this.executeEntityActionMutation(t);return this.processEntityActionResult(r)}catch(t){return this.handleEntityActionError(t)}}createEntityActionInput(e){const t={EntityActionID:e.EntityAction.ID,InvocationType:e.InvocationType.Name,ListID:e.ListID,ViewID:e.ViewID};return e.Params&&(t.Params=this.convertActionParams(e.Params)),e.EntityObject&&this.addEntityInformation(t,e.EntityObject),t}convertActionParams(e){return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{Name:t.Name,Value:r,Type:t.Type}})}addEntityInformation(e,t){e.EntityName=t.EntityInfo?.Name,t.PrimaryKey&&(e.PrimaryKey=this.convertPrimaryKey(t.PrimaryKey))}convertPrimaryKey(e){return{KeyValuePairs:e.KeyValuePairs.map(t=>this.convertKeyValuePair(t))}}convertKeyValuePair(e){return{FieldName:e.FieldName,Value:e.Value!==null&&e.Value!==void 0?typeof e.Value=="object"?JSON.stringify(e.Value):e.Value.toString():null}}async executeEntityActionMutation(e){const t=m`
884
+ `;return await this._dataProvider.ExecuteGQL(t,e)}processActionResult(e,t){if(!e?.RunAction)throw new Error("Invalid response from server");let r;try{e.RunAction.ResultData&&(r=JSON.parse(e.RunAction.ResultData))}catch(s){d(`Failed to parse action result data: ${s}`)}return{Success:e.RunAction.Success,Message:e.RunAction.Message,Result:r,LogEntry:null,Params:t||[],RunParams:null}}handleActionError(e,t){const r=e;return d(`Error running action: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Result:null,LogEntry:null,Params:t||[],RunParams:null}}async RunEntityAction(e){try{const t=this.createEntityActionInput(e),r=await this.executeEntityActionMutation(t);return this.processEntityActionResult(r)}catch(t){return this.handleEntityActionError(t)}}createEntityActionInput(e){const t={EntityActionID:e.EntityAction.ID,InvocationType:e.InvocationType.Name,ListID:e.ListID,ViewID:e.ViewID};return e.Params&&(t.Params=this.convertActionParams(e.Params)),e.EntityObject&&this.addEntityInformation(t,e.EntityObject),t}convertActionParams(e){return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{Name:t.Name,Value:r,Type:t.Type}})}addEntityInformation(e,t){e.EntityName=t.EntityInfo?.Name,t.PrimaryKey&&(e.PrimaryKey=this.convertPrimaryKey(t.PrimaryKey))}convertPrimaryKey(e){return{KeyValuePairs:e.KeyValuePairs.map(t=>this.convertKeyValuePair(t))}}convertKeyValuePair(e){return{FieldName:e.FieldName,Value:e.Value!==null&&e.Value!==void 0?typeof e.Value=="object"?JSON.stringify(e.Value):e.Value.toString():null}}async executeEntityActionMutation(e){const t=m`
883
885
  mutation RunEntityAction($input: EntityActionInput!) {
884
886
  RunEntityAction(input: $input) {
885
887
  Success
@@ -887,7 +889,7 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
887
889
  ResultData
888
890
  }
889
891
  }
890
- `;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){l(`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 l(`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`
892
+ `;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 $e{static{h(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`
891
893
  mutation CreateAPIKey($input: CreateAPIKeyInput!) {
892
894
  CreateAPIKey(input: $input) {
893
895
  Success
@@ -896,14 +898,14 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
896
898
  Error
897
899
  }
898
900
  }
899
- `;return await this._dataProvider.ExecuteGQL(t,e)}processCreateAPIKeyResult(e){const t=e;return t?.CreateAPIKey?{Success:t.CreateAPIKey.Success,RawKey:t.CreateAPIKey.RawKey,APIKeyID:t.CreateAPIKey.APIKeyID,Error:t.CreateAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}handleCreateAPIKeyError(e){const t=e;return l(`Error creating API key: ${t.message}`),{Success:!1,Error:`Error: ${t.message}`}}async RevokeAPIKey(e){try{const t=m`
901
+ `;return await this._dataProvider.ExecuteGQL(t,e)}processCreateAPIKeyResult(e){const t=e;return t?.CreateAPIKey?{Success:t.CreateAPIKey.Success,RawKey:t.CreateAPIKey.RawKey,APIKeyID:t.CreateAPIKey.APIKeyID,Error:t.CreateAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}handleCreateAPIKeyError(e){const t=e;return d(`Error creating API key: ${t.message}`),{Success:!1,Error:`Error: ${t.message}`}}async RevokeAPIKey(e){try{const t=m`
900
902
  mutation RevokeAPIKey($apiKeyId: String!) {
901
903
  RevokeAPIKey(apiKeyId: $apiKeyId) {
902
904
  Success
903
905
  Error
904
906
  }
905
907
  }
906
- `,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 l(`Error revoking API key: ${r.message}`),{Success:!1,Error:`Error: ${r.message}`}}}}class Ae{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`
908
+ `,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 Ae{static{h(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`
907
909
  mutation RunTest(
908
910
  $testId: String!,
909
911
  $verbose: Boolean,
@@ -957,7 +959,7 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
957
959
  query IsTestRunning($testId: String!) {
958
960
  IsTestRunning(testId: $testId)
959
961
  }
960
- `;return(await this._dataProvider.ExecuteGQL(t,{testId:e})).IsTestRunning}catch(t){return l(`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 l(`${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`
962
+ `;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=P(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=P(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{h(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=m`
961
963
  query GetRegistryComponent(
962
964
  $registryName: String!,
963
965
  $namespace: String!,
@@ -978,7 +980,7 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
978
980
  specification
979
981
  }
980
982
  }
981
- `,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 l(`Failed to parse component specification: ${a}`),null}}return null}return null}catch(t){throw l(t),new Error(`Failed to get registry component: ${t instanceof Error?t.message:"Unknown error"}`)}}async GetRegistryComponentWithHash(e){try{const t=m`
983
+ `,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`
982
984
  query GetRegistryComponent(
983
985
  $registryName: String!,
984
986
  $namespace: String!,
@@ -999,7 +1001,7 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
999
1001
  specification
1000
1002
  }
1001
1003
  }
1002
- `,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){l(`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 l(t),new Error(`Failed to get registry component with hash: ${t instanceof Error?t.message:"Unknown error"}`)}}async SearchRegistryComponents(e){try{const t=m`
1004
+ `,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`
1003
1005
  query SearchRegistryComponents($params: SearchRegistryComponentsInput!) {
1004
1006
  SearchRegistryComponents(params: $params) {
1005
1007
  components
@@ -1008,7 +1010,7 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
1008
1010
  limit
1009
1011
  }
1010
1012
  }
1011
- `,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 l(t),new Error(`Failed to search registry components: ${t instanceof Error?t.message:"Unknown error"}`)}}async ResolveComponentDependencies(e,t){try{const r=m`
1013
+ `,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`
1012
1014
  query ResolveComponentDependencies(
1013
1015
  $registryId: String!,
1014
1016
  $componentId: String!
@@ -1033,7 +1035,7 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
1033
1035
  }
1034
1036
  }
1035
1037
  }
1036
- `,s=await this._dataProvider.ExecuteGQL(r,{registryId:e,componentId:t});return s&&s.ResolveComponentDependencies?s.ResolveComponentDependencies:null}catch(r){throw l(r),new Error(`Failed to resolve component dependencies: ${r instanceof Error?r.message:"Unknown error"}`)}}async ComponentExists(e){try{return await this.GetRegistryComponent(e)!==null}catch{return!1}}async GetLatestVersion(e,t,r){try{return(await this.GetRegistryComponent({registryName:e,namespace:t,name:r,version:"latest"}))?.version||null}catch(s){return l(s),null}}async SendComponentFeedback(e){try{const t=m`
1038
+ `,s=await this._dataProvider.ExecuteGQL(r,{registryId:e,componentId:t});return s&&s.ResolveComponentDependencies?s.ResolveComponentDependencies:null}catch(r){throw d(r),new Error(`Failed to resolve component dependencies: ${r instanceof Error?r.message:"Unknown error"}`)}}async ComponentExists(e){try{return await this.GetRegistryComponent(e)!==null}catch{return!1}}async GetLatestVersion(e,t,r){try{return(await this.GetRegistryComponent({registryName:e,namespace:t,name:r,version:"latest"}))?.version||null}catch(s){return d(s),null}}async SendComponentFeedback(e){try{const t=m`
1037
1039
  mutation SendComponentFeedback($feedback: ComponentFeedbackInput!) {
1038
1040
  SendComponentFeedback(feedback: $feedback) {
1039
1041
  success
@@ -1041,7 +1043,7 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
1041
1043
  error
1042
1044
  }
1043
1045
  }
1044
- `,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return l(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}}class be{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`
1046
+ `,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 be{static{h(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`
1045
1047
  mutation CreateVersionLabel($input: CreateVersionLabelInput!, $sessionId: String) {
1046
1048
  CreateVersionLabel(input: $input, sessionId: $sessionId) {
1047
1049
  Success
@@ -1057,7 +1059,7 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
1057
1059
  }
1058
1060
  }
1059
1061
  }
1060
- `,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 l(`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 xe{static{p(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const s=m`
1062
+ `,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 xe{static{h(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const s=m`
1061
1063
  query ListStorageObjects($input: ListStorageObjectsInput!) {
1062
1064
  ListStorageObjects(input: $input) {
1063
1065
  objects {
@@ -1074,34 +1076,34 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
1074
1076
  prefixes
1075
1077
  }
1076
1078
  }
1077
- `,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 l(`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 l(`Error checking directory existence: ${r}`),!1}}async CreateDirectory(e,t){try{const r=m`
1079
+ `,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`
1078
1080
  mutation CreateDirectory($input: CreateDirectoryInput!) {
1079
1081
  CreateDirectory(input: $input)
1080
1082
  }
1081
- `,s={input:{AccountID:e,Path:t}};return(await this._dataProvider.ExecuteGQL(r,s))?.CreateDirectory??!1}catch(r){return l(`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 l(`Error checking object existence: ${r}`),!1}}async CreatePreAuthUploadUrl(e,t,r){try{const s=m`
1083
+ `,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`
1082
1084
  mutation CreatePreAuthUploadUrl($input: CreatePreAuthUploadUrlInput!) {
1083
1085
  CreatePreAuthUploadUrl(input: $input) {
1084
1086
  UploadUrl
1085
1087
  ProviderKey
1086
1088
  }
1087
1089
  }
1088
- `,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 l(`Error creating pre-auth upload URL: ${n}`),n}}async CreatePreAuthDownloadUrl(e,t){try{const r=m`
1090
+ `,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`
1089
1091
  query CreatePreAuthDownloadUrl($input: CreatePreAuthDownloadUrlInput!) {
1090
1092
  CreatePreAuthDownloadUrl(input: $input)
1091
1093
  }
1092
- `,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 l(`Error creating pre-auth download URL: ${s}`),s}}async DeleteObject(e,t){try{const r=m`
1094
+ `,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`
1093
1095
  mutation DeleteStorageObject($input: DeleteStorageObjectInput!) {
1094
1096
  DeleteStorageObject(input: $input)
1095
1097
  }
1096
- `,s={input:{AccountID:e,ObjectName:t}};return(await this._dataProvider.ExecuteGQL(r,s))?.DeleteStorageObject??!1}catch(r){return l(`Error deleting storage object: ${r}`),!1}}async MoveObject(e,t,r){try{const s=m`
1098
+ `,s={input:{AccountID:e,ObjectName:t}};return(await this._dataProvider.ExecuteGQL(r,s))?.DeleteStorageObject??!1}catch(r){return d(`Error deleting storage object: ${r}`),!1}}async MoveObject(e,t,r){try{const s=m`
1097
1099
  mutation MoveStorageObject($input: MoveStorageObjectInput!) {
1098
1100
  MoveStorageObject(input: $input)
1099
1101
  }
1100
- `,n={input:{AccountID:e,OldName:t,NewName:r}};return(await this._dataProvider.ExecuteGQL(s,n))?.MoveStorageObject??!1}catch(s){return l(`Error moving storage object: ${s}`),!1}}async CopyObject(e,t,r){try{const s=m`
1102
+ `,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`
1101
1103
  mutation CopyStorageObject($input: CopyStorageObjectInput!) {
1102
1104
  CopyStorageObject(input: $input)
1103
1105
  }
1104
- `,n={input:{AccountID:e,SourceName:t,DestinationName:r}};return(await this._dataProvider.ExecuteGQL(s,n))?.CopyStorageObject??!1}catch(s){return l(`Error copying storage object: ${s}`),!1}}async CopyObjectBetweenAccounts(e,t,r,s){try{const n=m`
1106
+ `,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`
1105
1107
  mutation CopyObjectBetweenAccounts($input: CopyObjectBetweenAccountsInput!) {
1106
1108
  CopyObjectBetweenAccounts(input: $input) {
1107
1109
  success
@@ -1113,7 +1115,7 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
1113
1115
  destinationPath
1114
1116
  }
1115
1117
  }
1116
- `,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 l(`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`
1118
+ `,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`
1117
1119
  query SearchAcrossAccounts($input: SearchAcrossAccountsInput!) {
1118
1120
  SearchAcrossAccounts(input: $input) {
1119
1121
  accountResults {
@@ -1141,5 +1143,5 @@ var B=Object.defineProperty;var p=(h,e)=>B(h,"name",{value:e,configurable:!0});i
1141
1143
  failedAccounts
1142
1144
  }
1143
1145
  }
1144
- `,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 l(`Error searching across accounts: ${s}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}export{Se as ActionItemInput,Re as ActionItemOutput,k as BrowserIndexedDBStorageProvider,_ as BrowserStorageProviderBase,N as FieldMapper,De as GetDataOutput,G as GraphQLAIClient,$e as GraphQLActionClient,Ne as GraphQLComponentRegistryClient,S as GraphQLDataProvider,ve as GraphQLEncryptionClient,xe as GraphQLFileStorageClient,ye as GraphQLProviderConfigData,Ee as GraphQLSystemUserClient,Ae as GraphQLTestingClient,F as GraphQLTransactionGroup,be as GraphQLVersionHistoryClient,pe as RoleInput,fe as RolesAndUsersInput,Ce as SimpleRemoteEntity,Pe as SimpleRemoteEntityField,we as SimpleRemoteEntityOutput,K as SyncDataAction,Ie as SyncDataResult,ge as SyncRolesAndUsersResult,he as UserInput,ke as gql,me as setupGraphQLClient};
1146
+ `,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{Se as ActionItemInput,Re as ActionItemOutput,k as BrowserIndexedDBStorageProvider,_ as BrowserStorageProviderBase,N as FieldMapper,De as GetDataOutput,T as GraphQLAIClient,ve as GraphQLActionClient,Ne as GraphQLComponentRegistryClient,I as GraphQLDataProvider,$e as GraphQLEncryptionClient,xe as GraphQLFileStorageClient,ye as GraphQLProviderConfigData,Ee as GraphQLSystemUserClient,Ae as GraphQLTestingClient,G as GraphQLTransactionGroup,be as GraphQLVersionHistoryClient,pe as RoleInput,fe as RolesAndUsersInput,Ce as SimpleRemoteEntity,Pe as SimpleRemoteEntityField,we as SimpleRemoteEntityOutput,K as SyncDataAction,Ie as SyncDataResult,ge as SyncRolesAndUsersResult,he as UserInput,ke as gql,me as setupGraphQLClient};
1145
1147
  //# sourceMappingURL=index.mjs.map