@memberjunction/graphql-dataprovider 5.39.0 → 5.40.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 re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0});import{gql as c,GraphQLClient as q}from"graphql-request";import{gql as mt}from"graphql-request";import{TransactionGroupBase as se,TransactionResult as ne,LogError as l,LogStatus as b,LogErrorEx as A,ProviderBase as ae,UserInfo as O,getGraphQLTypeNameBase as M,ProviderType as oe,BaseEntityResult as U,EntityFieldTSType as N,TransactionItem as k,CompositeKey as ie,UserRoleInfo as ce,InMemoryLocalStorageProvider as ue,BaseEntity as le,ProviderConfigDataBase as de,SetProvider as ye,StartupManager as me,IsPlatformSQL as ge,IsVerboseLoggingEnabled as pe}from"@memberjunction/core";import{SafeJSONParse as v,CleanAndParseJSON as Se,GetGlobalObjectStore as B,UUIDsEqual as he,MJGlobal as K,MJEventType as j}from"@memberjunction/global";import{ViewInfo as J}from"@memberjunction/core-entities";import{BehaviorSubject as Ie,Observable as T,Subject as fe,Subscription as Re}from"rxjs";import{createClient as De}from"graphql-ws";import{v4 as Ee}from"uuid";import{openDB as ve}from"@tempfix/idb";class w{static{y(this,"FieldMapper")}static{this.DB_PREFIX="__mj_"}static{this.GQL_PREFIX="_mj__"}constructor(){}MapFields(e){if(e)for(const t in e){const r=this.MapFieldName(t);r!==t&&(e[r]=e[t],delete e[t])}return e}MapFieldName(e){return e.startsWith(w.DB_PREFIX)?w.GQL_PREFIX+e.substring(w.DB_PREFIX.length):e}ReverseMapFieldName(e){return e.startsWith(w.GQL_PREFIX)?w.DB_PREFIX+e.substring(w.GQL_PREFIX.length):e}ReverseMapFields(e){for(const t in e){const r=this.ReverseMapFieldName(t);r!==t&&(e[r]=e[t],delete e[t])}return e}}class W extends se{static{y(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=c`
1
+ var re=Object.defineProperty;var d=(m,e)=>re(m,"name",{value:e,configurable:!0});import{gql as c,GraphQLClient as O}from"graphql-request";import{gql as St}from"graphql-request";import{TransactionGroupBase as se,TransactionResult as ne,LogError as l,LogStatus as M,LogErrorEx as A,ProviderBase as ae,UserInfo as q,getGraphQLTypeNameBase as N,ProviderType as oe,BaseEntityResult as U,EntityFieldTSType as b,TransactionItem as k,CompositeKey as ie,UserRoleInfo as ce,InMemoryLocalStorageProvider as ue,BaseEntity as le,ProviderConfigDataBase as de,SetProvider as ye,StartupManager as me,IsPlatformSQL as ge,IsVerboseLoggingEnabled as Se}from"@memberjunction/core";import{SafeJSONParse as E,CleanAndParseJSON as pe,GetGlobalObjectStore as B,UUIDsEqual as he,MJGlobal as K,MJEventType as j}from"@memberjunction/global";import{ViewInfo as J}from"@memberjunction/core-entities";import{BehaviorSubject as Ie,Observable as T,Subject as fe,Subscription as Re}from"rxjs";import{createClient as De}from"graphql-ws";import{v4 as Ee}from"uuid";import{openDB as ve}from"@tempfix/idb";class C{static{d(this,"FieldMapper")}static{this.DB_PREFIX="__mj_"}static{this.GQL_PREFIX="_mj__"}constructor(){}MapFields(e){if(e)for(const t in e){const r=this.MapFieldName(t);r!==t&&(e[r]=e[t],delete e[t])}return e}MapFieldName(e){return e.startsWith(C.DB_PREFIX)?C.GQL_PREFIX+e.substring(C.DB_PREFIX.length):e}ReverseMapFieldName(e){return e.startsWith(C.GQL_PREFIX)?C.DB_PREFIX+e.substring(C.GQL_PREFIX.length):e}ReverseMapFields(e){for(const t in e){const r=this.ReverseMapFieldName(t);r!==t&&(e[r]=e[t],delete e[t])}return e}}class W extends se{static{d(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 re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0})
6
6
  ResultsJSON
7
7
  }
8
8
  }
9
- `,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const r={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const n=s.ExecuteTransactionGroup,a=[];for(let i=0;i<this.PendingTransactions.length;i++){const o=n.ResultsJSON[i],d=v(o),u=this.PendingTransactions[i];a.push(new ne(u,d,d!==null))}return a}else throw new Error("Failed to execute transaction group")}}const we=720*1e3,Ce=6;class P{static{y(this,"FireAndForgetHelper")}static async Execute(e){const t=e.operationLabel??e.mutationFieldName,r=e.timeoutMs??we,s=e.maxStallReconciles??Ce;let n,a=!1,i=0;const{promise:o,resolve:d,reject:u}=P.createCompletionPromise(),f=y(p=>{a||(a=!0,g.clear(),p())},"finish"),R=y(p=>f(()=>d(p)),"settleResolve"),S=y(p=>f(()=>u(p)),"settleReject"),h=y(async()=>{if(a)return;if(!e.onStall){S(new Error(P.timeoutMessage(e.timeoutErrorMessage,r)));return}let p;try{b(`[FireAndForget:${t}] Idle window elapsed, reconciling against server run record`),p=await e.onStall()}catch(D){S(D);return}a||(p==="continue"?++i>s?S(new Error(`The operation is still reported as running but no signal has arrived after ${i} checks. Please refresh the page to check the latest status.`)):g.reset():"resolve"in p?(b(`[FireAndForget:${t}] Reconciliation recovered a completed run`),R(p.resolve)):S(p.reject))},"onStall"),g=P.createIdleTimer(r,()=>{h()});try{g.reset(),n=P.subscribeToPubSub(e,{onActivity:y(()=>{i=0,g.reset()},"onActivity"),onCompletion:y(D=>R(D),"onCompletion"),onStreamEnd:y(()=>{h()},"onStreamEnd")});const p=await P.executeMutation(e);if(!e.validateAck(p)){g.clear();const D=p?.errorMessage??"Server rejected the request";return l(`[FireAndForget:${t}] Server rejected: ${D}`),e.createErrorResult(D)}return b(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await o}catch(p){throw l(`[FireAndForget:${t}] Error: ${p.message}`),p}finally{g.clear(),n&&n.unsubscribe()}}static createCompletionPromise(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}static createIdleTimer(e,t){let r;return{reset:y(()=>{r&&clearTimeout(r),r=setTimeout(t,e)},"reset"),clear:y(()=>{r&&clearTimeout(r),r=void 0},"clear")}}static timeoutMessage(e,t){const r=Math.round(t/6e4);return e??`The operation may still be running on the server but the client received no updates for ${r} minutes. Please refresh the page to check the latest status.`}static subscribeToPubSub(e,t){const r=e.dataProvider.sessionId,s=e.operationLabel??e.mutationFieldName;return e.dataProvider.PushStatusUpdates(r).subscribe({next:y(n=>{t.onActivity();try{const a=JSON.parse(n);e.onMessage&&e.onMessage(a),e.isCompletionEvent(a)&&(b(`[FireAndForget:${s}] Completion event received`),t.onCompletion(e.extractResult(a)))}catch(a){console.error(`[FireAndForget:${s}] Failed to parse PubSub message:`,a)}},"next"),error:y(()=>t.onStreamEnd(),"error"),complete:y(()=>t.onStreamEnd(),"complete")})}static async executeMutation(e){return(await e.dataProvider.ExecuteGQL(e.mutation,e.variables))[e.mutationFieldName]}}class z{static{y(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 r={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const n=s.ExecuteTransactionGroup,a=[];for(let i=0;i<this.PendingTransactions.length;i++){const o=n.ResultsJSON[i],y=E(o),u=this.PendingTransactions[i];a.push(new ne(u,y,y!==null))}return a}else throw new Error("Failed to execute transaction group")}}const Ce=720*1e3,we=6;class P{static{d(this,"FireAndForgetHelper")}static async Execute(e){const t=e.operationLabel??e.mutationFieldName,r=e.timeoutMs??Ce,s=e.maxStallReconciles??we;let n,a=!1,i=0;const{promise:o,resolve:y,reject:u}=P.createCompletionPromise(),f=d(S=>{a||(a=!0,g.clear(),S())},"finish"),R=d(S=>f(()=>y(S)),"settleResolve"),p=d(S=>f(()=>u(S)),"settleReject"),h=d(async()=>{if(a)return;if(!e.onStall){p(new Error(P.timeoutMessage(e.timeoutErrorMessage,r)));return}let S;try{M(`[FireAndForget:${t}] Idle window elapsed, reconciling against server run record`),S=await e.onStall()}catch(D){p(D);return}a||(S==="continue"?++i>s?p(new Error(`The operation is still reported as running but no signal has arrived after ${i} checks. Please refresh the page to check the latest status.`)):g.reset():"resolve"in S?(M(`[FireAndForget:${t}] Reconciliation recovered a completed run`),R(S.resolve)):p(S.reject))},"onStall"),g=P.createIdleTimer(r,()=>{h()});try{g.reset(),n=P.subscribeToPubSub(e,{onActivity:d(()=>{i=0,g.reset()},"onActivity"),onCompletion:d(D=>R(D),"onCompletion"),onStreamEnd:d(()=>{h()},"onStreamEnd")});const S=await P.executeMutation(e);if(!e.validateAck(S)){g.clear();const D=S?.errorMessage??"Server rejected the request";return l(`[FireAndForget:${t}] Server rejected: ${D}`),e.createErrorResult(D)}return M(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await o}catch(S){throw l(`[FireAndForget:${t}] Error: ${S.message}`),S}finally{g.clear(),n&&n.unsubscribe()}}static createCompletionPromise(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}static createIdleTimer(e,t){let r;return{reset:d(()=>{r&&clearTimeout(r),r=setTimeout(t,e)},"reset"),clear:d(()=>{r&&clearTimeout(r),r=void 0},"clear")}}static timeoutMessage(e,t){const r=Math.round(t/6e4);return e??`The operation may still be running on the server but the client received no updates for ${r} minutes. Please refresh the page to check the latest status.`}static subscribeToPubSub(e,t){const r=e.dataProvider.sessionId,s=e.operationLabel??e.mutationFieldName;return e.dataProvider.PushStatusUpdates(r).subscribe({next:d(n=>{t.onActivity();try{const a=JSON.parse(n);e.onMessage&&e.onMessage(a),e.isCompletionEvent(a)&&(M(`[FireAndForget:${s}] Completion event received`),t.onCompletion(e.extractResult(a)))}catch(a){console.error(`[FireAndForget:${s}] Failed to parse PubSub message:`,a)}},"next"),error:d(()=>t.onStreamEnd(),"error"),complete:d(()=>t.onStreamEnd(),"complete")})}static async executeMutation(e){return(await e.dataProvider.ExecuteGQL(e.mutation,e.variables))[e.mutationFieldName]}}class z{static{d(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 re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0})
65
65
  chatResult
66
66
  }
67
67
  }
68
- `,r=this.preparePromptVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(s)}catch(t){return this.handlePromptError(t)}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,n;try{t.parsedResult&&(r=Se(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(n=JSON.parse(t.chatResult))}catch{n=t.chatResult}return{success:t.success,output:t.output,parsedResult:r,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:s,chatResult:n}}handlePromptError(e){const t=e;return l(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){try{const s=this.buildRunAIAgentMutation(),n=this.prepareAgentVariables(e,t,r);n.fireAndForget=!0;const a={};return await P.Execute({dataProvider:this._dataProvider,mutation:s,variables:n,mutationFieldName:"RunAIAgent",operationLabel:"RunAIAgent",validateAck:y(i=>i?.success===!0,"validateAck"),isCompletionEvent:y(i=>this.isAgentCompletionEvent(i),"isCompletionEvent"),extractResult:y(i=>this.extractAgentResult(i),"extractResult"),onMessage:y(i=>{this.captureAgentRunId(i,a),e.onProgress&&this.forwardAgentProgress(i,e.onProgress)},"onMessage"),onStall:y(()=>this.reconcileAgentRun(a.id?`ID='${a.id}'`:void 0),"onStall"),createErrorResult:y(i=>this.createAgentErrorResult(i),"createErrorResult")})}catch(s){return this.handleAgentError(s)}}buildRunAIAgentMutation(){return c`
68
+ `,r=this.preparePromptVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(s)}catch(t){return this.handlePromptError(t)}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,n;try{t.parsedResult&&(r=pe(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(n=JSON.parse(t.chatResult))}catch{n=t.chatResult}return{success:t.success,output:t.output,parsedResult:r,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:s,chatResult:n}}handlePromptError(e){const t=e;return l(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){try{const s=this.buildRunAIAgentMutation(),n=this.prepareAgentVariables(e,t,r);n.fireAndForget=!0;const a={};return await P.Execute({dataProvider:this._dataProvider,mutation:s,variables:n,mutationFieldName:"RunAIAgent",operationLabel:"RunAIAgent",validateAck:d(i=>i?.success===!0,"validateAck"),isCompletionEvent:d(i=>this.isAgentCompletionEvent(i),"isCompletionEvent"),extractResult:d(i=>this.extractAgentResult(i),"extractResult"),onMessage:d(i=>{this.captureAgentRunId(i,a),e.onProgress&&this.forwardAgentProgress(i,e.onProgress)},"onMessage"),onStall:d(()=>this.reconcileAgentRun(a.id?`ID='${a.id}'`:void 0),"onStall"),createErrorResult:d(i=>this.createAgentErrorResult(i),"createErrorResult")})}catch(s){return this.handleAgentError(s)}}buildRunAIAgentMutation(){return c`
69
69
  mutation RunAIAgent(
70
70
  $agentId: String!,
71
71
  $messages: String!,
@@ -106,7 +106,7 @@ var re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0})
106
106
  result
107
107
  }
108
108
  }
109
- `}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),t!==void 0&&(s.sourceArtifactId=t),r!==void 0&&(s.sourceArtifactVersionId=r),s}processAgentResult(e){return v(e)}handleAgentError(e){const r=e?.message||String(e);l(`Error running AI agent: ${r}`);const s=r.includes("Failed to fetch")||r.includes("NetworkError"),n=r.includes("timed out")||r.includes("timeout");let a;return s?a="Lost connection to the server. The agent may still be running. Please refresh to check the latest status.":a=r,{success:!1,agentRun:void 0,errorMessage:a}}async RunAIAgentFromConversationDetail(e){try{const t=this.buildConversationDetailMutation(),r=this.prepareConversationDetailVariables(e);return await P.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunAIAgentFromConversationDetail",operationLabel:"RunAIAgentFromConversationDetail",validateAck:y(s=>s?.success===!0,"validateAck"),isCompletionEvent:y(s=>this.isConversationDetailCompletionEvent(s,e.conversationDetailId),"isCompletionEvent"),extractResult:y(s=>this.extractAgentResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardConversationDetailProgress(s,e.onProgress):void 0,onStall:y(()=>this.reconcileAgentRun(`ConversationDetailID='${e.conversationDetailId}'`),"onStall"),createErrorResult:y(s=>this.createAgentErrorResult(s),"createErrorResult")})}catch(t){return this.handleAgentError(t)}}buildConversationDetailMutation(){return c`
109
+ `}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),t!==void 0&&(s.sourceArtifactId=t),r!==void 0&&(s.sourceArtifactVersionId=r),s}processAgentResult(e){return E(e)}handleAgentError(e){const r=e?.message||String(e);l(`Error running AI agent: ${r}`);const s=r.includes("Failed to fetch")||r.includes("NetworkError"),n=r.includes("timed out")||r.includes("timeout");let a;return s?a="Lost connection to the server. The agent may still be running. Please refresh to check the latest status.":a=r,{success:!1,agentRun:void 0,errorMessage:a}}async RunAIAgentFromConversationDetail(e){try{const t=this.buildConversationDetailMutation(),r=this.prepareConversationDetailVariables(e);return await P.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunAIAgentFromConversationDetail",operationLabel:"RunAIAgentFromConversationDetail",validateAck:d(s=>s?.success===!0,"validateAck"),isCompletionEvent:d(s=>this.isConversationDetailCompletionEvent(s,e.conversationDetailId),"isCompletionEvent"),extractResult:d(s=>this.extractAgentResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardConversationDetailProgress(s,e.onProgress):void 0,onStall:d(()=>this.reconcileAgentRun(`ConversationDetailID='${e.conversationDetailId}'`),"onStall"),createErrorResult:d(s=>this.createAgentErrorResult(s),"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 re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0})
145
145
  result
146
146
  }
147
147
  }
148
- `}prepareConversationDetailVariables(e){const t={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId,fireAndForget:!0};return e.maxHistoryMessages!==void 0&&(t.maxHistoryMessages=e.maxHistoryMessages),e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(t.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.createArtifacts!==void 0&&(t.createArtifacts=e.createArtifacts),e.createNotification!==void 0&&(t.createNotification=e.createNotification),e.sourceArtifactId!==void 0&&(t.sourceArtifactId=e.sourceArtifactId),e.sourceArtifactVersionId!==void 0&&(t.sourceArtifactVersionId=e.sourceArtifactVersionId),t}isAgentCompletionEvent(e){const t=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&t?.type==="complete"}isConversationDetailCompletionEvent(e,t){const r=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&r?.type==="complete"&&r?.conversationDetailId===t}captureAgentRunId(e,t){const r=e.data,s=r?.agentRunId??r?.runId;s&&s!=="unknown"&&(t.id=s)}async reconcileAgentRun(e){if(!e)return"continue";const t=await this._dataProvider.RunView({EntityName:"MJ: AI Agent Runs",ExtraFilter:e,OrderBy:"__mj_CreatedAt DESC",ResultType:"entity_object",BypassCache:!0}),r=t.Success?t.Results?.[0]:void 0;return!r||r.Status==="Running"?"continue":{resolve:{success:r.Status==="Completed"||r.Status==="Paused"||r.Status==="AwaitingFeedback",agentRun:r,payload:r.Result?v(r.Result)??void 0:void 0,errorMessage:r.ErrorMessage??void 0}}}extractAgentResult(e){const t=e.data,r=t.result;return r?v(r):{success:t.success,agentRun:void 0}}forwardAgentProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const s=e.data?.progress;s&&t({step:s.currentStep,percentage:s.percentage,message:s.message,metadata:s})}forwardConversationDetailProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const r=e.data,s=r?.progress;s&&t({currentStep:s.currentStep,percentage:s.percentage,message:s.message,metadata:{...s,agentRun:r?.agentRun,agentRunId:r?.agentRunId}})}createAgentErrorResult(e){return{success:!1,agentRun:void 0,errorMessage:e}}async ExecuteSimplePrompt(e){try{const t=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 r=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&r?.type==="complete"&&r?.conversationDetailId===t}captureAgentRunId(e,t){const r=e.data,s=r?.agentRunId??r?.runId;s&&s!=="unknown"&&(t.id=s)}async reconcileAgentRun(e){if(!e)return"continue";const t=await this._dataProvider.RunView({EntityName:"MJ: AI Agent Runs",ExtraFilter:e,OrderBy:"__mj_CreatedAt DESC",ResultType:"entity_object",BypassCache:!0}),r=t.Success?t.Results?.[0]:void 0;return!r||r.Status==="Running"?"continue":{resolve:{success:r.Status==="Completed"||r.Status==="Paused"||r.Status==="AwaitingFeedback",agentRun:r,payload:r.Result?E(r.Result)??void 0:void 0,errorMessage:r.ErrorMessage??void 0}}}extractAgentResult(e){const t=e.data,r=t.result;return r?E(r):{success:t.success,agentRun:void 0}}forwardAgentProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const s=e.data?.progress;s&&t({step:s.currentStep,percentage:s.percentage,message:s.message,metadata:s})}forwardConversationDetailProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const r=e.data,s=r?.progress;s&&t({currentStep:s.currentStep,percentage:s.percentage,message:s.message,metadata:{...s,agentRun:r?.agentRun,agentRunId:r?.agentRunId}})}createAgentErrorResult(e){return{success:!1,agentRun:void 0,errorMessage:e}}async ExecuteSimplePrompt(e){try{const t=c`
149
149
  mutation ExecuteSimplePrompt(
150
150
  $systemPrompt: String!,
151
151
  $messages: String,
@@ -297,7 +297,7 @@ var re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0})
297
297
  }
298
298
  }
299
299
  }
300
- `,r={entityDocumentID:e.entityDocumentID};e.maxRecords!==void 0&&(r.maxRecords=e.maxRecords),e.filter!==void 0&&(r.filter=e.filter);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.FetchEntityVectors)throw new Error("Invalid response from server");return s.FetchEntityVectors}catch(t){const r=t;return l("GraphQLAIClient.FetchEntityVectors failed",void 0,r),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,ErrorMessage:r.message||"Unknown error"}}}}const L="5.39.0",$="default";class H{static{y(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||$;let r=this._storage.get(t);return r||(r=new Map,this._storage.set(t,r)),r}async GetItem(e,t){const s=this.getCategoryMap(t||$).get(e);return s===void 0?null:s}async GetItems(e,t){const r=new Map;if(e.length===0)return r;const s=this.getCategoryMap(t||$);for(const n of new Set(e)){const a=s.get(n);r.set(n,a===void 0?null:a)}return r}async SetItem(e,t,r){this.getCategoryMap(r||$).set(e,t)}async Remove(e,t){this.getCategoryMap(t||$).delete(e)}async ClearCategory(e){const t=e||$;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||$);return t?Array.from(t.keys()):[]}}const $e="MJ_Metadata",Pe=0;function Ae(){try{const m=L.split("."),e=parseInt(m[0],10),t=parseInt(m[1],10);if(!Number.isFinite(e)||!Number.isFinite(t))throw new Error(`Could not parse major.minor from version "${L}"`);return e*1e3+t+Pe}catch(m){return A({error:m,message:"Failed to derive IDB version from PACKAGE_VERSION; using fallback 99999"}),99999}}y(Ae,"computeIdbVersion");const be=Ae(),X=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"];class Y extends H{static{y(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=ve($e,be,{upgrade:y((e,t,r)=>{try{b(`[IDBCache] Upgrading IndexedDB schema v${t} \u2192 v${r} (package ${L}). Dropping all stores; caches will repopulate on first use.`);for(const s of Array.from(e.objectStoreNames))e.deleteObjectStore(s);for(const s of X)e.objectStoreNames.contains(s)||e.createObjectStore(s)}catch(s){A({error:s,message:s?.message})}},"upgrade"),blocked:y((e,t)=>{b(`[IDBCache] Upgrade from v${e} to v${t} blocked by another tab. Close other tabs to allow the upgrade to proceed.`)},"blocked")}),this.dbPromise.then(e=>{this._dbReady=!0,e.onversionchange=()=>{b("[IDBCache] DB schema upgraded in another tab \u2014 closing local connection."),e.close(),this._dbReady=!1}}).catch(e=>{A({error:e,message:"IndexedDB initialization failed: "+e?.message})})}get IsReady(){return this._dbReady}isKnownCategory(e){const t=`mj:${e}`;return X.includes(t)}getStoreName(e){const t=e||$;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||$;return this.isKnownCategory(r)?e:`[${r}]:${e}`}async SetItem(e,t,r){try{const s=await this.dbPromise,n=this.getStoreName(r),a=this.getStoreKey(e,r),i=s.transaction(n,"readwrite");await i.objectStore(n).put(t,a),await i.done}catch(s){A({error:s,message:s?.message})}}async GetItem(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t),a=await r.transaction(s).objectStore(s).get(n);return a===void 0?null:a}catch(r){return A({error:r,message:r?.message}),null}}async GetItems(e,t){const r=new Map;if(e.length===0)return r;try{const s=await this.dbPromise,n=this.getStoreName(t),a=Array.from(new Set(e)),i=a.map(R=>this.getStoreKey(R,t)),o=s.transaction(n,"readonly"),d=o.objectStore(n),u=i.map(R=>d.get(R)),f=await Promise.all(u);await o.done;for(let R=0;R<a.length;R++){const S=f[R];r.set(a[R],S===void 0?null:S)}return r}catch(s){A({error:s,message:s?.message});for(const n of new Set(e))r.set(n,null);return r}}async Remove(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t),a=r.transaction(s,"readwrite");await a.objectStore(s).delete(n),await a.done}catch(r){A({error:r,message:r?.message})}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||$,s=this.getStoreName(e);if(this.isKnownCategory(r)){const n=t.transaction(s,"readwrite");await n.objectStore(s).clear(),await n.done}else{const n=`[${r}]:`,a=t.transaction("mj:default","readwrite"),i=a.objectStore("mj:default"),o=await i.getAllKeys();for(const d of o)typeof d=="string"&&d.startsWith(n)&&await i.delete(d);await a.done}}catch(t){A({error:t,message:t?.message})}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||$,s=this.getStoreName(e),i=await t.transaction(s,"readonly").objectStore(s).getAllKeys();if(this.isKnownCategory(r))return i.map(d=>String(d));const o=`[${r}]:`;return i.map(d=>String(d)).filter(d=>d.startsWith(o)).map(d=>d.slice(o.length))}catch(t){return A({error:t,message:t?.message}),[]}}}class Ne extends de{static{y(this,"GraphQLProviderConfigData")}get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get MJAPIKey(){return this.Data.MJAPIKey}set MJAPIKey(e){this.Data.MJAPIKey=e}get UserAPIKey(){return this.Data.UserAPIKey}set UserAPIKey(e){this.Data.UserAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}get OnAuthenticationError(){return this.Data.OnAuthenticationError}set OnAuthenticationError(e){this.Data.OnAuthenticationError=e}constructor(e,t,r,s,n,a,i,o,d,u){super({Token:e,URL:t,WSURL:r,MJAPIKey:o,UserAPIKey:d,RefreshTokenFunction:s,OnAuthenticationError:u},n,a,i)}}class I extends ae{static{y(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._dynamicHeaders=new Map,this._innerCurrentUserQueryString=`CurrentUser {
300
+ `,r={entityDocumentID:e.entityDocumentID};e.maxRecords!==void 0&&(r.maxRecords=e.maxRecords),e.filter!==void 0&&(r.filter=e.filter);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.FetchEntityVectors)throw new Error("Invalid response from server");return s.FetchEntityVectors}catch(t){const r=t;return l("GraphQLAIClient.FetchEntityVectors failed",void 0,r),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,ErrorMessage:r.message||"Unknown error"}}}}const L="5.40.0",$="default";class H{static{d(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||$;let r=this._storage.get(t);return r||(r=new Map,this._storage.set(t,r)),r}async GetItem(e,t){const s=this.getCategoryMap(t||$).get(e);return s===void 0?null:s}async GetItems(e,t){const r=new Map;if(e.length===0)return r;const s=this.getCategoryMap(t||$);for(const n of new Set(e)){const a=s.get(n);r.set(n,a===void 0?null:a)}return r}async SetItem(e,t,r){this.getCategoryMap(r||$).set(e,t)}async Remove(e,t){this.getCategoryMap(t||$).delete(e)}async ClearCategory(e){const t=e||$;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||$);return t?Array.from(t.keys()):[]}}const $e="MJ_Metadata",Pe=0;function Ae(){try{const m=L.split("."),e=parseInt(m[0],10),t=parseInt(m[1],10);if(!Number.isFinite(e)||!Number.isFinite(t))throw new Error(`Could not parse major.minor from version "${L}"`);return e*1e3+t+Pe}catch(m){return A({error:m,message:"Failed to derive IDB version from PACKAGE_VERSION; using fallback 99999"}),99999}}d(Ae,"computeIdbVersion");const Me=Ae(),X=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"];class Y extends H{static{d(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=ve($e,Me,{upgrade:d((e,t,r)=>{try{M(`[IDBCache] Upgrading IndexedDB schema v${t} \u2192 v${r} (package ${L}). Dropping all stores; caches will repopulate on first use.`);for(const s of Array.from(e.objectStoreNames))e.deleteObjectStore(s);for(const s of X)e.objectStoreNames.contains(s)||e.createObjectStore(s)}catch(s){A({error:s,message:s?.message})}},"upgrade"),blocked:d((e,t)=>{M(`[IDBCache] Upgrade from v${e} to v${t} blocked by another tab. Close other tabs to allow the upgrade to proceed.`)},"blocked")}),this.dbPromise.then(e=>{this._dbReady=!0,e.onversionchange=()=>{M("[IDBCache] DB schema upgraded in another tab \u2014 closing local connection."),e.close(),this._dbReady=!1}}).catch(e=>{A({error:e,message:"IndexedDB initialization failed: "+e?.message})})}get IsReady(){return this._dbReady}isKnownCategory(e){const t=`mj:${e}`;return X.includes(t)}getStoreName(e){const t=e||$;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||$;return this.isKnownCategory(r)?e:`[${r}]:${e}`}async SetItem(e,t,r){try{const s=await this.dbPromise,n=this.getStoreName(r),a=this.getStoreKey(e,r),i=s.transaction(n,"readwrite");await i.objectStore(n).put(t,a),await i.done}catch(s){A({error:s,message:s?.message})}}async GetItem(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t),a=await r.transaction(s).objectStore(s).get(n);return a===void 0?null:a}catch(r){return A({error:r,message:r?.message}),null}}async GetItems(e,t){const r=new Map;if(e.length===0)return r;try{const s=await this.dbPromise,n=this.getStoreName(t),a=Array.from(new Set(e)),i=a.map(R=>this.getStoreKey(R,t)),o=s.transaction(n,"readonly"),y=o.objectStore(n),u=i.map(R=>y.get(R)),f=await Promise.all(u);await o.done;for(let R=0;R<a.length;R++){const p=f[R];r.set(a[R],p===void 0?null:p)}return r}catch(s){A({error:s,message:s?.message});for(const n of new Set(e))r.set(n,null);return r}}async Remove(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t),a=r.transaction(s,"readwrite");await a.objectStore(s).delete(n),await a.done}catch(r){A({error:r,message:r?.message})}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||$,s=this.getStoreName(e);if(this.isKnownCategory(r)){const n=t.transaction(s,"readwrite");await n.objectStore(s).clear(),await n.done}else{const n=`[${r}]:`,a=t.transaction("mj:default","readwrite"),i=a.objectStore("mj:default"),o=await i.getAllKeys();for(const y of o)typeof y=="string"&&y.startsWith(n)&&await i.delete(y);await a.done}}catch(t){A({error:t,message:t?.message})}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||$,s=this.getStoreName(e),i=await t.transaction(s,"readonly").objectStore(s).getAllKeys();if(this.isKnownCategory(r))return i.map(y=>String(y));const o=`[${r}]:`;return i.map(y=>String(y)).filter(y=>y.startsWith(o)).map(y=>y.slice(o.length))}catch(t){return A({error:t,message:t?.message}),[]}}}class be extends de{static{d(this,"GraphQLProviderConfigData")}get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get MJAPIKey(){return this.Data.MJAPIKey}set MJAPIKey(e){this.Data.MJAPIKey=e}get UserAPIKey(){return this.Data.UserAPIKey}set UserAPIKey(e){this.Data.UserAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}get OnAuthenticationError(){return this.Data.OnAuthenticationError}set OnAuthenticationError(e){this.Data.OnAuthenticationError=e}constructor(e,t,r,s,n,a,i,o,y,u){super({Token:e,URL:t,WSURL:r,MJAPIKey:o,UserAPIKey:y,RefreshTokenFunction:s,OnAuthenticationError:u},n,a,i)}}class I extends ae{static{d(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._dynamicHeaders=new Map,this._innerCurrentUserQueryString=`CurrentUser {
301
301
  ${this.userInfoString()}
302
302
  MJUserRoles_UserIDArray {
303
303
  ${this.userRoleInfoString()}
@@ -306,7 +306,7 @@ var re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0})
306
306
  `,this._currentUserQuery=c`query CurrentUserAndRoles {
307
307
  ${this._innerCurrentUserQueryString}
308
308
  CurrentUserTenantContext
309
- }`,this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject=new Ie("unknown"),this._isDisposingSocketIntentionally=!1,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=B();if(e&&e[I._globalStoreKey])return e[I._globalStoreKey];e&&(e[I._globalStoreKey]=this)}static{this._globalStoreKey="___SINGLETON__GraphQLDataProvider"}static get Instance(){const e=B();return e?e[I._globalStoreKey]:void 0}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new z(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 Ee()}get LocalStoragePrefix(){if(this._configData===void 0||this._configData.URL===void 0)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const r=this.LocalStoragePrefix+"sessionId";await t.SetItem(r,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,r,s){try{return this._configData=e,r?(this._sessionId=await this.GetPreferredUUID(s),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey,e.UserAPIKey),await this.SaveStoredSessionID(this._sessionId)):(I.Instance._configData=e,I.Instance._sessionId===void 0&&(I.Instance._sessionId=await this.GetPreferredUUID(s)),I.Instance._client||(I.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,I.Instance._sessionId,e.MJAPIKey,e.UserAPIKey)),await I.Instance.SaveStoredSessionID(I.Instance._sessionId),this._sessionId=I.Instance._sessionId,this._client=I.Instance._client),super.Config(e)}catch(n){throw 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),I.Instance&&I.Instance!==this&&I.Instance._configData===this._configData&&(I.Instance._dynamicHeaders.set(e,t),I.Instance._client&&I.Instance._client.setHeader(e,t))}RemoveDynamicHeader(e){this._dynamicHeaders.delete(e),this._client&&this._client.setHeader(e,""),I.Instance&&I.Instance!==this&&I.Instance._configData===this._configData&&(I.Instance._dynamicHeaders.delete(e),I.Instance._client&&I.Instance._client.setHeader(e,""))}GetDynamicHeaders(){return this._dynamicHeaders}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),r=t.MJUserRoles_UserIDArray.map(n=>this.ConvertBackToMJFields(n));t.MJUserRoles_UserIDArray=r;const s=new O(this,{...t,UserRoles:r});return e.CurrentUserTenantContext&&typeof e.CurrentUserTenantContext=="object"&&(s.TenantContext=e.CurrentUserTenantContext),s}}async RunReport(e,t){const r=c`
309
+ }`,this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject=new Ie("unknown"),this._isDisposingSocketIntentionally=!1,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=B();if(e&&e[I._globalStoreKey])return e[I._globalStoreKey];e&&(e[I._globalStoreKey]=this)}static{this.VerboseCacheInvalidationLogging=!1}static{this._globalStoreKey="___SINGLETON__GraphQLDataProvider"}static get Instance(){const e=B();return e?e[I._globalStoreKey]:void 0}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new z(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 Ee()}get LocalStoragePrefix(){if(this._configData===void 0||this._configData.URL===void 0)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const r=this.LocalStoragePrefix+"sessionId";await t.SetItem(r,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,r,s){try{return this._configData=e,r?(this._sessionId=await this.GetPreferredUUID(s),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey,e.UserAPIKey),await this.SaveStoredSessionID(this._sessionId)):(I.Instance._configData=e,I.Instance._sessionId===void 0&&(I.Instance._sessionId=await this.GetPreferredUUID(s)),I.Instance._client||(I.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,I.Instance._sessionId,e.MJAPIKey,e.UserAPIKey)),await I.Instance.SaveStoredSessionID(I.Instance._sessionId),this._sessionId=I.Instance._sessionId,this._client=I.Instance._client),super.Config(e)}catch(n){throw 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),I.Instance&&I.Instance!==this&&I.Instance._configData===this._configData&&(I.Instance._dynamicHeaders.set(e,t),I.Instance._client&&I.Instance._client.setHeader(e,t))}RemoveDynamicHeader(e){this._dynamicHeaders.delete(e),this._client&&this._client.setHeader(e,""),I.Instance&&I.Instance!==this&&I.Instance._configData===this._configData&&(I.Instance._dynamicHeaders.delete(e),I.Instance._client&&I.Instance._client.setHeader(e,""))}GetDynamicHeaders(){return this._dynamicHeaders}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),r=t.MJUserRoles_UserIDArray.map(n=>this.ConvertBackToMJFields(n));t.MJUserRoles_UserIDArray=r;const s=new q(this,{...t,UserRoles:r});return e.CurrentUserTenantContext&&typeof e.CurrentUserTenantContext=="object"&&(s.TenantContext=e.CurrentUserTenantContext),s}}async RunReport(e,t){const r=c`
310
310
  query GetReportDataQuery ($ReportID: String!) {
311
311
  GetReportData(ReportID: $ReportID) {
312
312
  Success
@@ -333,13 +333,13 @@ var re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0})
333
333
  ${this.QueryReturnFieldList}
334
334
  }
335
335
  }
336
- `,d={QueryID:e};t!==void 0&&(d.CategoryID=t),r!==void 0&&(d.CategoryPath=r),n!==void 0&&(d.Parameters=n),a!==void 0&&(d.MaxRows=a),i!==void 0&&(d.StartRow=i);const u=await this.ExecuteGQL(o,d);if(u&&u.GetQueryData)return this.TransformQueryPayload(u.GetQueryData)}async RunQueryByName(e,t,r,s,n,a,i){const o=c`
336
+ `,y={QueryID:e};t!==void 0&&(y.CategoryID=t),r!==void 0&&(y.CategoryPath=r),n!==void 0&&(y.Parameters=n),a!==void 0&&(y.MaxRows=a),i!==void 0&&(y.StartRow=i);const u=await this.ExecuteGQL(o,y);if(u&&u.GetQueryData)return this.TransformQueryPayload(u.GetQueryData)}async RunQueryByName(e,t,r,s,n,a,i){const o=c`
337
337
  query GetQueryDataByNameQuery($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
338
338
  GetQueryDataByName(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
339
339
  ${this.QueryReturnFieldList}
340
340
  }
341
341
  }
342
- `,d={QueryName:e};t!==void 0&&(d.CategoryID=t),r!==void 0&&(d.CategoryPath=r),n!==void 0&&(d.Parameters=n),a!==void 0&&(d.MaxRows=a),i!==void 0&&(d.StartRow=i);const u=await this.ExecuteGQL(o,d);if(u&&u.GetQueryDataByName)return this.TransformQueryPayload(u.GetQueryDataByName)}get QueryReturnFieldList(){return`
342
+ `,y={QueryName:e};t!==void 0&&(y.CategoryID=t),r!==void 0&&(y.CategoryPath=r),n!==void 0&&(y.Parameters=n),a!==void 0&&(y.MaxRows=a),i!==void 0&&(y.StartRow=i);const u=await this.ExecuteGQL(o,y);if(u&&u.GetQueryDataByName)return this.TransformQueryPayload(u.GetQueryDataByName)}get QueryReturnFieldList(){return`
343
343
  Success
344
344
  QueryID
345
345
  QueryName
@@ -364,14 +364,14 @@ var re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0})
364
364
  }
365
365
  }
366
366
  }
367
- `,a=(await this.ExecuteGQL(s,{input:r}))?.RunQueriesWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map(o=>{if((o.status==="stale"||o.status==="no_validation")&&o.Results){const d=JSON.parse(o.Results);return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,results:d,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}});return{success:a.success,results:i,errorMessage:a.errorMessage}}catch(r){return l(`Error in RunQueriesWithCacheCheck: ${r}`),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async InternalRunView(e,t){try{let r="",s="";if(e){const n={};let a,i;if(e.ViewEntity)i=e.ViewEntity,a=i.Entity;else{const{entityName:g,v:p}=await this.getEntityNameAndUserView(e,t);i=p,a=g}const o=this.Entities.find(g=>g.Name===a);if(!o)throw new Error(`Entity ${a} not found in metadata`);let d=!1;const u=M(o);e.ViewID?(r=`Run${u}ViewByID`,s="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(r=`Run${u}ViewByName`,s="RunViewByNameInput",n.ViewName=e.ViewName):(d=!0,r=`Run${u}DynamicView`,s="RunDynamicViewInput",n.EntityName=e.EntityName),n.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",n.OrderBy=e.OrderBy?e.OrderBy:"",n.UserSearchString=e.UserSearchString?e.UserSearchString:"",n.Fields=e.Fields,n.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,e.MaxRows!==void 0&&(n.MaxRows=e.MaxRows),e.StartRow!==void 0&&(n.StartRow=e.StartRow),n.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,n.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(n.AuditLogDescription=e.AuditLogDescription),e.BypassCache!==void 0&&(n.BypassCache=e.BypassCache),d||(n.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",n.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,n.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",n.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1),e.Aggregates&&e.Aggregates.length>0&&(n.Aggregates=e.Aggregates.map(g=>({expression:g.expression,alias:g.alias})));const f=this.getViewRunTimeFieldList(o,i,e,d),R=e.Aggregates&&e.Aggregates.length>0?`
367
+ `,a=(await this.ExecuteGQL(s,{input:r}))?.RunQueriesWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map(o=>{if((o.status==="stale"||o.status==="no_validation")&&o.Results){const y=JSON.parse(o.Results);return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,results:y,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}});return{success:a.success,results:i,errorMessage:a.errorMessage}}catch(r){return l(`Error in RunQueriesWithCacheCheck: ${r}`),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async InternalRunView(e,t){try{let r="",s="";if(e){const n={};let a,i;if(e.ViewEntity)i=e.ViewEntity,a=i.Entity;else{const{entityName:g,v:S}=await this.getEntityNameAndUserView(e,t);i=S,a=g}const o=this.Entities.find(g=>g.Name===a);if(!o)throw new Error(`Entity ${a} not found in metadata`);let y=!1;const u=N(o);e.ViewID?(r=`Run${u}ViewByID`,s="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(r=`Run${u}ViewByName`,s="RunViewByNameInput",n.ViewName=e.ViewName):(y=!0,r=`Run${u}DynamicView`,s="RunDynamicViewInput",n.EntityName=e.EntityName),n.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",n.OrderBy=e.OrderBy?e.OrderBy:"",n.UserSearchString=e.UserSearchString?e.UserSearchString:"",n.Fields=e.Fields,n.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,e.MaxRows!==void 0&&(n.MaxRows=e.MaxRows),e.StartRow!==void 0&&(n.StartRow=e.StartRow),n.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,n.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(n.AuditLogDescription=e.AuditLogDescription),e.BypassCache!==void 0&&(n.BypassCache=e.BypassCache),y||(n.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",n.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,n.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",n.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1),e.Aggregates&&e.Aggregates.length>0&&(n.Aggregates=e.Aggregates.map(g=>({expression:g.expression,alias:g.alias})));const f=this.getViewRunTimeFieldList(o,i,e,y),R=e.Aggregates&&e.Aggregates.length>0?`
368
368
  AggregateResults {
369
369
  alias
370
370
  expression
371
371
  value
372
372
  error
373
373
  }
374
- AggregateExecutionTime`:"",S=c`
374
+ AggregateExecutionTime`:"",p=c`
375
375
  query RunViewQuery ($input: ${s}!) {
376
376
  ${r}(input: $input) {
377
377
  Results {
@@ -385,7 +385,7 @@ var re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0})
385
385
  Success
386
386
  ErrorMessage${R}
387
387
  }
388
- }`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:a,queryName:r,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const h=await this.ExecuteGQL(S,{input:n});if(h&&h[r]){const g=h[r].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:a,aggregateResultCount:g?.length||0,aggregateResults:g,aggregateExecutionTime:h[r].AggregateExecutionTime});const p=h[r].Results;if(p&&p.length>0){const C=o.Fields.filter(E=>E.CodeName!==E.Name&&E.CodeName!==void 0);p.forEach(E=>{this.ConvertBackToMJFields(E),C.forEach(x=>{E[x.Name]=E[x.CodeName]})})}return h[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw l(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],n=[];for(const u of e){let f="",R="";const S={};let h=null,g=null;if(u.ViewEntity)g=u.ViewEntity,h=g.Get("Entity");else{const{entityName:E,v:x}=await this.getEntityNameAndUserView(u,t);g=x,h=E}const p=this.Entities.find(E=>E.Name===h);if(!p)throw new Error(`Entity ${h} not found in metadata`);s.push(p);let D=!1;const C=M(p);u.ViewID?(f=`Run${C}ViewByID`,R="RunViewByIDInput",S.ViewID=u.ViewID):u.ViewName?(f=`Run${C}ViewByName`,R="RunViewByNameInput",S.ViewName=u.ViewName):(D=!0,f=`Run${C}DynamicView`,R="RunDynamicViewInput",S.EntityName=u.EntityName),S.ExtraFilter=u.ExtraFilter||"",S.OrderBy=u.OrderBy||"",S.UserSearchString=u.UserSearchString||"",S.Fields=u.Fields,S.IgnoreMaxRows=u.IgnoreMaxRows||!1,u.MaxRows!==void 0&&(S.MaxRows=u.MaxRows),u.StartRow!==void 0&&(S.StartRow=u.StartRow),u.AfterKey&&(S.AfterKey={KeyValuePairs:u.AfterKey.KeyValuePairs}),S.ForceAuditLog=u.ForceAuditLog||!1,S.ResultType=u.ResultType||"simple",u.AuditLogDescription&&u.AuditLogDescription.length>0&&(S.AuditLogDescription=u.AuditLogDescription),u.BypassCache!==void 0&&(S.BypassCache=u.BypassCache),D||(S.ExcludeUserViewRunID=u.ExcludeUserViewRunID||"",S.ExcludeDataFromAllPriorViewRuns=u.ExcludeDataFromAllPriorViewRuns||!1,S.OverrideExcludeFilter=u.OverrideExcludeFilter||"",S.SaveViewResults=u.SaveViewResults||!1),u.Aggregates&&u.Aggregates.length>0&&(S.Aggregates=u.Aggregates.map(E=>({expression:E.expression,alias:E.alias}))),r.push(S),n.push(...this.getViewRunTimeFieldList(p,g,u,D))}const i=e.some(u=>u.Aggregates&&u.Aggregates.length>0)?`
388
+ }`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:a,queryName:r,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const h=await this.ExecuteGQL(p,{input:n});if(h&&h[r]){const g=h[r].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:a,aggregateResultCount:g?.length||0,aggregateResults:g,aggregateExecutionTime:h[r].AggregateExecutionTime});const S=h[r].Results;if(S&&S.length>0){const w=o.Fields.filter(v=>v.CodeName!==v.Name&&v.CodeName!==void 0);S.forEach(v=>{this.ConvertBackToMJFields(v),w.forEach(x=>{v[x.Name]=v[x.CodeName]})})}return h[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw l(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],n=[];for(const u of e){let f="",R="";const p={};let h=null,g=null;if(u.ViewEntity)g=u.ViewEntity,h=g.Get("Entity");else{const{entityName:v,v:x}=await this.getEntityNameAndUserView(u,t);g=x,h=v}const S=this.Entities.find(v=>v.Name===h);if(!S)throw new Error(`Entity ${h} not found in metadata`);s.push(S);let D=!1;const w=N(S);u.ViewID?(f=`Run${w}ViewByID`,R="RunViewByIDInput",p.ViewID=u.ViewID):u.ViewName?(f=`Run${w}ViewByName`,R="RunViewByNameInput",p.ViewName=u.ViewName):(D=!0,f=`Run${w}DynamicView`,R="RunDynamicViewInput",p.EntityName=u.EntityName),p.ExtraFilter=u.ExtraFilter||"",p.OrderBy=u.OrderBy||"",p.UserSearchString=u.UserSearchString||"",p.Fields=u.Fields,p.IgnoreMaxRows=u.IgnoreMaxRows||!1,u.MaxRows!==void 0&&(p.MaxRows=u.MaxRows),u.StartRow!==void 0&&(p.StartRow=u.StartRow),u.AfterKey&&(p.AfterKey={KeyValuePairs:u.AfterKey.KeyValuePairs}),p.ForceAuditLog=u.ForceAuditLog||!1,p.ResultType=u.ResultType||"simple",u.AuditLogDescription&&u.AuditLogDescription.length>0&&(p.AuditLogDescription=u.AuditLogDescription),u.BypassCache!==void 0&&(p.BypassCache=u.BypassCache),D||(p.ExcludeUserViewRunID=u.ExcludeUserViewRunID||"",p.ExcludeDataFromAllPriorViewRuns=u.ExcludeDataFromAllPriorViewRuns||!1,p.OverrideExcludeFilter=u.OverrideExcludeFilter||"",p.SaveViewResults=u.SaveViewResults||!1),u.Aggregates&&u.Aggregates.length>0&&(p.Aggregates=u.Aggregates.map(v=>({expression:v.expression,alias:v.alias}))),r.push(p),n.push(...this.getViewRunTimeFieldList(S,g,u,D))}const i=e.some(u=>u.Aggregates&&u.Aggregates.length>0)?`
389
389
  AggregateResults {
390
390
  alias
391
391
  expression
@@ -410,7 +410,7 @@ var re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0})
410
410
  Success
411
411
  ErrorMessage${i}
412
412
  }
413
- }`,d=await this.ExecuteGQL(o,{input:r});if(d&&d.RunViews){const u=d.RunViews;for(const[f,R]of u.entries())R.Results=R.Results.map(S=>{let h=JSON.parse(S.Data);return this.ConvertBackToMJFields(h),h});return u}return null}catch(r){throw l(r),r}}async RunViewsWithCacheCheck(e,t){try{const r=e.map(o=>({params:{EntityName:o.params.EntityName||"",ExtraFilter:o.params.ExtraFilter||"",OrderBy:o.params.OrderBy||"",Fields:o.params.Fields,UserSearchString:o.params.UserSearchString||"",IgnoreMaxRows:o.params.IgnoreMaxRows||!1,MaxRows:o.params.MaxRows,StartRow:o.params.StartRow,AfterKey:o.params.AfterKey?{KeyValuePairs:o.params.AfterKey.KeyValuePairs}:null,ForceAuditLog:o.params.ForceAuditLog||!1,AuditLogDescription:o.params.AuditLogDescription||"",ResultType:o.params.ResultType||"simple"},cacheStatus:o.cacheStatus?{maxUpdatedAt:o.cacheStatus.maxUpdatedAt,rowCount:o.cacheStatus.rowCount}:null})),s=c`
413
+ }`,y=await this.ExecuteGQL(o,{input:r});if(y&&y.RunViews){const u=y.RunViews;for(const[f,R]of u.entries())R.Results=R.Results.map(p=>{let h=JSON.parse(p.Data);return this.ConvertBackToMJFields(h),h});return u}return null}catch(r){throw l(r),r}}async RunViewsWithCacheCheck(e,t){try{const r=e.map(o=>({params:{EntityName:o.params.EntityName||"",ExtraFilter:o.params.ExtraFilter||"",OrderBy:o.params.OrderBy||"",Fields:o.params.Fields,UserSearchString:o.params.UserSearchString||"",IgnoreMaxRows:o.params.IgnoreMaxRows||!1,MaxRows:o.params.MaxRows,StartRow:o.params.StartRow,AfterKey:o.params.AfterKey?{KeyValuePairs:o.params.AfterKey.KeyValuePairs}:null,ForceAuditLog:o.params.ForceAuditLog||!1,AuditLogDescription:o.params.AuditLogDescription||"",ResultType:o.params.ResultType||"simple"},cacheStatus:o.cacheStatus?{maxUpdatedAt:o.cacheStatus.maxUpdatedAt,rowCount:o.cacheStatus.rowCount}:null})),s=c`
414
414
  query RunViewsWithCacheCheckQuery($input: [RunViewWithCacheCheckInput!]!) {
415
415
  RunViewsWithCacheCheck(input: $input) {
416
416
  success
@@ -443,7 +443,7 @@ var re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0})
443
443
  }
444
444
  }
445
445
  }
446
- `,a=(await this.ExecuteGQL(s,{input:r}))?.RunViewsWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map((o,d)=>{const u=e[d];if(o.status==="differential"&&o.differentialData){const f=o.differentialData.updatedRows.map(R=>{const S=JSON.parse(R.Data);return this.ConvertBackToMJFields(S),S});return{viewIndex:o.viewIndex,status:o.status,results:void 0,differentialData:{updatedRows:f,deletedRecordIDs:o.differentialData.deletedRecordIDs},maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}if(o.status==="stale"&&o.Results){const f=o.Results.map(R=>{const S=JSON.parse(R.Data);return this.ConvertBackToMJFields(S),S});return{viewIndex:o.viewIndex,status:o.status,results:f,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}return{viewIndex:o.viewIndex,status:o.status,results:void 0,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}});return{success:a.success,results:i,errorMessage:a.errorMessage}}catch(r){return l(r),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async getEntityNameAndUserView(e,t){let r,s;if(e.EntityName)r=e.EntityName;else if(e.ViewID)s=await J.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await J.GetViewEntityByName(e.ViewName,t),r=s.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:r,v:s}}getViewRunTimeFieldList(e,t,r,s){const n=[],a=new w;if(r.Fields){for(const i of e.PrimaryKeys)r.Fields.find(o=>o.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);r.Fields.forEach(i=>{n.push(a.MapFieldName(i))})}else if(s)e.Fields.forEach(i=>{i.IsBinaryFieldType||n.push(a.MapFieldName(i.CodeName))});else{for(const i of e.PrimaryKeys)n.find(o=>o.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);t.Columns.forEach(i=>{i.hidden===!1&&!n.find(o=>o.trim().toLowerCase()===i.EntityField?.Name.trim().toLowerCase())&&i.EntityField&&n.push(a.MapFieldName(i.EntityField.CodeName))})}return n}get ProviderType(){return oe.Network}async GetRecordChanges(e,t){try{const r={EntityName:"MJ: Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},s=await this.RunView(r);return s?s.Results.sort((n,a)=>n.ChangedAt>a.ChangedAt?-1:1):null}catch(r){throw l(r),r}}async GetRecordDependencies(e,t){try{const r=c`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
446
+ `,a=(await this.ExecuteGQL(s,{input:r}))?.RunViewsWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map((o,y)=>{const u=e[y];if(o.status==="differential"&&o.differentialData){const f=o.differentialData.updatedRows.map(R=>{const p=JSON.parse(R.Data);return this.ConvertBackToMJFields(p),p});return{viewIndex:o.viewIndex,status:o.status,results:void 0,differentialData:{updatedRows:f,deletedRecordIDs:o.differentialData.deletedRecordIDs},maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}if(o.status==="stale"&&o.Results){const f=o.Results.map(R=>{const p=JSON.parse(R.Data);return this.ConvertBackToMJFields(p),p});return{viewIndex:o.viewIndex,status:o.status,results:f,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}return{viewIndex:o.viewIndex,status:o.status,results:void 0,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}});return{success:a.success,results:i,errorMessage:a.errorMessage}}catch(r){return l(r),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async getEntityNameAndUserView(e,t){let r,s;if(e.EntityName)r=e.EntityName;else if(e.ViewID)s=await J.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await J.GetViewEntityByName(e.ViewName,t),r=s.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:r,v:s}}getViewRunTimeFieldList(e,t,r,s){const n=[],a=new C;if(r.Fields){for(const i of e.PrimaryKeys)r.Fields.find(o=>o.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);r.Fields.forEach(i=>{n.push(a.MapFieldName(i))})}else if(s)e.Fields.forEach(i=>{i.IsBinaryFieldType||n.push(a.MapFieldName(i.CodeName))});else{for(const i of e.PrimaryKeys)n.find(o=>o.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);t.Columns.forEach(i=>{i.hidden===!1&&!n.find(o=>o.trim().toLowerCase()===i.EntityField?.Name.trim().toLowerCase())&&i.EntityField&&n.push(a.MapFieldName(i.EntityField.CodeName))})}return n}get ProviderType(){return oe.Network}async GetRecordChanges(e,t){try{const r={EntityName:"MJ: Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},s=await this.RunView(r);return s?s.Results.sort((n,a)=>n.ChangedAt>a.ChangedAt?-1:1):null}catch(r){throw l(r),r}}async GetRecordDependencies(e,t){try{const r=c`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
447
447
  GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
448
448
  EntityName
449
449
  RelatedEntityName
@@ -510,32 +510,32 @@ var re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0})
510
510
  Message
511
511
  }
512
512
  }
513
- }`,a={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(o=>({FieldName:o.FieldName,Value:o.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(o=>o.Copy())};return(await this.ExecuteGQL(n,{request:a}))?.MergeRecords}catch(n){return l(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){if(r?.IsParentEntitySave){const n=new U;return n.StartedAt=new Date,n.EndedAt=new Date,n.Type=e.IsSaved?"update":"create",n.Success=!0,n.NewValues=e.GetAll(),e.RegisterResultHistoryEntry(n),n.NewValues}const s=new U;try{e.RegisterTransactionPreprocessing();const n={input:{}},a=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(h=>({FieldName:h.CodeName,Value:h.Value})),e.RegisterResultHistoryEntry(s);const i=M(e.EntityInfo),o=`${a}${i}`,d=e.Fields.filter(h=>!h.ReadOnly||h.IsPrimaryKey&&e.IsSaved),u=new w,f=` ${o}(input: $input) {
513
+ }`,a={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(o=>({FieldName:o.FieldName,Value:o.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(o=>o.Copy())};return(await this.ExecuteGQL(n,{request:a}))?.MergeRecords}catch(n){return l(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){if(r?.IsParentEntitySave){const n=new U;return n.StartedAt=new Date,n.EndedAt=new Date,n.Type=e.IsSaved?"update":"create",n.Success=!0,n.NewValues=e.GetAll(),e.RegisterResultHistoryEntry(n),n.NewValues}const s=new U;try{e.RegisterTransactionPreprocessing();const n={input:{}},a=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(h=>({FieldName:h.CodeName,Value:h.Value})),e.RegisterResultHistoryEntry(s);const i=N(e.EntityInfo),o=`${a}${i}`,y=e.Fields.filter(h=>!h.ReadOnly||h.IsPrimaryKey&&e.IsSaved),u=new C,f=` ${o}(input: $input) {
514
514
  ${e.Fields.map(h=>u.MapFieldName(h.CodeName)).join(`
515
515
  `)}
516
516
  }`,R=c`mutation ${a}${i} ($input: ${o}Input!) {
517
517
  ${f}
518
518
  }
519
- `;for(let h=0;h<d.length;h++){const g=d[h];let p=e.Get(g.Name);if(p)switch(g.EntityFieldInfo.TSType){case N.Date:p=p.getTime();break;case N.Boolean:typeof p!="boolean"&&(p=parseInt(p)!==0);break;case N.Number:if(typeof p!="number"){const D=Number(p);isNaN(D)||(p=D)}break}p===null&&g.EntityFieldInfo.AllowsNull===!1&&(g.EntityFieldInfo.DefaultValue!==null?p=g.EntityFieldInfo.DefaultValue:g.FieldType===N.Number||g.FieldType===N.Boolean?p=0:p=""),n.input[u.MapFieldName(g.CodeName)]=p}const S=e.RestoreContext;if(S&&(n.input.RestoreContext___={SourceChangeID:S.SourceChangeID,Reason:S.Reason}),a.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const h=[];e.Fields.forEach(g=>{let p=null;g.OldValue!==null&&g.OldValue!==void 0&&(g.EntityFieldInfo.TSType===N.Date?p=g.OldValue.getTime().toString():g.EntityFieldInfo.TSType===N.Boolean?p=g.OldValue===!0?"1":"0":typeof g.OldValue!="string"?p=g.OldValue.toString():p=g.OldValue),h.push({Key:u.MapFieldName(g.CodeName),Value:p})}),n.input.OldValues___=h}if(e.TransactionGroup){const h=[{varName:"input",inputType:o+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new k(e,s.Type==="create"?"Create":"Update",f,n,{mutationName:o,mutationInputTypes:h},(g,p)=>{s.EndedAt=new Date,p&&g?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(g)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const h=await this.ExecuteGQL(R,n);if(h&&h[o])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(h[o]),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(n){return s.Success=!1,s.EndedAt=new Date,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,l(n),null}}async Load(e,t,r=null,s){try{const n={};let a="",i="";for(let S=0;S<t.KeyValuePairs.length;S++){const h=e.Fields.find(D=>D.Name.trim().toLowerCase()===t.KeyValuePairs[S].FieldName.trim().toLowerCase()).EntityFieldInfo,g=t.GetValueByIndex(S),p=h.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${h.CodeName}: ${p}!`,a.length>0&&(a+=", "),a+=`${h.CodeName}: $${h.CodeName}`,h.TSType===N.Number){if(isNaN(t.GetValueByIndex(S)))throw new Error(`Primary Key value ${g} (${h.Name}) is not a valid number`);n[h.CodeName]=parseInt(g)}else n[h.CodeName]=g}const o=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",d=M(e.EntityInfo),u=new w,f=c`query Single${d}${o.length>0?"Full":""} (${i}) {
520
- ${d}(${a}) {
521
- ${e.Fields.filter(S=>!S.EntityFieldInfo.IsBinaryFieldType).map(S=>S.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?S.CodeName.replace("__mj_","_mj__"):S.CodeName).join(`
519
+ `;for(let h=0;h<y.length;h++){const g=y[h];let S=e.Get(g.Name);if(S)switch(g.EntityFieldInfo.TSType){case b.Date:S=S.getTime();break;case b.Boolean:typeof S!="boolean"&&(S=parseInt(S)!==0);break;case b.Number:if(typeof S!="number"){const D=Number(S);isNaN(D)||(S=D)}break}S===null&&g.EntityFieldInfo.AllowsNull===!1&&(g.EntityFieldInfo.DefaultValue!==null?S=g.EntityFieldInfo.DefaultValue:g.FieldType===b.Number||g.FieldType===b.Boolean?S=0:S=""),n.input[u.MapFieldName(g.CodeName)]=S}const p=e.RestoreContext;if(p&&(n.input.RestoreContext___={SourceChangeID:p.SourceChangeID,Reason:p.Reason}),a.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const h=[];e.Fields.forEach(g=>{let S=null;g.OldValue!==null&&g.OldValue!==void 0&&(g.EntityFieldInfo.TSType===b.Date?S=g.OldValue.getTime().toString():g.EntityFieldInfo.TSType===b.Boolean?S=g.OldValue===!0?"1":"0":typeof g.OldValue!="string"?S=g.OldValue.toString():S=g.OldValue),h.push({Key:u.MapFieldName(g.CodeName),Value:S})}),n.input.OldValues___=h}if(e.TransactionGroup){const h=[{varName:"input",inputType:o+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new k(e,s.Type==="create"?"Create":"Update",f,n,{mutationName:o,mutationInputTypes:h},(g,S)=>{s.EndedAt=new Date,S&&g?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(g)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const h=await this.ExecuteGQL(R,n);if(h&&h[o])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(h[o]),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(n){return s.Success=!1,s.EndedAt=new Date,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,l(n),null}}async Load(e,t,r=null,s){try{const n={};let a="",i="";for(let p=0;p<t.KeyValuePairs.length;p++){const h=e.Fields.find(D=>D.Name.trim().toLowerCase()===t.KeyValuePairs[p].FieldName.trim().toLowerCase()).EntityFieldInfo,g=t.GetValueByIndex(p),S=h.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${h.CodeName}: ${S}!`,a.length>0&&(a+=", "),a+=`${h.CodeName}: $${h.CodeName}`,h.TSType===b.Number){if(isNaN(t.GetValueByIndex(p)))throw new Error(`Primary Key value ${g} (${h.Name}) is not a valid number`);n[h.CodeName]=parseInt(g)}else n[h.CodeName]=g}const o=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",y=N(e.EntityInfo),u=new C,f=c`query Single${y}${o.length>0?"Full":""} (${i}) {
520
+ ${y}(${a}) {
521
+ ${e.Fields.filter(p=>!p.EntityFieldInfo.IsBinaryFieldType).map(p=>p.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?p.CodeName.replace("__mj_","_mj__"):p.CodeName).join(`
522
522
  `)}
523
523
  ${o}
524
524
  }
525
525
  }
526
- `,R=await this.ExecuteGQL(f,n);return R&&R[d]?this.ConvertBackToMJFields(R[d]):null}catch(n){return l(n),null}}ConvertBackToMJFields(e){return new w().ReverseMapFields(e),e}getRelatedEntityString(e,t){let r="";for(let s=0;s<e.RelatedEntities.length;s++)if(t.indexOf(e.RelatedEntities[s].RelatedEntity)>=0){const n=e.RelatedEntities[s],a=this.Entities.find(o=>he(o.ID,n.RelatedEntityID));let i="";n.Type.toLowerCase().trim()==="many to many"?i=`${n.RelatedEntityCodeName}_${n.JoinEntityJoinField.replace(/\s/g,"")}`:i=`${n.RelatedEntityCodeName}_${n.RelatedEntityJoinField.replace(/\s/g,"")}`,r+=`
526
+ `,R=await this.ExecuteGQL(f,n);return R&&R[y]?this.ConvertBackToMJFields(R[y]):null}catch(n){return l(n),null}}ConvertBackToMJFields(e){return new C().ReverseMapFields(e),e}getRelatedEntityString(e,t){let r="";for(let s=0;s<e.RelatedEntities.length;s++)if(t.indexOf(e.RelatedEntities[s].RelatedEntity)>=0){const n=e.RelatedEntities[s],a=this.Entities.find(o=>he(o.ID,n.RelatedEntityID));let i="";n.Type.toLowerCase().trim()==="many to many"?i=`${n.RelatedEntityCodeName}_${n.JoinEntityJoinField.replace(/\s/g,"")}`:i=`${n.RelatedEntityCodeName}_${n.RelatedEntityJoinField.replace(/\s/g,"")}`,r+=`
527
527
  ${i} {
528
528
  ${a.Fields.map(o=>o.CodeName).join(`
529
529
  `)}
530
530
  }
531
- `}return r}async Delete(e,t,r){const s=new U;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(h=>({FieldName:h.CodeName,Value:h.Value})),e.RegisterResultHistoryEntry(s);const n={},a=[];let i="",o="",d="";for(let h of e.PrimaryKey.KeyValuePairs){const g=e.Fields.find(p=>p.Name.trim().toLowerCase()===h.FieldName.trim().toLowerCase());n[g.CodeName]=g.Value,a.push({varName:g.CodeName,inputType:g.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${g.CodeName}: $${g.CodeName}`,o.length>0&&(o+=", "),o+=`$${g.CodeName}: ${g.EntityFieldInfo.GraphQLType}!`,d.length>0&&(d+=`
532
- `),d+=`${g.CodeName}`}a.push({varName:"options___",inputType:"DeleteOptionsInput!"}),n.options___={SkipEntityAIActions:t?.SkipEntityAIActions??!1,SkipEntityActions:t?.SkipEntityActions??!1,ReplayOnly:t?.ReplayOnly??!1,IsParentEntityDelete:t?.IsParentEntityDelete??!1};const f="Delete"+M(e.EntityInfo),R=c`${f}(${i}, options___: $options___) {
533
- ${d}
531
+ `}return r}async Delete(e,t,r){const s=new U;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(h=>({FieldName:h.CodeName,Value:h.Value})),e.RegisterResultHistoryEntry(s);const n={},a=[];let i="",o="",y="";for(let h of e.PrimaryKey.KeyValuePairs){const g=e.Fields.find(S=>S.Name.trim().toLowerCase()===h.FieldName.trim().toLowerCase());n[g.CodeName]=g.Value,a.push({varName:g.CodeName,inputType:g.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${g.CodeName}: $${g.CodeName}`,o.length>0&&(o+=", "),o+=`$${g.CodeName}: ${g.EntityFieldInfo.GraphQLType}!`,y.length>0&&(y+=`
532
+ `),y+=`${g.CodeName}`}a.push({varName:"options___",inputType:"DeleteOptionsInput!"}),n.options___={SkipEntityAIActions:t?.SkipEntityAIActions??!1,SkipEntityActions:t?.SkipEntityActions??!1,ReplayOnly:t?.ReplayOnly??!1,IsParentEntityDelete:t?.IsParentEntityDelete??!1};const f="Delete"+N(e.EntityInfo),R=c`${f}(${i}, options___: $options___) {
533
+ ${y}
534
534
  }
535
- `,S=c`mutation ${f} (${o}, $options___: DeleteOptionsInput!) {
535
+ `,p=c`mutation ${f} (${o}, $options___: DeleteOptionsInput!) {
536
536
  ${R}
537
537
  }
538
- `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new k(e,"Delete",R,n,{mutationName:f,mutationInputTypes:a},(h,g)=>{if(s.EndedAt=new Date,g&&h){let p=!0;for(const D of e.PrimaryKey.KeyValuePairs)D.Value!==h[D.FieldName]&&(p=!1);p?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const h=await this.ExecuteGQL(S,n);if(h&&h[f]){const g=h[f];for(let p of e.PrimaryKey.KeyValuePairs){let D=g[p.FieldName],C=p.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: ${p.FieldName}, Original: ${C}, Returned: ${D}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(n){return s.EndedAt=new Date,s.Success=!1,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,l(n),!1}}async GetDatasetByName(e,t){const r=c`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
538
+ `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new k(e,"Delete",R,n,{mutationName:f,mutationInputTypes:a},(h,g)=>{if(s.EndedAt=new Date,g&&h){let S=!0;for(const D of e.PrimaryKey.KeyValuePairs)D.Value!==h[D.FieldName]&&(S=!1);S?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const h=await this.ExecuteGQL(p,n);if(h&&h[f]){const g=h[f];for(let S of e.PrimaryKey.KeyValuePairs){let D=g[S.FieldName],w=S.Value;if(typeof w=="number"&&(w=w.toString()),typeof D=="number"&&(D=D.toString()),w!==D)throw new Error(`Primary key value mismatch in server Delete response. Field: ${S.FieldName}, Original: ${w}, Returned: ${D}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(n){return s.EndedAt=new Date,s.Success=!1,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,l(n),!1}}async GetDatasetByName(e,t){const r=c`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
539
539
  GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
540
540
  DatasetID
541
541
  DatasetName
@@ -544,7 +544,7 @@ var re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0})
544
544
  LatestUpdateDate
545
545
  Results
546
546
  }
547
- }`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetByName&&s.GetDatasetByName.Success?{DatasetID:s.GetDatasetByName.DatasetID,DatasetName:s.GetDatasetByName.DatasetName,Success:s.GetDatasetByName.Success,Status:s.GetDatasetByName.Status,LatestUpdateDate:new Date(s.GetDatasetByName.LatestUpdateDate),Results:JSON.parse(s.GetDatasetByName.Results)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,Results:null}}static{this._datasetStatusQueue=[]}static{this._datasetStatusTimer=null}static{this._datasetStatusCoalesceMs=10}async GetDatasetStatusByName(e,t){return I._datasetStatusCoalesceMs>0&&!t?this.enqueueDatasetStatusCheck(e):this.executeDatasetStatusByName(e,t)}enqueueDatasetStatusCheck(e){return new Promise((t,r)=>{I._datasetStatusQueue.push({datasetName:e,resolve:t,reject:r}),I._datasetStatusTimer||(I._datasetStatusTimer=setTimeout(()=>this.flushDatasetStatusQueue(),I._datasetStatusCoalesceMs))})}async flushDatasetStatusQueue(){I._datasetStatusTimer=null;const e=I._datasetStatusQueue.splice(0);if(e.length===0)return;if(e.length===1){try{const r=await this.executeDatasetStatusByName(e[0].datasetName,e[0].itemFilters);e[0].resolve(r)}catch(r){e[0].reject(r)}return}const t=e.map(r=>r.datasetName);b(`\u26A1 [Coalesce] Batching ${t.length} dataset status checks into 1 request: [${t.join(", ")}]`);try{const r=c`query GetMultipleDatasetStatusByName($DatasetNames: [String!]!) {
547
+ }`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetByName&&s.GetDatasetByName.Success?{DatasetID:s.GetDatasetByName.DatasetID,DatasetName:s.GetDatasetByName.DatasetName,Success:s.GetDatasetByName.Success,Status:s.GetDatasetByName.Status,LatestUpdateDate:new Date(s.GetDatasetByName.LatestUpdateDate),Results:JSON.parse(s.GetDatasetByName.Results)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,Results:null}}static{this._datasetStatusQueue=[]}static{this._datasetStatusTimer=null}static{this._datasetStatusCoalesceMs=10}async GetDatasetStatusByName(e,t){return I._datasetStatusCoalesceMs>0&&!t?this.enqueueDatasetStatusCheck(e):this.executeDatasetStatusByName(e,t)}enqueueDatasetStatusCheck(e){return new Promise((t,r)=>{I._datasetStatusQueue.push({datasetName:e,resolve:t,reject:r}),I._datasetStatusTimer||(I._datasetStatusTimer=setTimeout(()=>this.flushDatasetStatusQueue(),I._datasetStatusCoalesceMs))})}async flushDatasetStatusQueue(){I._datasetStatusTimer=null;const e=I._datasetStatusQueue.splice(0);if(e.length===0)return;if(e.length===1){try{const r=await this.executeDatasetStatusByName(e[0].datasetName,e[0].itemFilters);e[0].resolve(r)}catch(r){e[0].reject(r)}return}const t=e.map(r=>r.datasetName);M(`\u26A1 [Coalesce] Batching ${t.length} dataset status checks into 1 request: [${t.join(", ")}]`);try{const r=c`query GetMultipleDatasetStatusByName($DatasetNames: [String!]!) {
548
548
  GetMultipleDatasetStatusByName(DatasetNames: $DatasetNames) {
549
549
  DatasetID
550
550
  DatasetName
@@ -567,7 +567,7 @@ var re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0})
567
567
  Success
568
568
  IsFavorite
569
569
  }
570
- }`,i=await this.ExecuteGQL(a,{params:{UserID:e,EntityID:n.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)}}});if(i&&i.GetRecordFavoriteStatus&&i.GetRecordFavoriteStatus.Success)return i.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,t,r,s,n){const a=this.Entities.find(d=>d.Name===t);if(!a)throw new Error(`Entity ${t} not found in metadata`);const i=c`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
570
+ }`,i=await this.ExecuteGQL(a,{params:{UserID:e,EntityID:n.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)}}});if(i&&i.GetRecordFavoriteStatus&&i.GetRecordFavoriteStatus.Success)return i.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,t,r,s,n){const a=this.Entities.find(y=>y.Name===t);if(!a)throw new Error(`Entity ${t} not found in metadata`);const i=c`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
571
571
  SetRecordFavoriteStatus(params: $params){
572
572
  Success
573
573
  }
@@ -602,16 +602,16 @@ var re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0})
602
602
  ErrorMessage
603
603
  Result
604
604
  }
605
- }`,r=await this.ExecuteGQL(t,{DataContextItemID:e});if(r&&r.GetDataContextItemData){if(r.GetDataContextItemData.Success)return JSON.parse(r.GetDataContextItemData.Result);throw new Error(r.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw l(t),t}}static async ExecuteGQL(e,t,r=!0){return I.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(console.error("[GraphQL] ExecuteGQL error caught:",{hasResponse:!!s?.response,hasErrors:!!s?.response?.errors,errorCount:s?.response?.errors?.length,firstError:s?.response?.errors?.[0],errorCode:s?.response?.errors?.[0]?.extensions?.code,errorMessage:s?.response?.errors?.[0]?.message,fullError:s}),s&&s.response&&s.response.errors?.length>0)if(s.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw l("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw l(s),s}}async RefreshToken(){const e=I.Instance&&I.Instance._configData===this._configData;if(e&&I.Instance._refreshPromise)return I.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(I.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&I.Instance&&(I.Instance._refreshPromise=null)}}async performTokenRefresh(){if(this._configData.Data.RefreshTokenFunction)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,I.Instance&&I.Instance._configData===this._configData&&(I.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 I.Instance.RefreshToken()}static async clearClientCache(e=new Set){const t=[];for(let r=0;r<localStorage.length;r++){const s=localStorage.key(r);s&&!e.has(s)&&t.push(s)}t.forEach(r=>localStorage.removeItem(r)),await new Promise(r=>{const s=indexedDB.deleteDatabase("MJ_Metadata");s.onsuccess=()=>r(),s.onerror=()=>r(),s.onblocked=()=>r()})}CreateNewGraphQLClient(e,t,r,s,n){const a={"x-session-id":r};t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),n&&(a["x-api-key"]=n);const i=new q(e,{headers:a});for(const[o,d]of this._dynamicHeaders)i.setHeader(o,d);return i}userInfoString(){return this.infoString(new O(null,null))}userRoleInfoString(){return this.infoString(new ce(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
605
+ }`,r=await this.ExecuteGQL(t,{DataContextItemID:e});if(r&&r.GetDataContextItemData){if(r.GetDataContextItemData.Success)return JSON.parse(r.GetDataContextItemData.Result);throw new Error(r.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw l(t),t}}static async ExecuteGQL(e,t,r=!0){return I.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(console.error("[GraphQL] ExecuteGQL error caught:",{hasResponse:!!s?.response,hasErrors:!!s?.response?.errors,errorCount:s?.response?.errors?.length,firstError:s?.response?.errors?.[0],errorCode:s?.response?.errors?.[0]?.extensions?.code,errorMessage:s?.response?.errors?.[0]?.message,fullError:s}),s&&s.response&&s.response.errors?.length>0)if(s.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw l("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw l(s),s}}async RefreshToken(){const e=I.Instance&&I.Instance._configData===this._configData;if(e&&I.Instance._refreshPromise)return I.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(I.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&I.Instance&&(I.Instance._refreshPromise=null)}}async performTokenRefresh(){if(this._configData.Data.RefreshTokenFunction)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,I.Instance&&I.Instance._configData===this._configData&&(I.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 I.Instance.RefreshToken()}static async clearClientCache(e=new Set){const t=[];for(let r=0;r<localStorage.length;r++){const s=localStorage.key(r);s&&!e.has(s)&&t.push(s)}t.forEach(r=>localStorage.removeItem(r)),await new Promise(r=>{const s=indexedDB.deleteDatabase("MJ_Metadata");s.onsuccess=()=>r(),s.onerror=()=>r(),s.onblocked=()=>r()})}CreateNewGraphQLClient(e,t,r,s,n){const a={"x-session-id":r};t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),n&&(a["x-api-key"]=n);const i=new O(e,{headers:a});for(const[o,y]of this._dynamicHeaders)i.setHeader(o,y);return i}userInfoString(){return this.infoString(new q(null,null))}userRoleInfoString(){return this.infoString(new ce(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
606
606
  `:s.startsWith("_")||(t+=s+`
607
- `);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new Y:this._localStorageProvider=new ue),this._localStorageProvider}get Metadata(){return this}get SocketConnectivity$(){return this._socketStateSubject.asObservable()}get SocketConnectionState(){return this._socketStateSubject.value}ForceSocketReconnect(){this.disposeWSClient()}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._isDisposingSocketIntentionally=!1,this._wsClient=De({url:this.ConfigData.WSURL,connectionParams:y(()=>({Authorization:"Bearer "+this.ConfigData.Token}),"connectionParams"),keepAlive:3e4,retryAttempts:3,shouldRetry:y(()=>!0,"shouldRetry")}),this._wsClientCreatedAt=e,this._wsClient.on("connected",()=>{this._socketStateSubject.next("connected")}),this._wsClient.on("closed",t=>{if(this._isDisposingSocketIntentionally)return;this._socketStateSubject.next("disconnected"),t?.code===4403&&this._configData.Data.RefreshTokenFunction&&this.RefreshToken().catch(()=>{})}),this._subscriptionCleanupTimer||(this._subscriptionCleanupTimer=setInterval(()=>{this.cleanupStaleSubscriptions()},this.SUBSCRIPTION_CLEANUP_INTERVAL_MS))),this._wsClient}disposeWSClient(){if(this._wsClient){this._isDisposingSocketIntentionally=!0;try{this._wsClient.dispose()}catch(e){console.error("[GraphQLDataProvider] Error disposing WebSocket client:",e)}this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject.next("unknown")}}completeAllSubjects(){this._pushStatusSubjects.forEach((e,t)=>{try{e.subject.complete(),e.subscription.unsubscribe()}catch(r){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,r)}}),this._pushStatusSubjects.clear()}cleanupStaleSubscriptions(){if(!this._isCleaningUp){this._isCleaningUp=!0;try{const e=Date.now(),t=this._pushStatusSubjects.size,r=Array.from(this._pushStatusSubjects.entries()),s=[];r.forEach(([n,a])=>{const i=e-a.lastRequestedAt,o=e-a.lastEmissionAt;a.activeSubscribers===0&&i>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&o>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${n} for cleanup: activeSubscribers=${a.activeSubscribers}, timeSinceRequested=${Math.round(i/1e3)}s, timeSinceEmission=${Math.round(o/1e3)}s`),s.push(n))}),s.forEach(n=>{const a=this._pushStatusSubjects.get(n);if(a)try{a.subject.complete(),a.subscription.unsubscribe(),this._pushStatusSubjects.delete(n),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${n}`)}catch(i){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${n}:`,i)}}),s.length>0&&console.log(`[GraphQLDataProvider] Cleaned up ${s.length} stale subscription(s)`),this._pushStatusSubjects.size===0&&this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&(console.log("[GraphQLDataProvider] Disposing of idle WebSocket client"),this.disposeWSClient())}finally{this._isCleaningUp=!1}}}subscribe(e,t){return new T(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=s.subscribe({query:e,variables:t},{next:y(a=>{r.next(a.data)},"next"),error:y(async a=>{const i=a;if(i?.extensions?.code==="JWT_EXPIRED"||i?.message?.includes("token has expired")||i?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] WebSocket JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),r.complete()}catch(d){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",d),r.error(d)}}else r.error(a)},"error"),complete:y(()=>{r.complete()},"complete")});return()=>{this._activeSubscriptionCount--,n()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),r=this._pushStatusSubjects.get(e);if(r)return r.lastRequestedAt=t,new T(o=>{r.activeSubscribers++;const d=r.subject.subscribe(o);return()=>{const u=this._pushStatusSubjects.get(e);u&&u.activeSubscribers>0&&u.activeSubscribers--,d.unsubscribe()}});const s=c`subscription StatusUpdates($sessionId: String!) {
607
+ `);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new Y:this._localStorageProvider=new ue),this._localStorageProvider}get Metadata(){return this}get SocketConnectivity$(){return this._socketStateSubject.asObservable()}get SocketConnectionState(){return this._socketStateSubject.value}ForceSocketReconnect(){this.disposeWSClient()}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._isDisposingSocketIntentionally=!1,this._wsClient=De({url:this.ConfigData.WSURL,connectionParams:d(()=>({Authorization:"Bearer "+this.ConfigData.Token}),"connectionParams"),keepAlive:3e4,retryAttempts:3,shouldRetry:d(()=>!0,"shouldRetry")}),this._wsClientCreatedAt=e,this._wsClient.on("connected",()=>{this._socketStateSubject.next("connected")}),this._wsClient.on("closed",t=>{if(this._isDisposingSocketIntentionally)return;this._socketStateSubject.next("disconnected"),t?.code===4403&&this._configData.Data.RefreshTokenFunction&&this.RefreshToken().catch(()=>{})}),this._subscriptionCleanupTimer||(this._subscriptionCleanupTimer=setInterval(()=>{this.cleanupStaleSubscriptions()},this.SUBSCRIPTION_CLEANUP_INTERVAL_MS))),this._wsClient}disposeWSClient(){if(this._wsClient){this._isDisposingSocketIntentionally=!0;try{this._wsClient.dispose()}catch(e){console.error("[GraphQLDataProvider] Error disposing WebSocket client:",e)}this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject.next("unknown")}}completeAllSubjects(){this._pushStatusSubjects.forEach((e,t)=>{try{e.subject.complete(),e.subscription.unsubscribe()}catch(r){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,r)}}),this._pushStatusSubjects.clear()}cleanupStaleSubscriptions(){if(!this._isCleaningUp){this._isCleaningUp=!0;try{const e=Date.now(),t=this._pushStatusSubjects.size,r=Array.from(this._pushStatusSubjects.entries()),s=[];r.forEach(([n,a])=>{const i=e-a.lastRequestedAt,o=e-a.lastEmissionAt;a.activeSubscribers===0&&i>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&o>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${n} for cleanup: activeSubscribers=${a.activeSubscribers}, timeSinceRequested=${Math.round(i/1e3)}s, timeSinceEmission=${Math.round(o/1e3)}s`),s.push(n))}),s.forEach(n=>{const a=this._pushStatusSubjects.get(n);if(a)try{a.subject.complete(),a.subscription.unsubscribe(),this._pushStatusSubjects.delete(n),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${n}`)}catch(i){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${n}:`,i)}}),s.length>0&&console.log(`[GraphQLDataProvider] Cleaned up ${s.length} stale subscription(s)`),this._pushStatusSubjects.size===0&&this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&(console.log("[GraphQLDataProvider] Disposing of idle WebSocket client"),this.disposeWSClient())}finally{this._isCleaningUp=!1}}}subscribe(e,t){return new T(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=s.subscribe({query:e,variables:t},{next:d(a=>{r.next(a.data)},"next"),error:d(async a=>{const i=a;if(i?.extensions?.code==="JWT_EXPIRED"||i?.message?.includes("token has expired")||i?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] WebSocket JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),r.complete()}catch(y){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",y),r.error(y)}}else r.error(a)},"error"),complete:d(()=>{r.complete()},"complete")});return()=>{this._activeSubscriptionCount--,n()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),r=this._pushStatusSubjects.get(e);if(r)return r.lastRequestedAt=t,new T(o=>{r.activeSubscribers++;const y=r.subject.subscribe(o);return()=>{const u=this._pushStatusSubjects.get(e);u&&u.activeSubscribers>0&&u.activeSubscribers--,y.unsubscribe()}});const s=c`subscription StatusUpdates($sessionId: String!) {
608
608
  statusUpdates(sessionId: $sessionId) {
609
609
  date
610
610
  message
611
611
  sessionId
612
612
  }
613
613
  }
614
- `,n=new fe,a=this.getOrCreateWSClient(),i=new Re;return i.add(new T(o=>{const d=a.subscribe({query:s,variables:{sessionId:e}},{next:y(u=>{const f=this._pushStatusSubjects.get(e);f&&(f.lastEmissionAt=Date.now()),o.next(u.data.statusUpdates.message)},"next"),error:y(async u=>{const f=u;if(f?.extensions?.code==="JWT_EXPIRED"||f?.message?.includes("token has expired")||f?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),o.complete()}catch(S){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",S),o.error(S)}}else o.error(u)},"error"),complete:y(()=>{o.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,d()}}).subscribe({next:y(o=>n.next(o),"next"),error:y(o=>{n.error(o),this._pushStatusSubjects.delete(e)},"error"),complete:y(()=>{n.complete(),this._pushStatusSubjects.delete(e)},"complete")})),this._pushStatusSubjects.set(e,{subject:n,subscription:i,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new T(o=>{const d=this._pushStatusSubjects.get(e);d&&d.activeSubscribers++;const u=n.subscribe(o);return()=>{const f=this._pushStatusSubjects.get(e);f&&f.activeSubscribers>0&&f.activeSubscribers--,u.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.UnsubscribeFromCacheInvalidation(),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}ClientToolRequests(e){return this.subscribe(`
614
+ `,n=new fe,a=this.getOrCreateWSClient(),i=new Re;return i.add(new T(o=>{const y=a.subscribe({query:s,variables:{sessionId:e}},{next:d(u=>{const f=this._pushStatusSubjects.get(e);f&&(f.lastEmissionAt=Date.now()),o.next(u.data.statusUpdates.message)},"next"),error:d(async u=>{const f=u;if(f?.extensions?.code==="JWT_EXPIRED"||f?.message?.includes("token has expired")||f?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),o.complete()}catch(p){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",p),o.error(p)}}else o.error(u)},"error"),complete:d(()=>{o.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,y()}}).subscribe({next:d(o=>n.next(o),"next"),error:d(o=>{n.error(o),this._pushStatusSubjects.delete(e)},"error"),complete:d(()=>{n.complete(),this._pushStatusSubjects.delete(e)},"complete")})),this._pushStatusSubjects.set(e,{subject:n,subscription:i,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new T(o=>{const y=this._pushStatusSubjects.get(e);y&&y.activeSubscribers++;const u=n.subscribe(o);return()=>{const f=this._pushStatusSubjects.get(e);f&&f.activeSubscribers>0&&f.activeSubscribers--,u.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.UnsubscribeFromCacheInvalidation(),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}ClientToolRequests(e){return this.subscribe(`
615
615
  subscription ClientToolRequest($sessionID: String!) {
616
616
  ClientToolRequest(sessionID: $sessionID) {
617
617
  AgentRunID
@@ -633,7 +633,7 @@ var re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0})
633
633
  OriginSessionID
634
634
  RecordData
635
635
  }
636
- }`,t=this.subscribe(e);this._cacheInvalidationSubscription=t.subscribe({next:y(r=>{const s=r?.cacheInvalidation;if(!s)return;if(s.OriginSessionID&&s.OriginSessionID===this.sessionId){console.debug(`[GraphQLDataProvider] Skipping self-originated cache invalidation for "${s.EntityName}" (action: ${s.Action})`);return}console.debug(`[GraphQLDataProvider] Cache invalidation received: ${s.Action} for "${s.EntityName}" from server ${s.SourceServerID?.substring(0,8)||"unknown"}`);const n={type:"remote-invalidate",entityName:s.EntityName,baseEntity:null,provider:this,payload:{primaryKeyValues:s.PrimaryKeyValues,action:s.Action,sourceServerId:s.SourceServerID,timestamp:s.Timestamp,recordData:s.RecordData}};K.Instance.RaiseEvent({event:j.ComponentEvent,eventCode:le.BaseEventCode,args:n,component:this})},"next"),error:y(r=>{console.error("[GraphQLDataProvider] Cache invalidation subscription error:",r),this._cacheInvalidationSubscription=null},"error"),complete:y(()=>{console.log("[GraphQLDataProvider] Cache invalidation subscription completed, will re-establish on next WebSocket creation"),this._cacheInvalidationSubscription=null},"complete")})}UnsubscribeFromCacheInvalidation(){this._cacheInvalidationSubscription&&(this._cacheInvalidationSubscription.unsubscribe(),this._cacheInvalidationSubscription=null)}async FindISAChildEntity(e,t,r){if(!e.IsParentType)return null;const s=`query FindISAChildEntity($EntityName: String!, $RecordID: String!) {
636
+ }`,t=this.subscribe(e);this._cacheInvalidationSubscription=t.subscribe({next:d(r=>{const s=r?.cacheInvalidation;if(!s)return;if(s.OriginSessionID&&s.OriginSessionID===this.sessionId){I.VerboseCacheInvalidationLogging&&console.debug(`[GraphQLDataProvider] Skipping self-originated cache invalidation for "${s.EntityName}" (action: ${s.Action})`);return}I.VerboseCacheInvalidationLogging&&console.debug(`[GraphQLDataProvider] Cache invalidation received: ${s.Action} for "${s.EntityName}" from server ${s.SourceServerID?.substring(0,8)||"unknown"}`);const n={type:"remote-invalidate",entityName:s.EntityName,baseEntity:null,provider:this,payload:{primaryKeyValues:s.PrimaryKeyValues,action:s.Action,sourceServerId:s.SourceServerID,timestamp:s.Timestamp,recordData:s.RecordData}};K.Instance.RaiseEvent({event:j.ComponentEvent,eventCode:le.BaseEventCode,args:n,component:this})},"next"),error:d(r=>{console.error("[GraphQLDataProvider] Cache invalidation subscription error:",r),this._cacheInvalidationSubscription=null},"error"),complete:d(()=>{console.log("[GraphQLDataProvider] Cache invalidation subscription completed, will re-establish on next WebSocket creation"),this._cacheInvalidationSubscription=null},"complete")})}UnsubscribeFromCacheInvalidation(){this._cacheInvalidationSubscription&&(this._cacheInvalidationSubscription.unsubscribe(),this._cacheInvalidationSubscription=null)}async FindISAChildEntity(e,t,r){if(!e.IsParentType)return null;const s=`query FindISAChildEntity($EntityName: String!, $RecordID: String!) {
637
637
  FindISAChildEntity(EntityName: $EntityName, RecordID: $RecordID) {
638
638
  Success
639
639
  ChildEntityName
@@ -645,14 +645,14 @@ var re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0})
645
645
  ChildEntityNames
646
646
  ErrorMessage
647
647
  }
648
- }`;try{const n=await this.ExecuteGQL(s,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntities?.Success&&n.FindISAChildEntities.ChildEntityNames?n.FindISAChildEntities.ChildEntityNames.map(a=>({ChildEntityName:a})):[]}catch(n){return l(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function Me(m){const e=new I;return ye(e),await e.Config(m),await e.preValidateAndRefresh(),K.Instance.RaiseEvent({event:j.LoggedIn,eventCode:null,component:this,args:null}),await me.Instance.Startup(),e}y(Me,"setupGraphQLClient");class Te{static{y(this,"SyncRolesAndUsersResult")}}class xe{static{y(this,"RoleInput")}}class Le{static{y(this,"UserInput")}}class Fe{static{y(this,"RolesAndUsersInput")}}var Z=(m=>(m.Create="Create",m.Update="Update",m.CreateOrUpdate="CreateOrUpdate",m.Delete="Delete",m.DeleteWithFilter="DeleteWithFilter",m))(Z||{});class Qe{static{y(this,"ActionItemInput")}}class Ue{static{y(this,"SyncDataResult")}constructor(){this.Results=[]}}class Ge{static{y(this,"ActionItemOutput")}}class Ve{static{y(this,"GraphQLSystemUserClient")}get Client(){return this._client}constructor(e,t,r,s){const n={"x-session-id":r};this._sessionId=r,t&&(n.authorization="Bearer "+t),s&&(n["x-mj-api-key"]=s),this._client=new q(e,{headers:n})}resolvePlatformSQL(e){if(e!=null)return ge(e)?e.default:e}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
648
+ }`;try{const n=await this.ExecuteGQL(s,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntities?.Success&&n.FindISAChildEntities.ChildEntityNames?n.FindISAChildEntities.ChildEntityNames.map(a=>({ChildEntityName:a})):[]}catch(n){return l(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function Ne(m){const e=new I;return ye(e),await e.Config(m),await e.preValidateAndRefresh(),K.Instance.RaiseEvent({event:j.LoggedIn,eventCode:null,component:this,args:null}),await me.Instance.Startup(),e}d(Ne,"setupGraphQLClient");class Te{static{d(this,"SyncRolesAndUsersResult")}}class xe{static{d(this,"RoleInput")}}class Le{static{d(this,"UserInput")}}class Fe{static{d(this,"RolesAndUsersInput")}}var Z=(m=>(m.Create="Create",m.Update="Update",m.CreateOrUpdate="CreateOrUpdate",m.Delete="Delete",m.DeleteWithFilter="DeleteWithFilter",m))(Z||{});class Qe{static{d(this,"ActionItemInput")}}class Ue{static{d(this,"SyncDataResult")}constructor(){this.Results=[]}}class Ge{static{d(this,"ActionItemOutput")}}class Ve{static{d(this,"GraphQLSystemUserClient")}get Client(){return this._client}constructor(e,t,r,s){const n={"x-session-id":r};this._sessionId=r,t&&(n.authorization="Bearer "+t),s&&(n["x-mj-api-key"]=s),this._client=new O(e,{headers:n})}resolvePlatformSQL(e){if(e!=null)return ge(e)?e.default:e}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
649
649
  GetData(input: $input) {
650
650
  Success
651
651
  ErrorMessages
652
652
  Queries
653
653
  Results
654
654
  }
655
- }`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(n=>n?v(n):null),ErrorMessages:s.GetData.ErrorMessages,Queries:s.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:s.GetData?.ErrorMessages??["Unknown error"],Queries:s.GetData?.Queries??e}}catch(r){let s=r instanceof Error?r.message:String(r);const n=s.match(/Error: ([^:]+)\./);if(n&&(s=n[1]+"."),pe()){const a=`GraphQLSystemUserClient::GetData - Error getting data - ${r}`;l(a)}return{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
655
+ }`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(n=>n?E(n):null),ErrorMessages:s.GetData.ErrorMessages,Queries:s.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:s.GetData?.ErrorMessages??["Unknown error"],Queries:s.GetData?.Queries??e}}catch(r){let s=r instanceof Error?r.message:String(r);const n=s.match(/Error: ([^:]+)\./);if(n&&(s=n[1]+"."),Se()){const a=`GraphQLSystemUserClient::GetData - Error getting data - ${r}`;l(a)}return{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
656
656
  GetAllEntities {
657
657
  Success
658
658
  ErrorMessage
@@ -783,7 +783,7 @@ var re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0})
783
783
  ErrorMessage
784
784
  AppliedParameters
785
785
  }
786
- }`,r={QueryID:e.QueryID};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataSystemUser?{...s.GetQueryDataSystemUser,Results:s.GetQueryDataSystemUser.Results?v(s.GetQueryDataSystemUser.Results):null}:{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return 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) {
786
+ }`,r={QueryID:e.QueryID};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataSystemUser?{...s.GetQueryDataSystemUser,Results:s.GetQueryDataSystemUser.Results?E(s.GetQueryDataSystemUser.Results):null}:{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return l(`GraphQLSystemUserClient::GetQueryDataSystemUser - Error executing query - ${t}`),{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async GetQueryDataByName(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataByNameSystemUser($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
787
787
  GetQueryDataByNameSystemUser(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
788
788
  QueryID
789
789
  QueryName
@@ -795,7 +795,7 @@ var re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0})
795
795
  ErrorMessage
796
796
  AppliedParameters
797
797
  }
798
- }`,r={QueryName:e.QueryName};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataByNameSystemUser?{...s.GetQueryDataByNameSystemUser,Results:s.GetQueryDataByNameSystemUser.Results?v(s.GetQueryDataByNameSystemUser.Results):null}:{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return l(`GraphQLSystemUserClient::GetQueryDataByNameSystemUser - Error executing query - ${t}`),{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async CreateQuery(e){try{const r=await this.Client.request(`mutation CreateQuerySystemUser($input: CreateQuerySystemUserInput!) {
798
+ }`,r={QueryName:e.QueryName};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataByNameSystemUser?{...s.GetQueryDataByNameSystemUser,Results:s.GetQueryDataByNameSystemUser.Results?E(s.GetQueryDataByNameSystemUser.Results):null}:{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return l(`GraphQLSystemUserClient::GetQueryDataByNameSystemUser - Error executing query - ${t}`),{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async CreateQuery(e){try{const r=await this.Client.request(`mutation CreateQuerySystemUser($input: CreateQuerySystemUserInput!) {
799
799
  CreateQuerySystemUser(input: $input) {
800
800
  Success
801
801
  ErrorMessage
@@ -1006,7 +1006,7 @@ var re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0})
1006
1006
  result
1007
1007
  }
1008
1008
  }
1009
- `,r=this.prepareAgentVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIAgentSystemUser?this.processAgentResult(s.RunAIAgentSystemUser.result):{success:!1,agentRun:void 0}}catch(t){return l(`GraphQLSystemUserClient::RunAIAgent - Error running AI agent - ${t}`),{success:!1,agentRun:void 0}}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}prepareAgentVariables(e){const t={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._sessionId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),t}processPromptResult(e){let t,r,s;try{e.parsedResult&&(t=JSON.parse(e.parsedResult))}catch{t=e.parsedResult}try{e.validationResult&&(r=JSON.parse(e.validationResult))}catch{r=e.validationResult}try{e.chatResult&&(s=JSON.parse(e.chatResult))}catch{s=e.chatResult}return{success:e.success,output:e.output,parsedResult:t,error:e.error,executionTimeMs:e.executionTimeMs,tokensUsed:e.tokensUsed,promptRunId:e.promptRunId,rawResult:e.rawResult,validationResult:r,chatResult:s}}processAgentResult(e){return v(e)}async TestQuerySQL(e){try{const r=await this.Client.request(`query TestQuerySQL($input: TestQuerySQLInput!) {
1009
+ `,r=this.prepareAgentVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIAgentSystemUser?this.processAgentResult(s.RunAIAgentSystemUser.result):{success:!1,agentRun:void 0}}catch(t){return l(`GraphQLSystemUserClient::RunAIAgent - Error running AI agent - ${t}`),{success:!1,agentRun:void 0}}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}prepareAgentVariables(e){const t={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._sessionId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),t}processPromptResult(e){let t,r,s;try{e.parsedResult&&(t=JSON.parse(e.parsedResult))}catch{t=e.parsedResult}try{e.validationResult&&(r=JSON.parse(e.validationResult))}catch{r=e.validationResult}try{e.chatResult&&(s=JSON.parse(e.chatResult))}catch{s=e.chatResult}return{success:e.success,output:e.output,parsedResult:t,error:e.error,executionTimeMs:e.executionTimeMs,tokensUsed:e.tokensUsed,promptRunId:e.promptRunId,rawResult:e.rawResult,validationResult:r,chatResult:s}}processAgentResult(e){return E(e)}async TestQuerySQL(e){try{const r=await this.Client.request(`query TestQuerySQL($input: TestQuerySQLInput!) {
1010
1010
  TestQuerySQL(input: $input) {
1011
1011
  Success
1012
1012
  Results
@@ -1015,7 +1015,7 @@ var re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0})
1015
1015
  ErrorMessage
1016
1016
  AppliedParameters
1017
1017
  }
1018
- }`,{input:e});return r&&r.TestQuerySQL?{Success:r.TestQuerySQL.Success,Results:r.TestQuerySQL.Results?v(r.TestQuerySQL.Results):null,RowCount:r.TestQuerySQL.RowCount,ExecutionTime:r.TestQuerySQL.ExecutionTime,ErrorMessage:r.TestQuerySQL.ErrorMessage,AppliedParameters:r.TestQuerySQL.AppliedParameters?v(r.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`
1018
+ }`,{input:e});return r&&r.TestQuerySQL?{Success:r.TestQuerySQL.Success,Results:r.TestQuerySQL.Results?E(r.TestQuerySQL.Results):null,RowCount:r.TestQuerySQL.RowCount,ExecutionTime:r.TestQuerySQL.ExecutionTime,ErrorMessage:r.TestQuerySQL.ErrorMessage,AppliedParameters:r.TestQuerySQL.AppliedParameters?E(r.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`
1019
1019
  query ExecuteSimplePromptSystemUser(
1020
1020
  $systemPrompt: String!,
1021
1021
  $messages: String,
@@ -1147,7 +1147,7 @@ var re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0})
1147
1147
  ErrorMessage
1148
1148
  }
1149
1149
  }
1150
- `,r={query:e.Query};e.MaxResults!==void 0&&(r.maxResults=e.MaxResults);const s=await this.Client.request(t,r);return s?.PreviewSearchAsSystemUser?this.mapSearchResponse(s.PreviewSearchAsSystemUser):this.searchErrorResponse("Invalid response from server")}catch(t){return l(`GraphQLSystemUserClient::PreviewSearch - Error executing preview search - ${t}`),this.searchErrorResponse(t instanceof Error?t.message:String(t))}}mapSearchResponse(e){return{Success:e.Success,Results:(e.Results||[]).map(t=>({ID:t.ID,EntityName:t.EntityName,RecordID:t.RecordID,SourceType:t.SourceType,ResultType:t.ResultType,Title:t.Title,Snippet:t.Snippet,Score:t.Score,ScoreBreakdown:this.mapScoreBreakdown(t.ScoreBreakdown),Tags:t.Tags||[],EntityIcon:t.EntityIcon,RecordName:t.RecordName,MatchedAt:t.MatchedAt,RawMetadata:t.RawMetadata,ProviderId:t.ProviderId,ProviderLabel:t.ProviderLabel,ProviderIcon:t.ProviderIcon})),TotalCount:e.TotalCount,ElapsedMs:e.ElapsedMs,SourceCounts:this.mapSourceCounts(e.SourceCounts),Providers:(e.Providers||[]).map(t=>({ID:t.ID,Name:t.Name,DisplayName:t.DisplayName,Icon:t.Icon,SourceType:t.SourceType,Priority:t.Priority})),ErrorMessage:e.ErrorMessage}}mapScoreBreakdown(e){if(!e)return{};const t={};return e.Vector!==void 0&&(t.Vector=e.Vector),e.FullText!==void 0&&(t.FullText=e.FullText),e.Entity!==void 0&&(t.Entity=e.Entity),e.Storage!==void 0&&(t.Storage=e.Storage),t}mapSourceCounts(e){return e?{Vector:e.Vector??0,FullText:e.FullText??0,Entity:e.Entity??0,Storage:e.Storage??0}:{Vector:0,FullText:0,Entity:0,Storage:0}}searchErrorResponse(e){return{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,SourceCounts:{Vector:0,FullText:0,Entity:0,Storage:0},Providers:[],ErrorMessage:`Error: ${e}`}}}class _e{static{y(this,"GetDataOutput")}}class qe{static{y(this,"SimpleRemoteEntityOutput")}}class Oe{static{y(this,"SimpleRemoteEntity")}}class ke{static{y(this,"SimpleRemoteEntityField")}}class Be{static{y(this,"GraphQLActionClient")}constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),n=this.createActionVariables(e,s,r),a=await this.executeActionMutation(n);return this.processActionResult(a,t)}catch(s){return this.handleActionError(s,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{...t,Value:r}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=c`
1150
+ `,r={query:e.Query};e.MaxResults!==void 0&&(r.maxResults=e.MaxResults);const s=await this.Client.request(t,r);return s?.PreviewSearchAsSystemUser?this.mapSearchResponse(s.PreviewSearchAsSystemUser):this.searchErrorResponse("Invalid response from server")}catch(t){return l(`GraphQLSystemUserClient::PreviewSearch - Error executing preview search - ${t}`),this.searchErrorResponse(t instanceof Error?t.message:String(t))}}mapSearchResponse(e){return{Success:e.Success,Results:(e.Results||[]).map(t=>({ID:t.ID,EntityName:t.EntityName,RecordID:t.RecordID,SourceType:t.SourceType,ResultType:t.ResultType,Title:t.Title,Snippet:t.Snippet,Score:t.Score,ScoreBreakdown:this.mapScoreBreakdown(t.ScoreBreakdown),Tags:t.Tags||[],EntityIcon:t.EntityIcon,RecordName:t.RecordName,MatchedAt:t.MatchedAt,RawMetadata:t.RawMetadata,ProviderId:t.ProviderId,ProviderLabel:t.ProviderLabel,ProviderIcon:t.ProviderIcon})),TotalCount:e.TotalCount,ElapsedMs:e.ElapsedMs,SourceCounts:this.mapSourceCounts(e.SourceCounts),Providers:(e.Providers||[]).map(t=>({ID:t.ID,Name:t.Name,DisplayName:t.DisplayName,Icon:t.Icon,SourceType:t.SourceType,Priority:t.Priority})),ErrorMessage:e.ErrorMessage}}mapScoreBreakdown(e){if(!e)return{};const t={};return e.Vector!==void 0&&(t.Vector=e.Vector),e.FullText!==void 0&&(t.FullText=e.FullText),e.Entity!==void 0&&(t.Entity=e.Entity),e.Storage!==void 0&&(t.Storage=e.Storage),t}mapSourceCounts(e){return e?{Vector:e.Vector??0,FullText:e.FullText??0,Entity:e.Entity??0,Storage:e.Storage??0}:{Vector:0,FullText:0,Entity:0,Storage:0}}searchErrorResponse(e){return{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,SourceCounts:{Vector:0,FullText:0,Entity:0,Storage:0},Providers:[],ErrorMessage:`Error: ${e}`}}}class _e{static{d(this,"GetDataOutput")}}class Oe{static{d(this,"SimpleRemoteEntityOutput")}}class qe{static{d(this,"SimpleRemoteEntity")}}class ke{static{d(this,"SimpleRemoteEntityField")}}class Be{static{d(this,"GraphQLActionClient")}constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),n=this.createActionVariables(e,s,r),a=await this.executeActionMutation(n);return this.processActionResult(a,t)}catch(s){return this.handleActionError(s,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{...t,Value:r}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=c`
1151
1151
  mutation RunAction($input: RunActionInput!) {
1152
1152
  RunAction(input: $input) {
1153
1153
  Success
@@ -1164,7 +1164,7 @@ var re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0})
1164
1164
  ResultData
1165
1165
  }
1166
1166
  }
1167
- `;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(r){l(`Failed to parse entity action result data: ${r}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return l(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}}class Ke{static{y(this,"GraphQLListsClient")}constructor(e){this.dataProvider=e}async PreviewListDelta(e){const t=c`
1167
+ `;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(r){l(`Failed to parse entity action result data: ${r}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return l(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}}class Ke{static{d(this,"GraphQLListsClient")}constructor(e){this.dataProvider=e}async PreviewListDelta(e){const t=c`
1168
1168
  query PreviewListDelta($input: ComputeDeltaInput!) {
1169
1169
  PreviewListDelta(input: $input) {
1170
1170
  ...ListDeltaFields
@@ -1314,7 +1314,7 @@ var re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0})
1314
1314
  Message
1315
1315
  PermissionID
1316
1316
  }
1317
- `;function je(m){return m.kind==="user"?{Kind:"user",UserID:m.userId}:{Kind:"role",RoleID:m.roleId}}y(je,"serializeShareTarget");function V(m){if(!m||typeof m!="object")throw new Error("GraphQLListsClient: empty/invalid ShareResult response");const e=m;return{Success:e.Success,ResultCode:e.ResultCode,Message:e.Message,PermissionID:e.PermissionID??void 0}}y(V,"parseShareResult");function Je(m){const e=m,t=e.Target.Kind==="user"?{kind:"user",userId:e.Target.UserID}:{kind:"role",roleId:e.Target.RoleID};return{PermissionID:e.PermissionID,ListID:e.ListID,Target:t,PermissionLevel:e.PermissionLevel,Status:e.Status,SharedByUserID:e.SharedByUserID??null,CreatedAt:new Date(e.CreatedAt)}}y(Je,"parseShareSummary");function _(m){switch(m.kind){case"list":return{Kind:"list",ListID:m.listId};case"view":return{Kind:"view",ViewID:m.viewId};case"adhoc":return{Kind:"adhoc",EntityName:m.entityName,ExtraFilter:m.extraFilter}}}y(_,"serializeListSource");function te(m){if(!m||typeof m!="object")throw new Error("GraphQLListsClient: empty/invalid ListDelta response from server");const e=m;return{TargetListId:e.TargetListId,EntityName:e.EntityName,ToAdd:e.ToAdd,ToRemove:e.ToRemove,Unchanged:e.Unchanged,Counts:e.Counts,Warnings:e.Warnings.map(We),DeltaToken:e.DeltaToken}}y(te,"parseListDelta");function We(m){let e;if(m.DetailsJSON)try{e=JSON.parse(m.DetailsJSON)}catch(t){l(`GraphQLListsClient: failed to parse warning details JSON: ${t}`)}return{Code:m.Code,Message:m.Message,Details:e}}y(We,"parseWarning");function Q(m){if(!m||typeof m!="object")throw new Error("GraphQLListsClient: empty/invalid ApplyResult response from server");const e=m;return{Success:e.Success,ResultCode:e.ResultCode,Message:e.Message,CreatedListId:e.CreatedListId??void 0,TargetListId:e.TargetListId??void 0,Counts:e.AddedCount!=null||e.RemovedCount!=null||e.FailedCount!=null?{Added:e.AddedCount??0,Removed:e.RemovedCount??0,Failed:e.FailedCount??0}:void 0,Errors:e.Errors??void 0}}y(Q,"parseApplyResult");class ze{static{y(this,"GraphQLEncryptionClient")}constructor(e){this._dataProvider=e}async CreateAPIKey(e){try{const t=this.createAPIKeyVariables(e),r=await this.executeCreateAPIKeyMutation(t);return this.processCreateAPIKeyResult(r)}catch(t){return this.handleCreateAPIKeyError(t)}}createAPIKeyVariables(e){return{input:{Label:e.Label,Description:e.Description,ExpiresAt:e.ExpiresAt?.toISOString(),ScopeIDs:e.ScopeIDs}}}async executeCreateAPIKeyMutation(e){const t=c`
1317
+ `;function je(m){return m.kind==="user"?{Kind:"user",UserID:m.userId}:{Kind:"role",RoleID:m.roleId}}d(je,"serializeShareTarget");function V(m){if(!m||typeof m!="object")throw new Error("GraphQLListsClient: empty/invalid ShareResult response");const e=m;return{Success:e.Success,ResultCode:e.ResultCode,Message:e.Message,PermissionID:e.PermissionID??void 0}}d(V,"parseShareResult");function Je(m){const e=m,t=e.Target.Kind==="user"?{kind:"user",userId:e.Target.UserID}:{kind:"role",roleId:e.Target.RoleID};return{PermissionID:e.PermissionID,ListID:e.ListID,Target:t,PermissionLevel:e.PermissionLevel,Status:e.Status,SharedByUserID:e.SharedByUserID??null,CreatedAt:new Date(e.CreatedAt)}}d(Je,"parseShareSummary");function _(m){switch(m.kind){case"list":return{Kind:"list",ListID:m.listId};case"view":return{Kind:"view",ViewID:m.viewId};case"adhoc":return{Kind:"adhoc",EntityName:m.entityName,ExtraFilter:m.extraFilter}}}d(_,"serializeListSource");function te(m){if(!m||typeof m!="object")throw new Error("GraphQLListsClient: empty/invalid ListDelta response from server");const e=m;return{TargetListId:e.TargetListId,EntityName:e.EntityName,ToAdd:e.ToAdd,ToRemove:e.ToRemove,Unchanged:e.Unchanged,Counts:e.Counts,Warnings:e.Warnings.map(We),DeltaToken:e.DeltaToken}}d(te,"parseListDelta");function We(m){let e;if(m.DetailsJSON)try{e=JSON.parse(m.DetailsJSON)}catch(t){l(`GraphQLListsClient: failed to parse warning details JSON: ${t}`)}return{Code:m.Code,Message:m.Message,Details:e}}d(We,"parseWarning");function Q(m){if(!m||typeof m!="object")throw new Error("GraphQLListsClient: empty/invalid ApplyResult response from server");const e=m;return{Success:e.Success,ResultCode:e.ResultCode,Message:e.Message,CreatedListId:e.CreatedListId??void 0,TargetListId:e.TargetListId??void 0,Counts:e.AddedCount!=null||e.RemovedCount!=null||e.FailedCount!=null?{Added:e.AddedCount??0,Removed:e.RemovedCount??0,Failed:e.FailedCount??0}:void 0,Errors:e.Errors??void 0}}d(Q,"parseApplyResult");class ze{static{d(this,"GraphQLEncryptionClient")}constructor(e){this._dataProvider=e}async CreateAPIKey(e){try{const t=this.createAPIKeyVariables(e),r=await this.executeCreateAPIKeyMutation(t);return this.processCreateAPIKeyResult(r)}catch(t){return this.handleCreateAPIKeyError(t)}}createAPIKeyVariables(e){return{input:{Label:e.Label,Description:e.Description,ExpiresAt:e.ExpiresAt?.toISOString(),ScopeIDs:e.ScopeIDs}}}async executeCreateAPIKeyMutation(e){const t=c`
1318
1318
  mutation CreateAPIKey($input: CreateAPIKeyInput!) {
1319
1319
  CreateAPIKey(input: $input) {
1320
1320
  Success
@@ -1330,7 +1330,33 @@ var re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0})
1330
1330
  Error
1331
1331
  }
1332
1332
  }
1333
- `,s=await this._dataProvider.ExecuteGQL(t,{apiKeyId:e});return s?.RevokeAPIKey?{Success:s.RevokeAPIKey.Success,Error:s.RevokeAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}catch(t){const r=t;return l(`Error revoking API key: ${r.message}`),{Success:!1,Error:`Error: ${r.message}`}}}}class He{static{y(this,"GraphQLTestingClient")}constructor(e){this._dataProvider=e}async RunTest(e){try{const t=this.buildRunTestMutation(),r=this.buildRunTestVariables(e),s={};return await P.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTest",operationLabel:"RunTest",validateAck:y(n=>n?.success===!0,"validateAck"),isCompletionEvent:y(n=>this.isTestCompletionEvent(n,e.testId),"isCompletionEvent"),extractResult:y(n=>this.extractTestResult(n),"extractResult"),onMessage:y(n=>{this.captureTestRunId(n,s),e.onProgress&&this.forwardTestProgress(n,e.onProgress)},"onMessage"),onStall:y(()=>this.reconcileTestRun(s),"onStall"),createErrorResult:y(n=>({success:!1,errorMessage:n,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTest")}}async RunTestSuite(e){try{const t=this.buildRunTestSuiteMutation(),r=this.buildRunTestSuiteVariables(e);return await P.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTestSuite",operationLabel:"RunTestSuite",validateAck:y(s=>s?.success===!0,"validateAck"),isCompletionEvent:y(s=>this.isSuiteCompletionEvent(s,e.suiteId),"isCompletionEvent"),extractResult:y(s=>this.extractSuiteResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardTestProgress(s,e.onProgress):void 0,createErrorResult:y(s=>({success:!1,errorMessage:s,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTestSuite")}}async IsTestRunning(e){try{const t=c`
1333
+ `,s=await this._dataProvider.ExecuteGQL(t,{apiKeyId:e});return s?.RevokeAPIKey?{Success:s.RevokeAPIKey.Success,Error:s.RevokeAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}catch(t){const r=t;return l(`Error revoking API key: ${r.message}`),{Success:!1,Error:`Error: ${r.message}`}}}}class He{static{d(this,"GraphQLClusterClient")}constructor(e){this._dataProvider=e}async RunClusterAnalysis(e){try{const t=c`
1334
+ mutation RunClusterAnalysis($input: RunClusterAnalysisInput!) {
1335
+ RunClusterAnalysis(input: $input) {
1336
+ Success
1337
+ ErrorMessage
1338
+ ClusterCount
1339
+ RecordCount
1340
+ OutlierCount
1341
+ SilhouetteScore
1342
+ ComputationTimeMs
1343
+ MetricsJSON
1344
+ ClustersJSON
1345
+ PointsJSON
1346
+ AnalysisID
1347
+ }
1348
+ }
1349
+ `,s=(await this._dataProvider.ExecuteGQL(t,{input:e}))?.RunClusterAnalysis;if(!s)throw new Error("Invalid response from server");return this.parseResult(s)}catch(t){const r=t;return l("GraphQLClusterClient.RunClusterAnalysis failed",void 0,r),this.errorResult(r.message||"Unknown error occurred")}}parseResult(e){const t=this.parseMetrics(e),r=E(e.ClustersJSON)??[],s=E(e.PointsJSON)??[];return{Success:e.Success,ErrorMessage:e.ErrorMessage,Metrics:t,Clusters:r,Points:s,AnalysisID:e.AnalysisID}}parseMetrics(e){const t=E(e.MetricsJSON);return t||{SilhouetteScore:e.SilhouetteScore,ClusterCount:e.ClusterCount,ComputationTimeMs:e.ComputationTimeMs,RecordCount:e.RecordCount,OutlierCount:e.OutlierCount}}errorResult(e){return{Success:!1,ErrorMessage:e,Metrics:{SilhouetteScore:0,ClusterCount:0,ComputationTimeMs:0,RecordCount:0,OutlierCount:0},Clusters:[],Points:[]}}}class Xe{static{d(this,"GraphQLClassifyClient")}constructor(e){this._dataProvider=e}async GenerateSeedTaxonomy(e){try{const t=c`
1350
+ mutation GenerateSeedTaxonomy($sourceID: String!, $sampleSize: Int!) {
1351
+ GenerateSeedTaxonomy(sourceID: $sourceID, sampleSize: $sampleSize) {
1352
+ Success
1353
+ ErrorMessage
1354
+ Method
1355
+ SampleSize
1356
+ NodesJSON
1357
+ }
1358
+ }
1359
+ `,s=(await this._dataProvider.ExecuteGQL(t,{sourceID:e.SourceID,sampleSize:e.SampleSize}))?.GenerateSeedTaxonomy;if(!s)throw new Error("Invalid response from server");return this.parseResult(s)}catch(t){const r=t;return l("GraphQLClassifyClient.GenerateSeedTaxonomy failed",void 0,r),this.errorResult(r.message||"Unknown error occurred")}}parseResult(e){const t=E(e.NodesJSON)??[];return{Success:e.Success,ErrorMessage:e.ErrorMessage,Method:e.Method,SampleSize:e.SampleSize,Nodes:t}}errorResult(e){return{Success:!1,ErrorMessage:e,SampleSize:0,Nodes:[]}}}class Ye{static{d(this,"GraphQLTestingClient")}constructor(e){this._dataProvider=e}async RunTest(e){try{const t=this.buildRunTestMutation(),r=this.buildRunTestVariables(e),s={};return await P.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTest",operationLabel:"RunTest",validateAck:d(n=>n?.success===!0,"validateAck"),isCompletionEvent:d(n=>this.isTestCompletionEvent(n,e.testId),"isCompletionEvent"),extractResult:d(n=>this.extractTestResult(n),"extractResult"),onMessage:d(n=>{this.captureTestRunId(n,s),e.onProgress&&this.forwardTestProgress(n,e.onProgress)},"onMessage"),onStall:d(()=>this.reconcileTestRun(s),"onStall"),createErrorResult:d(n=>({success:!1,errorMessage:n,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTest")}}async RunTestSuite(e){try{const t=this.buildRunTestSuiteMutation(),r=this.buildRunTestSuiteVariables(e);return await P.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTestSuite",operationLabel:"RunTestSuite",validateAck:d(s=>s?.success===!0,"validateAck"),isCompletionEvent:d(s=>this.isSuiteCompletionEvent(s,e.suiteId),"isCompletionEvent"),extractResult:d(s=>this.extractSuiteResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardTestProgress(s,e.onProgress):void 0,createErrorResult:d(s=>({success:!1,errorMessage:s,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTestSuite")}}async IsTestRunning(e){try{const t=c`
1334
1360
  query IsTestRunning($testId: String!) {
1335
1361
  IsTestRunning(testId: $testId)
1336
1362
  }
@@ -1388,7 +1414,7 @@ var re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0})
1388
1414
  result
1389
1415
  }
1390
1416
  }
1391
- `}buildRunTestVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0;return{testId:e.testId,verbose:e.verbose,environment:e.environment,tags:t,variables:r,fireAndForget:!0}}buildRunTestSuiteVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0,s=e.selectedTestIds&&e.selectedTestIds.length>0?JSON.stringify(e.selectedTestIds):void 0;return{suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel,tags:t,variables:r,selectedTestIds:s,sequenceStart:e.sequenceStart,sequenceEnd:e.sequenceEnd,fireAndForget:!0}}isTestCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetComplete"&&r?.type==="complete"&&r?.testId===t}isSuiteCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetSuiteComplete"&&r?.type==="complete"&&r?.suiteId===t}captureTestRunId(e,t){if(e.resolver!=="RunTestResolver")return;const s=e.data?.testRunId;s&&(t.id=s)}async reconcileTestRun(e){if(!e.id)return"continue";const t=await this._dataProvider.RunView({EntityName:"MJ: Test Runs",ExtraFilter:`ID='${e.id}'`,ResultType:"entity_object",BypassCache:!0}),r=t.Success?t.Results?.[0]:void 0;if(!r||r.Status==="Pending"||r.Status==="Running")return"continue";const s=r.Status==="Passed";return{resolve:{success:s,errorMessage:s?void 0:`Test run ${r.Status}`,result:null}}}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 s=e.data?.progress;s&&t(s)}}handleError(e,t){const r=e.message;return l(`${t} failed: ${r}`),{success:!1,errorMessage:r.includes("Failed to fetch")||r.includes("NetworkError")?"Lost connection to the server. The test may still be running. Please refresh to check the latest status.":r,result:null}}}class Xe{static{y(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=c`
1417
+ `}buildRunTestVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0;return{testId:e.testId,verbose:e.verbose,environment:e.environment,tags:t,variables:r,fireAndForget:!0}}buildRunTestSuiteVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0,s=e.selectedTestIds&&e.selectedTestIds.length>0?JSON.stringify(e.selectedTestIds):void 0;return{suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel,tags:t,variables:r,selectedTestIds:s,sequenceStart:e.sequenceStart,sequenceEnd:e.sequenceEnd,fireAndForget:!0}}isTestCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetComplete"&&r?.type==="complete"&&r?.testId===t}isSuiteCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetSuiteComplete"&&r?.type==="complete"&&r?.suiteId===t}captureTestRunId(e,t){if(e.resolver!=="RunTestResolver")return;const s=e.data?.testRunId;s&&(t.id=s)}async reconcileTestRun(e){if(!e.id)return"continue";const t=await this._dataProvider.RunView({EntityName:"MJ: Test Runs",ExtraFilter:`ID='${e.id}'`,ResultType:"entity_object",BypassCache:!0}),r=t.Success?t.Results?.[0]:void 0;if(!r||r.Status==="Pending"||r.Status==="Running")return"continue";const s=r.Status==="Passed";return{resolve:{success:s,errorMessage:s?void 0:`Test run ${r.Status}`,result:null}}}extractTestResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?E(t.result):null}}extractSuiteResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?E(t.result):null}}forwardTestProgress(e,t){if(e.resolver==="RunTestResolver"&&e.type==="TestExecutionProgress"&&e.status==="ok"){const s=e.data?.progress;s&&t(s)}}handleError(e,t){const r=e.message;return l(`${t} failed: ${r}`),{success:!1,errorMessage:r.includes("Failed to fetch")||r.includes("NetworkError")?"Lost connection to the server. The test may still be running. Please refresh to check the latest status.":r,result:null}}}class Ze{static{d(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=c`
1392
1418
  query GetRegistryComponent(
1393
1419
  $registryName: String!,
1394
1420
  $namespace: String!,
@@ -1472,7 +1498,7 @@ var re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0})
1472
1498
  error
1473
1499
  }
1474
1500
  }
1475
- `,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return l(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}}class Ye{static{y(this,"GraphQLVersionHistoryClient")}constructor(e){this._dataProvider=e}async CreateLabel(e){let t;try{e.OnProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(a=>{try{const i=JSON.parse(a);i.resolver==="VersionHistoryResolver"&&i.type==="CreateLabelProgress"&&i.status==="ok"&&i.data&&e.OnProgress(i.data)}catch{}}));const r=c`
1501
+ `,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return l(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}}class et{static{d(this,"GraphQLVersionHistoryClient")}constructor(e){this._dataProvider=e}async CreateLabel(e){let t;try{e.OnProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(a=>{try{const i=JSON.parse(a);i.resolver==="VersionHistoryResolver"&&i.type==="CreateLabelProgress"&&i.status==="ok"&&i.data&&e.OnProgress(i.data)}catch{}}));const r=c`
1476
1502
  mutation CreateVersionLabel($input: CreateVersionLabelInput!, $sessionId: String) {
1477
1503
  CreateVersionLabel(input: $input, sessionId: $sessionId) {
1478
1504
  Success
@@ -1488,7 +1514,7 @@ var re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0})
1488
1514
  }
1489
1515
  }
1490
1516
  }
1491
- `,s={input:this.buildInput(e),sessionId:this._dataProvider.sessionId},n=await this._dataProvider.ExecuteGQL(r,s);return this.processResult(n)}catch(r){const s=r instanceof Error?r.message:String(r);return l(`GraphQLVersionHistoryClient.CreateLabel error: ${s}`),{Success:!1,Error:s}}finally{t&&t.unsubscribe()}}buildInput(e){const t={Name:e.Name};return e.Description!=null&&(t.Description=e.Description),e.Scope!=null&&(t.Scope=e.Scope),e.EntityName!=null&&(t.EntityName=e.EntityName),e.ParentID!=null&&(t.ParentID=e.ParentID),e.ExternalSystemID!=null&&(t.ExternalSystemID=e.ExternalSystemID),e.IncludeDependencies!=null&&(t.IncludeDependencies=e.IncludeDependencies),e.MaxDepth!=null&&(t.MaxDepth=e.MaxDepth),e.ExcludeEntities!=null&&(t.ExcludeEntities=e.ExcludeEntities),e.RecordKeys&&e.RecordKeys.length>0&&(t.RecordKeys=e.RecordKeys.map(r=>({Key:r.Key,Value:r.Value}))),t}processResult(e){const t=e?.CreateVersionLabel;if(!t)return{Success:!1,Error:"Invalid response from server."};const r=Array.isArray(t.CaptureErrors)?t.CaptureErrors.map(s=>({EntityName:s.EntityName??"",RecordID:s.RecordID??"",ErrorMessage:s.ErrorMessage??""})):void 0;return{Success:t.Success,LabelID:t.LabelID,LabelName:t.LabelName,ItemsCaptured:t.ItemsCaptured,SyntheticSnapshotsCreated:t.SyntheticSnapshotsCreated,Error:t.Error,CaptureErrors:r}}}class Ze{static{y(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const s=c`
1517
+ `,s={input:this.buildInput(e),sessionId:this._dataProvider.sessionId},n=await this._dataProvider.ExecuteGQL(r,s);return this.processResult(n)}catch(r){const s=r instanceof Error?r.message:String(r);return l(`GraphQLVersionHistoryClient.CreateLabel error: ${s}`),{Success:!1,Error:s}}finally{t&&t.unsubscribe()}}buildInput(e){const t={Name:e.Name};return e.Description!=null&&(t.Description=e.Description),e.Scope!=null&&(t.Scope=e.Scope),e.EntityName!=null&&(t.EntityName=e.EntityName),e.ParentID!=null&&(t.ParentID=e.ParentID),e.ExternalSystemID!=null&&(t.ExternalSystemID=e.ExternalSystemID),e.IncludeDependencies!=null&&(t.IncludeDependencies=e.IncludeDependencies),e.MaxDepth!=null&&(t.MaxDepth=e.MaxDepth),e.ExcludeEntities!=null&&(t.ExcludeEntities=e.ExcludeEntities),e.RecordKeys&&e.RecordKeys.length>0&&(t.RecordKeys=e.RecordKeys.map(r=>({Key:r.Key,Value:r.Value}))),t}processResult(e){const t=e?.CreateVersionLabel;if(!t)return{Success:!1,Error:"Invalid response from server."};const r=Array.isArray(t.CaptureErrors)?t.CaptureErrors.map(s=>({EntityName:s.EntityName??"",RecordID:s.RecordID??"",ErrorMessage:s.ErrorMessage??""})):void 0;return{Success:t.Success,LabelID:t.LabelID,LabelName:t.LabelName,ItemsCaptured:t.ItemsCaptured,SyntheticSnapshotsCreated:t.SyntheticSnapshotsCreated,Error:t.Error,CaptureErrors:r}}}class tt{static{d(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const s=c`
1492
1518
  query ListStorageObjects($input: ListStorageObjectsInput!) {
1493
1519
  ListStorageObjects(input: $input) {
1494
1520
  objects {
@@ -1572,7 +1598,7 @@ var re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0})
1572
1598
  failedAccounts
1573
1599
  }
1574
1600
  }
1575
- `,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:r?.maxResultsPerAccount,FileTypes:r?.fileTypes,SearchContent:r?.searchContent}},a=await this._dataProvider.ExecuteGQL(s,n);if(!a?.SearchAcrossAccounts)throw new Error("Invalid response from server");const i=a.SearchAcrossAccounts;return{accountResults:i.accountResults.map(o=>({accountId:o.accountID,accountName:o.accountName,success:o.success,errorMessage:o.errorMessage,results:o.results.map(d=>({path:d.path,name:d.name,size:d.size,contentType:d.contentType,lastModified:new Date(d.lastModified),relevance:d.relevance,excerpt:d.excerpt,matchInFilename:d.matchInFilename,objectId:d.objectId})),totalMatches:o.totalMatches,hasMore:o.hasMore,nextPageToken:o.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(s){return l(`Error searching across accounts: ${s}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}class et{static{y(this,"GraphQLSearchClient")}constructor(e){this._dataProvider=e}async ExecuteSearch(e){try{const t=this.buildSearchKnowledgeMutation(),r=this.prepareSearchVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processSearchKnowledgeResult(s)}catch(t){return this.handleSearchError(t)}}async PreviewSearch(e,t){try{const r=this.buildPreviewSearchMutation(),s=this.preparePreviewVariables(e,t),n=await this._dataProvider.ExecuteGQL(r,s);return this.processPreviewSearchResult(n)}catch(r){return this.handleSearchError(r)}}buildSearchKnowledgeMutation(){return c`
1601
+ `,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:r?.maxResultsPerAccount,FileTypes:r?.fileTypes,SearchContent:r?.searchContent}},a=await this._dataProvider.ExecuteGQL(s,n);if(!a?.SearchAcrossAccounts)throw new Error("Invalid response from server");const i=a.SearchAcrossAccounts;return{accountResults:i.accountResults.map(o=>({accountId:o.accountID,accountName:o.accountName,success:o.success,errorMessage:o.errorMessage,results:o.results.map(y=>({path:y.path,name:y.name,size:y.size,contentType:y.contentType,lastModified:new Date(y.lastModified),relevance:y.relevance,excerpt:y.excerpt,matchInFilename:y.matchInFilename,objectId:y.objectId})),totalMatches:o.totalMatches,hasMore:o.hasMore,nextPageToken:o.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(s){return l(`Error searching across accounts: ${s}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}class rt{static{d(this,"GraphQLSearchClient")}constructor(e){this._dataProvider=e}async ExecuteSearch(e){try{const t=this.buildSearchKnowledgeMutation(),r=this.prepareSearchVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processSearchKnowledgeResult(s)}catch(t){return this.handleSearchError(t)}}async PreviewSearch(e,t){try{const r=this.buildPreviewSearchMutation(),s=this.preparePreviewVariables(e,t),n=await this._dataProvider.ExecuteGQL(r,s);return this.processPreviewSearchResult(n)}catch(r){return this.handleSearchError(r)}}buildSearchKnowledgeMutation(){return c`
1576
1602
  mutation SearchKnowledge($query: String!, $maxResults: Float, $filters: SearchFiltersInput, $minScore: Float, $scopeIDs: [ID!], $searchContext: SearchContextInput) {
1577
1603
  SearchKnowledge(query: $query, maxResults: $maxResults, filters: $filters, minScore: $minScore, scopeIDs: $scopeIDs, searchContext: $searchContext) {
1578
1604
  Success
@@ -1711,7 +1737,7 @@ var re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0})
1711
1737
  ElapsedMs
1712
1738
  ErrorMessage
1713
1739
  }
1714
- }`;n=this._dataProvider.subscribe(o,{streamID:i.StreamID}).subscribe({next:y(d=>{const u=d?.SearchStreamEvents;u&&(t.next(u),u.Phase==="final"?(t.complete(),n?.unsubscribe()):u.Phase==="error"&&(t.error(new Error(u.ErrorMessage??"Stream error")),n?.unsubscribe()))},"next"),error:y(d=>t.error(d),"error")})}catch(a){t.error(a)}})(),()=>{n?.unsubscribe()}})}prepareFilters(e){const t={};return e.EntityNames!==void 0&&e.EntityNames.length>0&&(t.EntityNames=e.EntityNames),e.SourceTypes!==void 0&&e.SourceTypes.length>0&&(t.SourceTypes=e.SourceTypes),e.Tags!==void 0&&e.Tags.length>0&&(t.Tags=e.Tags),t}preparePreviewVariables(e,t){const r={query:e};return t!==void 0&&(r.maxResults=t),r}processSearchKnowledgeResult(e){if(!e?.SearchKnowledge)throw new Error("Invalid response from server");const t=e.SearchKnowledge;return this.mapSearchResponse(t)}processPreviewSearchResult(e){if(!e?.PreviewSearch)throw new Error("Invalid response from server");const t=e.PreviewSearch;return this.mapSearchResponse(t)}mapSearchResponse(e){return{Success:e.Success,Results:(e.Results||[]).map(t=>this.mapResultItem(t)),TotalCount:e.TotalCount,ElapsedMs:e.ElapsedMs,SourceCounts:this.mapSourceCounts(e.SourceCounts),Providers:(e.Providers||[]).map(t=>({ID:t.ID,Name:t.Name,DisplayName:t.DisplayName,Icon:t.Icon,SourceType:t.SourceType,Priority:t.Priority})),ErrorMessage:e.ErrorMessage}}mapResultItem(e){return{ID:e.ID,EntityName:e.EntityName,RecordID:e.RecordID,SourceType:e.SourceType,ResultType:e.ResultType,Title:e.Title,Snippet:e.Snippet,Score:e.Score,ScoreBreakdown:this.mapScoreBreakdown(e.ScoreBreakdown),Tags:e.Tags||[],EntityIcon:e.EntityIcon,RecordName:e.RecordName,MatchedAt:e.MatchedAt,RawMetadata:e.RawMetadata,ProviderId:e.ProviderId,ProviderLabel:e.ProviderLabel,ProviderIcon:e.ProviderIcon}}mapScoreBreakdown(e){if(!e)return{};const t={};return e.Vector!==void 0&&(t.Vector=e.Vector),e.FullText!==void 0&&(t.FullText=e.FullText),e.Entity!==void 0&&(t.Entity=e.Entity),e.Storage!==void 0&&(t.Storage=e.Storage),t}mapSourceCounts(e){return e?{Vector:e.Vector??0,FullText:e.FullText??0,Entity:e.Entity??0,Storage:e.Storage??0}:{Vector:0,FullText:0,Entity:0,Storage:0}}handleSearchError(e){const t=e;return l(`Error executing search: ${t}`),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,SourceCounts:{Vector:0,FullText:0,Entity:0,Storage:0},Providers:[],ErrorMessage:`Error: ${t.message}`}}}class tt{static{y(this,"GraphQLIntegrationClient")}constructor(e){this._dataProvider=e}async DiscoverObjects(e){try{const t=c`
1740
+ }`;n=this._dataProvider.subscribe(o,{streamID:i.StreamID}).subscribe({next:d(y=>{const u=y?.SearchStreamEvents;u&&(t.next(u),u.Phase==="final"?(t.complete(),n?.unsubscribe()):u.Phase==="error"&&(t.error(new Error(u.ErrorMessage??"Stream error")),n?.unsubscribe()))},"next"),error:d(y=>t.error(y),"error")})}catch(a){t.error(a)}})(),()=>{n?.unsubscribe()}})}prepareFilters(e){const t={};return e.EntityNames!==void 0&&e.EntityNames.length>0&&(t.EntityNames=e.EntityNames),e.SourceTypes!==void 0&&e.SourceTypes.length>0&&(t.SourceTypes=e.SourceTypes),e.Tags!==void 0&&e.Tags.length>0&&(t.Tags=e.Tags),t}preparePreviewVariables(e,t){const r={query:e};return t!==void 0&&(r.maxResults=t),r}processSearchKnowledgeResult(e){if(!e?.SearchKnowledge)throw new Error("Invalid response from server");const t=e.SearchKnowledge;return this.mapSearchResponse(t)}processPreviewSearchResult(e){if(!e?.PreviewSearch)throw new Error("Invalid response from server");const t=e.PreviewSearch;return this.mapSearchResponse(t)}mapSearchResponse(e){return{Success:e.Success,Results:(e.Results||[]).map(t=>this.mapResultItem(t)),TotalCount:e.TotalCount,ElapsedMs:e.ElapsedMs,SourceCounts:this.mapSourceCounts(e.SourceCounts),Providers:(e.Providers||[]).map(t=>({ID:t.ID,Name:t.Name,DisplayName:t.DisplayName,Icon:t.Icon,SourceType:t.SourceType,Priority:t.Priority})),ErrorMessage:e.ErrorMessage}}mapResultItem(e){return{ID:e.ID,EntityName:e.EntityName,RecordID:e.RecordID,SourceType:e.SourceType,ResultType:e.ResultType,Title:e.Title,Snippet:e.Snippet,Score:e.Score,ScoreBreakdown:this.mapScoreBreakdown(e.ScoreBreakdown),Tags:e.Tags||[],EntityIcon:e.EntityIcon,RecordName:e.RecordName,MatchedAt:e.MatchedAt,RawMetadata:e.RawMetadata,ProviderId:e.ProviderId,ProviderLabel:e.ProviderLabel,ProviderIcon:e.ProviderIcon}}mapScoreBreakdown(e){if(!e)return{};const t={};return e.Vector!==void 0&&(t.Vector=e.Vector),e.FullText!==void 0&&(t.FullText=e.FullText),e.Entity!==void 0&&(t.Entity=e.Entity),e.Storage!==void 0&&(t.Storage=e.Storage),t}mapSourceCounts(e){return e?{Vector:e.Vector??0,FullText:e.FullText??0,Entity:e.Entity??0,Storage:e.Storage??0}:{Vector:0,FullText:0,Entity:0,Storage:0}}handleSearchError(e){const t=e;return l(`Error executing search: ${t}`),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,SourceCounts:{Vector:0,FullText:0,Entity:0,Storage:0},Providers:[],ErrorMessage:`Error: ${t.message}`}}}class st{static{d(this,"GraphQLIntegrationClient")}constructor(e){this._dataProvider=e}async DiscoverObjects(e){try{const t=c`
1715
1741
  query IntegrationDiscoverObjects($companyIntegrationID: String!) {
1716
1742
  IntegrationDiscoverObjects(companyIntegrationID: $companyIntegrationID) {
1717
1743
  Success
@@ -1862,7 +1888,7 @@ var re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0})
1862
1888
  PipelineSteps { Name Status DurationMs Message }
1863
1889
  GitCommitSuccess APIRestarted
1864
1890
  }
1865
- }`,d={Connectors:e.map(f=>({CompanyIntegrationID:f.CompanyIntegrationID,SourceObjects:f.SourceObjects.map(R=>({SourceObjectID:R.SourceObjectID??null,SourceObjectName:R.SourceObjectName??null,Fields:R.Fields??null}))})),StartSync:t,FullSync:r,SyncScope:s},u=(await this._dataProvider.ExecuteGQL(o,{input:d,platform:n,skipGitCommit:a,skipRestart:i}))?.IntegrationApplyAllBatch;return u?{Success:u.Success,Message:u.Message,Steps:u.PipelineSteps,GitCommitSuccess:u.GitCommitSuccess,APIRestarted:u.APIRestarted,EntityMapsCreated:u.ConnectorResults?.[0]?.EntityMapsCreated,SyncRunID:u.ConnectorResults?.[0]?.SyncRunID,Warnings:u.ConnectorResults?.flatMap(f=>f.Warnings??[])}:{Success:!1,Message:"No response"}}catch(o){return{Success:!1,Message:o.message}}}async ApplyAll(e,t,r="sqlserver",s=!1,n=!1){try{const a=c`mutation IntegrationApplyAll(
1891
+ }`,y={Connectors:e.map(f=>({CompanyIntegrationID:f.CompanyIntegrationID,SourceObjects:f.SourceObjects.map(R=>({SourceObjectID:R.SourceObjectID??null,SourceObjectName:R.SourceObjectName??null,Fields:R.Fields??null}))})),StartSync:t,FullSync:r,SyncScope:s},u=(await this._dataProvider.ExecuteGQL(o,{input:y,platform:n,skipGitCommit:a,skipRestart:i}))?.IntegrationApplyAllBatch;return u?{Success:u.Success,Message:u.Message,Steps:u.PipelineSteps,GitCommitSuccess:u.GitCommitSuccess,APIRestarted:u.APIRestarted,EntityMapsCreated:u.ConnectorResults?.[0]?.EntityMapsCreated,SyncRunID:u.ConnectorResults?.[0]?.SyncRunID,Warnings:u.ConnectorResults?.flatMap(f=>f.Warnings??[])}:{Success:!1,Message:"No response"}}catch(o){return{Success:!1,Message:o.message}}}async ApplyAll(e,t,r="sqlserver",s=!1,n=!1){try{const a=c`mutation IntegrationApplyAll(
1866
1892
  $input: ApplyAllInput!, $platform: String!, $skipGitCommit: Boolean!, $skipRestart: Boolean!
1867
1893
  ) {
1868
1894
  IntegrationApplyAll(input: $input, platform: $platform, skipGitCommit: $skipGitCommit, skipRestart: $skipRestart) {
@@ -1904,5 +1930,5 @@ var re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0})
1904
1930
  IntegrationGetConnectorCapabilities(companyIntegrationID: $companyIntegrationID) {
1905
1931
  Success Message SupportsGet SupportsCreate SupportsUpdate SupportsDelete SupportsSearch
1906
1932
  }
1907
- }`;return(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationGetConnectorCapabilities??{Success:!1,Message:"No response"}}catch(t){return{Success:!1,Message:t.message}}}handleError(e,t){const r=e;return l(`Error in integration discovery: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Data:t}}}export{Qe as ActionItemInput,Ge as ActionItemOutput,Y as BrowserIndexedDBStorageProvider,H as BrowserStorageProviderBase,w as FieldMapper,P as FireAndForgetHelper,_e as GetDataOutput,z as GraphQLAIClient,Be as GraphQLActionClient,Xe as GraphQLComponentRegistryClient,I as GraphQLDataProvider,ze as GraphQLEncryptionClient,Ze as GraphQLFileStorageClient,tt as GraphQLIntegrationClient,Ke as GraphQLListsClient,Ne as GraphQLProviderConfigData,et as GraphQLSearchClient,Ve as GraphQLSystemUserClient,He as GraphQLTestingClient,W as GraphQLTransactionGroup,Ye as GraphQLVersionHistoryClient,L as PACKAGE_VERSION,xe as RoleInput,Fe as RolesAndUsersInput,Oe as SimpleRemoteEntity,ke as SimpleRemoteEntityField,qe as SimpleRemoteEntityOutput,Z as SyncDataAction,Ue as SyncDataResult,Te as SyncRolesAndUsersResult,Le as UserInput,mt as gql,Me as setupGraphQLClient};
1933
+ }`;return(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationGetConnectorCapabilities??{Success:!1,Message:"No response"}}catch(t){return{Success:!1,Message:t.message}}}handleError(e,t){const r=e;return l(`Error in integration discovery: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Data:t}}}export{Qe as ActionItemInput,Ge as ActionItemOutput,Y as BrowserIndexedDBStorageProvider,H as BrowserStorageProviderBase,C as FieldMapper,P as FireAndForgetHelper,_e as GetDataOutput,z as GraphQLAIClient,Be as GraphQLActionClient,Xe as GraphQLClassifyClient,He as GraphQLClusterClient,Ze as GraphQLComponentRegistryClient,I as GraphQLDataProvider,ze as GraphQLEncryptionClient,tt as GraphQLFileStorageClient,st as GraphQLIntegrationClient,Ke as GraphQLListsClient,be as GraphQLProviderConfigData,rt as GraphQLSearchClient,Ve as GraphQLSystemUserClient,Ye as GraphQLTestingClient,W as GraphQLTransactionGroup,et as GraphQLVersionHistoryClient,L as PACKAGE_VERSION,xe as RoleInput,Fe as RolesAndUsersInput,qe as SimpleRemoteEntity,ke as SimpleRemoteEntityField,Oe as SimpleRemoteEntityOutput,Z as SyncDataAction,Ue as SyncDataResult,Te as SyncRolesAndUsersResult,Le as UserInput,St as gql,Ne as setupGraphQLClient};
1908
1934
  //# sourceMappingURL=index.mjs.map