@memberjunction/graphql-dataprovider 5.24.0 → 5.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var G=Object.defineProperty;var g=(h,e)=>G(h,"name",{value:e,configurable:!0});var u=require("graphql-request"),c=require("@memberjunction/core"),D=require("@memberjunction/global"),N=require("@memberjunction/core-entities"),b=require("rxjs"),U=require("graphql-ws"),V=require("uuid"),_=require("@tempfix/idb");class v{static{g(this,"FieldMapper")}static{this.DB_PREFIX="__mj_"}static{this.GQL_PREFIX="_mj__"}constructor(){}MapFields(e){if(e)for(const t in e){const r=this.MapFieldName(t);r!==t&&(e[r]=e[t],delete e[t])}return e}MapFieldName(e){return e.startsWith(v.DB_PREFIX)?v.GQL_PREFIX+e.substring(v.DB_PREFIX.length):e}ReverseMapFieldName(e){return e.startsWith(v.GQL_PREFIX)?v.DB_PREFIX+e.substring(v.GQL_PREFIX.length):e}ReverseMapFields(e){for(const t in e){const r=this.ReverseMapFieldName(t);r!==t&&(e[r]=e[t],delete e[t])}return e}}class M extends c.TransactionGroupBase{static{g(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=u.gql`
1
+ "use strict";var U=Object.defineProperty;var g=(h,e)=>U(h,"name",{value:e,configurable:!0});var u=require("graphql-request"),c=require("@memberjunction/core"),R=require("@memberjunction/global"),b=require("@memberjunction/core-entities"),N=require("rxjs"),G=require("graphql-ws"),V=require("uuid"),_=require("@tempfix/idb");class w{static{g(this,"FieldMapper")}static{this.DB_PREFIX="__mj_"}static{this.GQL_PREFIX="_mj__"}constructor(){}MapFields(e){if(e)for(const t in e){const r=this.MapFieldName(t);r!==t&&(e[r]=e[t],delete e[t])}return e}MapFieldName(e){return e.startsWith(w.DB_PREFIX)?w.GQL_PREFIX+e.substring(w.DB_PREFIX.length):e}ReverseMapFieldName(e){return e.startsWith(w.GQL_PREFIX)?w.DB_PREFIX+e.substring(w.GQL_PREFIX.length):e}ReverseMapFields(e){for(const t in e){const r=this.ReverseMapFieldName(t);r!==t&&(e[r]=e[t],delete e[t])}return e}}class M extends c.TransactionGroupBase{static{g(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=u.gql`
2
2
  mutation ExecuteTransactionGroup($group: TransactionInputType!) {
3
3
  ExecuteTransactionGroup(group: $group) {
4
4
  Success
@@ -6,7 +6,7 @@
6
6
  ResultsJSON
7
7
  }
8
8
  }
9
- `,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const r={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const n=s.ExecuteTransactionGroup,a=[];for(let i=0;i<this.PendingTransactions.length;i++){const o=n.ResultsJSON[i],l=D.SafeJSONParse(o),d=this.PendingTransactions[i];a.push(new c.TransactionResult(d,l,l!==null))}return a}else throw new Error("Failed to execute transaction group")}}const O=900*1e3;class P{static{g(this,"FireAndForgetHelper")}static async Execute(e){const t=e.operationLabel??e.mutationFieldName;let r,s;try{const{promise:n,resolve:a,reject:i}=P.createCompletionPromise();s=P.setupTimeout(i,e.timeoutMs,e.timeoutErrorMessage),r=P.subscribeToPubSub(e,a,s);const o=await P.executeMutation(e);if(!e.validateAck(o)){s&&clearTimeout(s);const l=o?.errorMessage??"Server rejected the request";return c.LogError(`[FireAndForget:${t}] Server rejected: ${l}`),e.createErrorResult(l)}return c.LogStatus(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await n}catch(n){s&&clearTimeout(s);const a=n;throw c.LogError(`[FireAndForget:${t}] Error: ${a.message}`),n}finally{s&&clearTimeout(s),r&&r.unsubscribe()}}static createCompletionPromise(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}static setupTimeout(e,t,r){const s=t??O,n=r??"The operation may still be running on the server but the client timed out after 15 minutes. Please refresh the page to check the latest status.";return setTimeout(()=>{e(new Error(n))},s)}static subscribeToPubSub(e,t,r){const s=e.dataProvider.sessionId,n=e.operationLabel??e.mutationFieldName;return e.dataProvider.PushStatusUpdates(s).subscribe(a=>{try{const i=JSON.parse(a);e.onMessage&&e.onMessage(i),e.isCompletionEvent(i)&&(clearTimeout(r),c.LogStatus(`[FireAndForget:${n}] Completion event received`),t(e.extractResult(i)))}catch(i){console.error(`[FireAndForget:${n}] Failed to parse PubSub message:`,i)}})}static async executeMutation(e){return(await e.dataProvider.ExecuteGQL(e.mutation,e.variables))[e.mutationFieldName]}}class x{static{g(this,"GraphQLAIClient")}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=u.gql`
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],l=R.SafeJSONParse(o),d=this.PendingTransactions[i];a.push(new c.TransactionResult(d,l,l!==null))}return a}else throw new Error("Failed to execute transaction group")}}const O=900*1e3;class P{static{g(this,"FireAndForgetHelper")}static async Execute(e){const t=e.operationLabel??e.mutationFieldName;let r,s;try{const{promise:n,resolve:a,reject:i}=P.createCompletionPromise();s=P.setupTimeout(i,e.timeoutMs,e.timeoutErrorMessage),r=P.subscribeToPubSub(e,a,s);const o=await P.executeMutation(e);if(!e.validateAck(o)){s&&clearTimeout(s);const l=o?.errorMessage??"Server rejected the request";return c.LogError(`[FireAndForget:${t}] Server rejected: ${l}`),e.createErrorResult(l)}return c.LogStatus(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await n}catch(n){s&&clearTimeout(s);const a=n;throw c.LogError(`[FireAndForget:${t}] Error: ${a.message}`),n}finally{s&&clearTimeout(s),r&&r.unsubscribe()}}static createCompletionPromise(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}static setupTimeout(e,t,r){const s=t??O,n=r??"The operation may still be running on the server but the client timed out after 15 minutes. Please refresh the page to check the latest status.";return setTimeout(()=>{e(new Error(n))},s)}static subscribeToPubSub(e,t,r){const s=e.dataProvider.sessionId,n=e.operationLabel??e.mutationFieldName;return e.dataProvider.PushStatusUpdates(s).subscribe(a=>{try{const i=JSON.parse(a);e.onMessage&&e.onMessage(i),e.isCompletionEvent(i)&&(clearTimeout(r),c.LogStatus(`[FireAndForget:${n}] Completion event received`),t(e.extractResult(i)))}catch(i){console.error(`[FireAndForget:${n}] Failed to parse PubSub message:`,i)}})}static async executeMutation(e){return(await e.dataProvider.ExecuteGQL(e.mutation,e.variables))[e.mutationFieldName]}}class x{static{g(this,"GraphQLAIClient")}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=u.gql`
10
10
  mutation RunAIPrompt(
11
11
  $promptId: String!,
12
12
  $data: String,
@@ -65,7 +65,7 @@
65
65
  chatResult
66
66
  }
67
67
  }
68
- `,r=this.preparePromptVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(s)}catch(t){return this.handlePromptError(t)}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,n;try{t.parsedResult&&(r=D.CleanAndParseJSON(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 c.LogError(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){try{const s=this.buildRunAIAgentMutation(),n=this.prepareAgentVariables(e,t,r);return n.fireAndForget=!0,await P.Execute({dataProvider:this._dataProvider,mutation:s,variables:n,mutationFieldName:"RunAIAgent",operationLabel:"RunAIAgent",validateAck:g(a=>a?.success===!0,"validateAck"),isCompletionEvent:g(a=>this.isAgentCompletionEvent(a),"isCompletionEvent"),extractResult:g(a=>this.extractAgentResult(a),"extractResult"),onMessage:e.onProgress?a=>this.forwardAgentProgress(a,e.onProgress):void 0,createErrorResult:g(a=>this.createAgentErrorResult(a),"createErrorResult")})}catch(s){return this.handleAgentError(s)}}buildRunAIAgentMutation(){return u.gql`
68
+ `,r=this.preparePromptVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(s)}catch(t){return this.handlePromptError(t)}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,n;try{t.parsedResult&&(r=R.CleanAndParseJSON(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 c.LogError(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){try{const s=this.buildRunAIAgentMutation(),n=this.prepareAgentVariables(e,t,r);return n.fireAndForget=!0,await P.Execute({dataProvider:this._dataProvider,mutation:s,variables:n,mutationFieldName:"RunAIAgent",operationLabel:"RunAIAgent",validateAck:g(a=>a?.success===!0,"validateAck"),isCompletionEvent:g(a=>this.isAgentCompletionEvent(a),"isCompletionEvent"),extractResult:g(a=>this.extractAgentResult(a),"extractResult"),onMessage:e.onProgress?a=>this.forwardAgentProgress(a,e.onProgress):void 0,createErrorResult:g(a=>this.createAgentErrorResult(a),"createErrorResult")})}catch(s){return this.handleAgentError(s)}}buildRunAIAgentMutation(){return u.gql`
69
69
  mutation RunAIAgent(
70
70
  $agentId: String!,
71
71
  $messages: String!,
@@ -106,7 +106,7 @@
106
106
  result
107
107
  }
108
108
  }
109
- `}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 D.SafeJSONParse(e)}handleAgentError(e){const r=e?.message||String(e);c.LogError(`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){try{const t=this.buildConversationDetailMutation(),r=this.prepareConversationDetailVariables(e);return await P.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunAIAgentFromConversationDetail",operationLabel:"RunAIAgentFromConversationDetail",validateAck:g(s=>s?.success===!0,"validateAck"),isCompletionEvent:g(s=>this.isConversationDetailCompletionEvent(s,e.conversationDetailId),"isCompletionEvent"),extractResult:g(s=>this.extractAgentResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardConversationDetailProgress(s,e.onProgress):void 0,createErrorResult:g(s=>this.createAgentErrorResult(s),"createErrorResult")})}catch(t){return this.handleAgentError(t)}}buildConversationDetailMutation(){return u.gql`
109
+ `}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 R.SafeJSONParse(e)}handleAgentError(e){const r=e?.message||String(e);c.LogError(`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){try{const t=this.buildConversationDetailMutation(),r=this.prepareConversationDetailVariables(e);return await P.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunAIAgentFromConversationDetail",operationLabel:"RunAIAgentFromConversationDetail",validateAck:g(s=>s?.success===!0,"validateAck"),isCompletionEvent:g(s=>this.isConversationDetailCompletionEvent(s,e.conversationDetailId),"isCompletionEvent"),extractResult:g(s=>this.extractAgentResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardConversationDetailProgress(s,e.onProgress):void 0,createErrorResult:g(s=>this.createAgentErrorResult(s),"createErrorResult")})}catch(t){return this.handleAgentError(t)}}buildConversationDetailMutation(){return u.gql`
110
110
  mutation RunAIAgentFromConversationDetail(
111
111
  $conversationDetailId: String!,
112
112
  $agentId: String!,
@@ -145,7 +145,7 @@
145
145
  result
146
146
  }
147
147
  }
148
- `}prepareConversationDetailVariables(e){const t={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId,fireAndForget:!0};return e.maxHistoryMessages!==void 0&&(t.maxHistoryMessages=e.maxHistoryMessages),e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(t.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.createArtifacts!==void 0&&(t.createArtifacts=e.createArtifacts),e.createNotification!==void 0&&(t.createNotification=e.createNotification),e.sourceArtifactId!==void 0&&(t.sourceArtifactId=e.sourceArtifactId),e.sourceArtifactVersionId!==void 0&&(t.sourceArtifactVersionId=e.sourceArtifactVersionId),t}isAgentCompletionEvent(e){const t=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&t?.type==="complete"}isConversationDetailCompletionEvent(e,t){const r=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&r?.type==="complete"&&r?.conversationDetailId===t}extractAgentResult(e){const t=e.data,r=t.result;return r?D.SafeJSONParse(r):{success:t.success,agentRun:void 0}}forwardAgentProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const s=e.data?.progress;s&&t({step:s.currentStep,percentage:s.percentage,message:s.message,metadata:s})}forwardConversationDetailProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const r=e.data,s=r?.progress;s&&t({currentStep:s.currentStep,percentage:s.percentage,message:s.message,metadata:{...s,agentRun:r?.agentRun,agentRunId:r?.agentRunId}})}createAgentErrorResult(e){return{success:!1,agentRun:void 0,errorMessage:e}}async ExecuteSimplePrompt(e){try{const t=u.gql`
148
+ `}prepareConversationDetailVariables(e){const t={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId,fireAndForget:!0};return e.maxHistoryMessages!==void 0&&(t.maxHistoryMessages=e.maxHistoryMessages),e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(t.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.createArtifacts!==void 0&&(t.createArtifacts=e.createArtifacts),e.createNotification!==void 0&&(t.createNotification=e.createNotification),e.sourceArtifactId!==void 0&&(t.sourceArtifactId=e.sourceArtifactId),e.sourceArtifactVersionId!==void 0&&(t.sourceArtifactVersionId=e.sourceArtifactVersionId),t}isAgentCompletionEvent(e){const t=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&t?.type==="complete"}isConversationDetailCompletionEvent(e,t){const r=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&r?.type==="complete"&&r?.conversationDetailId===t}extractAgentResult(e){const t=e.data,r=t.result;return r?R.SafeJSONParse(r):{success:t.success,agentRun:void 0}}forwardAgentProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const s=e.data?.progress;s&&t({step:s.currentStep,percentage:s.percentage,message:s.message,metadata:s})}forwardConversationDetailProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const r=e.data,s=r?.progress;s&&t({currentStep:s.currentStep,percentage:s.percentage,message:s.message,metadata:{...s,agentRun:r?.agentRun,agentRunId:r?.agentRunId}})}createAgentErrorResult(e){return{success:!1,agentRun:void 0,errorMessage:e}}async ExecuteSimplePrompt(e){try{const t=u.gql`
149
149
  mutation ExecuteSimplePrompt(
150
150
  $systemPrompt: String!,
151
151
  $messages: String,
@@ -249,7 +249,7 @@
249
249
  }
250
250
  }
251
251
  }
252
- `,r={entityDocumentID:e.entityDocumentID};e.maxRecords!==void 0&&(r.maxRecords=e.maxRecords),e.filter!==void 0&&(r.filter=e.filter);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.FetchEntityVectors)throw new Error("Invalid response from server");return s.FetchEntityVectors}catch(t){const r=t;return c.LogError("GraphQLAIClient.FetchEntityVectors failed",void 0,r),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,ErrorMessage:r.message||"Unknown error"}}}}const $="default";class L{static{g(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||$;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||$).get(e)??null}async SetItem(e,t,r){this.getCategoryMap(r||$).set(e,t)}async Remove(e,t){this.getCategoryMap(t||$).delete(e)}async ClearCategory(e){const t=e||$;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||$);return t?Array.from(t.keys()):[]}}const k="MJ_Metadata",B=3,T=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"],Q="Metadata_KVPairs";class F extends L{static{g(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=_.openDB(k,B,{upgrade(e){try{e.objectStoreNames.contains(Q)&&e.deleteObjectStore(Q);for(const t of T)e.objectStoreNames.contains(t)||e.createObjectStore(t)}catch(t){c.LogErrorEx({error:t,message:t?.message})}}}),this.dbPromise.then(()=>{this._dbReady=!0}).catch(e=>{c.LogErrorEx({error:e,message:"IndexedDB initialization failed: "+e?.message})})}isKnownCategory(e){const t=`mj:${e}`;return T.includes(t)}getStoreName(e){const t=e||$;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||$;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){c.LogErrorEx({error:s,message:s?.message}),await super.SetItem(e,t,r)}}async GetItem(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t);return await r.transaction(s).objectStore(s).get(n)??null}catch(r){return c.LogErrorEx({error:r,message:r?.message}),await super.GetItem(e,t)}}async Remove(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t),a=r.transaction(s,"readwrite");await a.objectStore(s).delete(n),await a.done}catch(r){c.LogErrorEx({error:r,message:r?.message}),await super.Remove(e,t)}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||$,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 l of o)typeof l=="string"&&l.startsWith(n)&&await i.delete(l);await a.done}}catch(t){c.LogErrorEx({error:t,message:t?.message}),await super.ClearCategory(e)}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||$,s=this.getStoreName(e),i=await t.transaction(s,"readonly").objectStore(s).getAllKeys();if(this.isKnownCategory(r))return i.map(l=>String(l));const o=`[${r}]:`;return i.map(l=>String(l)).filter(l=>l.startsWith(o)).map(l=>l.slice(o.length))}catch(t){return c.LogErrorEx({error:t,message:t?.message}),await super.GetCategoryKeys(e)}}}class K extends c.ProviderConfigDataBase{static{g(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}get OnAuthenticationError(){return this.Data.OnAuthenticationError}set OnAuthenticationError(e){this.Data.OnAuthenticationError=e}constructor(e,t,r,s,n,a,i,o,l,d){super({Token:e,URL:t,WSURL:r,MJAPIKey:o,UserAPIKey:l,RefreshTokenFunction:s,OnAuthenticationError:d},n,a,i)}}class S extends c.ProviderBase{static{g(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._dynamicHeaders=new Map,this._innerCurrentUserQueryString=`CurrentUser {
252
+ `,r={entityDocumentID:e.entityDocumentID};e.maxRecords!==void 0&&(r.maxRecords=e.maxRecords),e.filter!==void 0&&(r.filter=e.filter);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.FetchEntityVectors)throw new Error("Invalid response from server");return s.FetchEntityVectors}catch(t){const r=t;return c.LogError("GraphQLAIClient.FetchEntityVectors failed",void 0,r),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,ErrorMessage:r.message||"Unknown error"}}}}const $="default";class T{static{g(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||$;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||$).get(e)??null}async SetItem(e,t,r){this.getCategoryMap(r||$).set(e,t)}async Remove(e,t){this.getCategoryMap(t||$).delete(e)}async ClearCategory(e){const t=e||$;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||$);return t?Array.from(t.keys()):[]}}const k="MJ_Metadata",B=3,L=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"],F="Metadata_KVPairs";class Q extends T{static{g(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=_.openDB(k,B,{upgrade(e){try{e.objectStoreNames.contains(F)&&e.deleteObjectStore(F);for(const t of L)e.objectStoreNames.contains(t)||e.createObjectStore(t)}catch(t){c.LogErrorEx({error:t,message:t?.message})}}}),this.dbPromise.then(()=>{this._dbReady=!0}).catch(e=>{c.LogErrorEx({error:e,message:"IndexedDB initialization failed: "+e?.message})})}isKnownCategory(e){const t=`mj:${e}`;return L.includes(t)}getStoreName(e){const t=e||$;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||$;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){c.LogErrorEx({error:s,message:s?.message}),await super.SetItem(e,t,r)}}async GetItem(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t);return await r.transaction(s).objectStore(s).get(n)??null}catch(r){return c.LogErrorEx({error:r,message:r?.message}),await super.GetItem(e,t)}}async Remove(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t),a=r.transaction(s,"readwrite");await a.objectStore(s).delete(n),await a.done}catch(r){c.LogErrorEx({error:r,message:r?.message}),await super.Remove(e,t)}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||$,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 l of o)typeof l=="string"&&l.startsWith(n)&&await i.delete(l);await a.done}}catch(t){c.LogErrorEx({error:t,message:t?.message}),await super.ClearCategory(e)}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||$,s=this.getStoreName(e),i=await t.transaction(s,"readonly").objectStore(s).getAllKeys();if(this.isKnownCategory(r))return i.map(l=>String(l));const o=`[${r}]:`;return i.map(l=>String(l)).filter(l=>l.startsWith(o)).map(l=>l.slice(o.length))}catch(t){return c.LogErrorEx({error:t,message:t?.message}),await super.GetCategoryKeys(e)}}}class K extends c.ProviderConfigDataBase{static{g(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}get OnAuthenticationError(){return this.Data.OnAuthenticationError}set OnAuthenticationError(e){this.Data.OnAuthenticationError=e}constructor(e,t,r,s,n,a,i,o,l,d){super({Token:e,URL:t,WSURL:r,MJAPIKey:o,UserAPIKey:l,RefreshTokenFunction:s,OnAuthenticationError:d},n,a,i)}}class S extends c.ProviderBase{static{g(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._dynamicHeaders=new Map,this._innerCurrentUserQueryString=`CurrentUser {
253
253
  ${this.userInfoString()}
254
254
  MJUserRoles_UserIDArray {
255
255
  ${this.userRoleInfoString()}
@@ -258,7 +258,7 @@
258
258
  `,this._currentUserQuery=u.gql`query CurrentUserAndRoles {
259
259
  ${this._innerCurrentUserQueryString}
260
260
  CurrentUserTenantContext
261
- }`,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,this._cacheInvalidationSubscription=null;const e=D.GetGlobalObjectStore();if(e&&e[S._globalStoreKey])return e[S._globalStoreKey];e&&(e[S._globalStoreKey]=this)}static{this._globalStoreKey="___SINGLETON__GraphQLDataProvider"}static get Instance(){const e=D.GetGlobalObjectStore();return e?e[S._globalStoreKey]:void 0}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new x(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}async InternalExecuteQueryFromSpec(e,t){throw new Error("ExecuteQueryFromSpec is not supported by this provider.")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return V.v4()}get LocalStoragePrefix(){if(this._configData===void 0||this._configData.URL===void 0)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const r=this.LocalStoragePrefix+"sessionId";await t.SetItem(r,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,r,s){try{return this._configData=e,r?(this._sessionId=await this.GetPreferredUUID(s),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey,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 c.LogError(n),n}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}SetDynamicHeader(e,t){this._dynamicHeaders.set(e,t),this._client&&this._client.setHeader(e,t),S.Instance&&S.Instance!==this&&S.Instance._configData===this._configData&&(S.Instance._dynamicHeaders.set(e,t),S.Instance._client&&S.Instance._client.setHeader(e,t))}RemoveDynamicHeader(e){this._dynamicHeaders.delete(e),this._client&&this._client.setHeader(e,""),S.Instance&&S.Instance!==this&&S.Instance._configData===this._configData&&(S.Instance._dynamicHeaders.delete(e),S.Instance._client&&S.Instance._client.setHeader(e,""))}GetDynamicHeaders(){return this._dynamicHeaders}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),r=t.MJUserRoles_UserIDArray.map(n=>this.ConvertBackToMJFields(n));t.MJUserRoles_UserIDArray=r;const s=new c.UserInfo(this,{...t,UserRoles:r});return e.CurrentUserTenantContext&&typeof e.CurrentUserTenantContext=="object"&&(s.TenantContext=e.CurrentUserTenantContext),s}}async RunReport(e,t){const r=u.gql`
261
+ }`,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,this._cacheInvalidationSubscription=null;const e=R.GetGlobalObjectStore();if(e&&e[S._globalStoreKey])return e[S._globalStoreKey];e&&(e[S._globalStoreKey]=this)}static{this._globalStoreKey="___SINGLETON__GraphQLDataProvider"}static get Instance(){const e=R.GetGlobalObjectStore();return e?e[S._globalStoreKey]:void 0}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new x(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}async InternalExecuteQueryFromSpec(e,t){throw new Error("ExecuteQueryFromSpec is not supported by this provider.")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return V.v4()}get LocalStoragePrefix(){if(this._configData===void 0||this._configData.URL===void 0)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const r=this.LocalStoragePrefix+"sessionId";await t.SetItem(r,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,r,s){try{return this._configData=e,r?(this._sessionId=await this.GetPreferredUUID(s),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey,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 c.LogError(n),n}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}SetDynamicHeader(e,t){this._dynamicHeaders.set(e,t),this._client&&this._client.setHeader(e,t),S.Instance&&S.Instance!==this&&S.Instance._configData===this._configData&&(S.Instance._dynamicHeaders.set(e,t),S.Instance._client&&S.Instance._client.setHeader(e,t))}RemoveDynamicHeader(e){this._dynamicHeaders.delete(e),this._client&&this._client.setHeader(e,""),S.Instance&&S.Instance!==this&&S.Instance._configData===this._configData&&(S.Instance._dynamicHeaders.delete(e),S.Instance._client&&S.Instance._client.setHeader(e,""))}GetDynamicHeaders(){return this._dynamicHeaders}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),r=t.MJUserRoles_UserIDArray.map(n=>this.ConvertBackToMJFields(n));t.MJUserRoles_UserIDArray=r;const s=new c.UserInfo(this,{...t,UserRoles:r});return e.CurrentUserTenantContext&&typeof e.CurrentUserTenantContext=="object"&&(s.TenantContext=e.CurrentUserTenantContext),s}}async RunReport(e,t){const r=u.gql`
262
262
  query GetReportDataQuery ($ReportID: String!) {
263
263
  GetReportData(ReportID: $ReportID) {
264
264
  Success
@@ -337,7 +337,7 @@
337
337
  Success
338
338
  ErrorMessage${E}
339
339
  }
340
- }`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:a,queryName:r,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const m=await this.ExecuteGQL(y,{input:n});if(m&&m[r]){const p=m[r].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:a,aggregateResultCount:p?.length||0,aggregateResults:p,aggregateExecutionTime:m[r].AggregateExecutionTime});const f=m[r].Results;if(f&&f.length>0){const C=o.Fields.filter(w=>w.CodeName!==w.Name&&w.CodeName!==void 0);f.forEach(w=>{this.ConvertBackToMJFields(w),C.forEach(A=>{w[A.Name]=w[A.CodeName]})})}return m[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw c.LogError(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],n=[];for(const d of e){let I="",E="";const y={};let m=null,p=null;if(d.ViewEntity)p=d.ViewEntity,m=p.Get("Entity");else{const{entityName:w,v:A}=await this.getEntityNameAndUserView(d,t);p=A,m=w}const f=this.Entities.find(w=>w.Name===m);if(!f)throw new Error(`Entity ${m} not found in metadata`);s.push(f);let R=!1;const C=c.getGraphQLTypeNameBase(f);d.ViewID?(I=`Run${C}ViewByID`,E="RunViewByIDInput",y.ViewID=d.ViewID):d.ViewName?(I=`Run${C}ViewByName`,E="RunViewByNameInput",y.ViewName=d.ViewName):(R=!0,I=`Run${C}DynamicView`,E="RunDynamicViewInput",y.EntityName=d.EntityName),y.ExtraFilter=d.ExtraFilter||"",y.OrderBy=d.OrderBy||"",y.UserSearchString=d.UserSearchString||"",y.Fields=d.Fields,y.IgnoreMaxRows=d.IgnoreMaxRows||!1,d.MaxRows!==void 0&&(y.MaxRows=d.MaxRows),d.StartRow!==void 0&&(y.StartRow=d.StartRow),y.ForceAuditLog=d.ForceAuditLog||!1,y.ResultType=d.ResultType||"simple",d.AuditLogDescription&&d.AuditLogDescription.length>0&&(y.AuditLogDescription=d.AuditLogDescription),R||(y.ExcludeUserViewRunID=d.ExcludeUserViewRunID||"",y.ExcludeDataFromAllPriorViewRuns=d.ExcludeDataFromAllPriorViewRuns||!1,y.OverrideExcludeFilter=d.OverrideExcludeFilter||"",y.SaveViewResults=d.SaveViewResults||!1),d.Aggregates&&d.Aggregates.length>0&&(y.Aggregates=d.Aggregates.map(w=>({expression:w.expression,alias:w.alias}))),r.push(y),n.push(...this.getViewRunTimeFieldList(f,p,d,R))}const i=e.some(d=>d.Aggregates&&d.Aggregates.length>0)?`
340
+ }`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:a,queryName:r,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const m=await this.ExecuteGQL(y,{input:n});if(m&&m[r]){const p=m[r].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:a,aggregateResultCount:p?.length||0,aggregateResults:p,aggregateExecutionTime:m[r].AggregateExecutionTime});const f=m[r].Results;if(f&&f.length>0){const C=o.Fields.filter(v=>v.CodeName!==v.Name&&v.CodeName!==void 0);f.forEach(v=>{this.ConvertBackToMJFields(v),C.forEach(A=>{v[A.Name]=v[A.CodeName]})})}return m[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw c.LogError(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],n=[];for(const d of e){let I="",E="";const y={};let m=null,p=null;if(d.ViewEntity)p=d.ViewEntity,m=p.Get("Entity");else{const{entityName:v,v:A}=await this.getEntityNameAndUserView(d,t);p=A,m=v}const f=this.Entities.find(v=>v.Name===m);if(!f)throw new Error(`Entity ${m} not found in metadata`);s.push(f);let D=!1;const C=c.getGraphQLTypeNameBase(f);d.ViewID?(I=`Run${C}ViewByID`,E="RunViewByIDInput",y.ViewID=d.ViewID):d.ViewName?(I=`Run${C}ViewByName`,E="RunViewByNameInput",y.ViewName=d.ViewName):(D=!0,I=`Run${C}DynamicView`,E="RunDynamicViewInput",y.EntityName=d.EntityName),y.ExtraFilter=d.ExtraFilter||"",y.OrderBy=d.OrderBy||"",y.UserSearchString=d.UserSearchString||"",y.Fields=d.Fields,y.IgnoreMaxRows=d.IgnoreMaxRows||!1,d.MaxRows!==void 0&&(y.MaxRows=d.MaxRows),d.StartRow!==void 0&&(y.StartRow=d.StartRow),y.ForceAuditLog=d.ForceAuditLog||!1,y.ResultType=d.ResultType||"simple",d.AuditLogDescription&&d.AuditLogDescription.length>0&&(y.AuditLogDescription=d.AuditLogDescription),D||(y.ExcludeUserViewRunID=d.ExcludeUserViewRunID||"",y.ExcludeDataFromAllPriorViewRuns=d.ExcludeDataFromAllPriorViewRuns||!1,y.OverrideExcludeFilter=d.OverrideExcludeFilter||"",y.SaveViewResults=d.SaveViewResults||!1),d.Aggregates&&d.Aggregates.length>0&&(y.Aggregates=d.Aggregates.map(v=>({expression:v.expression,alias:v.alias}))),r.push(y),n.push(...this.getViewRunTimeFieldList(f,p,d,D))}const i=e.some(d=>d.Aggregates&&d.Aggregates.length>0)?`
341
341
  AggregateResults {
342
342
  alias
343
343
  expression
@@ -395,7 +395,7 @@
395
395
  }
396
396
  }
397
397
  }
398
- `,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,l)=>{const d=e[l];if(o.status==="differential"&&o.differentialData){const I=o.differentialData.updatedRows.map(E=>{const y=JSON.parse(E.Data);return this.ConvertBackToMJFields(y),y});return{viewIndex:o.viewIndex,status:o.status,results:void 0,differentialData:{updatedRows:I,deletedRecordIDs:o.differentialData.deletedRecordIDs},maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}if(o.status==="stale"&&o.Results){const I=o.Results.map(E=>{const y=JSON.parse(E.Data);return this.ConvertBackToMJFields(y),y});return{viewIndex:o.viewIndex,status:o.status,results:I,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 c.LogError(r),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async getEntityNameAndUserView(e,t){let r,s;if(e.EntityName)r=e.EntityName;else if(e.ViewID)s=await N.ViewInfo.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await N.ViewInfo.GetViewEntityByName(e.ViewName,t),r=s.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:r,v:s}}getViewRunTimeFieldList(e,t,r,s){const n=[],a=new v;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 c.ProviderType.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 c.LogError(r),r}}async GetRecordDependencies(e,t){try{const r=u.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
398
+ `,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,l)=>{const d=e[l];if(o.status==="differential"&&o.differentialData){const I=o.differentialData.updatedRows.map(E=>{const y=JSON.parse(E.Data);return this.ConvertBackToMJFields(y),y});return{viewIndex:o.viewIndex,status:o.status,results:void 0,differentialData:{updatedRows:I,deletedRecordIDs:o.differentialData.deletedRecordIDs},maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}if(o.status==="stale"&&o.Results){const I=o.Results.map(E=>{const y=JSON.parse(E.Data);return this.ConvertBackToMJFields(y),y});return{viewIndex:o.viewIndex,status:o.status,results:I,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 c.LogError(r),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async getEntityNameAndUserView(e,t){let r,s;if(e.EntityName)r=e.EntityName;else if(e.ViewID)s=await b.ViewInfo.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await b.ViewInfo.GetViewEntityByName(e.ViewName,t),r=s.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:r,v:s}}getViewRunTimeFieldList(e,t,r,s){const n=[],a=new w;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 c.ProviderType.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 c.LogError(r),r}}async GetRecordDependencies(e,t){try{const r=u.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
399
399
  GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
400
400
  EntityName
401
401
  RelatedEntityName
@@ -446,20 +446,20 @@
446
446
  Message
447
447
  }
448
448
  }
449
- }`,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 c.LogError(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 c.BaseEntityResult;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 c.BaseEntityResult;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(y=>({FieldName:y.CodeName,Value:y.Value})),e.ResultHistory.push(s);const i=c.getGraphQLTypeNameBase(e.EntityInfo),o=`${a}${i}`,l=e.Fields.filter(y=>!y.ReadOnly||y.IsPrimaryKey&&e.IsSaved),d=new v,I=` ${o}(input: $input) {
449
+ }`,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 c.LogError(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 c.BaseEntityResult;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 c.BaseEntityResult;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(y=>({FieldName:y.CodeName,Value:y.Value})),e.ResultHistory.push(s);const i=c.getGraphQLTypeNameBase(e.EntityInfo),o=`${a}${i}`,l=e.Fields.filter(y=>!y.ReadOnly||y.IsPrimaryKey&&e.IsSaved),d=new w,I=` ${o}(input: $input) {
450
450
  ${e.Fields.map(y=>d.MapFieldName(y.CodeName)).join(`
451
451
  `)}
452
452
  }`,E=u.gql`mutation ${a}${i} ($input: ${o}Input!) {
453
453
  ${I}
454
454
  }
455
- `;for(let y=0;y<l.length;y++){const m=l[y];let p=e.Get(m.Name);if(p)switch(m.EntityFieldInfo.TSType){case c.EntityFieldTSType.Date:p=p.getTime();break;case c.EntityFieldTSType.Boolean:typeof p!="boolean"&&(p=parseInt(p)!==0);break;case c.EntityFieldTSType.Number:if(typeof p!="number"){const f=Number(p);isNaN(f)||(p=f)}break}p===null&&m.EntityFieldInfo.AllowsNull===!1&&(m.EntityFieldInfo.DefaultValue!==null?p=m.EntityFieldInfo.DefaultValue:m.FieldType===c.EntityFieldTSType.Number||m.FieldType===c.EntityFieldTSType.Boolean?p=0:p=""),n.input[d.MapFieldName(m.CodeName)]=p}if(a.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const y=[];e.Fields.forEach(m=>{let p=null;m.OldValue!==null&&m.OldValue!==void 0&&(m.EntityFieldInfo.TSType===c.EntityFieldTSType.Date?p=m.OldValue.getTime().toString():m.EntityFieldInfo.TSType===c.EntityFieldTSType.Boolean?p=m.OldValue===!0?"1":"0":typeof m.OldValue!="string"?p=m.OldValue.toString():p=m.OldValue),y.push({Key:d.MapFieldName(m.CodeName),Value:p})}),n.input.OldValues___=y}if(e.TransactionGroup){const y=[{varName:"input",inputType:o+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,s.Type==="create"?"Create":"Update",I,n,{mutationName:o,mutationInputTypes:y},(m,p)=>{s.EndedAt=new Date,p&&m?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(m)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const y=await this.ExecuteGQL(E,n);if(y&&y[o])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(y[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,c.LogError(n),null}}async Load(e,t,r=null,s){try{const n={};let a="",i="";for(let y=0;y<t.KeyValuePairs.length;y++){const m=e.Fields.find(R=>R.Name.trim().toLowerCase()===t.KeyValuePairs[y].FieldName.trim().toLowerCase()).EntityFieldInfo,p=t.GetValueByIndex(y),f=m.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${m.CodeName}: ${f}!`,a.length>0&&(a+=", "),a+=`${m.CodeName}: $${m.CodeName}`,m.TSType===c.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(y)))throw new Error(`Primary Key value ${p} (${m.Name}) is not a valid number`);n[m.CodeName]=parseInt(p)}else n[m.CodeName]=p}const o=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",l=c.getGraphQLTypeNameBase(e.EntityInfo),d=new v,I=u.gql`query Single${l}${o.length>0?"Full":""} (${i}) {
455
+ `;for(let y=0;y<l.length;y++){const m=l[y];let p=e.Get(m.Name);if(p)switch(m.EntityFieldInfo.TSType){case c.EntityFieldTSType.Date:p=p.getTime();break;case c.EntityFieldTSType.Boolean:typeof p!="boolean"&&(p=parseInt(p)!==0);break;case c.EntityFieldTSType.Number:if(typeof p!="number"){const f=Number(p);isNaN(f)||(p=f)}break}p===null&&m.EntityFieldInfo.AllowsNull===!1&&(m.EntityFieldInfo.DefaultValue!==null?p=m.EntityFieldInfo.DefaultValue:m.FieldType===c.EntityFieldTSType.Number||m.FieldType===c.EntityFieldTSType.Boolean?p=0:p=""),n.input[d.MapFieldName(m.CodeName)]=p}if(a.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const y=[];e.Fields.forEach(m=>{let p=null;m.OldValue!==null&&m.OldValue!==void 0&&(m.EntityFieldInfo.TSType===c.EntityFieldTSType.Date?p=m.OldValue.getTime().toString():m.EntityFieldInfo.TSType===c.EntityFieldTSType.Boolean?p=m.OldValue===!0?"1":"0":typeof m.OldValue!="string"?p=m.OldValue.toString():p=m.OldValue),y.push({Key:d.MapFieldName(m.CodeName),Value:p})}),n.input.OldValues___=y}if(e.TransactionGroup){const y=[{varName:"input",inputType:o+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,s.Type==="create"?"Create":"Update",I,n,{mutationName:o,mutationInputTypes:y},(m,p)=>{s.EndedAt=new Date,p&&m?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(m)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const y=await this.ExecuteGQL(E,n);if(y&&y[o])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(y[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,c.LogError(n),null}}async Load(e,t,r=null,s){try{const n={};let a="",i="";for(let y=0;y<t.KeyValuePairs.length;y++){const m=e.Fields.find(D=>D.Name.trim().toLowerCase()===t.KeyValuePairs[y].FieldName.trim().toLowerCase()).EntityFieldInfo,p=t.GetValueByIndex(y),f=m.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${m.CodeName}: ${f}!`,a.length>0&&(a+=", "),a+=`${m.CodeName}: $${m.CodeName}`,m.TSType===c.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(y)))throw new Error(`Primary Key value ${p} (${m.Name}) is not a valid number`);n[m.CodeName]=parseInt(p)}else n[m.CodeName]=p}const o=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",l=c.getGraphQLTypeNameBase(e.EntityInfo),d=new w,I=u.gql`query Single${l}${o.length>0?"Full":""} (${i}) {
456
456
  ${l}(${a}) {
457
457
  ${e.Fields.filter(y=>!y.EntityFieldInfo.IsBinaryFieldType).map(y=>y.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?y.CodeName.replace("__mj_","_mj__"):y.CodeName).join(`
458
458
  `)}
459
459
  ${o}
460
460
  }
461
461
  }
462
- `,E=await this.ExecuteGQL(I,n);return E&&E[l]?this.ConvertBackToMJFields(E[l]):null}catch(n){return c.LogError(n),null}}ConvertBackToMJFields(e){return new v().ReverseMapFields(e),e}getRelatedEntityString(e,t){let r="";for(let s=0;s<e.RelatedEntities.length;s++)if(t.indexOf(e.RelatedEntities[s].RelatedEntity)>=0){const n=e.RelatedEntities[s],a=this.Entities.find(o=>D.UUIDsEqual(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+=`
462
+ `,E=await this.ExecuteGQL(I,n);return E&&E[l]?this.ConvertBackToMJFields(E[l]):null}catch(n){return c.LogError(n),null}}ConvertBackToMJFields(e){return new w().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=>R.UUIDsEqual(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+=`
463
463
  ${i} {
464
464
  ${a.Fields.map(o=>o.CodeName).join(`
465
465
  `)}
@@ -471,7 +471,7 @@
471
471
  `,y=u.gql`mutation ${I} (${o}, $options___: DeleteOptionsInput!) {
472
472
  ${E}
473
473
  }
474
- `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,"Delete",E,n,{mutationName:I,mutationInputTypes:a},(m,p)=>{if(s.EndedAt=new Date,p&&m){let f=!0;for(const R of e.PrimaryKey.KeyValuePairs)R.Value!==m[R.FieldName]&&(f=!1);f?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const m=await this.ExecuteGQL(y,n);if(m&&m[I]){const p=m[I];for(let f of e.PrimaryKey.KeyValuePairs){let R=p[f.FieldName],C=f.Value;if(typeof C=="number"&&(C=C.toString()),typeof R=="number"&&(R=R.toString()),C!==R)throw new Error(`Primary key value mismatch in server Delete response. Field: ${f.FieldName}, Original: ${C}, Returned: ${R}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(n){return s.EndedAt=new Date,s.Success=!1,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,c.LogError(n),!1}}async GetDatasetByName(e,t){const r=u.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
474
+ `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,"Delete",E,n,{mutationName:I,mutationInputTypes:a},(m,p)=>{if(s.EndedAt=new Date,p&&m){let f=!0;for(const D of e.PrimaryKey.KeyValuePairs)D.Value!==m[D.FieldName]&&(f=!1);f?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const m=await this.ExecuteGQL(y,n);if(m&&m[I]){const p=m[I];for(let f of e.PrimaryKey.KeyValuePairs){let D=p[f.FieldName],C=f.Value;if(typeof C=="number"&&(C=C.toString()),typeof D=="number"&&(D=D.toString()),C!==D)throw new Error(`Primary key value mismatch in server Delete response. Field: ${f.FieldName}, Original: ${C}, Returned: ${D}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(n){return s.EndedAt=new Date,s.Success=!1,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,c.LogError(n),!1}}async GetDatasetByName(e,t){const r=u.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
475
475
  GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
476
476
  DatasetID
477
477
  DatasetName
@@ -540,14 +540,14 @@
540
540
  }
541
541
  }`,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 c.LogError(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 c.LogError("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw c.LogError(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)try{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{const t=new Error("Refresh token function returned null or undefined token");throw this.notifyAuthenticationError(t),t}}catch(e){const t=e instanceof Error?e:new Error(String(e));throw this.notifyAuthenticationError(t),e}else{const e=new Error("No refresh token function provided");throw this.notifyAuthenticationError(e),e}}notifyAuthenticationError(e){try{const t=this._configData?.OnAuthenticationError;t&&t(e)}catch(t){console.error("[GraphQLDataProvider] Error in OnAuthenticationError callback:",t)}}static async RefreshToken(){return S.Instance.RefreshToken()}static async clearClientCache(e=new Set){const t=[];for(let r=0;r<localStorage.length;r++){const s=localStorage.key(r);s&&!e.has(s)&&t.push(s)}t.forEach(r=>localStorage.removeItem(r)),await new Promise(r=>{const s=indexedDB.deleteDatabase("MJ_Metadata");s.onsuccess=()=>r(),s.onerror=()=>r(),s.onblocked=()=>r()})}CreateNewGraphQLClient(e,t,r,s,n){const a={"x-session-id":r};t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),n&&(a["x-api-key"]=n);const i=new u.GraphQLClient(e,{headers:a});for(const[o,l]of this._dynamicHeaders)i.setHeader(o,l);return i}userInfoString(){return this.infoString(new c.UserInfo(null,null))}userRoleInfoString(){return this.infoString(new c.UserRoleInfo(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
542
542
  `:s.startsWith("_")||(t+=s+`
543
- `);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new F:this._localStorageProvider=new c.InMemoryLocalStorageProvider),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=U.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token},keepAlive:3e4,retryAttempts:3,shouldRetry:g(()=>!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 b.Observable(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=s.subscribe({query:e,variables:t},{next:g(a=>{r.next(a.data)},"next"),error:g(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(l){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",l),r.error(l)}}else r.error(a)},"error"),complete:g(()=>{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 b.Observable(o=>{r.activeSubscribers++;const l=r.subject.subscribe(o);return()=>{const d=this._pushStatusSubjects.get(e);d&&d.activeSubscribers>0&&d.activeSubscribers--,l.unsubscribe()}});const s=u.gql`subscription StatusUpdates($sessionId: String!) {
543
+ `);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new Q:this._localStorageProvider=new c.InMemoryLocalStorageProvider),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=G.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token},keepAlive:3e4,retryAttempts:3,shouldRetry:g(()=>!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 N.Observable(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=s.subscribe({query:e,variables:t},{next:g(a=>{r.next(a.data)},"next"),error:g(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(l){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",l),r.error(l)}}else r.error(a)},"error"),complete:g(()=>{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 N.Observable(o=>{r.activeSubscribers++;const l=r.subject.subscribe(o);return()=>{const d=this._pushStatusSubjects.get(e);d&&d.activeSubscribers>0&&d.activeSubscribers--,l.unsubscribe()}});const s=u.gql`subscription StatusUpdates($sessionId: String!) {
544
544
  statusUpdates(sessionId: $sessionId) {
545
545
  date
546
546
  message
547
547
  sessionId
548
548
  }
549
549
  }
550
- `,n=new b.Subject,a=this.getOrCreateWSClient(),i=new b.Subscription;return i.add(new b.Observable(o=>{const l=a.subscribe({query:s,variables:{sessionId:e}},{next:g(d=>{const I=this._pushStatusSubjects.get(e);I&&(I.lastEmissionAt=Date.now()),o.next(d.data.statusUpdates.message)},"next"),error:g(async d=>{const I=d;if(I?.extensions?.code==="JWT_EXPIRED"||I?.message?.includes("token has expired")||I?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),o.complete()}catch(y){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",y),o.error(y)}}else o.error(d)},"error"),complete:g(()=>{o.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,l()}}).subscribe({next:g(o=>n.next(o),"next"),error:g(o=>{n.error(o),this._pushStatusSubjects.delete(e)},"error"),complete:g(()=>{n.complete(),this._pushStatusSubjects.delete(e)},"complete")})),this._pushStatusSubjects.set(e,{subject:n,subscription:i,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new b.Observable(o=>{const l=this._pushStatusSubjects.get(e);l&&l.activeSubscribers++;const d=n.subscribe(o);return()=>{const I=this._pushStatusSubjects.get(e);I&&I.activeSubscribers>0&&I.activeSubscribers--,d.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.UnsubscribeFromCacheInvalidation(),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}ClientToolRequests(e){return this.subscribe(`
550
+ `,n=new N.Subject,a=this.getOrCreateWSClient(),i=new N.Subscription;return i.add(new N.Observable(o=>{const l=a.subscribe({query:s,variables:{sessionId:e}},{next:g(d=>{const I=this._pushStatusSubjects.get(e);I&&(I.lastEmissionAt=Date.now()),o.next(d.data.statusUpdates.message)},"next"),error:g(async d=>{const I=d;if(I?.extensions?.code==="JWT_EXPIRED"||I?.message?.includes("token has expired")||I?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),o.complete()}catch(y){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",y),o.error(y)}}else o.error(d)},"error"),complete:g(()=>{o.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,l()}}).subscribe({next:g(o=>n.next(o),"next"),error:g(o=>{n.error(o),this._pushStatusSubjects.delete(e)},"error"),complete:g(()=>{n.complete(),this._pushStatusSubjects.delete(e)},"complete")})),this._pushStatusSubjects.set(e,{subject:n,subscription:i,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new N.Observable(o=>{const l=this._pushStatusSubjects.get(e);l&&l.activeSubscribers++;const d=n.subscribe(o);return()=>{const I=this._pushStatusSubjects.get(e);I&&I.activeSubscribers>0&&I.activeSubscribers--,d.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.UnsubscribeFromCacheInvalidation(),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}ClientToolRequests(e){return this.subscribe(`
551
551
  subscription ClientToolRequest($sessionID: String!) {
552
552
  ClientToolRequest(sessionID: $sessionID) {
553
553
  AgentRunID
@@ -569,7 +569,7 @@
569
569
  OriginSessionID
570
570
  RecordData
571
571
  }
572
- }`,t=this.subscribe(e);this._cacheInvalidationSubscription=t.subscribe({next:g(r=>{const s=r?.cacheInvalidation;if(!s)return;if(s.OriginSessionID&&s.OriginSessionID===this.sessionId){console.debug(`[GraphQLDataProvider] Skipping self-originated cache invalidation for "${s.EntityName}" (action: ${s.Action})`);return}console.debug(`[GraphQLDataProvider] Cache invalidation received: ${s.Action} for "${s.EntityName}" from server ${s.SourceServerID?.substring(0,8)||"unknown"}`);const n={type:"remote-invalidate",entityName:s.EntityName,baseEntity:null,payload:{primaryKeyValues:s.PrimaryKeyValues,action:s.Action,sourceServerId:s.SourceServerID,timestamp:s.Timestamp,recordData:s.RecordData}};D.MJGlobal.Instance.RaiseEvent({event:D.MJEventType.ComponentEvent,eventCode:c.BaseEntity.BaseEventCode,args:n,component:this})},"next"),error:g(r=>{console.error("[GraphQLDataProvider] Cache invalidation subscription error:",r),this._cacheInvalidationSubscription=null},"error"),complete:g(()=>{console.log("[GraphQLDataProvider] Cache invalidation subscription completed, will re-establish on next WebSocket creation"),this._cacheInvalidationSubscription=null},"complete")})}UnsubscribeFromCacheInvalidation(){this._cacheInvalidationSubscription&&(this._cacheInvalidationSubscription.unsubscribe(),this._cacheInvalidationSubscription=null)}async FindISAChildEntity(e,t,r){if(!e.IsParentType)return null;const s=`query FindISAChildEntity($EntityName: String!, $RecordID: String!) {
572
+ }`,t=this.subscribe(e);this._cacheInvalidationSubscription=t.subscribe({next:g(r=>{const s=r?.cacheInvalidation;if(!s)return;if(s.OriginSessionID&&s.OriginSessionID===this.sessionId){console.debug(`[GraphQLDataProvider] Skipping self-originated cache invalidation for "${s.EntityName}" (action: ${s.Action})`);return}console.debug(`[GraphQLDataProvider] Cache invalidation received: ${s.Action} for "${s.EntityName}" from server ${s.SourceServerID?.substring(0,8)||"unknown"}`);const n={type:"remote-invalidate",entityName:s.EntityName,baseEntity:null,payload:{primaryKeyValues:s.PrimaryKeyValues,action:s.Action,sourceServerId:s.SourceServerID,timestamp:s.Timestamp,recordData:s.RecordData}};R.MJGlobal.Instance.RaiseEvent({event:R.MJEventType.ComponentEvent,eventCode:c.BaseEntity.BaseEventCode,args:n,component:this})},"next"),error:g(r=>{console.error("[GraphQLDataProvider] Cache invalidation subscription error:",r),this._cacheInvalidationSubscription=null},"error"),complete:g(()=>{console.log("[GraphQLDataProvider] Cache invalidation subscription completed, will re-establish on next WebSocket creation"),this._cacheInvalidationSubscription=null},"complete")})}UnsubscribeFromCacheInvalidation(){this._cacheInvalidationSubscription&&(this._cacheInvalidationSubscription.unsubscribe(),this._cacheInvalidationSubscription=null)}async FindISAChildEntity(e,t,r){if(!e.IsParentType)return null;const s=`query FindISAChildEntity($EntityName: String!, $RecordID: String!) {
573
573
  FindISAChildEntity(EntityName: $EntityName, RecordID: $RecordID) {
574
574
  Success
575
575
  ChildEntityName
@@ -581,14 +581,14 @@
581
581
  ChildEntityNames
582
582
  ErrorMessage
583
583
  }
584
- }`;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 c.LogError(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function j(h){const e=new S;return c.SetProvider(e),await e.Config(h),D.MJGlobal.Instance.RaiseEvent({event:D.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),await c.StartupManager.Instance.Startup(),e}g(j,"setupGraphQLClient");class J{static{g(this,"SyncRolesAndUsersResult")}}class W{static{g(this,"RoleInput")}}class z{static{g(this,"UserInput")}}class H{static{g(this,"RolesAndUsersInput")}}var q=(h=>(h.Create="Create",h.Update="Update",h.CreateOrUpdate="CreateOrUpdate",h.Delete="Delete",h.DeleteWithFilter="DeleteWithFilter",h))(q||{});class X{static{g(this,"ActionItemInput")}}class Y{static{g(this,"SyncDataResult")}constructor(){this.Results=[]}}class Z{static{g(this,"ActionItemOutput")}}class ee{static{g(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.GraphQLClient(e,{headers:n})}resolvePlatformSQL(e){if(e!=null)return c.IsPlatformSQL(e)?e.default:e}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
584
+ }`;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 c.LogError(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function j(h){const e=new S;return c.SetProvider(e),await e.Config(h),R.MJGlobal.Instance.RaiseEvent({event:R.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),await c.StartupManager.Instance.Startup(),e}g(j,"setupGraphQLClient");class J{static{g(this,"SyncRolesAndUsersResult")}}class W{static{g(this,"RoleInput")}}class z{static{g(this,"UserInput")}}class H{static{g(this,"RolesAndUsersInput")}}var q=(h=>(h.Create="Create",h.Update="Update",h.CreateOrUpdate="CreateOrUpdate",h.Delete="Delete",h.DeleteWithFilter="DeleteWithFilter",h))(q||{});class X{static{g(this,"ActionItemInput")}}class Y{static{g(this,"SyncDataResult")}constructor(){this.Results=[]}}class Z{static{g(this,"ActionItemOutput")}}class ee{static{g(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.GraphQLClient(e,{headers:n})}resolvePlatformSQL(e){if(e!=null)return c.IsPlatformSQL(e)?e.default:e}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
585
585
  GetData(input: $input) {
586
586
  Success
587
587
  ErrorMessages
588
588
  Queries
589
589
  Results
590
590
  }
591
- }`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(n=>n?D.SafeJSONParse(n):null),ErrorMessages:s.GetData.ErrorMessages,Queries:s.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:s.GetData?.ErrorMessages??["Unknown error"],Queries:s.GetData?.Queries??e}}catch(r){let s=r instanceof Error?r.message:String(r);const n=s.match(/Error: ([^:]+)\./);if(n&&(s=n[1]+"."),c.IsVerboseLoggingEnabled()){const a=`GraphQLSystemUserClient::GetData - Error getting data - ${r}`;c.LogError(a)}return{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
591
+ }`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(n=>n?R.SafeJSONParse(n):null),ErrorMessages:s.GetData.ErrorMessages,Queries:s.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:s.GetData?.ErrorMessages??["Unknown error"],Queries:s.GetData?.Queries??e}}catch(r){let s=r instanceof Error?r.message:String(r);const n=s.match(/Error: ([^:]+)\./);if(n&&(s=n[1]+"."),c.IsVerboseLoggingEnabled()){const a=`GraphQLSystemUserClient::GetData - Error getting data - ${r}`;c.LogError(a)}return{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
592
592
  GetAllEntities {
593
593
  Success
594
594
  ErrorMessage
@@ -719,7 +719,7 @@
719
719
  ErrorMessage
720
720
  AppliedParameters
721
721
  }
722
- }`,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?D.SafeJSONParse(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 c.LogError(`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) {
722
+ }`,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?R.SafeJSONParse(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 c.LogError(`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) {
723
723
  GetQueryDataByNameSystemUser(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
724
724
  QueryID
725
725
  QueryName
@@ -731,7 +731,7 @@
731
731
  ErrorMessage
732
732
  AppliedParameters
733
733
  }
734
- }`,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?D.SafeJSONParse(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 c.LogError(`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!) {
734
+ }`,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?R.SafeJSONParse(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 c.LogError(`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!) {
735
735
  CreateQuerySystemUser(input: $input) {
736
736
  Success
737
737
  ErrorMessage
@@ -942,7 +942,7 @@
942
942
  result
943
943
  }
944
944
  }
945
- `,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 c.LogError(`GraphQLSystemUserClient::RunAIAgent - Error running AI agent - ${t}`),{success:!1,agentRun:void 0}}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}prepareAgentVariables(e){const t={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._sessionId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),t}processPromptResult(e){let t,r,s;try{e.parsedResult&&(t=JSON.parse(e.parsedResult))}catch{t=e.parsedResult}try{e.validationResult&&(r=JSON.parse(e.validationResult))}catch{r=e.validationResult}try{e.chatResult&&(s=JSON.parse(e.chatResult))}catch{s=e.chatResult}return{success:e.success,output:e.output,parsedResult:t,error:e.error,executionTimeMs:e.executionTimeMs,tokensUsed:e.tokensUsed,promptRunId:e.promptRunId,rawResult:e.rawResult,validationResult:r,chatResult:s}}processAgentResult(e){return D.SafeJSONParse(e)}async TestQuerySQL(e){try{const r=await this.Client.request(`query TestQuerySQL($input: TestQuerySQLInput!) {
945
+ `,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 c.LogError(`GraphQLSystemUserClient::RunAIAgent - Error running AI agent - ${t}`),{success:!1,agentRun:void 0}}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}prepareAgentVariables(e){const t={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._sessionId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),t}processPromptResult(e){let t,r,s;try{e.parsedResult&&(t=JSON.parse(e.parsedResult))}catch{t=e.parsedResult}try{e.validationResult&&(r=JSON.parse(e.validationResult))}catch{r=e.validationResult}try{e.chatResult&&(s=JSON.parse(e.chatResult))}catch{s=e.chatResult}return{success:e.success,output:e.output,parsedResult:t,error:e.error,executionTimeMs:e.executionTimeMs,tokensUsed:e.tokensUsed,promptRunId:e.promptRunId,rawResult:e.rawResult,validationResult:r,chatResult:s}}processAgentResult(e){return R.SafeJSONParse(e)}async TestQuerySQL(e){try{const r=await this.Client.request(`query TestQuerySQL($input: TestQuerySQLInput!) {
946
946
  TestQuerySQL(input: $input) {
947
947
  Success
948
948
  Results
@@ -951,7 +951,7 @@
951
951
  ErrorMessage
952
952
  AppliedParameters
953
953
  }
954
- }`,{input:e});return r&&r.TestQuerySQL?{Success:r.TestQuerySQL.Success,Results:r.TestQuerySQL.Results?D.SafeJSONParse(r.TestQuerySQL.Results):null,RowCount:r.TestQuerySQL.RowCount,ExecutionTime:r.TestQuerySQL.ExecutionTime,ErrorMessage:r.TestQuerySQL.ErrorMessage,AppliedParameters:r.TestQuerySQL.AppliedParameters?D.SafeJSONParse(r.TestQuerySQL.AppliedParameters):void 0}:{Success:!1,Results:null,RowCount:0,ExecutionTime:0,ErrorMessage:"TestQuerySQL execution failed"}}catch(t){return c.LogError(`GraphQLSystemUserClient::TestQuerySQL - Error testing query SQL - ${t}`),{Success:!1,Results:null,RowCount:0,ExecutionTime:0,ErrorMessage:t instanceof Error?t.message:String(t)}}}async ExecuteSimplePrompt(e){try{const t=u.gql`
954
+ }`,{input:e});return r&&r.TestQuerySQL?{Success:r.TestQuerySQL.Success,Results:r.TestQuerySQL.Results?R.SafeJSONParse(r.TestQuerySQL.Results):null,RowCount:r.TestQuerySQL.RowCount,ExecutionTime:r.TestQuerySQL.ExecutionTime,ErrorMessage:r.TestQuerySQL.ErrorMessage,AppliedParameters:r.TestQuerySQL.AppliedParameters?R.SafeJSONParse(r.TestQuerySQL.AppliedParameters):void 0}:{Success:!1,Results:null,RowCount:0,ExecutionTime:0,ErrorMessage:"TestQuerySQL execution failed"}}catch(t){return c.LogError(`GraphQLSystemUserClient::TestQuerySQL - Error testing query SQL - ${t}`),{Success:!1,Results:null,RowCount:0,ExecutionTime:0,ErrorMessage:t instanceof Error?t.message:String(t)}}}async ExecuteSimplePrompt(e){try{const t=u.gql`
955
955
  query ExecuteSimplePromptSystemUser(
956
956
  $systemPrompt: String!,
957
957
  $messages: String,
@@ -989,7 +989,101 @@
989
989
  error
990
990
  }
991
991
  }
992
- `,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 c.LogError(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}}class te{static{g(this,"GetDataOutput")}}class re{static{g(this,"SimpleRemoteEntityOutput")}}class se{static{g(this,"SimpleRemoteEntity")}}class ne{static{g(this,"SimpleRemoteEntityField")}}class ae{static{g(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=u.gql`
992
+ `,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 c.LogError(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}async SearchKnowledge(e){try{const t=u.gql`
993
+ mutation SearchKnowledgeAsSystemUser($query: String!, $maxResults: Float, $filters: SearchFiltersInput, $minScore: Float) {
994
+ SearchKnowledgeAsSystemUser(query: $query, maxResults: $maxResults, filters: $filters, minScore: $minScore) {
995
+ Success
996
+ Results {
997
+ ID
998
+ EntityName
999
+ RecordID
1000
+ SourceType
1001
+ ResultType
1002
+ Title
1003
+ Snippet
1004
+ Score
1005
+ ScoreBreakdown {
1006
+ Vector
1007
+ FullText
1008
+ Entity
1009
+ Storage
1010
+ }
1011
+ Tags
1012
+ EntityIcon
1013
+ RecordName
1014
+ MatchedAt
1015
+ RawMetadata
1016
+ ProviderId
1017
+ ProviderLabel
1018
+ ProviderIcon
1019
+ }
1020
+ TotalCount
1021
+ ElapsedMs
1022
+ SourceCounts {
1023
+ Vector
1024
+ FullText
1025
+ Entity
1026
+ Storage
1027
+ }
1028
+ Providers {
1029
+ ID
1030
+ Name
1031
+ DisplayName
1032
+ Icon
1033
+ SourceType
1034
+ Priority
1035
+ }
1036
+ ErrorMessage
1037
+ }
1038
+ }
1039
+ `,r={query:e.Query};if(e.MaxResults!==void 0&&(r.maxResults=e.MaxResults),e.MinScore!==void 0&&(r.minScore=e.MinScore),e.Filters!==void 0){const n={};e.Filters.EntityNames?.length&&(n.EntityNames=e.Filters.EntityNames),e.Filters.SourceTypes?.length&&(n.SourceTypes=e.Filters.SourceTypes),e.Filters.Tags?.length&&(n.Tags=e.Filters.Tags),r.filters=n}const s=await this.Client.request(t,r);return s?.SearchKnowledgeAsSystemUser?this.mapSearchResponse(s.SearchKnowledgeAsSystemUser):this.searchErrorResponse("Invalid response from server")}catch(t){return c.LogError(`GraphQLSystemUserClient::SearchKnowledge - Error executing search - ${t}`),this.searchErrorResponse(t instanceof Error?t.message:String(t))}}async PreviewSearch(e){try{const t=u.gql`
1040
+ mutation PreviewSearchAsSystemUser($query: String!, $maxResults: Float) {
1041
+ PreviewSearchAsSystemUser(query: $query, maxResults: $maxResults) {
1042
+ Success
1043
+ Results {
1044
+ ID
1045
+ EntityName
1046
+ RecordID
1047
+ SourceType
1048
+ ResultType
1049
+ Title
1050
+ Snippet
1051
+ Score
1052
+ ScoreBreakdown {
1053
+ Vector
1054
+ FullText
1055
+ Entity
1056
+ Storage
1057
+ }
1058
+ Tags
1059
+ EntityIcon
1060
+ RecordName
1061
+ MatchedAt
1062
+ RawMetadata
1063
+ ProviderId
1064
+ ProviderLabel
1065
+ ProviderIcon
1066
+ }
1067
+ TotalCount
1068
+ ElapsedMs
1069
+ SourceCounts {
1070
+ Vector
1071
+ FullText
1072
+ Entity
1073
+ Storage
1074
+ }
1075
+ Providers {
1076
+ ID
1077
+ Name
1078
+ DisplayName
1079
+ Icon
1080
+ SourceType
1081
+ Priority
1082
+ }
1083
+ ErrorMessage
1084
+ }
1085
+ }
1086
+ `,r={query:e.Query};e.MaxResults!==void 0&&(r.maxResults=e.MaxResults);const s=await this.Client.request(t,r);return s?.PreviewSearchAsSystemUser?this.mapSearchResponse(s.PreviewSearchAsSystemUser):this.searchErrorResponse("Invalid response from server")}catch(t){return c.LogError(`GraphQLSystemUserClient::PreviewSearch - Error executing preview search - ${t}`),this.searchErrorResponse(t instanceof Error?t.message:String(t))}}mapSearchResponse(e){return{Success:e.Success,Results:(e.Results||[]).map(t=>({ID:t.ID,EntityName:t.EntityName,RecordID:t.RecordID,SourceType:t.SourceType,ResultType:t.ResultType,Title:t.Title,Snippet:t.Snippet,Score:t.Score,ScoreBreakdown:this.mapScoreBreakdown(t.ScoreBreakdown),Tags:t.Tags||[],EntityIcon:t.EntityIcon,RecordName:t.RecordName,MatchedAt:t.MatchedAt,RawMetadata:t.RawMetadata,ProviderId:t.ProviderId,ProviderLabel:t.ProviderLabel,ProviderIcon:t.ProviderIcon})),TotalCount:e.TotalCount,ElapsedMs:e.ElapsedMs,SourceCounts:this.mapSourceCounts(e.SourceCounts),Providers:(e.Providers||[]).map(t=>({ID:t.ID,Name:t.Name,DisplayName:t.DisplayName,Icon:t.Icon,SourceType:t.SourceType,Priority:t.Priority})),ErrorMessage:e.ErrorMessage}}mapScoreBreakdown(e){if(!e)return{};const t={};return e.Vector!==void 0&&(t.Vector=e.Vector),e.FullText!==void 0&&(t.FullText=e.FullText),e.Entity!==void 0&&(t.Entity=e.Entity),e.Storage!==void 0&&(t.Storage=e.Storage),t}mapSourceCounts(e){return e?{Vector:e.Vector??0,FullText:e.FullText??0,Entity:e.Entity??0,Storage:e.Storage??0}:{Vector:0,FullText:0,Entity:0,Storage:0}}searchErrorResponse(e){return{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,SourceCounts:{Vector:0,FullText:0,Entity:0,Storage:0},Providers:[],ErrorMessage:`Error: ${e}`}}}class te{static{g(this,"GetDataOutput")}}class re{static{g(this,"SimpleRemoteEntityOutput")}}class se{static{g(this,"SimpleRemoteEntity")}}class ne{static{g(this,"SimpleRemoteEntityField")}}class ae{static{g(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=u.gql`
993
1087
  mutation RunAction($input: RunActionInput!) {
994
1088
  RunAction(input: $input) {
995
1089
  Success
@@ -1080,7 +1174,7 @@
1080
1174
  result
1081
1175
  }
1082
1176
  }
1083
- `}buildRunTestVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0;return{testId:e.testId,verbose:e.verbose,environment:e.environment,tags:t,variables:r,fireAndForget:!0}}buildRunTestSuiteVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0,s=e.selectedTestIds&&e.selectedTestIds.length>0?JSON.stringify(e.selectedTestIds):void 0;return{suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel,tags:t,variables:r,selectedTestIds:s,sequenceStart:e.sequenceStart,sequenceEnd:e.sequenceEnd,fireAndForget:!0}}isTestCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetComplete"&&r?.type==="complete"&&r?.testId===t}isSuiteCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetSuiteComplete"&&r?.type==="complete"&&r?.suiteId===t}extractTestResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?D.SafeJSONParse(t.result):null}}extractSuiteResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?D.SafeJSONParse(t.result):null}}forwardTestProgress(e,t){if(e.resolver==="RunTestResolver"&&e.type==="TestExecutionProgress"&&e.status==="ok"){const s=e.data?.progress;s&&t(s)}}handleError(e,t){const r=e.message;return c.LogError(`${t} failed: ${r}`),{success:!1,errorMessage:r.includes("Failed to fetch")||r.includes("NetworkError")?"Lost connection to the server. The test may still be running. Please refresh to check the latest status.":r,result:null}}}class ce{static{g(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=u.gql`
1177
+ `}buildRunTestVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0;return{testId:e.testId,verbose:e.verbose,environment:e.environment,tags:t,variables:r,fireAndForget:!0}}buildRunTestSuiteVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0,s=e.selectedTestIds&&e.selectedTestIds.length>0?JSON.stringify(e.selectedTestIds):void 0;return{suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel,tags:t,variables:r,selectedTestIds:s,sequenceStart:e.sequenceStart,sequenceEnd:e.sequenceEnd,fireAndForget:!0}}isTestCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetComplete"&&r?.type==="complete"&&r?.testId===t}isSuiteCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetSuiteComplete"&&r?.type==="complete"&&r?.suiteId===t}extractTestResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?R.SafeJSONParse(t.result):null}}extractSuiteResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?R.SafeJSONParse(t.result):null}}forwardTestProgress(e,t){if(e.resolver==="RunTestResolver"&&e.type==="TestExecutionProgress"&&e.status==="ok"){const s=e.data?.progress;s&&t(s)}}handleError(e,t){const r=e.message;return c.LogError(`${t} failed: ${r}`),{success:!1,errorMessage:r.includes("Failed to fetch")||r.includes("NetworkError")?"Lost connection to the server. The test may still be running. Please refresh to check the latest status.":r,result:null}}}class ce{static{g(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=u.gql`
1084
1178
  query GetRegistryComponent(
1085
1179
  $registryName: String!,
1086
1180
  $namespace: String!,
@@ -1264,7 +1358,101 @@
1264
1358
  failedAccounts
1265
1359
  }
1266
1360
  }
1267
- `,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(l=>({path:l.path,name:l.name,size:l.size,contentType:l.contentType,lastModified:new Date(l.lastModified),relevance:l.relevance,excerpt:l.excerpt,matchInFilename:l.matchInFilename,objectId:l.objectId})),totalMatches:o.totalMatches,hasMore:o.hasMore,nextPageToken:o.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(s){const n=s;return c.LogError(`Error searching across accounts: ${n}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}class de{static{g(this,"GraphQLIntegrationClient")}constructor(e){this._dataProvider=e}async DiscoverObjects(e){try{const t=u.gql`
1361
+ `,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(l=>({path:l.path,name:l.name,size:l.size,contentType:l.contentType,lastModified:new Date(l.lastModified),relevance:l.relevance,excerpt:l.excerpt,matchInFilename:l.matchInFilename,objectId:l.objectId})),totalMatches:o.totalMatches,hasMore:o.hasMore,nextPageToken:o.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(s){const n=s;return c.LogError(`Error searching across accounts: ${n}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}class de{static{g(this,"GraphQLSearchClient")}constructor(e){this._dataProvider=e}async ExecuteSearch(e){try{const t=this.buildSearchKnowledgeMutation(),r=this.prepareSearchVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processSearchKnowledgeResult(s)}catch(t){return this.handleSearchError(t)}}async PreviewSearch(e,t){try{const r=this.buildPreviewSearchMutation(),s=this.preparePreviewVariables(e,t),n=await this._dataProvider.ExecuteGQL(r,s);return this.processPreviewSearchResult(n)}catch(r){return this.handleSearchError(r)}}buildSearchKnowledgeMutation(){return u.gql`
1362
+ mutation SearchKnowledge($query: String!, $maxResults: Float, $filters: SearchFiltersInput, $minScore: Float) {
1363
+ SearchKnowledge(query: $query, maxResults: $maxResults, filters: $filters, minScore: $minScore) {
1364
+ Success
1365
+ Results {
1366
+ ID
1367
+ EntityName
1368
+ RecordID
1369
+ SourceType
1370
+ ResultType
1371
+ Title
1372
+ Snippet
1373
+ Score
1374
+ ScoreBreakdown {
1375
+ Vector
1376
+ FullText
1377
+ Entity
1378
+ Storage
1379
+ }
1380
+ Tags
1381
+ EntityIcon
1382
+ RecordName
1383
+ MatchedAt
1384
+ RawMetadata
1385
+ ProviderId
1386
+ ProviderLabel
1387
+ ProviderIcon
1388
+ }
1389
+ TotalCount
1390
+ ElapsedMs
1391
+ SourceCounts {
1392
+ Vector
1393
+ FullText
1394
+ Entity
1395
+ Storage
1396
+ }
1397
+ Providers {
1398
+ ID
1399
+ Name
1400
+ DisplayName
1401
+ Icon
1402
+ SourceType
1403
+ Priority
1404
+ }
1405
+ ErrorMessage
1406
+ }
1407
+ }
1408
+ `}buildPreviewSearchMutation(){return u.gql`
1409
+ mutation PreviewSearch($query: String!, $maxResults: Float) {
1410
+ PreviewSearch(query: $query, maxResults: $maxResults) {
1411
+ Success
1412
+ Results {
1413
+ ID
1414
+ EntityName
1415
+ RecordID
1416
+ SourceType
1417
+ ResultType
1418
+ Title
1419
+ Snippet
1420
+ Score
1421
+ ScoreBreakdown {
1422
+ Vector
1423
+ FullText
1424
+ Entity
1425
+ Storage
1426
+ }
1427
+ Tags
1428
+ EntityIcon
1429
+ RecordName
1430
+ MatchedAt
1431
+ RawMetadata
1432
+ ProviderId
1433
+ ProviderLabel
1434
+ ProviderIcon
1435
+ }
1436
+ TotalCount
1437
+ ElapsedMs
1438
+ SourceCounts {
1439
+ Vector
1440
+ FullText
1441
+ Entity
1442
+ Storage
1443
+ }
1444
+ Providers {
1445
+ ID
1446
+ Name
1447
+ DisplayName
1448
+ Icon
1449
+ SourceType
1450
+ Priority
1451
+ }
1452
+ ErrorMessage
1453
+ }
1454
+ }
1455
+ `}prepareSearchVariables(e){const t={query:e.Query};return e.MaxResults!==void 0&&(t.maxResults=e.MaxResults),e.MinScore!==void 0&&(t.minScore=e.MinScore),e.Filters!==void 0&&(t.filters=this.prepareFilters(e.Filters)),t}prepareFilters(e){const t={};return e.EntityNames!==void 0&&e.EntityNames.length>0&&(t.EntityNames=e.EntityNames),e.SourceTypes!==void 0&&e.SourceTypes.length>0&&(t.SourceTypes=e.SourceTypes),e.Tags!==void 0&&e.Tags.length>0&&(t.Tags=e.Tags),t}preparePreviewVariables(e,t){const r={query:e};return t!==void 0&&(r.maxResults=t),r}processSearchKnowledgeResult(e){if(!e?.SearchKnowledge)throw new Error("Invalid response from server");const t=e.SearchKnowledge;return this.mapSearchResponse(t)}processPreviewSearchResult(e){if(!e?.PreviewSearch)throw new Error("Invalid response from server");const t=e.PreviewSearch;return this.mapSearchResponse(t)}mapSearchResponse(e){return{Success:e.Success,Results:(e.Results||[]).map(t=>this.mapResultItem(t)),TotalCount:e.TotalCount,ElapsedMs:e.ElapsedMs,SourceCounts:this.mapSourceCounts(e.SourceCounts),Providers:(e.Providers||[]).map(t=>({ID:t.ID,Name:t.Name,DisplayName:t.DisplayName,Icon:t.Icon,SourceType:t.SourceType,Priority:t.Priority})),ErrorMessage:e.ErrorMessage}}mapResultItem(e){return{ID:e.ID,EntityName:e.EntityName,RecordID:e.RecordID,SourceType:e.SourceType,ResultType:e.ResultType,Title:e.Title,Snippet:e.Snippet,Score:e.Score,ScoreBreakdown:this.mapScoreBreakdown(e.ScoreBreakdown),Tags:e.Tags||[],EntityIcon:e.EntityIcon,RecordName:e.RecordName,MatchedAt:e.MatchedAt,RawMetadata:e.RawMetadata,ProviderId:e.ProviderId,ProviderLabel:e.ProviderLabel,ProviderIcon:e.ProviderIcon}}mapScoreBreakdown(e){if(!e)return{};const t={};return e.Vector!==void 0&&(t.Vector=e.Vector),e.FullText!==void 0&&(t.FullText=e.FullText),e.Entity!==void 0&&(t.Entity=e.Entity),e.Storage!==void 0&&(t.Storage=e.Storage),t}mapSourceCounts(e){return e?{Vector:e.Vector??0,FullText:e.FullText??0,Entity:e.Entity??0,Storage:e.Storage??0}:{Vector:0,FullText:0,Entity:0,Storage:0}}handleSearchError(e){const t=e;return c.LogError(`Error executing search: ${t}`),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,SourceCounts:{Vector:0,FullText:0,Entity:0,Storage:0},Providers:[],ErrorMessage:`Error: ${t.message}`}}}class ye{static{g(this,"GraphQLIntegrationClient")}constructor(e){this._dataProvider=e}async DiscoverObjects(e){try{const t=u.gql`
1268
1456
  query IntegrationDiscoverObjects($companyIntegrationID: String!) {
1269
1457
  IntegrationDiscoverObjects(companyIntegrationID: $companyIntegrationID) {
1270
1458
  Success
@@ -1423,5 +1611,5 @@
1423
1611
  IntegrationGetConnectorCapabilities(companyIntegrationID: $companyIntegrationID) {
1424
1612
  Success Message SupportsGet SupportsCreate SupportsUpdate SupportsDelete SupportsSearch
1425
1613
  }
1426
- }`;return(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationGetConnectorCapabilities??{Success:!1,Message:"No response"}}catch(t){return{Success:!1,Message:t.message}}}handleError(e,t){const r=e;return c.LogError(`Error in integration discovery: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Data:t}}}Object.defineProperty(exports,"gql",{enumerable:!0,get:g(function(){return u.gql},"get")}),exports.ActionItemInput=X,exports.ActionItemOutput=Z,exports.BrowserIndexedDBStorageProvider=F,exports.BrowserStorageProviderBase=L,exports.FieldMapper=v,exports.FireAndForgetHelper=P,exports.GetDataOutput=te,exports.GraphQLAIClient=x,exports.GraphQLActionClient=ae,exports.GraphQLComponentRegistryClient=ce,exports.GraphQLDataProvider=S,exports.GraphQLEncryptionClient=oe,exports.GraphQLFileStorageClient=le,exports.GraphQLIntegrationClient=de,exports.GraphQLProviderConfigData=K,exports.GraphQLSystemUserClient=ee,exports.GraphQLTestingClient=ie,exports.GraphQLTransactionGroup=M,exports.GraphQLVersionHistoryClient=ue,exports.RoleInput=W,exports.RolesAndUsersInput=H,exports.SimpleRemoteEntity=se,exports.SimpleRemoteEntityField=ne,exports.SimpleRemoteEntityOutput=re,exports.SyncDataAction=q,exports.SyncDataResult=Y,exports.SyncRolesAndUsersResult=J,exports.UserInput=z,exports.setupGraphQLClient=j;
1614
+ }`;return(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationGetConnectorCapabilities??{Success:!1,Message:"No response"}}catch(t){return{Success:!1,Message:t.message}}}handleError(e,t){const r=e;return c.LogError(`Error in integration discovery: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Data:t}}}Object.defineProperty(exports,"gql",{enumerable:!0,get:g(function(){return u.gql},"get")}),exports.ActionItemInput=X,exports.ActionItemOutput=Z,exports.BrowserIndexedDBStorageProvider=Q,exports.BrowserStorageProviderBase=T,exports.FieldMapper=w,exports.FireAndForgetHelper=P,exports.GetDataOutput=te,exports.GraphQLAIClient=x,exports.GraphQLActionClient=ae,exports.GraphQLComponentRegistryClient=ce,exports.GraphQLDataProvider=S,exports.GraphQLEncryptionClient=oe,exports.GraphQLFileStorageClient=le,exports.GraphQLIntegrationClient=ye,exports.GraphQLProviderConfigData=K,exports.GraphQLSearchClient=de,exports.GraphQLSystemUserClient=ee,exports.GraphQLTestingClient=ie,exports.GraphQLTransactionGroup=M,exports.GraphQLVersionHistoryClient=ue,exports.RoleInput=W,exports.RolesAndUsersInput=H,exports.SimpleRemoteEntity=se,exports.SimpleRemoteEntityField=ne,exports.SimpleRemoteEntityOutput=re,exports.SyncDataAction=q,exports.SyncDataResult=Y,exports.SyncRolesAndUsersResult=J,exports.UserInput=z,exports.setupGraphQLClient=j;
1427
1615
  //# sourceMappingURL=index.cjs.map