@memberjunction/graphql-dataprovider 5.21.0 → 5.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var H=Object.defineProperty;var g=(h,e)=>H(h,"name",{value:e,configurable:!0});import{gql as c,GraphQLClient as L}from"graphql-request";import{gql as ze}from"graphql-request";import{TransactionGroupBase as z,TransactionResult as X,LogError as l,LogStatus as T,LogErrorEx as A,ProviderBase as Y,UserInfo as F,getGraphQLTypeNameBase as N,ProviderType as Z,BaseEntityResult as Q,EntityFieldTSType as b,TransactionItem as U,CompositeKey as ee,UserRoleInfo as te,InMemoryLocalStorageProvider as se,BaseEntity as re,ProviderConfigDataBase as ne,SetProvider as ae,StartupManager as oe,IsPlatformSQL as ie,IsVerboseLoggingEnabled as ce}from"@memberjunction/core";import{SafeJSONParse as v,GetGlobalObjectStore as G,UUIDsEqual as ue,MJGlobal as V,MJEventType as _}from"@memberjunction/global";import{ViewInfo as O}from"@memberjunction/core-entities";import{Observable as x,Subject as le,Subscription as de}from"rxjs";import{createClient as ye}from"graphql-ws";import{v4 as me}from"uuid";import{openDB as ge}from"@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 s=this.MapFieldName(t);s!==t&&(e[s]=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 s=this.ReverseMapFieldName(t);s!==t&&(e[s]=e[t],delete e[t])}return e}}class q extends z{static{g(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=c`
1
+ var z=Object.defineProperty;var g=(h,e)=>z(h,"name",{value:e,configurable:!0});import{gql as c,GraphQLClient as L}from"graphql-request";import{gql as Xe}from"graphql-request";import{TransactionGroupBase as H,TransactionResult as X,LogError as l,LogStatus as T,LogErrorEx as A,ProviderBase as Y,UserInfo as F,getGraphQLTypeNameBase as N,ProviderType as Z,BaseEntityResult as Q,EntityFieldTSType as b,TransactionItem as U,CompositeKey as ee,UserRoleInfo as te,InMemoryLocalStorageProvider as se,BaseEntity as re,ProviderConfigDataBase as ne,SetProvider as ae,StartupManager as oe,IsPlatformSQL as ie,IsVerboseLoggingEnabled as ce}from"@memberjunction/core";import{SafeJSONParse as C,CleanAndParseJSON as ue,GetGlobalObjectStore as G,UUIDsEqual as le,MJGlobal as V,MJEventType as _}from"@memberjunction/global";import{ViewInfo as q}from"@memberjunction/core-entities";import{Observable as x,Subject as de,Subscription as ye}from"rxjs";import{createClient as me}from"graphql-ws";import{v4 as ge}from"uuid";import{openDB as pe}from"@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 s=this.MapFieldName(t);s!==t&&(e[s]=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 s=this.ReverseMapFieldName(t);s!==t&&(e[s]=e[t],delete e[t])}return e}}class O extends H{static{g(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=c`
2
2
  mutation ExecuteTransactionGroup($group: TransactionInputType!) {
3
3
  ExecuteTransactionGroup(group: $group) {
4
4
  Success
@@ -6,7 +6,7 @@ var H=Object.defineProperty;var g=(h,e)=>H(h,"name",{value:e,configurable:!0});i
6
6
  ResultsJSON
7
7
  }
8
8
  }
9
- `,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const s={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},r=await this._provider.ExecuteGQL(e,s);if(r&&r.ExecuteTransactionGroup){const n=r.ExecuteTransactionGroup,a=[];for(let i=0;i<this.PendingTransactions.length;i++){const o=n.ResultsJSON[i],u=v(o),d=this.PendingTransactions[i];a.push(new X(d,u,u!==null))}return a}else throw new Error("Failed to execute transaction group")}}const pe=900*1e3;class P{static{g(this,"FireAndForgetHelper")}static async Execute(e){const t=e.operationLabel??e.mutationFieldName;let s,r;try{const{promise:n,resolve:a,reject:i}=P.createCompletionPromise();r=P.setupTimeout(i,e.timeoutMs,e.timeoutErrorMessage),s=P.subscribeToPubSub(e,a,r);const o=await P.executeMutation(e);if(!e.validateAck(o)){r&&clearTimeout(r);const u=o?.errorMessage??"Server rejected the request";return l(`[FireAndForget:${t}] Server rejected: ${u}`),e.createErrorResult(u)}return T(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await n}catch(n){throw r&&clearTimeout(r),l(`[FireAndForget:${t}] Error: ${n.message}`),n}finally{r&&clearTimeout(r),s&&s.unsubscribe()}}static createCompletionPromise(){let e,t;return{promise:new Promise((r,n)=>{e=r,t=n}),resolve:e,reject:t}}static setupTimeout(e,t,s){const r=t??pe,n=s??"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))},r)}static subscribeToPubSub(e,t,s){const r=e.dataProvider.sessionId,n=e.operationLabel??e.mutationFieldName;return e.dataProvider.PushStatusUpdates(r).subscribe(a=>{try{const i=JSON.parse(a);e.onMessage&&e.onMessage(i),e.isCompletionEvent(i)&&(clearTimeout(s),T(`[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 k{static{g(this,"GraphQLAIClient")}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=c`
9
+ `,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const s={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},r=await this._provider.ExecuteGQL(e,s);if(r&&r.ExecuteTransactionGroup){const n=r.ExecuteTransactionGroup,a=[];for(let i=0;i<this.PendingTransactions.length;i++){const o=n.ResultsJSON[i],u=C(o),d=this.PendingTransactions[i];a.push(new X(d,u,u!==null))}return a}else throw new Error("Failed to execute transaction group")}}const Se=900*1e3;class P{static{g(this,"FireAndForgetHelper")}static async Execute(e){const t=e.operationLabel??e.mutationFieldName;let s,r;try{const{promise:n,resolve:a,reject:i}=P.createCompletionPromise();r=P.setupTimeout(i,e.timeoutMs,e.timeoutErrorMessage),s=P.subscribeToPubSub(e,a,r);const o=await P.executeMutation(e);if(!e.validateAck(o)){r&&clearTimeout(r);const u=o?.errorMessage??"Server rejected the request";return l(`[FireAndForget:${t}] Server rejected: ${u}`),e.createErrorResult(u)}return T(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await n}catch(n){throw r&&clearTimeout(r),l(`[FireAndForget:${t}] Error: ${n.message}`),n}finally{r&&clearTimeout(r),s&&s.unsubscribe()}}static createCompletionPromise(){let e,t;return{promise:new Promise((r,n)=>{e=r,t=n}),resolve:e,reject:t}}static setupTimeout(e,t,s){const r=t??Se,n=s??"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))},r)}static subscribeToPubSub(e,t,s){const r=e.dataProvider.sessionId,n=e.operationLabel??e.mutationFieldName;return e.dataProvider.PushStatusUpdates(r).subscribe(a=>{try{const i=JSON.parse(a);e.onMessage&&e.onMessage(i),e.isCompletionEvent(i)&&(clearTimeout(s),T(`[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 k{static{g(this,"GraphQLAIClient")}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=c`
10
10
  mutation RunAIPrompt(
11
11
  $promptId: String!,
12
12
  $data: String,
@@ -65,7 +65,7 @@ var H=Object.defineProperty;var g=(h,e)=>H(h,"name",{value:e,configurable:!0});i
65
65
  chatResult
66
66
  }
67
67
  }
68
- `,s=this.preparePromptVariables(e),r=await this._dataProvider.ExecuteGQL(t,s);return this.processPromptResult(r)}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 s,r,n;try{t.parsedResult&&(s=JSON.parse(t.parsedResult))}catch{s=t.parsedResult}try{t.validationResult&&(r=JSON.parse(t.validationResult))}catch{r=t.validationResult}try{t.chatResult&&(n=JSON.parse(t.chatResult))}catch{n=t.chatResult}return{success:t.success,output:t.output,parsedResult:s,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:r,chatResult:n}}handlePromptError(e){const t=e;return l(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,s){try{const r=this.buildRunAIAgentMutation(),n=this.prepareAgentVariables(e,t,s);return n.fireAndForget=!0,await P.Execute({dataProvider:this._dataProvider,mutation:r,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(r){return this.handleAgentError(r)}}buildRunAIAgentMutation(){return c`
68
+ `,s=this.preparePromptVariables(e),r=await this._dataProvider.ExecuteGQL(t,s);return this.processPromptResult(r)}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 s,r,n;try{t.parsedResult&&(s=ue(t.parsedResult))}catch{s=t.parsedResult}try{t.validationResult&&(r=JSON.parse(t.validationResult))}catch{r=t.validationResult}try{t.chatResult&&(n=JSON.parse(t.chatResult))}catch{n=t.chatResult}return{success:t.success,output:t.output,parsedResult:s,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:r,chatResult:n}}handlePromptError(e){const t=e;return l(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,s){try{const r=this.buildRunAIAgentMutation(),n=this.prepareAgentVariables(e,t,s);return n.fireAndForget=!0,await P.Execute({dataProvider:this._dataProvider,mutation:r,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(r){return this.handleAgentError(r)}}buildRunAIAgentMutation(){return c`
69
69
  mutation RunAIAgent(
70
70
  $agentId: String!,
71
71
  $messages: String!,
@@ -106,7 +106,7 @@ var H=Object.defineProperty;var g=(h,e)=>H(h,"name",{value:e,configurable:!0});i
106
106
  result
107
107
  }
108
108
  }
109
- `}prepareAgentVariables(e,t,s){const r={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(r.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(r.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(r.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(r.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(r.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(r.conversationDetailId=e.conversationDetailId,r.createArtifacts=!0,r.createNotification=!0),t!==void 0&&(r.sourceArtifactId=t),s!==void 0&&(r.sourceArtifactVersionId=s),r}processAgentResult(e){return v(e)}handleAgentError(e){const s=e?.message||String(e);l(`Error running AI agent: ${s}`);const r=s.includes("Failed to fetch")||s.includes("NetworkError"),n=s.includes("timed out")||s.includes("timeout");let a;return r?a="Lost connection to the server. The agent may still be running. Please refresh to check the latest status.":a=s,{success:!1,agentRun:void 0,errorMessage:a}}async RunAIAgentFromConversationDetail(e){try{const t=this.buildConversationDetailMutation(),s=this.prepareConversationDetailVariables(e);return await P.Execute({dataProvider:this._dataProvider,mutation:t,variables:s,mutationFieldName:"RunAIAgentFromConversationDetail",operationLabel:"RunAIAgentFromConversationDetail",validateAck:g(r=>r?.success===!0,"validateAck"),isCompletionEvent:g(r=>this.isConversationDetailCompletionEvent(r,e.conversationDetailId),"isCompletionEvent"),extractResult:g(r=>this.extractAgentResult(r),"extractResult"),onMessage:e.onProgress?r=>this.forwardConversationDetailProgress(r,e.onProgress):void 0,createErrorResult:g(r=>this.createAgentErrorResult(r),"createErrorResult")})}catch(t){return this.handleAgentError(t)}}buildConversationDetailMutation(){return c`
109
+ `}prepareAgentVariables(e,t,s){const r={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(r.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(r.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(r.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(r.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(r.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(r.conversationDetailId=e.conversationDetailId,r.createArtifacts=!0,r.createNotification=!0),t!==void 0&&(r.sourceArtifactId=t),s!==void 0&&(r.sourceArtifactVersionId=s),r}processAgentResult(e){return C(e)}handleAgentError(e){const s=e?.message||String(e);l(`Error running AI agent: ${s}`);const r=s.includes("Failed to fetch")||s.includes("NetworkError"),n=s.includes("timed out")||s.includes("timeout");let a;return r?a="Lost connection to the server. The agent may still be running. Please refresh to check the latest status.":a=s,{success:!1,agentRun:void 0,errorMessage:a}}async RunAIAgentFromConversationDetail(e){try{const t=this.buildConversationDetailMutation(),s=this.prepareConversationDetailVariables(e);return await P.Execute({dataProvider:this._dataProvider,mutation:t,variables:s,mutationFieldName:"RunAIAgentFromConversationDetail",operationLabel:"RunAIAgentFromConversationDetail",validateAck:g(r=>r?.success===!0,"validateAck"),isCompletionEvent:g(r=>this.isConversationDetailCompletionEvent(r,e.conversationDetailId),"isCompletionEvent"),extractResult:g(r=>this.extractAgentResult(r),"extractResult"),onMessage:e.onProgress?r=>this.forwardConversationDetailProgress(r,e.onProgress):void 0,createErrorResult:g(r=>this.createAgentErrorResult(r),"createErrorResult")})}catch(t){return this.handleAgentError(t)}}buildConversationDetailMutation(){return c`
110
110
  mutation RunAIAgentFromConversationDetail(
111
111
  $conversationDetailId: String!,
112
112
  $agentId: String!,
@@ -145,7 +145,7 @@ var H=Object.defineProperty;var g=(h,e)=>H(h,"name",{value:e,configurable:!0});i
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 s=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&s?.type==="complete"&&s?.conversationDetailId===t}extractAgentResult(e){const t=e.data,s=t.result;return s?v(s):{success:t.success,agentRun:void 0}}forwardAgentProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const r=e.data?.progress;r&&t({step:r.currentStep,percentage:r.percentage,message:r.message,metadata:r})}forwardConversationDetailProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const s=e.data,r=s?.progress;r&&t({currentStep:r.currentStep,percentage:r.percentage,message:r.message,metadata:{...r,agentRun:s?.agentRun,agentRunId:s?.agentRunId}})}createAgentErrorResult(e){return{success:!1,agentRun:void 0,errorMessage:e}}async ExecuteSimplePrompt(e){try{const t=c`
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 s=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&s?.type==="complete"&&s?.conversationDetailId===t}extractAgentResult(e){const t=e.data,s=t.result;return s?C(s):{success:t.success,agentRun:void 0}}forwardAgentProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const r=e.data?.progress;r&&t({step:r.currentStep,percentage:r.percentage,message:r.message,metadata:r})}forwardConversationDetailProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const s=e.data,r=s?.progress;r&&t({currentStep:r.currentStep,percentage:r.percentage,message:r.message,metadata:{...r,agentRun:s?.agentRun,agentRunId:s?.agentRunId}})}createAgentErrorResult(e){return{success:!1,agentRun:void 0,errorMessage:e}}async ExecuteSimplePrompt(e){try{const t=c`
149
149
  mutation ExecuteSimplePrompt(
150
150
  $systemPrompt: String!,
151
151
  $messages: String,
@@ -183,7 +183,55 @@ var H=Object.defineProperty;var g=(h,e)=>H(h,"name",{value:e,configurable:!0});i
183
183
  error
184
184
  }
185
185
  }
186
- `,r={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this._dataProvider.ExecuteGQL(t,r);if(!n?.EmbedText)throw new Error("Invalid response from server");const a=n.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?a.embeddings:a.embeddings[0],modelName:a.modelName,vectorDimensions:a.vectorDimensions,error:a.error}}catch(t){const s=t;return l(`Error generating embeddings: ${s}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:s.message||"Unknown error occurred"}}}}const $="default";class B{static{g(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||$;let s=this._storage.get(t);return s||(s=new Map,this._storage.set(t,s)),s}async GetItem(e,t){return this.getCategoryMap(t||$).get(e)??null}async SetItem(e,t,s){this.getCategoryMap(s||$).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 Se="MJ_Metadata",he=3,K=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"],j="Metadata_KVPairs";class J extends B{static{g(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=ge(Se,he,{upgrade(e){try{e.objectStoreNames.contains(j)&&e.deleteObjectStore(j);for(const t of K)e.objectStoreNames.contains(t)||e.createObjectStore(t)}catch(t){A({error:t,message:t?.message})}}}),this.dbPromise.then(()=>{this._dbReady=!0}).catch(e=>{A({error:e,message:"IndexedDB initialization failed: "+e?.message})})}isKnownCategory(e){const t=`mj:${e}`;return K.includes(t)}getStoreName(e){const t=e||$;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const s=t||$;return this.isKnownCategory(s)?e:`[${s}]:${e}`}async SetItem(e,t,s){try{const r=await this.dbPromise,n=this.getStoreName(s),a=this.getStoreKey(e,s),i=r.transaction(n,"readwrite");await i.objectStore(n).put(t,a),await i.done}catch(r){A({error:r,message:r?.message}),await super.SetItem(e,t,s)}}async GetItem(e,t){try{const s=await this.dbPromise,r=this.getStoreName(t),n=this.getStoreKey(e,t);return await s.transaction(r).objectStore(r).get(n)??null}catch(s){return A({error:s,message:s?.message}),await super.GetItem(e,t)}}async Remove(e,t){try{const s=await this.dbPromise,r=this.getStoreName(t),n=this.getStoreKey(e,t),a=s.transaction(r,"readwrite");await a.objectStore(r).delete(n),await a.done}catch(s){A({error:s,message:s?.message}),await super.Remove(e,t)}}async ClearCategory(e){try{const t=await this.dbPromise,s=e||$,r=this.getStoreName(e);if(this.isKnownCategory(s)){const n=t.transaction(r,"readwrite");await n.objectStore(r).clear(),await n.done}else{const n=`[${s}]:`,a=t.transaction("mj:default","readwrite"),i=a.objectStore("mj:default"),o=await i.getAllKeys();for(const u of o)typeof u=="string"&&u.startsWith(n)&&await i.delete(u);await a.done}}catch(t){A({error:t,message:t?.message}),await super.ClearCategory(e)}}async GetCategoryKeys(e){try{const t=await this.dbPromise,s=e||$,r=this.getStoreName(e),i=await t.transaction(r,"readonly").objectStore(r).getAllKeys();if(this.isKnownCategory(s))return i.map(u=>String(u));const o=`[${s}]:`;return i.map(u=>String(u)).filter(u=>u.startsWith(o)).map(u=>u.slice(o.length))}catch(t){return A({error:t,message:t?.message}),await super.GetCategoryKeys(e)}}}class Ie extends ne{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,s,r,n,a,i,o,u,d){super({Token:e,URL:t,WSURL:s,MJAPIKey:o,UserAPIKey:u,RefreshTokenFunction:r,OnAuthenticationError:d},n,a,i)}}class S extends Y{static{g(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._dynamicHeaders=new Map,this._innerCurrentUserQueryString=`CurrentUser {
186
+ `,r={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this._dataProvider.ExecuteGQL(t,r);if(!n?.EmbedText)throw new Error("Invalid response from server");const a=n.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?a.embeddings:a.embeddings[0],modelName:a.modelName,vectorDimensions:a.vectorDimensions,error:a.error}}catch(t){const s=t;return l(`Error generating embeddings: ${s}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:s.message||"Unknown error occurred"}}}async RunAutotagPipeline(){try{const e=c`
187
+ mutation RunAutotagPipeline {
188
+ RunAutotagPipeline {
189
+ Success
190
+ Status
191
+ ErrorMessage
192
+ PipelineRunID
193
+ }
194
+ }
195
+ `,t=await this._dataProvider.ExecuteGQL(e,{});if(!t?.RunAutotagPipeline)throw new Error("Invalid response from server");return t.RunAutotagPipeline}catch(e){const t=e;return l("GraphQLAIClient.RunAutotagPipeline failed",void 0,t),{Success:!1,Status:"Error",ErrorMessage:t.message||"Unknown error"}}}async VectorizeEntity(e){try{const t=c`
196
+ mutation VectorizeEntity(
197
+ $entityDocumentID: String!,
198
+ $entityID: String!,
199
+ $batchSize: Float
200
+ ) {
201
+ VectorizeEntity(
202
+ entityDocumentID: $entityDocumentID,
203
+ entityID: $entityID,
204
+ batchSize: $batchSize
205
+ ) {
206
+ Success
207
+ Status
208
+ ErrorMessage
209
+ PipelineRunID
210
+ }
211
+ }
212
+ `,s={entityDocumentID:e.entityDocumentID,entityID:e.entityID};e.batchSize!==void 0&&(s.batchSize=e.batchSize);const r=await this._dataProvider.ExecuteGQL(t,s);if(!r?.VectorizeEntity)throw new Error("Invalid response from server");return r.VectorizeEntity}catch(t){const s=t;return l("GraphQLAIClient.VectorizeEntity failed",void 0,s),{Success:!1,Status:"Error",ErrorMessage:s.message||"Unknown error"}}}async FetchEntityVectors(e){try{const t=c`
213
+ query FetchEntityVectors(
214
+ $entityDocumentID: String!,
215
+ $maxRecords: Int,
216
+ $filter: String
217
+ ) {
218
+ FetchEntityVectors(
219
+ entityDocumentID: $entityDocumentID,
220
+ maxRecords: $maxRecords,
221
+ filter: $filter
222
+ ) {
223
+ Success
224
+ TotalCount
225
+ ElapsedMs
226
+ ErrorMessage
227
+ Results {
228
+ ID
229
+ Values
230
+ Metadata
231
+ }
232
+ }
233
+ }
234
+ `,s={entityDocumentID:e.entityDocumentID};e.maxRecords!==void 0&&(s.maxRecords=e.maxRecords),e.filter!==void 0&&(s.filter=e.filter);const r=await this._dataProvider.ExecuteGQL(t,s);if(!r?.FetchEntityVectors)throw new Error("Invalid response from server");return r.FetchEntityVectors}catch(t){const s=t;return l("GraphQLAIClient.FetchEntityVectors failed",void 0,s),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,ErrorMessage:s.message||"Unknown error"}}}}const $="default";class B{static{g(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||$;let s=this._storage.get(t);return s||(s=new Map,this._storage.set(t,s)),s}async GetItem(e,t){return this.getCategoryMap(t||$).get(e)??null}async SetItem(e,t,s){this.getCategoryMap(s||$).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 he="MJ_Metadata",Ie=3,K=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"],j="Metadata_KVPairs";class J extends B{static{g(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=pe(he,Ie,{upgrade(e){try{e.objectStoreNames.contains(j)&&e.deleteObjectStore(j);for(const t of K)e.objectStoreNames.contains(t)||e.createObjectStore(t)}catch(t){A({error:t,message:t?.message})}}}),this.dbPromise.then(()=>{this._dbReady=!0}).catch(e=>{A({error:e,message:"IndexedDB initialization failed: "+e?.message})})}isKnownCategory(e){const t=`mj:${e}`;return K.includes(t)}getStoreName(e){const t=e||$;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const s=t||$;return this.isKnownCategory(s)?e:`[${s}]:${e}`}async SetItem(e,t,s){try{const r=await this.dbPromise,n=this.getStoreName(s),a=this.getStoreKey(e,s),i=r.transaction(n,"readwrite");await i.objectStore(n).put(t,a),await i.done}catch(r){A({error:r,message:r?.message}),await super.SetItem(e,t,s)}}async GetItem(e,t){try{const s=await this.dbPromise,r=this.getStoreName(t),n=this.getStoreKey(e,t);return await s.transaction(r).objectStore(r).get(n)??null}catch(s){return A({error:s,message:s?.message}),await super.GetItem(e,t)}}async Remove(e,t){try{const s=await this.dbPromise,r=this.getStoreName(t),n=this.getStoreKey(e,t),a=s.transaction(r,"readwrite");await a.objectStore(r).delete(n),await a.done}catch(s){A({error:s,message:s?.message}),await super.Remove(e,t)}}async ClearCategory(e){try{const t=await this.dbPromise,s=e||$,r=this.getStoreName(e);if(this.isKnownCategory(s)){const n=t.transaction(r,"readwrite");await n.objectStore(r).clear(),await n.done}else{const n=`[${s}]:`,a=t.transaction("mj:default","readwrite"),i=a.objectStore("mj:default"),o=await i.getAllKeys();for(const u of o)typeof u=="string"&&u.startsWith(n)&&await i.delete(u);await a.done}}catch(t){A({error:t,message:t?.message}),await super.ClearCategory(e)}}async GetCategoryKeys(e){try{const t=await this.dbPromise,s=e||$,r=this.getStoreName(e),i=await t.transaction(r,"readonly").objectStore(r).getAllKeys();if(this.isKnownCategory(s))return i.map(u=>String(u));const o=`[${s}]:`;return i.map(u=>String(u)).filter(u=>u.startsWith(o)).map(u=>u.slice(o.length))}catch(t){return A({error:t,message:t?.message}),await super.GetCategoryKeys(e)}}}class fe extends ne{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,s,r,n,a,i,o,u,d){super({Token:e,URL:t,WSURL:s,MJAPIKey:o,UserAPIKey:u,RefreshTokenFunction:r,OnAuthenticationError:d},n,a,i)}}class S extends Y{static{g(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._dynamicHeaders=new Map,this._innerCurrentUserQueryString=`CurrentUser {
187
235
  ${this.userInfoString()}
188
236
  MJUserRoles_UserIDArray {
189
237
  ${this.userRoleInfoString()}
@@ -192,7 +240,7 @@ var H=Object.defineProperty;var g=(h,e)=>H(h,"name",{value:e,configurable:!0});i
192
240
  `,this._currentUserQuery=c`query CurrentUserAndRoles {
193
241
  ${this._innerCurrentUserQueryString}
194
242
  CurrentUserTenantContext
195
- }`,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=G();if(e&&e[S._globalStoreKey])return e[S._globalStoreKey];e&&(e[S._globalStoreKey]=this)}static{this._globalStoreKey="___SINGLETON__GraphQLDataProvider"}static get Instance(){const e=G();return e?e[S._globalStoreKey]:void 0}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new k(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 me()}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 s=this.LocalStoragePrefix+"sessionId";await t.SetItem(s,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,s,r){try{return this._configData=e,s?(this._sessionId=await this.GetPreferredUUID(r),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(r)),S.Instance._client||(S.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,S.Instance._sessionId,e.MJAPIKey,e.UserAPIKey)),await S.Instance.SaveStoredSessionID(S.Instance._sessionId),this._sessionId=S.Instance._sessionId,this._client=S.Instance._client),super.Config(e)}catch(n){throw l(n),n}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}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),s=t.MJUserRoles_UserIDArray.map(n=>this.ConvertBackToMJFields(n));t.MJUserRoles_UserIDArray=s;const r=new F(this,{...t,UserRoles:s});return e.CurrentUserTenantContext&&typeof e.CurrentUserTenantContext=="object"&&(r.TenantContext=e.CurrentUserTenantContext),r}}async RunReport(e,t){const s=c`
243
+ }`,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=G();if(e&&e[S._globalStoreKey])return e[S._globalStoreKey];e&&(e[S._globalStoreKey]=this)}static{this._globalStoreKey="___SINGLETON__GraphQLDataProvider"}static get Instance(){const e=G();return e?e[S._globalStoreKey]:void 0}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new k(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 ge()}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 s=this.LocalStoragePrefix+"sessionId";await t.SetItem(s,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,s,r){try{return this._configData=e,s?(this._sessionId=await this.GetPreferredUUID(r),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(r)),S.Instance._client||(S.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,S.Instance._sessionId,e.MJAPIKey,e.UserAPIKey)),await S.Instance.SaveStoredSessionID(S.Instance._sessionId),this._sessionId=S.Instance._sessionId,this._client=S.Instance._client),super.Config(e)}catch(n){throw l(n),n}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}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),s=t.MJUserRoles_UserIDArray.map(n=>this.ConvertBackToMJFields(n));t.MJUserRoles_UserIDArray=s;const r=new F(this,{...t,UserRoles:s});return e.CurrentUserTenantContext&&typeof e.CurrentUserTenantContext=="object"&&(r.TenantContext=e.CurrentUserTenantContext),r}}async RunReport(e,t){const s=c`
196
244
  query GetReportDataQuery ($ReportID: String!) {
197
245
  GetReportData(ReportID: $ReportID) {
198
246
  Success
@@ -250,7 +298,7 @@ var H=Object.defineProperty;var g=(h,e)=>H(h,"name",{value:e,configurable:!0});i
250
298
  }
251
299
  }
252
300
  }
253
- `,a=(await this.ExecuteGQL(r,{input:s}))?.RunQueriesWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map(o=>{if((o.status==="stale"||o.status==="no_validation")&&o.Results){const u=JSON.parse(o.Results);return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,results:u,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}});return{success:a.success,results:i,errorMessage:a.errorMessage}}catch(s){return l(`Error in RunQueriesWithCacheCheck: ${s}`),{success:!1,results:[],errorMessage:s instanceof Error?s.message:String(s)}}}async InternalRunView(e,t){try{let s="",r="";if(e){const n={};let a,i;if(e.ViewEntity)i=e.ViewEntity,a=i.Entity;else{const{entityName:p,v:f}=await this.getEntityNameAndUserView(e,t);i=f,a=p}const o=this.Entities.find(p=>p.Name===a);if(!o)throw new Error(`Entity ${a} not found in metadata`);let u=!1;const d=N(o);e.ViewID?(s=`Run${d}ViewByID`,r="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(s=`Run${d}ViewByName`,r="RunViewByNameInput",n.ViewName=e.ViewName):(u=!0,s=`Run${d}DynamicView`,r="RunDynamicViewInput",n.EntityName=e.EntityName),n.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",n.OrderBy=e.OrderBy?e.OrderBy:"",n.UserSearchString=e.UserSearchString?e.UserSearchString:"",n.Fields=e.Fields,n.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,e.MaxRows!==void 0&&(n.MaxRows=e.MaxRows),e.StartRow!==void 0&&(n.StartRow=e.StartRow),n.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,n.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(n.AuditLogDescription=e.AuditLogDescription),u||(n.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",n.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,n.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",n.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1),e.Aggregates&&e.Aggregates.length>0&&(n.Aggregates=e.Aggregates.map(p=>({expression:p.expression,alias:p.alias})));const I=this.getViewRunTimeFieldList(o,i,e,u),R=e.Aggregates&&e.Aggregates.length>0?`
301
+ `,a=(await this.ExecuteGQL(r,{input:s}))?.RunQueriesWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map(o=>{if((o.status==="stale"||o.status==="no_validation")&&o.Results){const u=JSON.parse(o.Results);return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,results:u,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}});return{success:a.success,results:i,errorMessage:a.errorMessage}}catch(s){return l(`Error in RunQueriesWithCacheCheck: ${s}`),{success:!1,results:[],errorMessage:s instanceof Error?s.message:String(s)}}}async InternalRunView(e,t){try{let s="",r="";if(e){const n={};let a,i;if(e.ViewEntity)i=e.ViewEntity,a=i.Entity;else{const{entityName:p,v:f}=await this.getEntityNameAndUserView(e,t);i=f,a=p}const o=this.Entities.find(p=>p.Name===a);if(!o)throw new Error(`Entity ${a} not found in metadata`);let u=!1;const d=N(o);e.ViewID?(s=`Run${d}ViewByID`,r="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(s=`Run${d}ViewByName`,r="RunViewByNameInput",n.ViewName=e.ViewName):(u=!0,s=`Run${d}DynamicView`,r="RunDynamicViewInput",n.EntityName=e.EntityName),n.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",n.OrderBy=e.OrderBy?e.OrderBy:"",n.UserSearchString=e.UserSearchString?e.UserSearchString:"",n.Fields=e.Fields,n.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,e.MaxRows!==void 0&&(n.MaxRows=e.MaxRows),e.StartRow!==void 0&&(n.StartRow=e.StartRow),n.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,n.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(n.AuditLogDescription=e.AuditLogDescription),u||(n.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",n.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,n.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",n.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1),e.Aggregates&&e.Aggregates.length>0&&(n.Aggregates=e.Aggregates.map(p=>({expression:p.expression,alias:p.alias})));const I=this.getViewRunTimeFieldList(o,i,e,u),D=e.Aggregates&&e.Aggregates.length>0?`
254
302
  AggregateResults {
255
303
  alias
256
304
  expression
@@ -269,9 +317,9 @@ var H=Object.defineProperty;var g=(h,e)=>H(h,"name",{value:e,configurable:!0});i
269
317
  TotalRowCount
270
318
  ExecutionTime
271
319
  Success
272
- ErrorMessage${R}
320
+ ErrorMessage${D}
273
321
  }
274
- }`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:a,queryName:s,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const m=await this.ExecuteGQL(y,{input:n});if(m&&m[s]){const p=m[s].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:a,aggregateResultCount:p?.length||0,aggregateResults:p,aggregateExecutionTime:m[s].AggregateExecutionTime});const f=m[s].Results;if(f&&f.length>0){const C=o.Fields.filter(E=>E.CodeName!==E.Name&&E.CodeName!==void 0);f.forEach(E=>{this.ConvertBackToMJFields(E),C.forEach(M=>{E[M.Name]=E[M.CodeName]})})}return m[s]}}else throw"No parameters passed to RunView";return null}catch(s){throw l(s),s}}async InternalRunViews(e,t){try{let s=[],r=[],n=[];for(const d of e){let I="",R="";const y={};let m=null,p=null;if(d.ViewEntity)p=d.ViewEntity,m=p.Get("Entity");else{const{entityName:E,v:M}=await this.getEntityNameAndUserView(d,t);p=M,m=E}const f=this.Entities.find(E=>E.Name===m);if(!f)throw new Error(`Entity ${m} not found in metadata`);r.push(f);let D=!1;const C=N(f);d.ViewID?(I=`Run${C}ViewByID`,R="RunViewByIDInput",y.ViewID=d.ViewID):d.ViewName?(I=`Run${C}ViewByName`,R="RunViewByNameInput",y.ViewName=d.ViewName):(D=!0,I=`Run${C}DynamicView`,R="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(E=>({expression:E.expression,alias:E.alias}))),s.push(y),n.push(...this.getViewRunTimeFieldList(f,p,d,D))}const i=e.some(d=>d.Aggregates&&d.Aggregates.length>0)?`
322
+ }`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:a,queryName:s,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const m=await this.ExecuteGQL(y,{input:n});if(m&&m[s]){const p=m[s].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:a,aggregateResultCount:p?.length||0,aggregateResults:p,aggregateExecutionTime:m[s].AggregateExecutionTime});const f=m[s].Results;if(f&&f.length>0){const v=o.Fields.filter(E=>E.CodeName!==E.Name&&E.CodeName!==void 0);f.forEach(E=>{this.ConvertBackToMJFields(E),v.forEach(M=>{E[M.Name]=E[M.CodeName]})})}return m[s]}}else throw"No parameters passed to RunView";return null}catch(s){throw l(s),s}}async InternalRunViews(e,t){try{let s=[],r=[],n=[];for(const d of e){let I="",D="";const y={};let m=null,p=null;if(d.ViewEntity)p=d.ViewEntity,m=p.Get("Entity");else{const{entityName:E,v:M}=await this.getEntityNameAndUserView(d,t);p=M,m=E}const f=this.Entities.find(E=>E.Name===m);if(!f)throw new Error(`Entity ${m} not found in metadata`);r.push(f);let R=!1;const v=N(f);d.ViewID?(I=`Run${v}ViewByID`,D="RunViewByIDInput",y.ViewID=d.ViewID):d.ViewName?(I=`Run${v}ViewByName`,D="RunViewByNameInput",y.ViewName=d.ViewName):(R=!0,I=`Run${v}DynamicView`,D="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(E=>({expression:E.expression,alias:E.alias}))),s.push(y),n.push(...this.getViewRunTimeFieldList(f,p,d,R))}const i=e.some(d=>d.Aggregates&&d.Aggregates.length>0)?`
275
323
  AggregateResults {
276
324
  alias
277
325
  expression
@@ -296,7 +344,7 @@ var H=Object.defineProperty;var g=(h,e)=>H(h,"name",{value:e,configurable:!0});i
296
344
  Success
297
345
  ErrorMessage${i}
298
346
  }
299
- }`,u=await this.ExecuteGQL(o,{input:s});if(u&&u.RunViews){const d=u.RunViews;for(const[I,R]of d.entries())R.Results=R.Results.map(y=>{let m=JSON.parse(y.Data);return this.ConvertBackToMJFields(m),m});return d}return null}catch(s){throw l(s),s}}async RunViewsWithCacheCheck(e,t){try{const s=e.map(o=>({params:{EntityName:o.params.EntityName||"",ExtraFilter:o.params.ExtraFilter||"",OrderBy:o.params.OrderBy||"",Fields:o.params.Fields,UserSearchString:o.params.UserSearchString||"",IgnoreMaxRows:o.params.IgnoreMaxRows||!1,MaxRows:o.params.MaxRows,StartRow:o.params.StartRow,ForceAuditLog:o.params.ForceAuditLog||!1,AuditLogDescription:o.params.AuditLogDescription||"",ResultType:o.params.ResultType||"simple"},cacheStatus:o.cacheStatus?{maxUpdatedAt:o.cacheStatus.maxUpdatedAt,rowCount:o.cacheStatus.rowCount}:null})),r=c`
347
+ }`,u=await this.ExecuteGQL(o,{input:s});if(u&&u.RunViews){const d=u.RunViews;for(const[I,D]of d.entries())D.Results=D.Results.map(y=>{let m=JSON.parse(y.Data);return this.ConvertBackToMJFields(m),m});return d}return null}catch(s){throw l(s),s}}async RunViewsWithCacheCheck(e,t){try{const s=e.map(o=>({params:{EntityName:o.params.EntityName||"",ExtraFilter:o.params.ExtraFilter||"",OrderBy:o.params.OrderBy||"",Fields:o.params.Fields,UserSearchString:o.params.UserSearchString||"",IgnoreMaxRows:o.params.IgnoreMaxRows||!1,MaxRows:o.params.MaxRows,StartRow:o.params.StartRow,ForceAuditLog:o.params.ForceAuditLog||!1,AuditLogDescription:o.params.AuditLogDescription||"",ResultType:o.params.ResultType||"simple"},cacheStatus:o.cacheStatus?{maxUpdatedAt:o.cacheStatus.maxUpdatedAt,rowCount:o.cacheStatus.rowCount}:null})),r=c`
300
348
  query RunViewsWithCacheCheckQuery($input: [RunViewWithCacheCheckInput!]!) {
301
349
  RunViewsWithCacheCheck(input: $input) {
302
350
  success
@@ -329,7 +377,7 @@ var H=Object.defineProperty;var g=(h,e)=>H(h,"name",{value:e,configurable:!0});i
329
377
  }
330
378
  }
331
379
  }
332
- `,a=(await this.ExecuteGQL(r,{input:s}))?.RunViewsWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map((o,u)=>{const d=e[u];if(o.status==="differential"&&o.differentialData){const I=o.differentialData.updatedRows.map(R=>{const y=JSON.parse(R.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(R=>{const y=JSON.parse(R.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(s){return l(s),{success:!1,results:[],errorMessage:s instanceof Error?s.message:String(s)}}}async getEntityNameAndUserView(e,t){let s,r;if(e.EntityName)s=e.EntityName;else if(e.ViewID)r=await O.GetViewEntity(e.ViewID,t),s=r.Entity;else if(e.ViewName)r=await O.GetViewEntityByName(e.ViewName,t),s=r.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:s,v:r}}getViewRunTimeFieldList(e,t,s,r){const n=[],a=new w;if(s.Fields){for(const i of e.PrimaryKeys)s.Fields.find(o=>o.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);s.Fields.forEach(i=>{n.push(a.MapFieldName(i))})}else if(r)e.Fields.forEach(i=>{i.IsBinaryFieldType||n.push(a.MapFieldName(i.CodeName))});else{for(const i of e.PrimaryKeys)n.find(o=>o.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);t.Columns.forEach(i=>{i.hidden===!1&&!n.find(o=>o.trim().toLowerCase()===i.EntityField?.Name.trim().toLowerCase())&&i.EntityField&&n.push(a.MapFieldName(i.EntityField.CodeName))})}return n}get ProviderType(){return Z.Network}async GetRecordChanges(e,t){try{const s={EntityName:"MJ: Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},r=await this.RunView(s);return r?r.Results.sort((n,a)=>n.ChangedAt>a.ChangedAt?-1:1):null}catch(s){throw l(s),s}}async GetRecordDependencies(e,t){try{const s=c`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
380
+ `,a=(await this.ExecuteGQL(r,{input:s}))?.RunViewsWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map((o,u)=>{const d=e[u];if(o.status==="differential"&&o.differentialData){const I=o.differentialData.updatedRows.map(D=>{const y=JSON.parse(D.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(D=>{const y=JSON.parse(D.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(s){return l(s),{success:!1,results:[],errorMessage:s instanceof Error?s.message:String(s)}}}async getEntityNameAndUserView(e,t){let s,r;if(e.EntityName)s=e.EntityName;else if(e.ViewID)r=await q.GetViewEntity(e.ViewID,t),s=r.Entity;else if(e.ViewName)r=await q.GetViewEntityByName(e.ViewName,t),s=r.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:s,v:r}}getViewRunTimeFieldList(e,t,s,r){const n=[],a=new w;if(s.Fields){for(const i of e.PrimaryKeys)s.Fields.find(o=>o.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);s.Fields.forEach(i=>{n.push(a.MapFieldName(i))})}else if(r)e.Fields.forEach(i=>{i.IsBinaryFieldType||n.push(a.MapFieldName(i.CodeName))});else{for(const i of e.PrimaryKeys)n.find(o=>o.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);t.Columns.forEach(i=>{i.hidden===!1&&!n.find(o=>o.trim().toLowerCase()===i.EntityField?.Name.trim().toLowerCase())&&i.EntityField&&n.push(a.MapFieldName(i.EntityField.CodeName))})}return n}get ProviderType(){return Z.Network}async GetRecordChanges(e,t){try{const s={EntityName:"MJ: Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},r=await this.RunView(s);return r?r.Results.sort((n,a)=>n.ChangedAt>a.ChangedAt?-1:1):null}catch(s){throw l(s),s}}async GetRecordDependencies(e,t){try{const s=c`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
333
381
  GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
334
382
  EntityName
335
383
  RelatedEntityName
@@ -383,29 +431,29 @@ var H=Object.defineProperty;var g=(h,e)=>H(h,"name",{value:e,configurable:!0});i
383
431
  }`,a={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(o=>({FieldName:o.FieldName,Value:o.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(o=>o.Copy())};return(await this.ExecuteGQL(n,{request:a}))?.MergeRecords}catch(n){return l(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,s){if(s?.IsParentEntitySave){const n=new Q;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 r=new Q;try{e.RegisterTransactionPreprocessing();const n={input:{}},a=e.IsSaved?"Update":"Create";r.StartedAt=new Date,r.Type=e.IsSaved?"update":"create",r.OriginalValues=e.Fields.map(y=>({FieldName:y.CodeName,Value:y.Value})),e.ResultHistory.push(r);const i=N(e.EntityInfo),o=`${a}${i}`,u=e.Fields.filter(y=>!y.ReadOnly||y.IsPrimaryKey&&e.IsSaved),d=new w,I=` ${o}(input: $input) {
384
432
  ${e.Fields.map(y=>d.MapFieldName(y.CodeName)).join(`
385
433
  `)}
386
- }`,R=c`mutation ${a}${i} ($input: ${o}Input!) {
434
+ }`,D=c`mutation ${a}${i} ($input: ${o}Input!) {
387
435
  ${I}
388
436
  }
389
- `;for(let y=0;y<u.length;y++){const m=u[y];let p=e.Get(m.Name);if(p)switch(m.EntityFieldInfo.TSType){case b.Date:p=p.getTime();break;case b.Boolean:typeof p!="boolean"&&(p=parseInt(p)!==0);break;case b.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===b.Number||m.FieldType===b.Boolean?p=0:p=""),n.input[d.MapFieldName(m.CodeName)]=p}if(a.trim().toLowerCase()==="update"&&s.SkipOldValuesCheck===!1){const y=[];e.Fields.forEach(m=>{let p=null;m.OldValue!==null&&m.OldValue!==void 0&&(m.EntityFieldInfo.TSType===b.Date?p=m.OldValue.getTime().toString():m.EntityFieldInfo.TSType===b.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 U(e,r.Type==="create"?"Create":"Update",I,n,{mutationName:o,mutationInputTypes:y},(m,p)=>{r.EndedAt=new Date,p&&m?(r.Success=!0,r.NewValues=this.ConvertBackToMJFields(m)):(r.Success=!1,r.Message="Transaction failed")})),!0}else{const y=await this.ExecuteGQL(R,n);if(y&&y[o])return r.Success=!0,r.EndedAt=new Date,r.NewValues=this.ConvertBackToMJFields(y[o]),r.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(n){return r.Success=!1,r.EndedAt=new Date,r.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,l(n),null}}async Load(e,t,s=null,r){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===b.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=s&&s.length>0?this.getRelatedEntityString(e.EntityInfo,s):"",u=N(e.EntityInfo),d=new w,I=c`query Single${u}${o.length>0?"Full":""} (${i}) {
437
+ `;for(let y=0;y<u.length;y++){const m=u[y];let p=e.Get(m.Name);if(p)switch(m.EntityFieldInfo.TSType){case b.Date:p=p.getTime();break;case b.Boolean:typeof p!="boolean"&&(p=parseInt(p)!==0);break;case b.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===b.Number||m.FieldType===b.Boolean?p=0:p=""),n.input[d.MapFieldName(m.CodeName)]=p}if(a.trim().toLowerCase()==="update"&&s.SkipOldValuesCheck===!1){const y=[];e.Fields.forEach(m=>{let p=null;m.OldValue!==null&&m.OldValue!==void 0&&(m.EntityFieldInfo.TSType===b.Date?p=m.OldValue.getTime().toString():m.EntityFieldInfo.TSType===b.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 U(e,r.Type==="create"?"Create":"Update",I,n,{mutationName:o,mutationInputTypes:y},(m,p)=>{r.EndedAt=new Date,p&&m?(r.Success=!0,r.NewValues=this.ConvertBackToMJFields(m)):(r.Success=!1,r.Message="Transaction failed")})),!0}else{const y=await this.ExecuteGQL(D,n);if(y&&y[o])return r.Success=!0,r.EndedAt=new Date,r.NewValues=this.ConvertBackToMJFields(y[o]),r.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(n){return r.Success=!1,r.EndedAt=new Date,r.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,l(n),null}}async Load(e,t,s=null,r){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===b.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=s&&s.length>0?this.getRelatedEntityString(e.EntityInfo,s):"",u=N(e.EntityInfo),d=new w,I=c`query Single${u}${o.length>0?"Full":""} (${i}) {
390
438
  ${u}(${a}) {
391
439
  ${e.Fields.filter(y=>!y.EntityFieldInfo.IsBinaryFieldType).map(y=>y.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?y.CodeName.replace("__mj_","_mj__"):y.CodeName).join(`
392
440
  `)}
393
441
  ${o}
394
442
  }
395
443
  }
396
- `,R=await this.ExecuteGQL(I,n);return R&&R[u]?this.ConvertBackToMJFields(R[u]):null}catch(n){return l(n),null}}ConvertBackToMJFields(e){return new w().ReverseMapFields(e),e}getRelatedEntityString(e,t){let s="";for(let r=0;r<e.RelatedEntities.length;r++)if(t.indexOf(e.RelatedEntities[r].RelatedEntity)>=0){const n=e.RelatedEntities[r],a=this.Entities.find(o=>ue(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,"")}`,s+=`
444
+ `,D=await this.ExecuteGQL(I,n);return D&&D[u]?this.ConvertBackToMJFields(D[u]):null}catch(n){return l(n),null}}ConvertBackToMJFields(e){return new w().ReverseMapFields(e),e}getRelatedEntityString(e,t){let s="";for(let r=0;r<e.RelatedEntities.length;r++)if(t.indexOf(e.RelatedEntities[r].RelatedEntity)>=0){const n=e.RelatedEntities[r],a=this.Entities.find(o=>le(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,"")}`,s+=`
397
445
  ${i} {
398
446
  ${a.Fields.map(o=>o.CodeName).join(`
399
447
  `)}
400
448
  }
401
449
  `}return s}async Delete(e,t,s){const r=new Q;try{e.RegisterTransactionPreprocessing(),r.StartedAt=new Date,r.Type="delete",r.OriginalValues=e.Fields.map(m=>({FieldName:m.CodeName,Value:m.Value})),e.ResultHistory.push(r);const n={},a=[];let i="",o="",u="";for(let m of e.PrimaryKey.KeyValuePairs){const p=e.Fields.find(f=>f.Name.trim().toLowerCase()===m.FieldName.trim().toLowerCase());n[p.CodeName]=p.Value,a.push({varName:p.CodeName,inputType:p.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${p.CodeName}: $${p.CodeName}`,o.length>0&&(o+=", "),o+=`$${p.CodeName}: ${p.EntityFieldInfo.GraphQLType}!`,u.length>0&&(u+=`
402
- `),u+=`${p.CodeName}`}a.push({varName:"options___",inputType:"DeleteOptionsInput!"}),n.options___={SkipEntityAIActions:t?.SkipEntityAIActions??!1,SkipEntityActions:t?.SkipEntityActions??!1,ReplayOnly:t?.ReplayOnly??!1,IsParentEntityDelete:t?.IsParentEntityDelete??!1};const I="Delete"+N(e.EntityInfo),R=c`${I}(${i}, options___: $options___) {
450
+ `),u+=`${p.CodeName}`}a.push({varName:"options___",inputType:"DeleteOptionsInput!"}),n.options___={SkipEntityAIActions:t?.SkipEntityAIActions??!1,SkipEntityActions:t?.SkipEntityActions??!1,ReplayOnly:t?.ReplayOnly??!1,IsParentEntityDelete:t?.IsParentEntityDelete??!1};const I="Delete"+N(e.EntityInfo),D=c`${I}(${i}, options___: $options___) {
403
451
  ${u}
404
452
  }
405
453
  `,y=c`mutation ${I} (${o}, $options___: DeleteOptionsInput!) {
406
- ${R}
454
+ ${D}
407
455
  }
408
- `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new U(e,"Delete",R,n,{mutationName:I,mutationInputTypes:a},(m,p)=>{if(r.EndedAt=new Date,p&&m){let f=!0;for(const D of e.PrimaryKey.KeyValuePairs)D.Value!==m[D.FieldName]&&(f=!1);f?r.Success=!0:(r.Success=!1,r.Message="Transaction failed to commit")}else r.Success=!1,r.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 r.Success=!0,r.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(n){return r.EndedAt=new Date,r.Success=!1,r.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,l(n),!1}}async GetDatasetByName(e,t){const s=c`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
456
+ `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new U(e,"Delete",D,n,{mutationName:I,mutationInputTypes:a},(m,p)=>{if(r.EndedAt=new Date,p&&m){let f=!0;for(const R of e.PrimaryKey.KeyValuePairs)R.Value!==m[R.FieldName]&&(f=!1);f?r.Success=!0:(r.Success=!1,r.Message="Transaction failed to commit")}else r.Success=!1,r.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],v=f.Value;if(typeof v=="number"&&(v=v.toString()),typeof R=="number"&&(R=R.toString()),v!==R)throw new Error(`Primary key value mismatch in server Delete response. Field: ${f.FieldName}, Original: ${v}, Returned: ${R}`)}return r.Success=!0,r.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(n){return r.EndedAt=new Date,r.Success=!1,r.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,l(n),!1}}async GetDatasetByName(e,t){const s=c`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
409
457
  GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
410
458
  DatasetID
411
459
  DatasetName
@@ -432,7 +480,7 @@ var H=Object.defineProperty;var g=(h,e)=>H(h,"name",{value:e,configurable:!0});i
432
480
  LatestUpdateDate
433
481
  EntityUpdateDates
434
482
  }
435
- }`,r=await this.ExecuteGQL(s,{DatasetName:e,ItemFilters:t});return r&&r.GetDatasetStatusByName&&r.GetDatasetStatusByName.Success?{DatasetID:r.GetDatasetStatusByName.DatasetID,DatasetName:r.GetDatasetStatusByName.DatasetName,Success:r.GetDatasetStatusByName.Success,Status:r.GetDatasetStatusByName.Status,LatestUpdateDate:new Date(r.GetDatasetStatusByName.LatestUpdateDate),EntityUpdateDates:JSON.parse(r.GetDatasetStatusByName.EntityUpdateDates)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,EntityUpdateDates:null}}async CreateTransactionGroup(){return new q(this)}async GetRecordFavoriteStatus(e,t,s){if(!s.Validate().IsValid)return!1;const n=this.Entities.find(o=>o.Name===t);if(!n)throw new Error(`Entity ${t} not found in metadata`);const a=c`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
483
+ }`,r=await this.ExecuteGQL(s,{DatasetName:e,ItemFilters:t});return r&&r.GetDatasetStatusByName&&r.GetDatasetStatusByName.Success?{DatasetID:r.GetDatasetStatusByName.DatasetID,DatasetName:r.GetDatasetStatusByName.DatasetName,Success:r.GetDatasetStatusByName.Success,Status:r.GetDatasetStatusByName.Status,LatestUpdateDate:new Date(r.GetDatasetStatusByName.LatestUpdateDate),EntityUpdateDates:JSON.parse(r.GetDatasetStatusByName.EntityUpdateDates)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,EntityUpdateDates:null}}async CreateTransactionGroup(){return new O(this)}async GetRecordFavoriteStatus(e,t,s){if(!s.Validate().IsValid)return!1;const n=this.Entities.find(o=>o.Name===t);if(!n)throw new Error(`Entity ${t} not found in metadata`);const a=c`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
436
484
  GetRecordFavoriteStatus(params: $params) {
437
485
  Success
438
486
  IsFavorite
@@ -474,14 +522,26 @@ var H=Object.defineProperty;var g=(h,e)=>H(h,"name",{value:e,configurable:!0});i
474
522
  }
475
523
  }`,s=await this.ExecuteGQL(t,{DataContextItemID:e});if(s&&s.GetDataContextItemData){if(s.GetDataContextItemData.Success)return JSON.parse(s.GetDataContextItemData.Result);throw new Error(s.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw l(t),t}}static async ExecuteGQL(e,t,s=!0){return S.Instance.ExecuteGQL(e,t,s)}async ExecuteGQL(e,t,s=!0){try{return await this._client.request(e,t)}catch(r){if(console.error("[GraphQL] ExecuteGQL error caught:",{hasResponse:!!r?.response,hasErrors:!!r?.response?.errors,errorCount:r?.response?.errors?.length,firstError:r?.response?.errors?.[0],errorCode:r?.response?.errors?.[0]?.extensions?.code,errorMessage:r?.response?.errors?.[0]?.message,fullError:r}),r&&r.response&&r.response.errors?.length>0)if(r.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(s)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw l("JWT_EXPIRED and refreshTokenIfNeeded is false"),r}else throw r;else throw l(r),r}}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 s=0;s<localStorage.length;s++){const r=localStorage.key(s);r&&!e.has(r)&&t.push(r)}t.forEach(s=>localStorage.removeItem(s)),await new Promise(s=>{const r=indexedDB.deleteDatabase("MJ_Metadata");r.onsuccess=()=>s(),r.onerror=()=>s(),r.onblocked=()=>s()})}CreateNewGraphQLClient(e,t,s,r,n){const a={"x-session-id":s};t&&(a.authorization="Bearer "+t),r&&(a["x-mj-api-key"]=r),n&&(a["x-api-key"]=n);const i=new L(e,{headers:a});for(const[o,u]of this._dynamicHeaders)i.setHeader(o,u);return i}userInfoString(){return this.infoString(new F(null,null))}userRoleInfoString(){return this.infoString(new te(null))}infoString(e){let t="";const s=Object.keys(e);for(const r of s)r.startsWith("__mj_")?t+=r.replace("__mj_","_mj__")+`
476
524
  `:r.startsWith("_")||(t+=r+`
477
- `);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new J:this._localStorageProvider=new se),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=ye({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(s){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,s)}}),this._pushStatusSubjects.clear()}cleanupStaleSubscriptions(){if(!this._isCleaningUp){this._isCleaningUp=!0;try{const e=Date.now(),t=this._pushStatusSubjects.size,s=Array.from(this._pushStatusSubjects.entries()),r=[];s.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`),r.push(n))}),r.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)}}),r.length>0&&console.log(`[GraphQLDataProvider] Cleaned up ${r.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 x(s=>{const r=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=r.subscribe({query:e,variables:t},{next:g(a=>{s.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(),s.complete()}catch(u){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",u),s.error(u)}}else s.error(a)},"error"),complete:g(()=>{s.complete()},"complete")});return()=>{this._activeSubscriptionCount--,n()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),s=this._pushStatusSubjects.get(e);if(s)return s.lastRequestedAt=t,new x(o=>{s.activeSubscribers++;const u=s.subject.subscribe(o);return()=>{const d=this._pushStatusSubjects.get(e);d&&d.activeSubscribers>0&&d.activeSubscribers--,u.unsubscribe()}});const r=c`subscription StatusUpdates($sessionId: String!) {
525
+ `);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new J:this._localStorageProvider=new se),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=me({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(s){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,s)}}),this._pushStatusSubjects.clear()}cleanupStaleSubscriptions(){if(!this._isCleaningUp){this._isCleaningUp=!0;try{const e=Date.now(),t=this._pushStatusSubjects.size,s=Array.from(this._pushStatusSubjects.entries()),r=[];s.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`),r.push(n))}),r.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)}}),r.length>0&&console.log(`[GraphQLDataProvider] Cleaned up ${r.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 x(s=>{const r=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=r.subscribe({query:e,variables:t},{next:g(a=>{s.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(),s.complete()}catch(u){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",u),s.error(u)}}else s.error(a)},"error"),complete:g(()=>{s.complete()},"complete")});return()=>{this._activeSubscriptionCount--,n()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),s=this._pushStatusSubjects.get(e);if(s)return s.lastRequestedAt=t,new x(o=>{s.activeSubscribers++;const u=s.subject.subscribe(o);return()=>{const d=this._pushStatusSubjects.get(e);d&&d.activeSubscribers>0&&d.activeSubscribers--,u.unsubscribe()}});const r=c`subscription StatusUpdates($sessionId: String!) {
478
526
  statusUpdates(sessionId: $sessionId) {
479
527
  date
480
528
  message
481
529
  sessionId
482
530
  }
483
531
  }
484
- `,n=new le,a=this.getOrCreateWSClient(),i=new de;return i.add(new x(o=>{const u=a.subscribe({query:r,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--,u()}}).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 x(o=>{const u=this._pushStatusSubjects.get(e);u&&u.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()}SubscribeToCacheInvalidation(){if(this._cacheInvalidationSubscription||!this.ConfigData?.WSURL)return;const e=c`subscription CacheInvalidation {
532
+ `,n=new de,a=this.getOrCreateWSClient(),i=new ye;return i.add(new x(o=>{const u=a.subscribe({query:r,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--,u()}}).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 x(o=>{const u=this._pushStatusSubjects.get(e);u&&u.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(`
533
+ subscription ClientToolRequest($sessionID: String!) {
534
+ ClientToolRequest(sessionID: $sessionID) {
535
+ AgentRunID
536
+ SessionID
537
+ RequestID
538
+ ToolName
539
+ Params
540
+ TimeoutMs
541
+ Description
542
+ }
543
+ }
544
+ `,{sessionID:e})}SubscribeToCacheInvalidation(){if(this._cacheInvalidationSubscription||!this.ConfigData?.WSURL)return;const e=c`subscription CacheInvalidation {
485
545
  cacheInvalidation {
486
546
  EntityName
487
547
  PrimaryKeyValues
@@ -503,14 +563,14 @@ var H=Object.defineProperty;var g=(h,e)=>H(h,"name",{value:e,configurable:!0});i
503
563
  ChildEntityNames
504
564
  ErrorMessage
505
565
  }
506
- }`;try{const n=await this.ExecuteGQL(r,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntities?.Success&&n.FindISAChildEntities.ChildEntityNames?n.FindISAChildEntities.ChildEntityNames.map(a=>({ChildEntityName:a})):[]}catch(n){return l(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function fe(h){const e=new S;return ae(e),await e.Config(h),V.Instance.RaiseEvent({event:_.LoggedIn,eventCode:null,component:this,args:null}),await oe.Instance.Startup(),e}g(fe,"setupGraphQLClient");class Re{static{g(this,"SyncRolesAndUsersResult")}}class De{static{g(this,"RoleInput")}}class Ee{static{g(this,"UserInput")}}class we{static{g(this,"RolesAndUsersInput")}}var W=(h=>(h.Create="Create",h.Update="Update",h.CreateOrUpdate="CreateOrUpdate",h.Delete="Delete",h.DeleteWithFilter="DeleteWithFilter",h))(W||{});class Ce{static{g(this,"ActionItemInput")}}class ve{static{g(this,"SyncDataResult")}constructor(){this.Results=[]}}class $e{static{g(this,"ActionItemOutput")}}class Pe{static{g(this,"GraphQLSystemUserClient")}get Client(){return this._client}constructor(e,t,s,r){const n={"x-session-id":s};this._sessionId=s,t&&(n.authorization="Bearer "+t),r&&(n["x-mj-api-key"]=r),this._client=new L(e,{headers:n})}resolvePlatformSQL(e){if(e!=null)return ie(e)?e.default:e}async GetData(e,t){try{const r=await this.Client.request(`query GetData($input: GetDataInputType!) {
566
+ }`;try{const n=await this.ExecuteGQL(r,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntities?.Success&&n.FindISAChildEntities.ChildEntityNames?n.FindISAChildEntities.ChildEntityNames.map(a=>({ChildEntityName:a})):[]}catch(n){return l(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function De(h){const e=new S;return ae(e),await e.Config(h),V.Instance.RaiseEvent({event:_.LoggedIn,eventCode:null,component:this,args:null}),await oe.Instance.Startup(),e}g(De,"setupGraphQLClient");class Re{static{g(this,"SyncRolesAndUsersResult")}}class Ee{static{g(this,"RoleInput")}}class we{static{g(this,"UserInput")}}class ve{static{g(this,"RolesAndUsersInput")}}var W=(h=>(h.Create="Create",h.Update="Update",h.CreateOrUpdate="CreateOrUpdate",h.Delete="Delete",h.DeleteWithFilter="DeleteWithFilter",h))(W||{});class Ce{static{g(this,"ActionItemInput")}}class $e{static{g(this,"SyncDataResult")}constructor(){this.Results=[]}}class Pe{static{g(this,"ActionItemOutput")}}class be{static{g(this,"GraphQLSystemUserClient")}get Client(){return this._client}constructor(e,t,s,r){const n={"x-session-id":s};this._sessionId=s,t&&(n.authorization="Bearer "+t),r&&(n["x-mj-api-key"]=r),this._client=new L(e,{headers:n})}resolvePlatformSQL(e){if(e!=null)return ie(e)?e.default:e}async GetData(e,t){try{const r=await this.Client.request(`query GetData($input: GetDataInputType!) {
507
567
  GetData(input: $input) {
508
568
  Success
509
569
  ErrorMessages
510
570
  Queries
511
571
  Results
512
572
  }
513
- }`,{input:{Queries:e,Token:t}});return r&&r.GetData?{Success:r.GetData.Success,Results:r.GetData.Results.map(n=>n?v(n):null),ErrorMessages:r.GetData.ErrorMessages,Queries:r.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:r.GetData?.ErrorMessages??["Unknown error"],Queries:r.GetData?.Queries??e}}catch(s){let r=s instanceof Error?s.message:String(s);const n=r.match(/Error: ([^:]+)\./);if(n&&(r=n[1]+"."),ce()){const a=`GraphQLSystemUserClient::GetData - Error getting data - ${s}`;l(a)}return{Success:!1,Results:[],ErrorMessages:[r],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
573
+ }`,{input:{Queries:e,Token:t}});return r&&r.GetData?{Success:r.GetData.Success,Results:r.GetData.Results.map(n=>n?C(n):null),ErrorMessages:r.GetData.ErrorMessages,Queries:r.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:r.GetData?.ErrorMessages??["Unknown error"],Queries:r.GetData?.Queries??e}}catch(s){let r=s instanceof Error?s.message:String(s);const n=r.match(/Error: ([^:]+)\./);if(n&&(r=n[1]+"."),ce()){const a=`GraphQLSystemUserClient::GetData - Error getting data - ${s}`;l(a)}return{Success:!1,Results:[],ErrorMessages:[r],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
514
574
  GetAllEntities {
515
575
  Success
516
576
  ErrorMessage
@@ -641,7 +701,7 @@ var H=Object.defineProperty;var g=(h,e)=>H(h,"name",{value:e,configurable:!0});i
641
701
  ErrorMessage
642
702
  AppliedParameters
643
703
  }
644
- }`,s={QueryID:e.QueryID};e.CategoryID!==void 0&&(s.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(s.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(s.Parameters=e.Parameters),e.MaxRows!==void 0&&(s.MaxRows=e.MaxRows),e.StartRow!==void 0&&(s.StartRow=e.StartRow);const r=await this.Client.request(t,s);return r&&r.GetQueryDataSystemUser?{...r.GetQueryDataSystemUser,Results:r.GetQueryDataSystemUser.Results?v(r.GetQueryDataSystemUser.Results):null}:{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return l(`GraphQLSystemUserClient::GetQueryDataSystemUser - Error executing query - ${t}`),{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async GetQueryDataByName(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataByNameSystemUser($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
704
+ }`,s={QueryID:e.QueryID};e.CategoryID!==void 0&&(s.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(s.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(s.Parameters=e.Parameters),e.MaxRows!==void 0&&(s.MaxRows=e.MaxRows),e.StartRow!==void 0&&(s.StartRow=e.StartRow);const r=await this.Client.request(t,s);return r&&r.GetQueryDataSystemUser?{...r.GetQueryDataSystemUser,Results:r.GetQueryDataSystemUser.Results?C(r.GetQueryDataSystemUser.Results):null}:{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return l(`GraphQLSystemUserClient::GetQueryDataSystemUser - Error executing query - ${t}`),{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async GetQueryDataByName(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataByNameSystemUser($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
645
705
  GetQueryDataByNameSystemUser(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
646
706
  QueryID
647
707
  QueryName
@@ -653,7 +713,7 @@ var H=Object.defineProperty;var g=(h,e)=>H(h,"name",{value:e,configurable:!0});i
653
713
  ErrorMessage
654
714
  AppliedParameters
655
715
  }
656
- }`,s={QueryName:e.QueryName};e.CategoryID!==void 0&&(s.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(s.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(s.Parameters=e.Parameters),e.MaxRows!==void 0&&(s.MaxRows=e.MaxRows),e.StartRow!==void 0&&(s.StartRow=e.StartRow);const r=await this.Client.request(t,s);return r&&r.GetQueryDataByNameSystemUser?{...r.GetQueryDataByNameSystemUser,Results:r.GetQueryDataByNameSystemUser.Results?v(r.GetQueryDataByNameSystemUser.Results):null}:{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return l(`GraphQLSystemUserClient::GetQueryDataByNameSystemUser - Error executing query - ${t}`),{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async CreateQuery(e){try{const s=await this.Client.request(`mutation CreateQuerySystemUser($input: CreateQuerySystemUserInput!) {
716
+ }`,s={QueryName:e.QueryName};e.CategoryID!==void 0&&(s.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(s.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(s.Parameters=e.Parameters),e.MaxRows!==void 0&&(s.MaxRows=e.MaxRows),e.StartRow!==void 0&&(s.StartRow=e.StartRow);const r=await this.Client.request(t,s);return r&&r.GetQueryDataByNameSystemUser?{...r.GetQueryDataByNameSystemUser,Results:r.GetQueryDataByNameSystemUser.Results?C(r.GetQueryDataByNameSystemUser.Results):null}:{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return l(`GraphQLSystemUserClient::GetQueryDataByNameSystemUser - Error executing query - ${t}`),{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async CreateQuery(e){try{const s=await this.Client.request(`mutation CreateQuerySystemUser($input: CreateQuerySystemUserInput!) {
657
717
  CreateQuerySystemUser(input: $input) {
658
718
  Success
659
719
  ErrorMessage
@@ -864,7 +924,7 @@ var H=Object.defineProperty;var g=(h,e)=>H(h,"name",{value:e,configurable:!0});i
864
924
  result
865
925
  }
866
926
  }
867
- `,s=this.prepareAgentVariables(e),r=await this.Client.request(t,s);return r&&r.RunAIAgentSystemUser?this.processAgentResult(r.RunAIAgentSystemUser.result):{success:!1,agentRun:void 0}}catch(t){return l(`GraphQLSystemUserClient::RunAIAgent - Error running AI agent - ${t}`),{success:!1,agentRun:void 0}}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}prepareAgentVariables(e){const t={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._sessionId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),t}processPromptResult(e){let t,s,r;try{e.parsedResult&&(t=JSON.parse(e.parsedResult))}catch{t=e.parsedResult}try{e.validationResult&&(s=JSON.parse(e.validationResult))}catch{s=e.validationResult}try{e.chatResult&&(r=JSON.parse(e.chatResult))}catch{r=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:s,chatResult:r}}processAgentResult(e){return v(e)}async TestQuerySQL(e){try{const s=await this.Client.request(`query TestQuerySQL($input: TestQuerySQLInput!) {
927
+ `,s=this.prepareAgentVariables(e),r=await this.Client.request(t,s);return r&&r.RunAIAgentSystemUser?this.processAgentResult(r.RunAIAgentSystemUser.result):{success:!1,agentRun:void 0}}catch(t){return l(`GraphQLSystemUserClient::RunAIAgent - Error running AI agent - ${t}`),{success:!1,agentRun:void 0}}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}prepareAgentVariables(e){const t={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._sessionId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),t}processPromptResult(e){let t,s,r;try{e.parsedResult&&(t=JSON.parse(e.parsedResult))}catch{t=e.parsedResult}try{e.validationResult&&(s=JSON.parse(e.validationResult))}catch{s=e.validationResult}try{e.chatResult&&(r=JSON.parse(e.chatResult))}catch{r=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:s,chatResult:r}}processAgentResult(e){return C(e)}async TestQuerySQL(e){try{const s=await this.Client.request(`query TestQuerySQL($input: TestQuerySQLInput!) {
868
928
  TestQuerySQL(input: $input) {
869
929
  Success
870
930
  Results
@@ -873,7 +933,7 @@ var H=Object.defineProperty;var g=(h,e)=>H(h,"name",{value:e,configurable:!0});i
873
933
  ErrorMessage
874
934
  AppliedParameters
875
935
  }
876
- }`,{input:e});return s&&s.TestQuerySQL?{Success:s.TestQuerySQL.Success,Results:s.TestQuerySQL.Results?v(s.TestQuerySQL.Results):null,RowCount:s.TestQuerySQL.RowCount,ExecutionTime:s.TestQuerySQL.ExecutionTime,ErrorMessage:s.TestQuerySQL.ErrorMessage,AppliedParameters:s.TestQuerySQL.AppliedParameters?v(s.TestQuerySQL.AppliedParameters):void 0}:{Success:!1,Results:null,RowCount:0,ExecutionTime:0,ErrorMessage:"TestQuerySQL execution failed"}}catch(t){return l(`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=c`
936
+ }`,{input:e});return s&&s.TestQuerySQL?{Success:s.TestQuerySQL.Success,Results:s.TestQuerySQL.Results?C(s.TestQuerySQL.Results):null,RowCount:s.TestQuerySQL.RowCount,ExecutionTime:s.TestQuerySQL.ExecutionTime,ErrorMessage:s.TestQuerySQL.ErrorMessage,AppliedParameters:s.TestQuerySQL.AppliedParameters?C(s.TestQuerySQL.AppliedParameters):void 0}:{Success:!1,Results:null,RowCount:0,ExecutionTime:0,ErrorMessage:"TestQuerySQL execution failed"}}catch(t){return l(`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=c`
877
937
  query ExecuteSimplePromptSystemUser(
878
938
  $systemPrompt: String!,
879
939
  $messages: String,
@@ -911,7 +971,7 @@ var H=Object.defineProperty;var g=(h,e)=>H(h,"name",{value:e,configurable:!0});i
911
971
  error
912
972
  }
913
973
  }
914
- `,r={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this.Client.request(t,r);if(!n?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const a=n.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?a.embeddings:a.embeddings[0],modelName:a.modelName,vectorDimensions:a.vectorDimensions,error:a.error}}catch(t){return l(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}}class be{static{g(this,"GetDataOutput")}}class Ae{static{g(this,"SimpleRemoteEntityOutput")}}class Ne{static{g(this,"SimpleRemoteEntity")}}class Me{static{g(this,"SimpleRemoteEntityField")}}class xe{static{g(this,"GraphQLActionClient")}constructor(e){this._dataProvider=e}async RunAction(e,t,s=!1){try{const r=this.serializeActionParameters(t),n=this.createActionVariables(e,r,s),a=await this.executeActionMutation(n);return this.processActionResult(a,t)}catch(r){return this.handleActionError(r,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let s=t.Value;return s!=null&&typeof s=="object"&&(s=JSON.stringify(s)),{...t,Value:s}})}createActionVariables(e,t,s=!1){return{input:{ActionID:e,Params:t,SkipActionLog:s}}}async executeActionMutation(e){const t=c`
974
+ `,r={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this.Client.request(t,r);if(!n?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const a=n.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?a.embeddings:a.embeddings[0],modelName:a.modelName,vectorDimensions:a.vectorDimensions,error:a.error}}catch(t){return l(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}}class Ae{static{g(this,"GetDataOutput")}}class Ne{static{g(this,"SimpleRemoteEntityOutput")}}class Me{static{g(this,"SimpleRemoteEntity")}}class xe{static{g(this,"SimpleRemoteEntityField")}}class Te{static{g(this,"GraphQLActionClient")}constructor(e){this._dataProvider=e}async RunAction(e,t,s=!1){try{const r=this.serializeActionParameters(t),n=this.createActionVariables(e,r,s),a=await this.executeActionMutation(n);return this.processActionResult(a,t)}catch(r){return this.handleActionError(r,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let s=t.Value;return s!=null&&typeof s=="object"&&(s=JSON.stringify(s)),{...t,Value:s}})}createActionVariables(e,t,s=!1){return{input:{ActionID:e,Params:t,SkipActionLog:s}}}async executeActionMutation(e){const t=c`
915
975
  mutation RunAction($input: RunActionInput!) {
916
976
  RunAction(input: $input) {
917
977
  Success
@@ -928,7 +988,7 @@ var H=Object.defineProperty;var g=(h,e)=>H(h,"name",{value:e,configurable:!0});i
928
988
  ResultData
929
989
  }
930
990
  }
931
- `;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(s){l(`Failed to parse entity action result data: ${s}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return l(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}}class Te{static{g(this,"GraphQLEncryptionClient")}constructor(e){this._dataProvider=e}async CreateAPIKey(e){try{const t=this.createAPIKeyVariables(e),s=await this.executeCreateAPIKeyMutation(t);return this.processCreateAPIKeyResult(s)}catch(t){return this.handleCreateAPIKeyError(t)}}createAPIKeyVariables(e){return{input:{Label:e.Label,Description:e.Description,ExpiresAt:e.ExpiresAt?.toISOString(),ScopeIDs:e.ScopeIDs}}}async executeCreateAPIKeyMutation(e){const t=c`
991
+ `;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(s){l(`Failed to parse entity action result data: ${s}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return l(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}}class Qe{static{g(this,"GraphQLEncryptionClient")}constructor(e){this._dataProvider=e}async CreateAPIKey(e){try{const t=this.createAPIKeyVariables(e),s=await this.executeCreateAPIKeyMutation(t);return this.processCreateAPIKeyResult(s)}catch(t){return this.handleCreateAPIKeyError(t)}}createAPIKeyVariables(e){return{input:{Label:e.Label,Description:e.Description,ExpiresAt:e.ExpiresAt?.toISOString(),ScopeIDs:e.ScopeIDs}}}async executeCreateAPIKeyMutation(e){const t=c`
932
992
  mutation CreateAPIKey($input: CreateAPIKeyInput!) {
933
993
  CreateAPIKey(input: $input) {
934
994
  Success
@@ -944,7 +1004,7 @@ var H=Object.defineProperty;var g=(h,e)=>H(h,"name",{value:e,configurable:!0});i
944
1004
  Error
945
1005
  }
946
1006
  }
947
- `,r=await this._dataProvider.ExecuteGQL(t,{apiKeyId:e});return r?.RevokeAPIKey?{Success:r.RevokeAPIKey.Success,Error:r.RevokeAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}catch(t){const s=t;return l(`Error revoking API key: ${s.message}`),{Success:!1,Error:`Error: ${s.message}`}}}}class Qe{static{g(this,"GraphQLTestingClient")}constructor(e){this._dataProvider=e}async RunTest(e){try{const t=this.buildRunTestMutation(),s=this.buildRunTestVariables(e);return await P.Execute({dataProvider:this._dataProvider,mutation:t,variables:s,mutationFieldName:"RunTest",operationLabel:"RunTest",validateAck:g(r=>r?.success===!0,"validateAck"),isCompletionEvent:g(r=>this.isTestCompletionEvent(r,e.testId),"isCompletionEvent"),extractResult:g(r=>this.extractTestResult(r),"extractResult"),onMessage:e.onProgress?r=>this.forwardTestProgress(r,e.onProgress):void 0,createErrorResult:g(r=>({success:!1,errorMessage:r,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTest")}}async RunTestSuite(e){try{const t=this.buildRunTestSuiteMutation(),s=this.buildRunTestSuiteVariables(e);return await P.Execute({dataProvider:this._dataProvider,mutation:t,variables:s,mutationFieldName:"RunTestSuite",operationLabel:"RunTestSuite",validateAck:g(r=>r?.success===!0,"validateAck"),isCompletionEvent:g(r=>this.isSuiteCompletionEvent(r,e.suiteId),"isCompletionEvent"),extractResult:g(r=>this.extractSuiteResult(r),"extractResult"),onMessage:e.onProgress?r=>this.forwardTestProgress(r,e.onProgress):void 0,createErrorResult:g(r=>({success:!1,errorMessage:r,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTestSuite")}}async IsTestRunning(e){try{const t=c`
1007
+ `,r=await this._dataProvider.ExecuteGQL(t,{apiKeyId:e});return r?.RevokeAPIKey?{Success:r.RevokeAPIKey.Success,Error:r.RevokeAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}catch(t){const s=t;return l(`Error revoking API key: ${s.message}`),{Success:!1,Error:`Error: ${s.message}`}}}}class Le{static{g(this,"GraphQLTestingClient")}constructor(e){this._dataProvider=e}async RunTest(e){try{const t=this.buildRunTestMutation(),s=this.buildRunTestVariables(e);return await P.Execute({dataProvider:this._dataProvider,mutation:t,variables:s,mutationFieldName:"RunTest",operationLabel:"RunTest",validateAck:g(r=>r?.success===!0,"validateAck"),isCompletionEvent:g(r=>this.isTestCompletionEvent(r,e.testId),"isCompletionEvent"),extractResult:g(r=>this.extractTestResult(r),"extractResult"),onMessage:e.onProgress?r=>this.forwardTestProgress(r,e.onProgress):void 0,createErrorResult:g(r=>({success:!1,errorMessage:r,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTest")}}async RunTestSuite(e){try{const t=this.buildRunTestSuiteMutation(),s=this.buildRunTestSuiteVariables(e);return await P.Execute({dataProvider:this._dataProvider,mutation:t,variables:s,mutationFieldName:"RunTestSuite",operationLabel:"RunTestSuite",validateAck:g(r=>r?.success===!0,"validateAck"),isCompletionEvent:g(r=>this.isSuiteCompletionEvent(r,e.suiteId),"isCompletionEvent"),extractResult:g(r=>this.extractSuiteResult(r),"extractResult"),onMessage:e.onProgress?r=>this.forwardTestProgress(r,e.onProgress):void 0,createErrorResult:g(r=>({success:!1,errorMessage:r,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTestSuite")}}async IsTestRunning(e){try{const t=c`
948
1008
  query IsTestRunning($testId: String!) {
949
1009
  IsTestRunning(testId: $testId)
950
1010
  }
@@ -1002,7 +1062,7 @@ var H=Object.defineProperty;var g=(h,e)=>H(h,"name",{value:e,configurable:!0});i
1002
1062
  result
1003
1063
  }
1004
1064
  }
1005
- `}buildRunTestVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,s=e.variables?JSON.stringify(e.variables):void 0;return{testId:e.testId,verbose:e.verbose,environment:e.environment,tags:t,variables:s,fireAndForget:!0}}buildRunTestSuiteVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,s=e.variables?JSON.stringify(e.variables):void 0,r=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:s,selectedTestIds:r,sequenceStart:e.sequenceStart,sequenceEnd:e.sequenceEnd,fireAndForget:!0}}isTestCompletionEvent(e,t){const s=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetComplete"&&s?.type==="complete"&&s?.testId===t}isSuiteCompletionEvent(e,t){const s=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetSuiteComplete"&&s?.type==="complete"&&s?.suiteId===t}extractTestResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?v(t.result):null}}extractSuiteResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?v(t.result):null}}forwardTestProgress(e,t){if(e.resolver==="RunTestResolver"&&e.type==="TestExecutionProgress"&&e.status==="ok"){const r=e.data?.progress;r&&t(r)}}handleError(e,t){const s=e.message;return l(`${t} failed: ${s}`),{success:!1,errorMessage:s.includes("Failed to fetch")||s.includes("NetworkError")?"Lost connection to the server. The test may still be running. Please refresh to check the latest status.":s,result:null}}}class Le{static{g(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=c`
1065
+ `}buildRunTestVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,s=e.variables?JSON.stringify(e.variables):void 0;return{testId:e.testId,verbose:e.verbose,environment:e.environment,tags:t,variables:s,fireAndForget:!0}}buildRunTestSuiteVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,s=e.variables?JSON.stringify(e.variables):void 0,r=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:s,selectedTestIds:r,sequenceStart:e.sequenceStart,sequenceEnd:e.sequenceEnd,fireAndForget:!0}}isTestCompletionEvent(e,t){const s=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetComplete"&&s?.type==="complete"&&s?.testId===t}isSuiteCompletionEvent(e,t){const s=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetSuiteComplete"&&s?.type==="complete"&&s?.suiteId===t}extractTestResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?C(t.result):null}}extractSuiteResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?C(t.result):null}}forwardTestProgress(e,t){if(e.resolver==="RunTestResolver"&&e.type==="TestExecutionProgress"&&e.status==="ok"){const r=e.data?.progress;r&&t(r)}}handleError(e,t){const s=e.message;return l(`${t} failed: ${s}`),{success:!1,errorMessage:s.includes("Failed to fetch")||s.includes("NetworkError")?"Lost connection to the server. The test may still be running. Please refresh to check the latest status.":s,result:null}}}class Fe{static{g(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=c`
1006
1066
  query GetRegistryComponent(
1007
1067
  $registryName: String!,
1008
1068
  $namespace: String!,
@@ -1086,7 +1146,7 @@ var H=Object.defineProperty;var g=(h,e)=>H(h,"name",{value:e,configurable:!0});i
1086
1146
  error
1087
1147
  }
1088
1148
  }
1089
- `,s=await this._dataProvider.ExecuteGQL(t,{feedback:e});return s&&s.SendComponentFeedback?s.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return l(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}}class Fe{static{g(this,"GraphQLVersionHistoryClient")}constructor(e){this._dataProvider=e}async CreateLabel(e){let t;try{e.OnProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(a=>{try{const i=JSON.parse(a);i.resolver==="VersionHistoryResolver"&&i.type==="CreateLabelProgress"&&i.status==="ok"&&i.data&&e.OnProgress(i.data)}catch{}}));const s=c`
1149
+ `,s=await this._dataProvider.ExecuteGQL(t,{feedback:e});return s&&s.SendComponentFeedback?s.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return l(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}}class Ue{static{g(this,"GraphQLVersionHistoryClient")}constructor(e){this._dataProvider=e}async CreateLabel(e){let t;try{e.OnProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(a=>{try{const i=JSON.parse(a);i.resolver==="VersionHistoryResolver"&&i.type==="CreateLabelProgress"&&i.status==="ok"&&i.data&&e.OnProgress(i.data)}catch{}}));const s=c`
1090
1150
  mutation CreateVersionLabel($input: CreateVersionLabelInput!, $sessionId: String) {
1091
1151
  CreateVersionLabel(input: $input, sessionId: $sessionId) {
1092
1152
  Success
@@ -1102,7 +1162,7 @@ var H=Object.defineProperty;var g=(h,e)=>H(h,"name",{value:e,configurable:!0});i
1102
1162
  }
1103
1163
  }
1104
1164
  }
1105
- `,r={input:this.buildInput(e),sessionId:this._dataProvider.sessionId},n=await this._dataProvider.ExecuteGQL(s,r);return this.processResult(n)}catch(s){const r=s instanceof Error?s.message:String(s);return l(`GraphQLVersionHistoryClient.CreateLabel error: ${r}`),{Success:!1,Error:r}}finally{t&&t.unsubscribe()}}buildInput(e){const t={Name:e.Name};return e.Description!=null&&(t.Description=e.Description),e.Scope!=null&&(t.Scope=e.Scope),e.EntityName!=null&&(t.EntityName=e.EntityName),e.ParentID!=null&&(t.ParentID=e.ParentID),e.ExternalSystemID!=null&&(t.ExternalSystemID=e.ExternalSystemID),e.IncludeDependencies!=null&&(t.IncludeDependencies=e.IncludeDependencies),e.MaxDepth!=null&&(t.MaxDepth=e.MaxDepth),e.ExcludeEntities!=null&&(t.ExcludeEntities=e.ExcludeEntities),e.RecordKeys&&e.RecordKeys.length>0&&(t.RecordKeys=e.RecordKeys.map(s=>({Key:s.Key,Value:s.Value}))),t}processResult(e){const t=e?.CreateVersionLabel;if(!t)return{Success:!1,Error:"Invalid response from server."};const s=Array.isArray(t.CaptureErrors)?t.CaptureErrors.map(r=>({EntityName:r.EntityName??"",RecordID:r.RecordID??"",ErrorMessage:r.ErrorMessage??""})):void 0;return{Success:t.Success,LabelID:t.LabelID,LabelName:t.LabelName,ItemsCaptured:t.ItemsCaptured,SyntheticSnapshotsCreated:t.SyntheticSnapshotsCreated,Error:t.Error,CaptureErrors:s}}}class Ue{static{g(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",s){try{const r=c`
1165
+ `,r={input:this.buildInput(e),sessionId:this._dataProvider.sessionId},n=await this._dataProvider.ExecuteGQL(s,r);return this.processResult(n)}catch(s){const r=s instanceof Error?s.message:String(s);return l(`GraphQLVersionHistoryClient.CreateLabel error: ${r}`),{Success:!1,Error:r}}finally{t&&t.unsubscribe()}}buildInput(e){const t={Name:e.Name};return e.Description!=null&&(t.Description=e.Description),e.Scope!=null&&(t.Scope=e.Scope),e.EntityName!=null&&(t.EntityName=e.EntityName),e.ParentID!=null&&(t.ParentID=e.ParentID),e.ExternalSystemID!=null&&(t.ExternalSystemID=e.ExternalSystemID),e.IncludeDependencies!=null&&(t.IncludeDependencies=e.IncludeDependencies),e.MaxDepth!=null&&(t.MaxDepth=e.MaxDepth),e.ExcludeEntities!=null&&(t.ExcludeEntities=e.ExcludeEntities),e.RecordKeys&&e.RecordKeys.length>0&&(t.RecordKeys=e.RecordKeys.map(s=>({Key:s.Key,Value:s.Value}))),t}processResult(e){const t=e?.CreateVersionLabel;if(!t)return{Success:!1,Error:"Invalid response from server."};const s=Array.isArray(t.CaptureErrors)?t.CaptureErrors.map(r=>({EntityName:r.EntityName??"",RecordID:r.RecordID??"",ErrorMessage:r.ErrorMessage??""})):void 0;return{Success:t.Success,LabelID:t.LabelID,LabelName:t.LabelName,ItemsCaptured:t.ItemsCaptured,SyntheticSnapshotsCreated:t.SyntheticSnapshotsCreated,Error:t.Error,CaptureErrors:s}}}class Ge{static{g(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",s){try{const r=c`
1106
1166
  query ListStorageObjects($input: ListStorageObjectsInput!) {
1107
1167
  ListStorageObjects(input: $input) {
1108
1168
  objects {
@@ -1186,7 +1246,7 @@ var H=Object.defineProperty;var g=(h,e)=>H(h,"name",{value:e,configurable:!0});i
1186
1246
  failedAccounts
1187
1247
  }
1188
1248
  }
1189
- `,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:s?.maxResultsPerAccount,FileTypes:s?.fileTypes,SearchContent:s?.searchContent}},a=await this._dataProvider.ExecuteGQL(r,n);if(!a?.SearchAcrossAccounts)throw new Error("Invalid response from server");const i=a.SearchAcrossAccounts;return{accountResults:i.accountResults.map(o=>({accountId:o.accountID,accountName:o.accountName,success:o.success,errorMessage:o.errorMessage,results:o.results.map(u=>({path:u.path,name:u.name,size:u.size,contentType:u.contentType,lastModified:new Date(u.lastModified),relevance:u.relevance,excerpt:u.excerpt,matchInFilename:u.matchInFilename,objectId:u.objectId})),totalMatches:o.totalMatches,hasMore:o.hasMore,nextPageToken:o.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(r){return l(`Error searching across accounts: ${r}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}class Ge{static{g(this,"GraphQLIntegrationClient")}constructor(e){this._dataProvider=e}async DiscoverObjects(e){try{const t=c`
1249
+ `,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:s?.maxResultsPerAccount,FileTypes:s?.fileTypes,SearchContent:s?.searchContent}},a=await this._dataProvider.ExecuteGQL(r,n);if(!a?.SearchAcrossAccounts)throw new Error("Invalid response from server");const i=a.SearchAcrossAccounts;return{accountResults:i.accountResults.map(o=>({accountId:o.accountID,accountName:o.accountName,success:o.success,errorMessage:o.errorMessage,results:o.results.map(u=>({path:u.path,name:u.name,size:u.size,contentType:u.contentType,lastModified:new Date(u.lastModified),relevance:u.relevance,excerpt:u.excerpt,matchInFilename:u.matchInFilename,objectId:u.objectId})),totalMatches:o.totalMatches,hasMore:o.hasMore,nextPageToken:o.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(r){return l(`Error searching across accounts: ${r}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}class Ve{static{g(this,"GraphQLIntegrationClient")}constructor(e){this._dataProvider=e}async DiscoverObjects(e){try{const t=c`
1190
1250
  query IntegrationDiscoverObjects($companyIntegrationID: String!) {
1191
1251
  IntegrationDiscoverObjects(companyIntegrationID: $companyIntegrationID) {
1192
1252
  Success
@@ -1345,5 +1405,5 @@ var H=Object.defineProperty;var g=(h,e)=>H(h,"name",{value:e,configurable:!0});i
1345
1405
  IntegrationGetConnectorCapabilities(companyIntegrationID: $companyIntegrationID) {
1346
1406
  Success Message SupportsGet SupportsCreate SupportsUpdate SupportsDelete SupportsSearch
1347
1407
  }
1348
- }`;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 s=e;return l(`Error in integration discovery: ${s}`),{Success:!1,Message:`Error: ${s.message}`,Data:t}}}export{Ce as ActionItemInput,$e as ActionItemOutput,J as BrowserIndexedDBStorageProvider,B as BrowserStorageProviderBase,w as FieldMapper,P as FireAndForgetHelper,be as GetDataOutput,k as GraphQLAIClient,xe as GraphQLActionClient,Le as GraphQLComponentRegistryClient,S as GraphQLDataProvider,Te as GraphQLEncryptionClient,Ue as GraphQLFileStorageClient,Ge as GraphQLIntegrationClient,Ie as GraphQLProviderConfigData,Pe as GraphQLSystemUserClient,Qe as GraphQLTestingClient,q as GraphQLTransactionGroup,Fe as GraphQLVersionHistoryClient,De as RoleInput,we as RolesAndUsersInput,Ne as SimpleRemoteEntity,Me as SimpleRemoteEntityField,Ae as SimpleRemoteEntityOutput,W as SyncDataAction,ve as SyncDataResult,Re as SyncRolesAndUsersResult,Ee as UserInput,ze as gql,fe as setupGraphQLClient};
1408
+ }`;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 s=e;return l(`Error in integration discovery: ${s}`),{Success:!1,Message:`Error: ${s.message}`,Data:t}}}export{Ce as ActionItemInput,Pe as ActionItemOutput,J as BrowserIndexedDBStorageProvider,B as BrowserStorageProviderBase,w as FieldMapper,P as FireAndForgetHelper,Ae as GetDataOutput,k as GraphQLAIClient,Te as GraphQLActionClient,Fe as GraphQLComponentRegistryClient,S as GraphQLDataProvider,Qe as GraphQLEncryptionClient,Ge as GraphQLFileStorageClient,Ve as GraphQLIntegrationClient,fe as GraphQLProviderConfigData,be as GraphQLSystemUserClient,Le as GraphQLTestingClient,O as GraphQLTransactionGroup,Ue as GraphQLVersionHistoryClient,Ee as RoleInput,ve as RolesAndUsersInput,Me as SimpleRemoteEntity,xe as SimpleRemoteEntityField,Ne as SimpleRemoteEntityOutput,W as SyncDataAction,$e as SyncDataResult,Re as SyncRolesAndUsersResult,we as UserInput,Xe as gql,De as setupGraphQLClient};
1349
1409
  //# sourceMappingURL=index.mjs.map