@memberjunction/graphql-dataprovider 5.41.0 → 5.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var j=Object.defineProperty;var d=(m,e)=>j(m,"name",{value:e,configurable:!0});var u=require("graphql-request"),c=require("@memberjunction/core"),R=require("@memberjunction/global"),G=require("@memberjunction/core-entities"),A=require("rxjs"),J=require("graphql-ws"),W=require("uuid"),z=require("@tempfix/idb");class P{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(P.DB_PREFIX)?P.GQL_PREFIX+e.substring(P.DB_PREFIX.length):e}ReverseMapFieldName(e){return e.startsWith(P.GQL_PREFIX)?P.DB_PREFIX+e.substring(P.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 q extends c.TransactionGroupBase{static{d(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=u.gql`
1
+ "use strict";var j=Object.defineProperty;var d=(m,e)=>j(m,"name",{value:e,configurable:!0});var u=require("graphql-request"),c=require("@memberjunction/core"),R=require("@memberjunction/global"),G=require("@memberjunction/core-entities"),L=require("rxjs"),J=require("graphql-ws"),W=require("uuid"),z=require("@tempfix/idb");class P{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(P.DB_PREFIX)?P.GQL_PREFIX+e.substring(P.DB_PREFIX.length):e}ReverseMapFieldName(e){return e.startsWith(P.GQL_PREFIX)?P.DB_PREFIX+e.substring(P.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 q extends c.TransactionGroupBase{static{d(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=u.gql`
2
2
  mutation ExecuteTransactionGroup($group: TransactionInputType!) {
3
3
  ExecuteTransactionGroup(group: $group) {
4
4
  Success
@@ -6,7 +6,7 @@
6
6
  ResultsJSON
7
7
  }
8
8
  }
9
- `,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const r={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const n=s.ExecuteTransactionGroup,a=[];for(let i=0;i<this.PendingTransactions.length;i++){const o=n.ResultsJSON[i],y=R.SafeJSONParse(o),l=this.PendingTransactions[i];a.push(new c.TransactionResult(l,y,y!==null))}return a}else throw new Error("Failed to execute transaction group")}}const H=720*1e3,X=6;class ${static{d(this,"FireAndForgetHelper")}static async Execute(e){const t=e.operationLabel??e.mutationFieldName,r=e.timeoutMs??H,s=e.maxStallReconciles??X;let n,a=!1,i=0;const{promise:o,resolve:y,reject:l}=$.createCompletionPromise(),f=d(E=>{a||(a=!0,S.clear(),E())},"finish"),I=d(E=>f(()=>y(E)),"settleResolve"),g=d(E=>f(()=>l(E)),"settleReject"),p=d(async()=>{if(a)return;if(!e.onStall){g(new Error($.timeoutMessage(e.timeoutErrorMessage,r)));return}let E;try{c.LogStatus(`[FireAndForget:${t}] Idle window elapsed, reconciling against server run record`),E=await e.onStall()}catch(D){g(D);return}a||(E==="continue"?++i>s?g(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.`)):S.reset():"resolve"in E?(c.LogStatus(`[FireAndForget:${t}] Reconciliation recovered a completed run`),I(E.resolve)):g(E.reject))},"onStall"),S=$.createIdleTimer(r,()=>{p()});try{S.reset(),n=$.subscribeToPubSub(e,{onActivity:d(()=>{i=0,S.reset()},"onActivity"),onCompletion:d(D=>I(D),"onCompletion"),onStreamEnd:d(()=>{p()},"onStreamEnd")});const E=await $.executeMutation(e);if(!e.validateAck(E)){S.clear();const D=E?.errorMessage??"Server rejected the request";return c.LogError(`[FireAndForget:${t}] Server rejected: ${D}`),e.createErrorResult(D)}return c.LogStatus(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await o}catch(E){const D=E;throw c.LogError(`[FireAndForget:${t}] Error: ${D.message}`),E}finally{S.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)&&(c.LogStatus(`[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 U{static{d(this,"GraphQLAIClient")}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=u.gql`
9
+ `,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const r={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const n=s.ExecuteTransactionGroup,o=[];for(let i=0;i<this.PendingTransactions.length;i++){const a=n.ResultsJSON[i],y=R.SafeJSONParse(a),l=this.PendingTransactions[i];o.push(new c.TransactionResult(l,y,y!==null))}return o}else throw new Error("Failed to execute transaction group")}}const H=720*1e3,X=6;class ${static{d(this,"FireAndForgetHelper")}static async Execute(e){const t=e.operationLabel??e.mutationFieldName,r=e.timeoutMs??H,s=e.maxStallReconciles??X;let n,o=!1,i=0;const{promise:a,resolve:y,reject:l}=$.createCompletionPromise(),f=d(E=>{o||(o=!0,S.clear(),E())},"finish"),I=d(E=>f(()=>y(E)),"settleResolve"),g=d(E=>f(()=>l(E)),"settleReject"),p=d(async()=>{if(o)return;if(!e.onStall){g(new Error($.timeoutMessage(e.timeoutErrorMessage,r)));return}let E;try{c.LogStatus(`[FireAndForget:${t}] Idle window elapsed, reconciling against server run record`),E=await e.onStall()}catch(D){g(D);return}o||(E==="continue"?++i>s?g(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.`)):S.reset():"resolve"in E?(c.LogStatus(`[FireAndForget:${t}] Reconciliation recovered a completed run`),I(E.resolve)):g(E.reject))},"onStall"),S=$.createIdleTimer(r,()=>{p()});try{S.reset(),n=$.subscribeToPubSub(e,{onActivity:d(()=>{i=0,S.reset()},"onActivity"),onCompletion:d(D=>I(D),"onCompletion"),onStreamEnd:d(()=>{p()},"onStreamEnd")});const E=await $.executeMutation(e);if(!e.validateAck(E)){S.clear();const D=E?.errorMessage??"Server rejected the request";return c.LogError(`[FireAndForget:${t}] Server rejected: ${D}`),e.createErrorResult(D)}return c.LogStatus(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await a}catch(E){const D=E;throw c.LogError(`[FireAndForget:${t}] Error: ${D.message}`),E}finally{S.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 o=JSON.parse(n);e.onMessage&&e.onMessage(o),e.isCompletionEvent(o)&&(c.LogStatus(`[FireAndForget:${s}] Completion event received`),t.onCompletion(e.extractResult(o)))}catch(o){console.error(`[FireAndForget:${s}] Failed to parse PubSub message:`,o)}},"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 U{static{d(this,"GraphQLAIClient")}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=u.gql`
10
10
  mutation RunAIPrompt(
11
11
  $promptId: String!,
12
12
  $data: String,
@@ -65,7 +65,7 @@
65
65
  chatResult
66
66
  }
67
67
  }
68
- `,r=this.preparePromptVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(s)}catch(t){return this.handlePromptError(t)}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,n;try{t.parsedResult&&(r=R.CleanAndParseJSON(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(n=JSON.parse(t.chatResult))}catch{n=t.chatResult}return{success:t.success,output:t.output,parsedResult:r,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:s,chatResult:n}}handlePromptError(e){const t=e;return c.LogError(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){try{const s=this.buildRunAIAgentMutation(),n=this.prepareAgentVariables(e,t,r);n.fireAndForget=!0;const a={};return await $.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 u.gql`
68
+ `,r=this.preparePromptVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(s)}catch(t){return this.handlePromptError(t)}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,n;try{t.parsedResult&&(r=R.CleanAndParseJSON(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(n=JSON.parse(t.chatResult))}catch{n=t.chatResult}return{success:t.success,output:t.output,parsedResult:r,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:s,chatResult:n}}handlePromptError(e){const t=e;return c.LogError(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){try{const s=this.buildRunAIAgentMutation(),n=this.prepareAgentVariables(e,t,r);n.fireAndForget=!0;const o={};return await $.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,o),e.onProgress&&this.forwardAgentProgress(i,e.onProgress)},"onMessage"),onStall:d(()=>this.reconcileAgentRun(o.id?`ID='${o.id}'`:void 0),"onStall"),createErrorResult:d(i=>this.createAgentErrorResult(i),"createErrorResult")})}catch(s){return this.handleAgentError(s)}}buildRunAIAgentMutation(){return u.gql`
69
69
  mutation RunAIAgent(
70
70
  $agentId: String!,
71
71
  $messages: String!,
@@ -106,7 +106,7 @@
106
106
  result
107
107
  }
108
108
  }
109
- `}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),t!==void 0&&(s.sourceArtifactId=t),r!==void 0&&(s.sourceArtifactVersionId=r),s}processAgentResult(e){return R.SafeJSONParse(e)}handleAgentError(e){const r=e?.message||String(e);c.LogError(`Error running AI agent: ${r}`);const s=r.includes("Failed to fetch")||r.includes("NetworkError"),n=r.includes("timed out")||r.includes("timeout");let a;return s?a="Lost connection to the server. The agent may still be running. Please refresh to check the latest status.":a=r,{success:!1,agentRun:void 0,errorMessage:a}}async RunAIAgentFromConversationDetail(e){try{const t=this.buildConversationDetailMutation(),r=this.prepareConversationDetailVariables(e);return await $.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 u.gql`
109
+ `}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),t!==void 0&&(s.sourceArtifactId=t),r!==void 0&&(s.sourceArtifactVersionId=r),s}processAgentResult(e){return R.SafeJSONParse(e)}handleAgentError(e){const r=e?.message||String(e);c.LogError(`Error running AI agent: ${r}`);const s=r.includes("Failed to fetch")||r.includes("NetworkError"),n=r.includes("timed out")||r.includes("timeout");let o;return s?o="Lost connection to the server. The agent may still be running. Please refresh to check the latest status.":o=r,{success:!1,agentRun:void 0,errorMessage:o}}async RunAIAgentFromConversationDetail(e){try{const t=this.buildConversationDetailMutation(),r=this.prepareConversationDetailVariables(e);return await $.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 u.gql`
110
110
  mutation RunAIAgentFromConversationDetail(
111
111
  $conversationDetailId: String!,
112
112
  $agentId: String!,
@@ -168,7 +168,7 @@
168
168
  executionTimeMs
169
169
  }
170
170
  }
171
- `,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.ExecuteSimplePrompt)throw new Error("Invalid response from server");const n=s.ExecuteSimplePrompt;let a;if(n.resultObject)try{a=JSON.parse(n.resultObject)}catch{a=n.resultObject}return{success:n.success,result:n.result,resultObject:a,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){const r=t;return c.LogError(`Error executing simple prompt: ${r}`),{success:!1,modelName:"Unknown",error:r.message||"Unknown error occurred"}}}async EmbedText(e){try{const t=u.gql`
171
+ `,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.ExecuteSimplePrompt)throw new Error("Invalid response from server");const n=s.ExecuteSimplePrompt;let o;if(n.resultObject)try{o=JSON.parse(n.resultObject)}catch{o=n.resultObject}return{success:n.success,result:n.result,resultObject:o,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){const r=t;return c.LogError(`Error executing simple prompt: ${r}`),{success:!1,modelName:"Unknown",error:r.message||"Unknown error occurred"}}}async EmbedText(e){try{const t=u.gql`
172
172
  mutation EmbedText(
173
173
  $textToEmbed: [String!]!,
174
174
  $modelSize: String!
@@ -183,7 +183,7 @@
183
183
  error
184
184
  }
185
185
  }
186
- `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this._dataProvider.ExecuteGQL(t,s);if(!n?.EmbedText)throw new Error("Invalid response from server");const a=n.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?a.embeddings:a.embeddings[0],modelName:a.modelName,vectorDimensions:a.vectorDimensions,error:a.error}}catch(t){const r=t;return c.LogError(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}async RunAutotagPipeline(e){try{const t=u.gql`
186
+ `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this._dataProvider.ExecuteGQL(t,s);if(!n?.EmbedText)throw new Error("Invalid response from server");const o=n.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?o.embeddings:o.embeddings[0],modelName:o.modelName,vectorDimensions:o.vectorDimensions,error:o.error}}catch(t){const r=t;return c.LogError(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}async RunAutotagPipeline(e){try{const t=u.gql`
187
187
  mutation RunAutotagPipeline($contentSourceIDs: [String!], $forceReprocess: Boolean) {
188
188
  RunAutotagPipeline(contentSourceIDs: $contentSourceIDs, forceReprocess: $forceReprocess) {
189
189
  Success
@@ -297,7 +297,7 @@
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 c.LogError("GraphQLAIClient.FetchEntityVectors failed",void 0,r),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,ErrorMessage:r.message||"Unknown error"}}}}const L="5.41.0",w="default";class V{static{d(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||w;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||w).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||w);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||w).set(e,t)}async Remove(e,t){this.getCategoryMap(t||w).delete(e)}async ClearCategory(e){const t=e||w;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||w);return t?Array.from(t.keys()):[]}}const Y="MJ_Metadata",Z=0;function ee(){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+Z}catch(m){return c.LogErrorEx({error:m,message:"Failed to derive IDB version from PACKAGE_VERSION; using fallback 99999"}),99999}}d(ee,"computeIdbVersion");const te=ee(),_=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"];class O extends V{static{d(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=z.openDB(Y,te,{upgrade:d((e,t,r)=>{try{c.LogStatus(`[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 _)e.objectStoreNames.contains(s)||e.createObjectStore(s)}catch(s){c.LogErrorEx({error:s,message:s?.message})}},"upgrade"),blocked:d((e,t)=>{c.LogStatus(`[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=()=>{c.LogStatus("[IDBCache] DB schema upgraded in another tab \u2014 closing local connection."),e.close(),this._dbReady=!1}}).catch(e=>{c.LogErrorEx({error:e,message:"IndexedDB initialization failed: "+e?.message})})}get IsReady(){return this._dbReady}isKnownCategory(e){const t=`mj:${e}`;return _.includes(t)}getStoreName(e){const t=e||w;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||w;return this.isKnownCategory(r)?e:`[${r}]:${e}`}async SetItem(e,t,r){try{const s=await this.dbPromise,n=this.getStoreName(r),a=this.getStoreKey(e,r),i=s.transaction(n,"readwrite");await i.objectStore(n).put(t,a),await i.done}catch(s){c.LogErrorEx({error:s,message:s?.message})}}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 c.LogErrorEx({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(I=>this.getStoreKey(I,t)),o=s.transaction(n,"readonly"),y=o.objectStore(n),l=i.map(I=>y.get(I)),f=await Promise.all(l);await o.done;for(let I=0;I<a.length;I++){const g=f[I];r.set(a[I],g===void 0?null:g)}return r}catch(s){c.LogErrorEx({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){c.LogErrorEx({error:r,message:r?.message})}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||w,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){c.LogErrorEx({error:t,message:t?.message})}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||w,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 c.LogErrorEx({error:t,message:t?.message}),[]}}}const N=new P;class re extends c.ProviderConfigDataBase{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,l){super({Token:e,URL:t,WSURL:r,MJAPIKey:o,UserAPIKey:y,RefreshTokenFunction:s,OnAuthenticationError:l},n,a,i)}}class h extends c.ProviderBase{static{d(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 c.LogError("GraphQLAIClient.FetchEntityVectors failed",void 0,r),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,ErrorMessage:r.message||"Unknown error"}}}}const M="5.42.0",w="default";class V{static{d(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||w;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||w).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||w);for(const n of new Set(e)){const o=s.get(n);r.set(n,o===void 0?null:o)}return r}async SetItem(e,t,r){this.getCategoryMap(r||w).set(e,t)}async Remove(e,t){this.getCategoryMap(t||w).delete(e)}async ClearCategory(e){const t=e||w;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||w);return t?Array.from(t.keys()):[]}}const Y="MJ_Metadata",Z=0;function ee(){try{const m=M.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 "${M}"`);return e*1e3+t+Z}catch(m){return c.LogErrorEx({error:m,message:"Failed to derive IDB version from PACKAGE_VERSION; using fallback 99999"}),99999}}d(ee,"computeIdbVersion");const te=ee(),_=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"];class O extends V{static{d(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=z.openDB(Y,te,{upgrade:d((e,t,r)=>{try{c.LogStatus(`[IDBCache] Upgrading IndexedDB schema v${t} \u2192 v${r} (package ${M}). Dropping all stores; caches will repopulate on first use.`);for(const s of Array.from(e.objectStoreNames))e.deleteObjectStore(s);for(const s of _)e.objectStoreNames.contains(s)||e.createObjectStore(s)}catch(s){c.LogErrorEx({error:s,message:s?.message})}},"upgrade"),blocked:d((e,t)=>{c.LogStatus(`[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=()=>{c.LogStatus("[IDBCache] DB schema upgraded in another tab \u2014 closing local connection."),e.close(),this._dbReady=!1}}).catch(e=>{c.LogErrorEx({error:e,message:"IndexedDB initialization failed: "+e?.message})})}get IsReady(){return this._dbReady}isKnownCategory(e){const t=`mj:${e}`;return _.includes(t)}getStoreName(e){const t=e||w;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||w;return this.isKnownCategory(r)?e:`[${r}]:${e}`}async SetItem(e,t,r){try{const s=await this.dbPromise,n=this.getStoreName(r),o=this.getStoreKey(e,r),i=s.transaction(n,"readwrite");await i.objectStore(n).put(t,o),await i.done}catch(s){c.LogErrorEx({error:s,message:s?.message})}}async GetItem(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t),o=await r.transaction(s).objectStore(s).get(n);return o===void 0?null:o}catch(r){return c.LogErrorEx({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),o=Array.from(new Set(e)),i=o.map(I=>this.getStoreKey(I,t)),a=s.transaction(n,"readonly"),y=a.objectStore(n),l=i.map(I=>y.get(I)),f=await Promise.all(l);await a.done;for(let I=0;I<o.length;I++){const g=f[I];r.set(o[I],g===void 0?null:g)}return r}catch(s){c.LogErrorEx({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),o=r.transaction(s,"readwrite");await o.objectStore(s).delete(n),await o.done}catch(r){c.LogErrorEx({error:r,message:r?.message})}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||w,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}]:`,o=t.transaction("mj:default","readwrite"),i=o.objectStore("mj:default"),a=await i.getAllKeys();for(const y of a)typeof y=="string"&&y.startsWith(n)&&await i.delete(y);await o.done}}catch(t){c.LogErrorEx({error:t,message:t?.message})}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||w,s=this.getStoreName(e),i=await t.transaction(s,"readonly").objectStore(s).getAllKeys();if(this.isKnownCategory(r))return i.map(y=>String(y));const a=`[${r}]:`;return i.map(y=>String(y)).filter(y=>y.startsWith(a)).map(y=>y.slice(a.length))}catch(t){return c.LogErrorEx({error:t,message:t?.message}),[]}}}const A=new P;class re extends c.ProviderConfigDataBase{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,o,i,a,y,l){super({Token:e,URL:t,WSURL:r,MJAPIKey:a,UserAPIKey:y,RefreshTokenFunction:s,OnAuthenticationError:l},n,o,i)}}class h extends c.ProviderBase{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 @@
306
306
  `,this._currentUserQuery=u.gql`query CurrentUserAndRoles {
307
307
  ${this._innerCurrentUserQueryString}
308
308
  CurrentUserTenantContext
309
- }`,this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject=new A.BehaviorSubject("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=R.GetGlobalObjectStore();if(e&&e[h._globalStoreKey])return e[h._globalStoreKey];e&&(e[h._globalStoreKey]=this)}static{this.VerboseCacheInvalidationLogging=!1}static{this._globalStoreKey="___SINGLETON__GraphQLDataProvider"}static get Instance(){const e=R.GetGlobalObjectStore();return e?e[h._globalStoreKey]:void 0}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new U(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}async InternalExecuteQueryFromSpec(e,t){throw new Error("ExecuteQueryFromSpec is not supported by this provider.")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return W.v4()}get LocalStoragePrefix(){if(this._configData===void 0||this._configData.URL===void 0)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const r=this.LocalStoragePrefix+"sessionId";await t.SetItem(r,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,r,s){try{return this._configData=e,r?(this._sessionId=await this.GetPreferredUUID(s),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey,e.UserAPIKey),await this.SaveStoredSessionID(this._sessionId)):(h.Instance._configData=e,h.Instance._sessionId===void 0&&(h.Instance._sessionId=await this.GetPreferredUUID(s)),h.Instance._client||(h.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,h.Instance._sessionId,e.MJAPIKey,e.UserAPIKey)),await h.Instance.SaveStoredSessionID(h.Instance._sessionId),this._sessionId=h.Instance._sessionId,this._client=h.Instance._client),super.Config(e)}catch(n){throw c.LogError(n),n}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}SetDynamicHeader(e,t){this._dynamicHeaders.set(e,t),this._client&&this._client.setHeader(e,t),h.Instance&&h.Instance!==this&&h.Instance._configData===this._configData&&(h.Instance._dynamicHeaders.set(e,t),h.Instance._client&&h.Instance._client.setHeader(e,t))}RemoveDynamicHeader(e){this._dynamicHeaders.delete(e),this._client&&this._client.setHeader(e,""),h.Instance&&h.Instance!==this&&h.Instance._configData===this._configData&&(h.Instance._dynamicHeaders.delete(e),h.Instance._client&&h.Instance._client.setHeader(e,""))}GetDynamicHeaders(){return this._dynamicHeaders}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),r=t.MJUserRoles_UserIDArray.map(n=>this.ConvertBackToMJFields(n));t.MJUserRoles_UserIDArray=r;const s=new c.UserInfo(this,{...t,UserRoles:r});return e.CurrentUserTenantContext&&typeof e.CurrentUserTenantContext=="object"&&(s.TenantContext=e.CurrentUserTenantContext),s}}async RunReport(e,t){const r=u.gql`
309
+ }`,this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject=new L.BehaviorSubject("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=R.GetGlobalObjectStore();if(e&&e[h._globalStoreKey])return e[h._globalStoreKey];e&&(e[h._globalStoreKey]=this)}static{this.VerboseCacheInvalidationLogging=!1}static{this._globalStoreKey="___SINGLETON__GraphQLDataProvider"}static get Instance(){const e=R.GetGlobalObjectStore();return e?e[h._globalStoreKey]:void 0}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new U(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}async InternalExecuteQueryFromSpec(e,t){throw new Error("ExecuteQueryFromSpec is not supported by this provider.")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return W.v4()}get LocalStoragePrefix(){if(this._configData===void 0||this._configData.URL===void 0)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const r=this.LocalStoragePrefix+"sessionId";await t.SetItem(r,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,r,s){try{return this._configData=e,r?(this._sessionId=await this.GetPreferredUUID(s),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey,e.UserAPIKey),await this.SaveStoredSessionID(this._sessionId)):(h.Instance._configData=e,h.Instance._sessionId===void 0&&(h.Instance._sessionId=await this.GetPreferredUUID(s)),h.Instance._client||(h.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,h.Instance._sessionId,e.MJAPIKey,e.UserAPIKey)),await h.Instance.SaveStoredSessionID(h.Instance._sessionId),this._sessionId=h.Instance._sessionId,this._client=h.Instance._client),super.Config(e)}catch(n){throw c.LogError(n),n}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}SetDynamicHeader(e,t){this._dynamicHeaders.set(e,t),this._client&&this._client.setHeader(e,t),h.Instance&&h.Instance!==this&&h.Instance._configData===this._configData&&(h.Instance._dynamicHeaders.set(e,t),h.Instance._client&&h.Instance._client.setHeader(e,t))}RemoveDynamicHeader(e){this._dynamicHeaders.delete(e),this._client&&this._client.setHeader(e,""),h.Instance&&h.Instance!==this&&h.Instance._configData===this._configData&&(h.Instance._dynamicHeaders.delete(e),h.Instance._client&&h.Instance._client.setHeader(e,""))}GetDynamicHeaders(){return this._dynamicHeaders}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),r=t.MJUserRoles_UserIDArray.map(n=>this.ConvertBackToMJFields(n));t.MJUserRoles_UserIDArray=r;const s=new c.UserInfo(this,{...t,UserRoles:r});return e.CurrentUserTenantContext&&typeof e.CurrentUserTenantContext=="object"&&(s.TenantContext=e.CurrentUserTenantContext),s}}async RunReport(e,t){const r=u.gql`
310
310
  query GetReportDataQuery ($ReportID: String!) {
311
311
  GetReportData(ReportID: $ReportID) {
312
312
  Success
@@ -321,25 +321,25 @@
321
321
  ${this.QueryReturnFieldList}
322
322
  }
323
323
  }
324
- `,a={SQL:e};r!==void 0&&(a.TimeoutSeconds=r),t!==void 0&&(a.MaxRows=t),s!==void 0&&(a.StartRow=s);const i=await this.ExecuteGQL(n,{input:a});return i?.ExecuteAdhocQuery?this.TransformQueryPayload(i.ExecuteAdhocQuery):{QueryID:"",QueryName:"Ad-Hoc Query",Success:!1,Results:[],RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Ad-hoc query execution failed \u2014 no response from server"}}async InternalRunQueries(e,t){const r=u.gql`
324
+ `,o={SQL:e};r!==void 0&&(o.TimeoutSeconds=r),t!==void 0&&(o.MaxRows=t),s!==void 0&&(o.StartRow=s);const i=await this.ExecuteGQL(n,{input:o});return i?.ExecuteAdhocQuery?this.TransformQueryPayload(i.ExecuteAdhocQuery):{QueryID:"",QueryName:"Ad-Hoc Query",Success:!1,Results:[],RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Ad-hoc query execution failed \u2014 no response from server"}}async InternalRunQueries(e,t){const r=u.gql`
325
325
  query RunQueriesBatch($input: [RunQueryInput!]!) {
326
326
  RunQueries(input: $input) {
327
327
  ${this.QueryReturnFieldList}
328
328
  }
329
329
  }
330
- `,s=e.map(a=>({QueryID:a.QueryID,QueryName:a.QueryName,CategoryID:a.CategoryID,CategoryPath:a.CategoryPath,Parameters:a.Parameters,MaxRows:a.MaxRows,StartRow:a.StartRow,ForceAuditLog:a.ForceAuditLog,AuditLogDescription:a.AuditLogDescription})),n=await this.ExecuteGQL(r,{input:s});return n&&n.RunQueries?n.RunQueries.map(a=>this.TransformQueryPayload(a)):[]}async RunQueryByID(e,t,r,s,n,a,i){const o=u.gql`
330
+ `,s=e.map(o=>({QueryID:o.QueryID,QueryName:o.QueryName,CategoryID:o.CategoryID,CategoryPath:o.CategoryPath,Parameters:o.Parameters,MaxRows:o.MaxRows,StartRow:o.StartRow,ForceAuditLog:o.ForceAuditLog,AuditLogDescription:o.AuditLogDescription})),n=await this.ExecuteGQL(r,{input:s});return n&&n.RunQueries?n.RunQueries.map(o=>this.TransformQueryPayload(o)):[]}async RunQueryByID(e,t,r,s,n,o,i){const a=u.gql`
331
331
  query GetQueryDataQuery($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
332
332
  GetQueryData(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
333
333
  ${this.QueryReturnFieldList}
334
334
  }
335
335
  }
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 l=await this.ExecuteGQL(o,y);if(l&&l.GetQueryData)return this.TransformQueryPayload(l.GetQueryData)}async RunQueryByName(e,t,r,s,n,a,i){const o=u.gql`
336
+ `,y={QueryID:e};t!==void 0&&(y.CategoryID=t),r!==void 0&&(y.CategoryPath=r),n!==void 0&&(y.Parameters=n),o!==void 0&&(y.MaxRows=o),i!==void 0&&(y.StartRow=i);const l=await this.ExecuteGQL(a,y);if(l&&l.GetQueryData)return this.TransformQueryPayload(l.GetQueryData)}async RunQueryByName(e,t,r,s,n,o,i){const a=u.gql`
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
- `,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 l=await this.ExecuteGQL(o,y);if(l&&l.GetQueryDataByName)return this.TransformQueryPayload(l.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),o!==void 0&&(y.MaxRows=o),i!==void 0&&(y.StartRow=i);const l=await this.ExecuteGQL(a,y);if(l&&l.GetQueryDataByName)return this.TransformQueryPayload(l.GetQueryDataByName)}get QueryReturnFieldList(){return`
343
343
  Success
344
344
  QueryID
345
345
  QueryName
@@ -348,7 +348,7 @@
348
348
  TotalRowCount
349
349
  ExecutionTime
350
350
  ErrorMessage
351
- AppliedParameters`}TransformQueryPayload(e){try{return{QueryID:e.QueryID,QueryName:e.QueryName,Success:e.Success,Results:JSON.parse(e.Results),RowCount:e.RowCount,TotalRowCount:e.TotalRowCount,ExecutionTime:e.ExecutionTime,ErrorMessage:e.ErrorMessage,AppliedParameters:e.AppliedParameters?JSON.parse(e.AppliedParameters):void 0}}catch(t){return c.LogError(`Error transforming query payload: ${t}`),null}}async RunQueriesWithCacheCheck(e,t){try{const r=e.map(o=>({params:{QueryID:o.params.QueryID||null,QueryName:o.params.QueryName||null,CategoryID:o.params.CategoryID||null,CategoryPath:o.params.CategoryPath||null,Parameters:o.params.Parameters||null,MaxRows:o.params.MaxRows??null,StartRow:o.params.StartRow??null,ForceAuditLog:o.params.ForceAuditLog||!1,AuditLogDescription:o.params.AuditLogDescription||null},cacheStatus:o.cacheStatus?{maxUpdatedAt:o.cacheStatus.maxUpdatedAt,rowCount:o.cacheStatus.rowCount}:null})),s=u.gql`
351
+ AppliedParameters`}TransformQueryPayload(e){try{return{QueryID:e.QueryID,QueryName:e.QueryName,Success:e.Success,Results:JSON.parse(e.Results),RowCount:e.RowCount,TotalRowCount:e.TotalRowCount,ExecutionTime:e.ExecutionTime,ErrorMessage:e.ErrorMessage,AppliedParameters:e.AppliedParameters?JSON.parse(e.AppliedParameters):void 0}}catch(t){return c.LogError(`Error transforming query payload: ${t}`),null}}async RunQueriesWithCacheCheck(e,t){try{const r=e.map(a=>({params:{QueryID:a.params.QueryID||null,QueryName:a.params.QueryName||null,CategoryID:a.params.CategoryID||null,CategoryPath:a.params.CategoryPath||null,Parameters:a.params.Parameters||null,MaxRows:a.params.MaxRows??null,StartRow:a.params.StartRow??null,ForceAuditLog:a.params.ForceAuditLog||!1,AuditLogDescription:a.params.AuditLogDescription||null},cacheStatus:a.cacheStatus?{maxUpdatedAt:a.cacheStatus.maxUpdatedAt,rowCount:a.cacheStatus.rowCount}:null})),s=u.gql`
352
352
  query RunQueriesWithCacheCheckQuery($input: [RunQueryWithCacheCheckInput!]!) {
353
353
  RunQueriesWithCacheCheck(input: $input) {
354
354
  success
@@ -364,7 +364,7 @@
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 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 c.LogError(`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:S,v:E}=await this.getEntityNameAndUserView(e,t);i=E,a=S}const o=this.EntityByName(a);if(!o)throw new Error(`Entity ${a} not found in metadata`);let y=!1;const l=c.getGraphQLTypeNameBase(o);e.ViewID?(r=`Run${l}ViewByID`,s="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(r=`Run${l}ViewByName`,s="RunViewByNameInput",n.ViewName=e.ViewName):(y=!0,r=`Run${l}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(S=>({expression:S.expression,alias:S.alias})));const f=this.getViewRunTimeFieldList(o,i,e,y),I=e.Aggregates&&e.Aggregates.length>0?`
367
+ `,o=(await this.ExecuteGQL(s,{input:r}))?.RunQueriesWithCacheCheck;if(!o)return{success:!1,results:[],errorMessage:"No response from server"};const i=o.results.map(a=>{if((a.status==="stale"||a.status==="no_validation")&&a.Results){const y=JSON.parse(a.Results);return{queryIndex:a.queryIndex,queryId:a.queryId,status:a.status,results:y,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}}return{queryIndex:a.queryIndex,queryId:a.queryId,status:a.status,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}});return{success:o.success,results:i,errorMessage:o.errorMessage}}catch(r){return c.LogError(`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 o,i;if(e.ViewEntity)i=e.ViewEntity,o=i.Entity;else{const{entityName:S,v:E}=await this.getEntityNameAndUserView(e,t);i=E,o=S}const a=this.EntityByName(o);if(!a)throw new Error(`Entity ${o} not found in metadata`);let y=!1;const l=c.getGraphQLTypeNameBase(a);e.ViewID?(r=`Run${l}ViewByID`,s="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(r=`Run${l}ViewByName`,s="RunViewByNameInput",n.ViewName=e.ViewName):(y=!0,r=`Run${l}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(S=>({expression:S.expression,alias:S.alias})));const f=this.getViewRunTimeFieldList(a,i,e,y),I=e.Aggregates&&e.Aggregates.length>0?`
368
368
  AggregateResults {
369
369
  alias
370
370
  expression
@@ -385,14 +385,14 @@
385
385
  Success
386
386
  ErrorMessage${I}
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 p=await this.ExecuteGQL(g,{input:n});if(p&&p[r]){const S=p[r].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:a,aggregateResultCount:S?.length||0,aggregateResults:S,aggregateExecutionTime:p[r].AggregateExecutionTime});const E=p[r].Results;if(E&&E.length>0){const C=o.Fields.filter(v=>v.CodeName!==v.Name&&v.CodeName!==void 0);E.forEach(v=>{this.ConvertBackToMJFields(v),C.forEach(b=>{v[b.Name]=v[b.CodeName]})})}return p[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw c.LogError(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],n=[];for(const l of e){let f="",I="";const g={};let p=null,S=null;if(l.ViewEntity)S=l.ViewEntity,p=S.Get("Entity");else{const{entityName:v,v:b}=await this.getEntityNameAndUserView(l,t);S=b,p=v}const E=this.EntityByName(p);if(!E)throw new Error(`Entity ${p} not found in metadata`);s.push(E);let D=!1;const C=c.getGraphQLTypeNameBase(E);l.ViewID?(f=`Run${C}ViewByID`,I="RunViewByIDInput",g.ViewID=l.ViewID):l.ViewName?(f=`Run${C}ViewByName`,I="RunViewByNameInput",g.ViewName=l.ViewName):(D=!0,f=`Run${C}DynamicView`,I="RunDynamicViewInput",g.EntityName=l.EntityName),g.ExtraFilter=l.ExtraFilter||"",g.OrderBy=l.OrderBy||"",g.UserSearchString=l.UserSearchString||"",g.Fields=l.Fields,g.IgnoreMaxRows=l.IgnoreMaxRows||!1,l.MaxRows!==void 0&&(g.MaxRows=l.MaxRows),l.StartRow!==void 0&&(g.StartRow=l.StartRow),l.AfterKey&&(g.AfterKey={KeyValuePairs:l.AfterKey.KeyValuePairs}),g.ForceAuditLog=l.ForceAuditLog||!1,g.ResultType=l.ResultType||"simple",l.AuditLogDescription&&l.AuditLogDescription.length>0&&(g.AuditLogDescription=l.AuditLogDescription),l.BypassCache!==void 0&&(g.BypassCache=l.BypassCache),D||(g.ExcludeUserViewRunID=l.ExcludeUserViewRunID||"",g.ExcludeDataFromAllPriorViewRuns=l.ExcludeDataFromAllPriorViewRuns||!1,g.OverrideExcludeFilter=l.OverrideExcludeFilter||"",g.SaveViewResults=l.SaveViewResults||!1),l.Aggregates&&l.Aggregates.length>0&&(g.Aggregates=l.Aggregates.map(v=>({expression:v.expression,alias:v.alias}))),r.push(g),n.push(...this.getViewRunTimeFieldList(E,S,l,D))}const i=e.some(l=>l.Aggregates&&l.Aggregates.length>0)?`
388
+ }`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:o,queryName:r,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const p=await this.ExecuteGQL(g,{input:n});if(p&&p[r]){const S=p[r].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:o,aggregateResultCount:S?.length||0,aggregateResults:S,aggregateExecutionTime:p[r].AggregateExecutionTime});const E=p[r].Results;if(E&&E.length>0){const C=a.Fields.filter(v=>v.CodeName!==v.Name&&v.CodeName!==void 0);E.forEach(v=>{this.ConvertBackToMJFields(v),C.forEach(N=>{v[N.Name]=v[N.CodeName]})})}return p[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw c.LogError(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],n=[];for(const l of e){let f="",I="";const g={};let p=null,S=null;if(l.ViewEntity)S=l.ViewEntity,p=S.Get("Entity");else{const{entityName:v,v:N}=await this.getEntityNameAndUserView(l,t);S=N,p=v}const E=this.EntityByName(p);if(!E)throw new Error(`Entity ${p} not found in metadata`);s.push(E);let D=!1;const C=c.getGraphQLTypeNameBase(E);l.ViewID?(f=`Run${C}ViewByID`,I="RunViewByIDInput",g.ViewID=l.ViewID):l.ViewName?(f=`Run${C}ViewByName`,I="RunViewByNameInput",g.ViewName=l.ViewName):(D=!0,f=`Run${C}DynamicView`,I="RunDynamicViewInput",g.EntityName=l.EntityName),g.ExtraFilter=l.ExtraFilter||"",g.OrderBy=l.OrderBy||"",g.UserSearchString=l.UserSearchString||"",g.Fields=l.Fields,g.IgnoreMaxRows=l.IgnoreMaxRows||!1,l.MaxRows!==void 0&&(g.MaxRows=l.MaxRows),l.StartRow!==void 0&&(g.StartRow=l.StartRow),l.AfterKey&&(g.AfterKey={KeyValuePairs:l.AfterKey.KeyValuePairs}),g.ForceAuditLog=l.ForceAuditLog||!1,g.ResultType=l.ResultType||"simple",l.AuditLogDescription&&l.AuditLogDescription.length>0&&(g.AuditLogDescription=l.AuditLogDescription),l.BypassCache!==void 0&&(g.BypassCache=l.BypassCache),D||(g.ExcludeUserViewRunID=l.ExcludeUserViewRunID||"",g.ExcludeDataFromAllPriorViewRuns=l.ExcludeDataFromAllPriorViewRuns||!1,g.OverrideExcludeFilter=l.OverrideExcludeFilter||"",g.SaveViewResults=l.SaveViewResults||!1),l.Aggregates&&l.Aggregates.length>0&&(g.Aggregates=l.Aggregates.map(v=>({expression:v.expression,alias:v.alias}))),r.push(g),n.push(...this.getViewRunTimeFieldList(E,S,l,D))}const i=e.some(l=>l.Aggregates&&l.Aggregates.length>0)?`
389
389
  AggregateResults {
390
390
  alias
391
391
  expression
392
392
  value
393
393
  error
394
394
  }
395
- AggregateExecutionTime`:"",o=u.gql`
395
+ AggregateExecutionTime`:"",a=u.gql`
396
396
  query RunViewsQuery ($input: [RunViewGenericInput!]!) {
397
397
  RunViews(input: $input) {
398
398
  Results {
@@ -410,7 +410,7 @@
410
410
  Success
411
411
  ErrorMessage${i}
412
412
  }
413
- }`,y=await this.ExecuteGQL(o,{input:r});if(y&&y.RunViews){const l=y.RunViews;for(const[f,I]of l.entries())I.Results=I.Results.map(g=>{let p=JSON.parse(g.Data);return this.ConvertBackToMJFields(p),p});return l}return null}catch(r){throw c.LogError(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=u.gql`
413
+ }`,y=await this.ExecuteGQL(a,{input:r});if(y&&y.RunViews){const l=y.RunViews;for(const[f,I]of l.entries())I.Results=I.Results.map(g=>{let p=JSON.parse(g.Data);return this.ConvertBackToMJFields(p),p});return l}return null}catch(r){throw c.LogError(r),r}}async RunViewsWithCacheCheck(e,t){try{const r=e.map(a=>({params:{EntityName:a.params.EntityName||"",ExtraFilter:a.params.ExtraFilter||"",OrderBy:a.params.OrderBy||"",Fields:a.params.Fields,UserSearchString:a.params.UserSearchString||"",IgnoreMaxRows:a.params.IgnoreMaxRows||!1,MaxRows:a.params.MaxRows,StartRow:a.params.StartRow,AfterKey:a.params.AfterKey?{KeyValuePairs:a.params.AfterKey.KeyValuePairs}:null,ForceAuditLog:a.params.ForceAuditLog||!1,AuditLogDescription:a.params.AuditLogDescription||"",ResultType:a.params.ResultType||"simple"},cacheStatus:a.cacheStatus?{maxUpdatedAt:a.cacheStatus.maxUpdatedAt,rowCount:a.cacheStatus.rowCount}:null})),s=u.gql`
414
414
  query RunViewsWithCacheCheckQuery($input: [RunViewWithCacheCheckInput!]!) {
415
415
  RunViewsWithCacheCheck(input: $input) {
416
416
  success
@@ -443,7 +443,7 @@
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,y)=>{const l=e[y];if(o.status==="differential"&&o.differentialData){const f=o.differentialData.updatedRows.map(I=>{const g=JSON.parse(I.Data);return this.ConvertBackToMJFields(g),g});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(I=>{const g=JSON.parse(I.Data);return this.ConvertBackToMJFields(g),g});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 c.LogError(r),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async getEntityNameAndUserView(e,t){let r,s;if(e.EntityName)r=e.EntityName;else if(e.ViewID)s=await G.ViewInfo.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await G.ViewInfo.GetViewEntityByName(e.ViewName,t),r=s.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:r,v:s}}getViewRunTimeFieldList(e,t,r,s){const n=[];if(r.Fields){for(const a of e.PrimaryKeys)r.Fields.find(i=>i.trim().toLowerCase()===a.Name.toLowerCase())===void 0&&n.push(a.Name);r.Fields.forEach(a=>{n.push(N.MapFieldName(a))})}else if(s)e.Fields.forEach(a=>{a.IsBinaryFieldType||n.push(N.MapFieldName(a.CodeName))});else{for(const a of e.PrimaryKeys)n.find(i=>i.trim().toLowerCase()===a.Name.toLowerCase())===void 0&&n.push(a.Name);t.Columns.forEach(a=>{a.hidden===!1&&!n.find(i=>i.trim().toLowerCase()===a.EntityField?.Name.trim().toLowerCase())&&a.EntityField&&n.push(N.MapFieldName(a.EntityField.CodeName))})}return n}get ProviderType(){return c.ProviderType.Network}async GetRecordChanges(e,t){try{const r={EntityName:"MJ: Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},s=await this.RunView(r);return s?s.Results.sort((n,a)=>n.ChangedAt>a.ChangedAt?-1:1):null}catch(r){throw c.LogError(r),r}}async GetRecordDependencies(e,t){try{const r=u.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
446
+ `,o=(await this.ExecuteGQL(s,{input:r}))?.RunViewsWithCacheCheck;if(!o)return{success:!1,results:[],errorMessage:"No response from server"};const i=o.results.map((a,y)=>{const l=e[y];if(a.status==="differential"&&a.differentialData){const f=a.differentialData.updatedRows.map(I=>{const g=JSON.parse(I.Data);return this.ConvertBackToMJFields(g),g});return{viewIndex:a.viewIndex,status:a.status,results:void 0,differentialData:{updatedRows:f,deletedRecordIDs:a.differentialData.deletedRecordIDs},maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}}if(a.status==="stale"&&a.Results){const f=a.Results.map(I=>{const g=JSON.parse(I.Data);return this.ConvertBackToMJFields(g),g});return{viewIndex:a.viewIndex,status:a.status,results:f,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}}return{viewIndex:a.viewIndex,status:a.status,results:void 0,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}});return{success:o.success,results:i,errorMessage:o.errorMessage}}catch(r){return c.LogError(r),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async getEntityNameAndUserView(e,t){let r,s;if(e.EntityName)r=e.EntityName;else if(e.ViewID)s=await G.ViewInfo.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await G.ViewInfo.GetViewEntityByName(e.ViewName,t),r=s.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:r,v:s}}getViewRunTimeFieldList(e,t,r,s){const n=[];if(r.Fields){for(const o of e.PrimaryKeys)r.Fields.find(i=>i.trim().toLowerCase()===o.Name.toLowerCase())===void 0&&n.push(o.Name);r.Fields.forEach(o=>{n.push(A.MapFieldName(o))})}else if(s)e.Fields.forEach(o=>{o.IsBinaryFieldType||n.push(A.MapFieldName(o.CodeName))});else{for(const o of e.PrimaryKeys)n.find(i=>i.trim().toLowerCase()===o.Name.toLowerCase())===void 0&&n.push(o.Name);t.Columns.forEach(o=>{o.hidden===!1&&!n.find(i=>i.trim().toLowerCase()===o.EntityField?.Name.trim().toLowerCase())&&o.EntityField&&n.push(A.MapFieldName(o.EntityField.CodeName))})}return n}get ProviderType(){return c.ProviderType.Network}async GetRecordChanges(e,t){try{const r={EntityName:"MJ: Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},s=await this.RunView(r);return s?s.Results.sort((n,o)=>n.ChangedAt>o.ChangedAt?-1:1):null}catch(r){throw c.LogError(r),r}}async GetRecordDependencies(e,t){try{const r=u.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
447
447
  GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
448
448
  EntityName
449
449
  RelatedEntityName
@@ -477,7 +477,7 @@
477
477
  }
478
478
  }
479
479
  }
480
- }`;let s={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(a=>a.Copy())};const n=await this.ExecuteGQL(r,{params:s});if(n&&n.GetRecordDuplicates)return n.GetRecordDuplicates}async SearchEntities(e){if(!e||e.length===0)return[];if(e.filter(i=>i?.entityName&&i?.searchText&&i.searchText.trim()).length===0)return e.map(()=>[]);const r=u.gql`query SearchEntitiesQuery($params: [SearchEntityInput!]!) {
480
+ }`;let s={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(o=>o.Copy())};const n=await this.ExecuteGQL(r,{params:s});if(n&&n.GetRecordDuplicates)return n.GetRecordDuplicates}async SearchEntities(e){if(!e||e.length===0)return[];if(e.filter(i=>i?.entityName&&i?.searchText&&i.searchText.trim()).length===0)return e.map(()=>[]);const r=u.gql`query SearchEntitiesQuery($params: [SearchEntityInput!]!) {
481
481
  SearchEntities(params: $params) {
482
482
  Success
483
483
  ErrorMessage
@@ -493,7 +493,15 @@
493
493
  }
494
494
  }
495
495
  }
496
- }`,s=e.map(i=>({EntityName:i.entityName,SearchText:i.searchText,Mode:i.options?.mode??"hybrid",RrfK:i.options?.rrfK,LexicalWeight:i.options?.weights?.lexical,SemanticWeight:i.options?.weights?.semantic,TopK:i.options?.topK,MinScore:i.options?.minScore,EntityDocumentID:i.options?.entityDocumentId})),n=await this.ExecuteGQL(r,{params:s});return n?.SearchEntities?.Success?n.SearchEntities.Groups.map(i=>i.Results.map(o=>({entityRecordDocumentId:o.EntityRecordDocumentID,recordId:o.RecordID,score:o.Score,matchType:o.MatchType,components:{lexical:o.LexicalScore??void 0,semantic:o.SemanticScore??void 0}}))):(n?.SearchEntities?.ErrorMessage&&c.LogError(`SearchEntities GraphQL error: ${n.SearchEntities.ErrorMessage}`),e.map(()=>[]))}async SearchEntity(e){return(await this.SearchEntities([e]))[0]??[]}async searchEntitiesSemanticPass(){return[]}async MergeRecords(e,t,r){const s=this.Entities.find(n=>n.Name.trim().toLowerCase()===e.EntityName.trim().toLowerCase());if(!s||!s.AllowRecordMerge)throw new Error(`Entity ${e.EntityName} does not allow record merging, check the AllowRecordMerge property in the entity metadata`);try{const n=u.gql`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
496
+ }`,s=e.map(i=>({EntityName:i.entityName,SearchText:i.searchText,Mode:i.options?.mode??"hybrid",RrfK:i.options?.rrfK,LexicalWeight:i.options?.weights?.lexical,SemanticWeight:i.options?.weights?.semantic,TopK:i.options?.topK,MinScore:i.options?.minScore,EntityDocumentID:i.options?.entityDocumentId})),n=await this.ExecuteGQL(r,{params:s});return n?.SearchEntities?.Success?n.SearchEntities.Groups.map(i=>i.Results.map(a=>({entityRecordDocumentId:a.EntityRecordDocumentID,recordId:a.RecordID,score:a.Score,matchType:a.MatchType,components:{lexical:a.LexicalScore??void 0,semantic:a.SemanticScore??void 0}}))):(n?.SearchEntities?.ErrorMessage&&c.LogError(`SearchEntities GraphQL error: ${n.SearchEntities.ErrorMessage}`),e.map(()=>[]))}async SearchEntity(e){return(await this.SearchEntities([e]))[0]??[]}async searchEntitiesSemanticPass(){return[]}async InternalRouteOperation(e,t,r){const s=u.gql`mutation ExecuteRemoteOperation($operationKey: String!, $inputJSON: String!, $invokeMode: String!) {
497
+ ExecuteRemoteOperation(input: { operationKey: $operationKey, inputJSON: $inputJSON, invokeMode: $invokeMode }) {
498
+ success
499
+ resultCode
500
+ outputJSON
501
+ handle
502
+ errorMessage
503
+ }
504
+ }`;try{const o=(await this.ExecuteGQL(s,{operationKey:e,inputJSON:JSON.stringify(t??null),invokeMode:r.mode??"attached"}))?.ExecuteRemoteOperation;return o?{Success:!!o.success,ResultCode:o.resultCode??void 0,Output:o.outputJSON!=null?JSON.parse(o.outputJSON):void 0,Handle:o.handle??void 0,ErrorMessage:o.errorMessage??void 0}:{Success:!1,ResultCode:"NO_RESPONSE",ErrorMessage:"No response from ExecuteRemoteOperation"}}catch(n){return{Success:!1,ResultCode:"TRANSPORT_ERROR",ErrorMessage:n instanceof Error?n.message:String(n)}}}async MergeRecords(e,t,r){const s=this.Entities.find(n=>n.Name.trim().toLowerCase()===e.EntityName.trim().toLowerCase());if(!s||!s.AllowRecordMerge)throw new Error(`Entity ${e.EntityName} does not allow record merging, check the AllowRecordMerge property in the entity metadata`);try{const n=u.gql`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
497
505
  MergeRecords(request: $request) {
498
506
  Success
499
507
  OverallStatus
@@ -510,32 +518,32 @@
510
518
  Message
511
519
  }
512
520
  }
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 c.LogError(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){if(r?.IsParentEntitySave){const n=new c.BaseEntityResult;return n.StartedAt=new Date,n.EndedAt=new Date,n.Type=e.IsSaved?"update":"create",n.Success=!0,n.NewValues=e.GetAll(),e.RegisterResultHistoryEntry(n),n.NewValues}const s=new c.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const n={input:{}},a=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(g=>({FieldName:g.CodeName,Value:g.Value})),e.RegisterResultHistoryEntry(s);const i=c.getGraphQLTypeNameBase(e.EntityInfo),o=`${a}${i}`,y=e.Fields.filter(g=>!g.ReadOnly||g.IsPrimaryKey&&e.IsSaved),l=` ${o}(input: $input) {
514
- ${e.Fields.map(g=>N.MapFieldName(g.CodeName)).join(`
521
+ }`,o={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(a=>({FieldName:a.FieldName,Value:a.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(a=>a.Copy())};return(await this.ExecuteGQL(n,{request:o}))?.MergeRecords}catch(n){return c.LogError(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){if(r?.IsParentEntitySave){const n=new c.BaseEntityResult;return n.StartedAt=new Date,n.EndedAt=new Date,n.Type=e.IsSaved?"update":"create",n.Success=!0,n.NewValues=e.GetAll(),e.RegisterResultHistoryEntry(n),n.NewValues}const s=new c.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const n={input:{}},o=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(g=>({FieldName:g.CodeName,Value:g.Value})),e.RegisterResultHistoryEntry(s);const i=c.getGraphQLTypeNameBase(e.EntityInfo),a=`${o}${i}`,y=e.Fields.filter(g=>!g.ReadOnly||g.IsPrimaryKey&&e.IsSaved),l=` ${a}(input: $input) {
522
+ ${e.Fields.map(g=>A.MapFieldName(g.CodeName)).join(`
515
523
  `)}
516
- }`,f=u.gql`mutation ${a}${i} ($input: ${o}Input!) {
524
+ }`,f=u.gql`mutation ${o}${i} ($input: ${a}Input!) {
517
525
  ${l}
518
526
  }
519
- `;for(let g=0;g<y.length;g++){const p=y[g];let S=e.Get(p.Name);if(S)switch(p.EntityFieldInfo.TSType){case c.EntityFieldTSType.Date:S=S.getTime();break;case c.EntityFieldTSType.Boolean:typeof S!="boolean"&&(S=parseInt(S)!==0);break;case c.EntityFieldTSType.Number:if(typeof S!="number"){const E=Number(S);isNaN(E)||(S=E)}break}S===null&&p.EntityFieldInfo.AllowsNull===!1&&(p.EntityFieldInfo.DefaultValue!==null?S=p.EntityFieldInfo.DefaultValue:p.FieldType===c.EntityFieldTSType.Number||p.FieldType===c.EntityFieldTSType.Boolean?S=0:S=""),n.input[N.MapFieldName(p.CodeName)]=S}const I=e.RestoreContext;if(I&&(n.input.RestoreContext___={SourceChangeID:I.SourceChangeID,Reason:I.Reason}),a.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const g=[];e.Fields.forEach(p=>{let S=null;p.OldValue!==null&&p.OldValue!==void 0&&(p.EntityFieldInfo.TSType===c.EntityFieldTSType.Date?S=p.OldValue.getTime().toString():p.EntityFieldInfo.TSType===c.EntityFieldTSType.Boolean?S=p.OldValue===!0?"1":"0":typeof p.OldValue!="string"?S=p.OldValue.toString():S=p.OldValue),g.push({Key:N.MapFieldName(p.CodeName),Value:S})}),n.input.OldValues___=g}if(e.TransactionGroup){const g=[{varName:"input",inputType:o+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,s.Type==="create"?"Create":"Update",l,n,{mutationName:o,mutationInputTypes:g},(p,S)=>{s.EndedAt=new Date,S&&p?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(p)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const g=await this.ExecuteGQL(f,n);if(g&&g[o])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(g[o]),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(n){return s.Success=!1,s.EndedAt=new Date,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,c.LogError(n),null}}async Load(e,t,r=null,s){try{const n={};let a="",i="";for(let I=0;I<t.KeyValuePairs.length;I++){const g=e.Fields.find(E=>E.Name.trim().toLowerCase()===t.KeyValuePairs[I].FieldName.trim().toLowerCase()).EntityFieldInfo,p=t.GetValueByIndex(I),S=g.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${g.CodeName}: ${S}!`,a.length>0&&(a+=", "),a+=`${g.CodeName}: $${g.CodeName}`,g.TSType===c.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(I)))throw new Error(`Primary Key value ${p} (${g.Name}) is not a valid number`);n[g.CodeName]=parseInt(p)}else n[g.CodeName]=p}const o=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",y=c.getGraphQLTypeNameBase(e.EntityInfo),l=u.gql`query Single${y}${o.length>0?"Full":""} (${i}) {
520
- ${y}(${a}) {
527
+ `;for(let g=0;g<y.length;g++){const p=y[g];let S=e.Get(p.Name);if(S)switch(p.EntityFieldInfo.TSType){case c.EntityFieldTSType.Date:S=S.getTime();break;case c.EntityFieldTSType.Boolean:typeof S!="boolean"&&(S=parseInt(S)!==0);break;case c.EntityFieldTSType.Number:if(typeof S!="number"){const E=Number(S);isNaN(E)||(S=E)}break}S===null&&p.EntityFieldInfo.AllowsNull===!1&&(p.EntityFieldInfo.DefaultValue!==null?S=p.EntityFieldInfo.DefaultValue:p.FieldType===c.EntityFieldTSType.Number||p.FieldType===c.EntityFieldTSType.Boolean?S=0:S=""),n.input[A.MapFieldName(p.CodeName)]=S}const I=e.RestoreContext;if(I&&(n.input.RestoreContext___={SourceChangeID:I.SourceChangeID,Reason:I.Reason}),o.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const g=[];e.Fields.forEach(p=>{let S=null;p.OldValue!==null&&p.OldValue!==void 0&&(p.EntityFieldInfo.TSType===c.EntityFieldTSType.Date?S=p.OldValue.getTime().toString():p.EntityFieldInfo.TSType===c.EntityFieldTSType.Boolean?S=p.OldValue===!0?"1":"0":typeof p.OldValue!="string"?S=p.OldValue.toString():S=p.OldValue),g.push({Key:A.MapFieldName(p.CodeName),Value:S})}),n.input.OldValues___=g}if(e.TransactionGroup){const g=[{varName:"input",inputType:a+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,s.Type==="create"?"Create":"Update",l,n,{mutationName:a,mutationInputTypes:g},(p,S)=>{s.EndedAt=new Date,S&&p?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(p)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const g=await this.ExecuteGQL(f,n);if(g&&g[a])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(g[a]),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(n){return s.Success=!1,s.EndedAt=new Date,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,c.LogError(n),null}}async Load(e,t,r=null,s){try{const n={};let o="",i="";for(let I=0;I<t.KeyValuePairs.length;I++){const g=e.Fields.find(E=>E.Name.trim().toLowerCase()===t.KeyValuePairs[I].FieldName.trim().toLowerCase()).EntityFieldInfo,p=t.GetValueByIndex(I),S=g.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${g.CodeName}: ${S}!`,o.length>0&&(o+=", "),o+=`${g.CodeName}: $${g.CodeName}`,g.TSType===c.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(I)))throw new Error(`Primary Key value ${p} (${g.Name}) is not a valid number`);n[g.CodeName]=parseInt(p)}else n[g.CodeName]=p}const a=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",y=c.getGraphQLTypeNameBase(e.EntityInfo),l=u.gql`query Single${y}${a.length>0?"Full":""} (${i}) {
528
+ ${y}(${o}) {
521
529
  ${e.Fields.filter(I=>!I.EntityFieldInfo.IsBinaryFieldType).map(I=>I.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?I.CodeName.replace("__mj_","_mj__"):I.CodeName).join(`
522
530
  `)}
523
- ${o}
531
+ ${a}
524
532
  }
525
533
  }
526
- `,f=await this.ExecuteGQL(l,n);return f&&f[y]?this.ConvertBackToMJFields(f[y]):null}catch(n){return c.LogError(n),null}}ConvertBackToMJFields(e){return N.ReverseMapFields(e),e}getRelatedEntityString(e,t){let r="";for(let s=0;s<e.RelatedEntities.length;s++)if(t.indexOf(e.RelatedEntities[s].RelatedEntity)>=0){const n=e.RelatedEntities[s],a=this.EntityByID(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+=`
534
+ `,f=await this.ExecuteGQL(l,n);return f&&f[y]?this.ConvertBackToMJFields(f[y]):null}catch(n){return c.LogError(n),null}}ConvertBackToMJFields(e){return A.ReverseMapFields(e),e}getRelatedEntityString(e,t){let r="";for(let s=0;s<e.RelatedEntities.length;s++)if(t.indexOf(e.RelatedEntities[s].RelatedEntity)>=0){const n=e.RelatedEntities[s],o=this.EntityByID(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
535
  ${i} {
528
- ${a.Fields.map(o=>o.CodeName).join(`
536
+ ${o.Fields.map(a=>a.CodeName).join(`
529
537
  `)}
530
538
  }
531
- `}return r}async Delete(e,t,r){const s=new c.BaseEntityResult;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(p=>({FieldName:p.CodeName,Value:p.Value})),e.RegisterResultHistoryEntry(s);const n={},a=[];let i="",o="",y="";for(let p of e.PrimaryKey.KeyValuePairs){const S=e.Fields.find(E=>E.Name.trim().toLowerCase()===p.FieldName.trim().toLowerCase());n[S.CodeName]=S.Value,a.push({varName:S.CodeName,inputType:S.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${S.CodeName}: $${S.CodeName}`,o.length>0&&(o+=", "),o+=`$${S.CodeName}: ${S.EntityFieldInfo.GraphQLType}!`,y.length>0&&(y+=`
532
- `),y+=`${S.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"+c.getGraphQLTypeNameBase(e.EntityInfo),I=u.gql`${f}(${i}, options___: $options___) {
539
+ `}return r}async Delete(e,t,r){const s=new c.BaseEntityResult;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(p=>({FieldName:p.CodeName,Value:p.Value})),e.RegisterResultHistoryEntry(s);const n={},o=[];let i="",a="",y="";for(let p of e.PrimaryKey.KeyValuePairs){const S=e.Fields.find(E=>E.Name.trim().toLowerCase()===p.FieldName.trim().toLowerCase());n[S.CodeName]=S.Value,o.push({varName:S.CodeName,inputType:S.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${S.CodeName}: $${S.CodeName}`,a.length>0&&(a+=", "),a+=`$${S.CodeName}: ${S.EntityFieldInfo.GraphQLType}!`,y.length>0&&(y+=`
540
+ `),y+=`${S.CodeName}`}o.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"+c.getGraphQLTypeNameBase(e.EntityInfo),I=u.gql`${f}(${i}, options___: $options___) {
533
541
  ${y}
534
542
  }
535
- `,g=u.gql`mutation ${f} (${o}, $options___: DeleteOptionsInput!) {
543
+ `,g=u.gql`mutation ${f} (${a}, $options___: DeleteOptionsInput!) {
536
544
  ${I}
537
545
  }
538
- `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,"Delete",I,n,{mutationName:f,mutationInputTypes:a},(p,S)=>{if(s.EndedAt=new Date,S&&p){let E=!0;for(const D of e.PrimaryKey.KeyValuePairs)D.Value!==p[D.FieldName]&&(E=!1);E?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const p=await this.ExecuteGQL(g,n);if(p&&p[f]){const S=p[f];for(let E of e.PrimaryKey.KeyValuePairs){let D=S[E.FieldName],C=E.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: ${E.FieldName}, Original: ${C}, Returned: ${D}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(n){return s.EndedAt=new Date,s.Success=!1,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,c.LogError(n),!1}}async GetDatasetByName(e,t){const r=u.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
546
+ `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,"Delete",I,n,{mutationName:f,mutationInputTypes:o},(p,S)=>{if(s.EndedAt=new Date,S&&p){let E=!0;for(const D of e.PrimaryKey.KeyValuePairs)D.Value!==p[D.FieldName]&&(E=!1);E?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const p=await this.ExecuteGQL(g,n);if(p&&p[f]){const S=p[f];for(let E of e.PrimaryKey.KeyValuePairs){let D=S[E.FieldName],C=E.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: ${E.FieldName}, Original: ${C}, Returned: ${D}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(n){return s.EndedAt=new Date,s.Success=!1,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,c.LogError(n),!1}}async GetDatasetByName(e,t){const r=u.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
539
547
  GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
540
548
  DatasetID
541
549
  DatasetName
@@ -553,7 +561,7 @@
553
561
  LatestUpdateDate
554
562
  EntityUpdateDates
555
563
  }
556
- }`,n=((await this.ExecuteGQL(r,{DatasetNames:t}))?.GetMultipleDatasetStatusByName||[]).map(a=>({DatasetID:a.DatasetID,DatasetName:a.DatasetName,Success:a.Success,Status:a.Status,LatestUpdateDate:a.LatestUpdateDate?new Date(a.LatestUpdateDate):null,EntityUpdateDates:a.EntityUpdateDates?JSON.parse(a.EntityUpdateDates):null}));for(const a of e){const i=n.find(o=>o.DatasetName===a.datasetName);i?a.resolve(i):a.resolve({DatasetID:"",DatasetName:a.datasetName,Success:!1,Status:"Not found in batch response",LatestUpdateDate:null,EntityUpdateDates:null})}}catch(r){c.LogError(`Dataset status batch failed, falling back to individual calls: ${r}`);const s=e.map(async n=>{try{const a=await this.executeDatasetStatusByName(n.datasetName,n.itemFilters);n.resolve(a)}catch(a){n.reject(a)}});await Promise.all(s)}}async executeDatasetStatusByName(e,t){const r=u.gql`query GetDatasetStatusByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
564
+ }`,n=((await this.ExecuteGQL(r,{DatasetNames:t}))?.GetMultipleDatasetStatusByName||[]).map(o=>({DatasetID:o.DatasetID,DatasetName:o.DatasetName,Success:o.Success,Status:o.Status,LatestUpdateDate:o.LatestUpdateDate?new Date(o.LatestUpdateDate):null,EntityUpdateDates:o.EntityUpdateDates?JSON.parse(o.EntityUpdateDates):null}));for(const o of e){const i=n.find(a=>a.DatasetName===o.datasetName);i?o.resolve(i):o.resolve({DatasetID:"",DatasetName:o.datasetName,Success:!1,Status:"Not found in batch response",LatestUpdateDate:null,EntityUpdateDates:null})}}catch(r){c.LogError(`Dataset status batch failed, falling back to individual calls: ${r}`);const s=e.map(async n=>{try{const o=await this.executeDatasetStatusByName(n.datasetName,n.itemFilters);n.resolve(o)}catch(o){n.reject(o)}});await Promise.all(s)}}async executeDatasetStatusByName(e,t){const r=u.gql`query GetDatasetStatusByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
557
565
  GetDatasetStatusByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
558
566
  DatasetID
559
567
  DatasetName
@@ -562,16 +570,16 @@
562
570
  LatestUpdateDate
563
571
  EntityUpdateDates
564
572
  }
565
- }`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetStatusByName&&s.GetDatasetStatusByName.Success?{DatasetID:s.GetDatasetStatusByName.DatasetID,DatasetName:s.GetDatasetStatusByName.DatasetName,Success:s.GetDatasetStatusByName.Success,Status:s.GetDatasetStatusByName.Status,LatestUpdateDate:new Date(s.GetDatasetStatusByName.LatestUpdateDate),EntityUpdateDates:JSON.parse(s.GetDatasetStatusByName.EntityUpdateDates)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,EntityUpdateDates:null}}async CreateTransactionGroup(){return new q(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const n=this.EntityByName(t);if(!n)throw new Error(`Entity ${t} not found in metadata`);const a=u.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
573
+ }`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetStatusByName&&s.GetDatasetStatusByName.Success?{DatasetID:s.GetDatasetStatusByName.DatasetID,DatasetName:s.GetDatasetStatusByName.DatasetName,Success:s.GetDatasetStatusByName.Success,Status:s.GetDatasetStatusByName.Status,LatestUpdateDate:new Date(s.GetDatasetStatusByName.LatestUpdateDate),EntityUpdateDates:JSON.parse(s.GetDatasetStatusByName.EntityUpdateDates)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,EntityUpdateDates:null}}async CreateTransactionGroup(){return new q(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const n=this.EntityByName(t);if(!n)throw new Error(`Entity ${t} not found in metadata`);const o=u.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
566
574
  GetRecordFavoriteStatus(params: $params) {
567
575
  Success
568
576
  IsFavorite
569
577
  }
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.EntityByName(t);if(!a)throw new Error(`Entity ${t} not found in metadata`);const i=u.gql`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
578
+ }`,i=await this.ExecuteGQL(o,{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 o=this.EntityByName(t);if(!o)throw new Error(`Entity ${t} not found in metadata`);const i=u.gql`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
571
579
  SetRecordFavoriteStatus(params: $params){
572
580
  Success
573
581
  }
574
- }`,o=await this.ExecuteGQL(i,{params:{UserID:e,EntityID:a.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)},IsFavorite:s}});if(o&&o.SetRecordFavoriteStatus!==null)return o.SetRecordFavoriteStatus.Success}async InternalGetEntityRecordName(e,t){if(!e||!t||t.KeyValuePairs?.length===0)return null;const r=u.gql`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
582
+ }`,a=await this.ExecuteGQL(i,{params:{UserID:e,EntityID:o.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)},IsFavorite:s}});if(a&&a.SetRecordFavoriteStatus!==null)return a.SetRecordFavoriteStatus.Success}async InternalGetEntityRecordName(e,t){if(!e||!t||t.KeyValuePairs?.length===0)return null;const r=u.gql`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
575
583
  GetEntityRecordName(EntityName: $EntityName, CompositeKey: $CompositeKey) {
576
584
  Success
577
585
  Status
@@ -602,16 +610,16 @@
602
610
  ErrorMessage
603
611
  Result
604
612
  }
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 c.LogError(t),t}}static async ExecuteGQL(e,t,r=!0){return h.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(console.error("[GraphQL] ExecuteGQL error caught:",{hasResponse:!!s?.response,hasErrors:!!s?.response?.errors,errorCount:s?.response?.errors?.length,firstError:s?.response?.errors?.[0],errorCode:s?.response?.errors?.[0]?.extensions?.code,errorMessage:s?.response?.errors?.[0]?.message,fullError:s}),s&&s.response&&s.response.errors?.length>0)if(s.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw c.LogError("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw c.LogError(s),s}}async RefreshToken(){const e=h.Instance&&h.Instance._configData===this._configData;if(e&&h.Instance._refreshPromise)return h.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(h.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&h.Instance&&(h.Instance._refreshPromise=null)}}async performTokenRefresh(){if(this._configData.Data.RefreshTokenFunction)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,h.Instance&&h.Instance._configData===this._configData&&(h.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 h.Instance.RefreshToken()}static async clearClientCache(e=new Set){const t=[];for(let r=0;r<localStorage.length;r++){const s=localStorage.key(r);s&&!e.has(s)&&t.push(s)}t.forEach(r=>localStorage.removeItem(r)),await new Promise(r=>{const s=indexedDB.deleteDatabase("MJ_Metadata");s.onsuccess=()=>r(),s.onerror=()=>r(),s.onblocked=()=>r()})}CreateNewGraphQLClient(e,t,r,s,n){const a={"x-session-id":r};t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),n&&(a["x-api-key"]=n);const i=new u.GraphQLClient(e,{headers:a});for(const[o,y]of this._dynamicHeaders)i.setHeader(o,y);return i}userInfoString(){return this.infoString(new c.UserInfo(null,null))}userRoleInfoString(){return this.infoString(new c.UserRoleInfo(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
613
+ }`,r=await this.ExecuteGQL(t,{DataContextItemID:e});if(r&&r.GetDataContextItemData){if(r.GetDataContextItemData.Success)return JSON.parse(r.GetDataContextItemData.Result);throw new Error(r.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw c.LogError(t),t}}static async ExecuteGQL(e,t,r=!0){return h.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(console.error("[GraphQL] ExecuteGQL error caught:",{hasResponse:!!s?.response,hasErrors:!!s?.response?.errors,errorCount:s?.response?.errors?.length,firstError:s?.response?.errors?.[0],errorCode:s?.response?.errors?.[0]?.extensions?.code,errorMessage:s?.response?.errors?.[0]?.message,fullError:s}),s&&s.response&&s.response.errors?.length>0)if(s.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw c.LogError("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw c.LogError(s),s}}async RefreshToken(){const e=h.Instance&&h.Instance._configData===this._configData;if(e&&h.Instance._refreshPromise)return h.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(h.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&h.Instance&&(h.Instance._refreshPromise=null)}}async performTokenRefresh(){if(this._configData.Data.RefreshTokenFunction)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,h.Instance&&h.Instance._configData===this._configData&&(h.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 h.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 o={"x-session-id":r};t&&(o.authorization="Bearer "+t),s&&(o["x-mj-api-key"]=s),n&&(o["x-api-key"]=n);const i=new u.GraphQLClient(e,{headers:o});for(const[a,y]of this._dynamicHeaders)i.setHeader(a,y);return i}userInfoString(){return this.infoString(new c.UserInfo(null,null))}userRoleInfoString(){return this.infoString(new c.UserRoleInfo(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
606
614
  `:s.startsWith("_")||(t+=s+`
607
- `);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new O:this._localStorageProvider=new c.InMemoryLocalStorageProvider),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=J.createClient({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 A.Observable(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 A.Observable(o=>{r.activeSubscribers++;const y=r.subject.subscribe(o);return()=>{const l=this._pushStatusSubjects.get(e);l&&l.activeSubscribers>0&&l.activeSubscribers--,y.unsubscribe()}});const s=u.gql`subscription StatusUpdates($sessionId: String!) {
615
+ `);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new O:this._localStorageProvider=new c.InMemoryLocalStorageProvider),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=J.createClient({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,o])=>{const i=e-o.lastRequestedAt,a=e-o.lastEmissionAt;o.activeSubscribers===0&&i>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&a>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${n} for cleanup: activeSubscribers=${o.activeSubscribers}, timeSinceRequested=${Math.round(i/1e3)}s, timeSinceEmission=${Math.round(a/1e3)}s`),s.push(n))}),s.forEach(n=>{const o=this._pushStatusSubjects.get(n);if(o)try{o.subject.complete(),o.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 L.Observable(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=s.subscribe({query:e,variables:t},{next:d(o=>{r.next(o.data)},"next"),error:d(async o=>{const i=o;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(o)},"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 L.Observable(a=>{r.activeSubscribers++;const y=r.subject.subscribe(a);return()=>{const l=this._pushStatusSubjects.get(e);l&&l.activeSubscribers>0&&l.activeSubscribers--,y.unsubscribe()}});const s=u.gql`subscription StatusUpdates($sessionId: String!) {
608
616
  statusUpdates(sessionId: $sessionId) {
609
617
  date
610
618
  message
611
619
  sessionId
612
620
  }
613
621
  }
614
- `,n=new A.Subject,a=this.getOrCreateWSClient(),i=new A.Subscription;return i.add(new A.Observable(o=>{const y=a.subscribe({query:s,variables:{sessionId:e}},{next:d(l=>{const f=this._pushStatusSubjects.get(e);f&&(f.lastEmissionAt=Date.now()),o.next(l.data.statusUpdates.message)},"next"),error:d(async l=>{const f=l;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(g){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",g),o.error(g)}}else o.error(l)},"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 A.Observable(o=>{const y=this._pushStatusSubjects.get(e);y&&y.activeSubscribers++;const l=n.subscribe(o);return()=>{const f=this._pushStatusSubjects.get(e);f&&f.activeSubscribers>0&&f.activeSubscribers--,l.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.UnsubscribeFromCacheInvalidation(),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}ClientToolRequests(e){return this.subscribe(`
622
+ `,n=new L.Subject,o=this.getOrCreateWSClient(),i=new L.Subscription;return i.add(new L.Observable(a=>{const y=o.subscribe({query:s,variables:{sessionId:e}},{next:d(l=>{const f=this._pushStatusSubjects.get(e);f&&(f.lastEmissionAt=Date.now()),a.next(l.data.statusUpdates.message)},"next"),error:d(async l=>{const f=l;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(),a.complete()}catch(g){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",g),a.error(g)}}else a.error(l)},"error"),complete:d(()=>{a.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,y()}}).subscribe({next:d(a=>n.next(a),"next"),error:d(a=>{n.error(a),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 L.Observable(a=>{const y=this._pushStatusSubjects.get(e);y&&y.activeSubscribers++;const l=n.subscribe(a);return()=>{const f=this._pushStatusSubjects.get(e);f&&f.activeSubscribers>0&&f.activeSubscribers--,l.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
623
  subscription ClientToolRequest($sessionID: String!) {
616
624
  ClientToolRequest(sessionID: $sessionID) {
617
625
  AgentRunID
@@ -645,14 +653,14 @@
645
653
  ChildEntityNames
646
654
  ErrorMessage
647
655
  }
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 c.LogError(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function se(m){const e=new h;return c.SetProvider(e),await e.Config(m),await e.preValidateAndRefresh(),R.MJGlobal.Instance.RaiseEvent({event:R.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),await c.StartupManager.Instance.Startup(),e}d(se,"setupGraphQLClient");class ne{static{d(this,"SyncRolesAndUsersResult")}}class ae{static{d(this,"RoleInput")}}class oe{static{d(this,"UserInput")}}class ie{static{d(this,"RolesAndUsersInput")}}var k=(m=>(m.Create="Create",m.Update="Update",m.CreateOrUpdate="CreateOrUpdate",m.Delete="Delete",m.DeleteWithFilter="DeleteWithFilter",m))(k||{});class ce{static{d(this,"ActionItemInput")}}class ue{static{d(this,"SyncDataResult")}constructor(){this.Results=[]}}class le{static{d(this,"ActionItemOutput")}}class de{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 u.GraphQLClient(e,{headers:n})}resolvePlatformSQL(e){if(e!=null)return c.IsPlatformSQL(e)?e.default:e}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
656
+ }`;try{const n=await this.ExecuteGQL(s,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntities?.Success&&n.FindISAChildEntities.ChildEntityNames?n.FindISAChildEntities.ChildEntityNames.map(o=>({ChildEntityName:o})):[]}catch(n){return c.LogError(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function se(m){const e=new h;return c.SetProvider(e),await e.Config(m),await e.preValidateAndRefresh(),R.MJGlobal.Instance.RaiseEvent({event:R.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),await c.StartupManager.Instance.Startup(),e}d(se,"setupGraphQLClient");class ne{static{d(this,"SyncRolesAndUsersResult")}}class oe{static{d(this,"RoleInput")}}class ae{static{d(this,"UserInput")}}class ie{static{d(this,"RolesAndUsersInput")}}var k=(m=>(m.Create="Create",m.Update="Update",m.CreateOrUpdate="CreateOrUpdate",m.Delete="Delete",m.DeleteWithFilter="DeleteWithFilter",m))(k||{});class ce{static{d(this,"ActionItemInput")}}class ue{static{d(this,"SyncDataResult")}constructor(){this.Results=[]}}class le{static{d(this,"ActionItemOutput")}}class de{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 u.GraphQLClient(e,{headers:n})}resolvePlatformSQL(e){if(e!=null)return c.IsPlatformSQL(e)?e.default:e}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
649
657
  GetData(input: $input) {
650
658
  Success
651
659
  ErrorMessages
652
660
  Queries
653
661
  Results
654
662
  }
655
- }`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(n=>n?R.SafeJSONParse(n):null),ErrorMessages:s.GetData.ErrorMessages,Queries:s.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:s.GetData?.ErrorMessages??["Unknown error"],Queries:s.GetData?.Queries??e}}catch(r){let s=r instanceof Error?r.message:String(r);const n=s.match(/Error: ([^:]+)\./);if(n&&(s=n[1]+"."),c.IsVerboseLoggingEnabled()){const a=`GraphQLSystemUserClient::GetData - Error getting data - ${r}`;c.LogError(a)}return{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
663
+ }`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(n=>n?R.SafeJSONParse(n):null),ErrorMessages:s.GetData.ErrorMessages,Queries:s.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:s.GetData?.ErrorMessages??["Unknown error"],Queries:s.GetData?.Queries??e}}catch(r){let s=r instanceof Error?r.message:String(r);const n=s.match(/Error: ([^:]+)\./);if(n&&(s=n[1]+"."),c.IsVerboseLoggingEnabled()){const o=`GraphQLSystemUserClient::GetData - Error getting data - ${r}`;c.LogError(o)}return{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
656
664
  GetAllEntities {
657
665
  Success
658
666
  ErrorMessage
@@ -1038,7 +1046,7 @@
1038
1046
  executionTimeMs
1039
1047
  }
1040
1048
  }
1041
- `,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this.Client.request(t,r);if(!s?.ExecuteSimplePromptSystemUser)return{success:!1,modelName:"Unknown",error:"Failed to execute simple prompt as system user"};const n=s.ExecuteSimplePromptSystemUser;let a;if(n.resultObject)try{a=JSON.parse(n.resultObject)}catch{a=n.resultObject}return{success:n.success,result:n.result,resultObject:a,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){return c.LogError(`GraphQLSystemUserClient::ExecuteSimplePrompt - Error executing simple prompt - ${t}`),{success:!1,modelName:"Unknown",error:t.toString()}}}async EmbedText(e){try{const t=u.gql`
1049
+ `,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this.Client.request(t,r);if(!s?.ExecuteSimplePromptSystemUser)return{success:!1,modelName:"Unknown",error:"Failed to execute simple prompt as system user"};const n=s.ExecuteSimplePromptSystemUser;let o;if(n.resultObject)try{o=JSON.parse(n.resultObject)}catch{o=n.resultObject}return{success:n.success,result:n.result,resultObject:o,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){return c.LogError(`GraphQLSystemUserClient::ExecuteSimplePrompt - Error executing simple prompt - ${t}`),{success:!1,modelName:"Unknown",error:t.toString()}}}async EmbedText(e){try{const t=u.gql`
1042
1050
  query EmbedTextSystemUser(
1043
1051
  $textToEmbed: [String!]!,
1044
1052
  $modelSize: String!
@@ -1053,7 +1061,7 @@
1053
1061
  error
1054
1062
  }
1055
1063
  }
1056
- `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this.Client.request(t,s);if(!n?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const a=n.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?a.embeddings:a.embeddings[0],modelName:a.modelName,vectorDimensions:a.vectorDimensions,error:a.error}}catch(t){return c.LogError(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}async SearchKnowledge(e){try{const t=u.gql`
1064
+ `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this.Client.request(t,s);if(!n?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const o=n.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?o.embeddings:o.embeddings[0],modelName:o.modelName,vectorDimensions:o.vectorDimensions,error:o.error}}catch(t){return c.LogError(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}async SearchKnowledge(e){try{const t=u.gql`
1057
1065
  mutation SearchKnowledgeAsSystemUser($query: String!, $maxResults: Float, $filters: SearchFiltersInput, $minScore: Float) {
1058
1066
  SearchKnowledgeAsSystemUser(query: $query, maxResults: $maxResults, filters: $filters, minScore: $minScore) {
1059
1067
  Success
@@ -1158,7 +1166,7 @@
1158
1166
  ErrorMessage
1159
1167
  }
1160
1168
  }
1161
- `,s={EntityNames:e,UserEmail:t},n=await this.Client.request(r,s);if(n?.CheckEntityPermissionsSystemUser){const a=n.CheckEntityPermissionsSystemUser;return{Success:a.Success,Results:(a.Results||[]).map(i=>({EntityName:i.EntityName,CanRead:i.CanRead})),ErrorMessage:a.ErrorMessage}}return{Success:!1,Results:[],ErrorMessage:"Invalid response from server"}}catch(r){return c.LogError(`GraphQLSystemUserClient::CheckEntityPermissionsSystemUser - Error checking entity permissions - ${r}`),{Success:!1,Results:[],ErrorMessage:r instanceof Error?r.message:String(r)}}}}class ye{static{d(this,"GetDataOutput")}}class ge{static{d(this,"SimpleRemoteEntityOutput")}}class me{static{d(this,"SimpleRemoteEntity")}}class Se{static{d(this,"SimpleRemoteEntityField")}}class pe{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=u.gql`
1169
+ `,s={EntityNames:e,UserEmail:t},n=await this.Client.request(r,s);if(n?.CheckEntityPermissionsSystemUser){const o=n.CheckEntityPermissionsSystemUser;return{Success:o.Success,Results:(o.Results||[]).map(i=>({EntityName:i.EntityName,CanRead:i.CanRead})),ErrorMessage:o.ErrorMessage}}return{Success:!1,Results:[],ErrorMessage:"Invalid response from server"}}catch(r){return c.LogError(`GraphQLSystemUserClient::CheckEntityPermissionsSystemUser - Error checking entity permissions - ${r}`),{Success:!1,Results:[],ErrorMessage:r instanceof Error?r.message:String(r)}}}}class ye{static{d(this,"GetDataOutput")}}class ge{static{d(this,"SimpleRemoteEntityOutput")}}class me{static{d(this,"SimpleRemoteEntity")}}class Se{static{d(this,"SimpleRemoteEntityField")}}class pe{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),o=await this.executeActionMutation(n);return this.processActionResult(o,t)}catch(s){return this.handleActionError(s,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{...t,Value:r}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=u.gql`
1162
1170
  mutation RunAction($input: RunActionInput!) {
1163
1171
  RunAction(input: $input) {
1164
1172
  Success
@@ -1188,28 +1196,28 @@
1188
1196
  ...ApplyResultFields
1189
1197
  }
1190
1198
  }
1191
- ${M}
1199
+ ${b}
1192
1200
  `,r=await this.dataProvider.ExecuteGQL(t,{input:{TargetListId:e.Delta.TargetListId,EntityName:e.Delta.EntityName,ToAdd:e.Delta.ToAdd,ToRemove:e.Delta.ToRemove,Unchanged:e.Delta.Unchanged,AddCount:e.Delta.Counts.Add,RemoveCount:e.Delta.Counts.Remove,UnchangedCount:e.Delta.Counts.Unchanged,SourceTotal:e.Delta.Counts.SourceTotal,TargetTotal:e.Delta.Counts.TargetTotal,DeltaToken:e.Delta.DeltaToken,ConfirmDrops:e.ConfirmDrops}});return T(r?.ApplyListDelta)}async MaterializeFromView(e,t){const r=u.gql`
1193
1201
  mutation MaterializeListFromView($viewId: String!, $options: MaterializeOptionsInput!) {
1194
1202
  MaterializeListFromView(viewId: $viewId, options: $options) {
1195
1203
  ...ApplyResultFields
1196
1204
  }
1197
1205
  }
1198
- ${M}
1206
+ ${b}
1199
1207
  `,s=await this.dataProvider.ExecuteGQL(r,{viewId:e,options:{ListName:t.ListName,CategoryId:t.CategoryId,Description:t.Description,RememberLineage:t.RememberLineage,UseSnapshot:t.UseSnapshot,RefreshMode:t.RefreshMode}});return T(s?.MaterializeListFromView)}async AddViewResultsToList(e,t){const r=u.gql`
1200
1208
  mutation AddViewResultsToList($viewId: String!, $listId: String!) {
1201
1209
  AddViewResultsToList(viewId: $viewId, listId: $listId) {
1202
1210
  ...ApplyResultFields
1203
1211
  }
1204
1212
  }
1205
- ${M}
1213
+ ${b}
1206
1214
  `,s=await this.dataProvider.ExecuteGQL(r,{viewId:e,listId:t});return T(s?.AddViewResultsToList)}async RefreshFromSource(e){const t=u.gql`
1207
1215
  mutation RefreshListFromSource($listId: String!, $mode: String!, $confirmDrops: Boolean!) {
1208
1216
  RefreshListFromSource(listId: $listId, mode: $mode, confirmDrops: $confirmDrops) {
1209
1217
  ...ApplyResultFields
1210
1218
  }
1211
1219
  }
1212
- ${M}
1220
+ ${b}
1213
1221
  `,r=await this.dataProvider.ExecuteGQL(t,{listId:e.ListId,mode:e.Mode,confirmDrops:e.ConfirmDrops});return T(r?.RefreshListFromSource)}async ComposeLists(e){const t=u.gql`
1214
1222
  mutation ComposeLists($input: ComposeListsInput!) {
1215
1223
  ComposeLists(input: $input) {
@@ -1306,7 +1314,7 @@
1306
1314
  }
1307
1315
  DeltaToken
1308
1316
  }
1309
- `,M=u.gql`
1317
+ `,b=u.gql`
1310
1318
  fragment ApplyResultFields on ApplyListResultType {
1311
1319
  Success
1312
1320
  ResultCode
@@ -1357,7 +1365,67 @@
1357
1365
  AnalysisID
1358
1366
  }
1359
1367
  }
1360
- `,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 c.LogError("GraphQLClusterClient.RunClusterAnalysis failed",void 0,r),this.errorResult(r.message||"Unknown error occurred")}}parseResult(e){const t=this.parseMetrics(e),r=R.SafeJSONParse(e.ClustersJSON)??[],s=R.SafeJSONParse(e.PointsJSON)??[];return{Success:e.Success,ErrorMessage:e.ErrorMessage,Metrics:t,Clusters:r,Points:s,AnalysisID:e.AnalysisID}}parseMetrics(e){const t=R.SafeJSONParse(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 ve{static{d(this,"GraphQLClassifyClient")}constructor(e){this._dataProvider=e}async GenerateSeedTaxonomy(e){try{const t=u.gql`
1368
+ `,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 c.LogError("GraphQLClusterClient.RunClusterAnalysis failed",void 0,r),this.errorResult(r.message||"Unknown error occurred")}}parseResult(e){const t=this.parseMetrics(e),r=R.SafeJSONParse(e.ClustersJSON)??[],s=R.SafeJSONParse(e.PointsJSON)??[];return{Success:e.Success,ErrorMessage:e.ErrorMessage,Metrics:t,Clusters:r,Points:s,AnalysisID:e.AnalysisID}}parseMetrics(e){const t=R.SafeJSONParse(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 ve{static{d(this,"GraphQLLiveKitClient")}constructor(e){this._dataProvider=e}async MintClientToken(e){try{const t=u.gql`
1369
+ mutation MintLiveKitClientToken($input: MintLiveKitClientTokenInput!) {
1370
+ MintLiveKitClientToken(input: $input) {
1371
+ Success
1372
+ ErrorMessage
1373
+ ServerUrl
1374
+ Token
1375
+ Identity
1376
+ RoomName
1377
+ }
1378
+ }
1379
+ `,s=(await this._dataProvider.ExecuteGQL(t,{input:e}))?.MintLiveKitClientToken;if(!s)throw new Error("Invalid response from server");return s}catch(t){const r=t;return c.LogError("GraphQLLiveKitClient.MintClientToken failed",void 0,r),{Success:!1,ErrorMessage:r.message||"Unknown error",ServerUrl:"",Token:"",Identity:"",RoomName:e.RoomName}}}async StartAgentRoomSession(e){try{const t=u.gql`
1380
+ mutation StartLiveKitAgentRoomSession($input: StartLiveKitAgentRoomSessionInput!) {
1381
+ StartLiveKitAgentRoomSession(input: $input) {
1382
+ Success
1383
+ ErrorMessage
1384
+ SessionBridgeID
1385
+ RoomName
1386
+ ServerUrl
1387
+ ClientToken
1388
+ Identity
1389
+ }
1390
+ }
1391
+ `,s=(await this._dataProvider.ExecuteGQL(t,{input:e}))?.StartLiveKitAgentRoomSession;if(!s)throw new Error("Invalid response from server");return s}catch(t){const r=t;return c.LogError("GraphQLLiveKitClient.StartAgentRoomSession failed",void 0,r),{Success:!1,ErrorMessage:r.message||"Unknown error",SessionBridgeID:"",RoomName:"",ServerUrl:"",ClientToken:"",Identity:""}}}async StopAgentRoomSession(e){try{const t=u.gql`
1392
+ mutation StopLiveKitAgentRoomSession($sessionBridgeID: String!) {
1393
+ StopLiveKitAgentRoomSession(sessionBridgeID: $sessionBridgeID)
1394
+ }
1395
+ `;return(await this._dataProvider.ExecuteGQL(t,{sessionBridgeID:e}))?.StopLiveKitAgentRoomSession===!0}catch(t){return c.LogError("GraphQLLiveKitClient.StopAgentRoomSession failed",void 0,t),!1}}async InviteUsers(e,t){try{const r=u.gql`
1396
+ mutation InviteUsersToLiveKitRoom($roomName: String!, $userIDs: [String!]!) {
1397
+ InviteUsersToLiveKitRoom(roomName: $roomName, userIDs: $userIDs)
1398
+ }
1399
+ `;return(await this._dataProvider.ExecuteGQL(r,{roomName:e,userIDs:t}))?.InviteUsersToLiveKitRoom===!0}catch(r){return c.LogError("GraphQLLiveKitClient.InviteUsers failed",void 0,r),!1}}async GetRealtimeModelVoices(){try{const e=u.gql`
1400
+ query GetRealtimeModelVoices {
1401
+ GetRealtimeModelVoices {
1402
+ ModelID
1403
+ ModelName
1404
+ Voices {
1405
+ ID
1406
+ Name
1407
+ }
1408
+ }
1409
+ }
1410
+ `;return(await this._dataProvider.ExecuteGQL(e,{}))?.GetRealtimeModelVoices??[]}catch(e){return c.LogError("GraphQLLiveKitClient.GetRealtimeModelVoices failed",void 0,e),[]}}async StartRecording(e,t){return this.runRecordingMutation(u.gql`
1411
+ mutation StartLiveKitRecording($input: LiveKitRecordingInput!) {
1412
+ StartLiveKitRecording(input: $input) {
1413
+ Success
1414
+ ErrorMessage
1415
+ EgressID
1416
+ Status
1417
+ }
1418
+ }
1419
+ `,{input:{RoomName:e,Layout:t}},"StartLiveKitRecording","")}async StopRecording(e){return this.runRecordingMutation(u.gql`
1420
+ mutation StopLiveKitRecording($egressID: String!) {
1421
+ StopLiveKitRecording(egressID: $egressID) {
1422
+ Success
1423
+ ErrorMessage
1424
+ EgressID
1425
+ Status
1426
+ }
1427
+ }
1428
+ `,{egressID:e},"StopLiveKitRecording",e)}async runRecordingMutation(e,t,r,s){try{const o=(await this._dataProvider.ExecuteGQL(e,t))?.[r];if(!o)throw new Error("Invalid response from server");return o}catch(n){const o=n;return c.LogError(`GraphQLLiveKitClient.${r} failed`,void 0,o),{Success:!1,ErrorMessage:o.message||"Unknown error",EgressID:s,Status:""}}}}class Ce{static{d(this,"GraphQLClassifyClient")}constructor(e){this._dataProvider=e}async GenerateSeedTaxonomy(e){try{const t=u.gql`
1361
1429
  mutation GenerateSeedTaxonomy($sourceID: String!, $sampleSize: Int!) {
1362
1430
  GenerateSeedTaxonomy(sourceID: $sourceID, sampleSize: $sampleSize) {
1363
1431
  Success
@@ -1367,7 +1435,7 @@
1367
1435
  NodesJSON
1368
1436
  }
1369
1437
  }
1370
- `,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 c.LogError("GraphQLClassifyClient.GenerateSeedTaxonomy failed",void 0,r),this.errorResult(r.message||"Unknown error occurred")}}parseResult(e){const t=R.SafeJSONParse(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 Ce{static{d(this,"GraphQLTestingClient")}constructor(e){this._dataProvider=e}async RunTest(e){try{const t=this.buildRunTestMutation(),r=this.buildRunTestVariables(e),s={};return await $.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 $.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=u.gql`
1438
+ `,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 c.LogError("GraphQLClassifyClient.GenerateSeedTaxonomy failed",void 0,r),this.errorResult(r.message||"Unknown error occurred")}}parseResult(e){const t=R.SafeJSONParse(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 we{static{d(this,"GraphQLTestingClient")}constructor(e){this._dataProvider=e}async RunTest(e){try{const t=this.buildRunTestMutation(),r=this.buildRunTestVariables(e),s={};return await $.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 $.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=u.gql`
1371
1439
  query IsTestRunning($testId: String!) {
1372
1440
  IsTestRunning(testId: $testId)
1373
1441
  }
@@ -1425,7 +1493,7 @@
1425
1493
  result
1426
1494
  }
1427
1495
  }
1428
- `}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?R.SafeJSONParse(t.result):null}}extractSuiteResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?R.SafeJSONParse(t.result):null}}forwardTestProgress(e,t){if(e.resolver==="RunTestResolver"&&e.type==="TestExecutionProgress"&&e.status==="ok"){const s=e.data?.progress;s&&t(s)}}handleError(e,t){const r=e.message;return c.LogError(`${t} failed: ${r}`),{success:!1,errorMessage:r.includes("Failed to fetch")||r.includes("NetworkError")?"Lost connection to the server. The test may still be running. Please refresh to check the latest status.":r,result:null}}}class we{static{d(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=u.gql`
1496
+ `}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?R.SafeJSONParse(t.result):null}}extractSuiteResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?R.SafeJSONParse(t.result):null}}forwardTestProgress(e,t){if(e.resolver==="RunTestResolver"&&e.type==="TestExecutionProgress"&&e.status==="ok"){const s=e.data?.progress;s&&t(s)}}handleError(e,t){const r=e.message;return c.LogError(`${t} failed: ${r}`),{success:!1,errorMessage:r.includes("Failed to fetch")||r.includes("NetworkError")?"Lost connection to the server. The test may still be running. Please refresh to check the latest status.":r,result:null}}}class $e{static{d(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=u.gql`
1429
1497
  query GetRegistryComponent(
1430
1498
  $registryName: String!,
1431
1499
  $namespace: String!,
@@ -1446,7 +1514,7 @@
1446
1514
  specification
1447
1515
  }
1448
1516
  }
1449
- `,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const n=s.GetRegistryComponent;if(n.notModified&&!n.specification)return null;if(n.specification){if(typeof n.specification=="object")return n.specification;try{return JSON.parse(n.specification)}catch(a){return c.LogError(`Failed to parse component specification: ${a}`),null}}return null}return null}catch(t){throw c.LogError(t),new Error(`Failed to get registry component: ${t instanceof Error?t.message:"Unknown error"}`)}}async GetRegistryComponentWithHash(e){try{const t=u.gql`
1517
+ `,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const n=s.GetRegistryComponent;if(n.notModified&&!n.specification)return null;if(n.specification){if(typeof n.specification=="object")return n.specification;try{return JSON.parse(n.specification)}catch(o){return c.LogError(`Failed to parse component specification: ${o}`),null}}return null}return null}catch(t){throw c.LogError(t),new Error(`Failed to get registry component: ${t instanceof Error?t.message:"Unknown error"}`)}}async GetRegistryComponentWithHash(e){try{const t=u.gql`
1450
1518
  query GetRegistryComponent(
1451
1519
  $registryName: String!,
1452
1520
  $namespace: String!,
@@ -1467,7 +1535,7 @@
1467
1535
  specification
1468
1536
  }
1469
1537
  }
1470
- `,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const n=s.GetRegistryComponent;let a;if(n.specification)try{a=JSON.parse(n.specification)}catch(i){c.LogError(`Failed to parse component specification in GetRegistryComponentWithHash: ${i}`),a=void 0}return{specification:a,hash:n.hash,notModified:n.notModified,message:n.message}}return{specification:void 0,hash:"",notModified:!1,message:"Component not found"}}catch(t){throw c.LogError(t),new Error(`Failed to get registry component with hash: ${t instanceof Error?t.message:"Unknown error"}`)}}async SearchRegistryComponents(e){try{const t=u.gql`
1538
+ `,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const n=s.GetRegistryComponent;let o;if(n.specification)try{o=JSON.parse(n.specification)}catch(i){c.LogError(`Failed to parse component specification in GetRegistryComponentWithHash: ${i}`),o=void 0}return{specification:o,hash:n.hash,notModified:n.notModified,message:n.message}}return{specification:void 0,hash:"",notModified:!1,message:"Component not found"}}catch(t){throw c.LogError(t),new Error(`Failed to get registry component with hash: ${t instanceof Error?t.message:"Unknown error"}`)}}async SearchRegistryComponents(e){try{const t=u.gql`
1471
1539
  query SearchRegistryComponents($params: SearchRegistryComponentsInput!) {
1472
1540
  SearchRegistryComponents(params: $params) {
1473
1541
  components
@@ -1509,7 +1577,7 @@
1509
1577
  error
1510
1578
  }
1511
1579
  }
1512
- `,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return c.LogError(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}}class $e{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=u.gql`
1580
+ `,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return c.LogError(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}}class Pe{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(o=>{try{const i=JSON.parse(o);i.resolver==="VersionHistoryResolver"&&i.type==="CreateLabelProgress"&&i.status==="ok"&&i.data&&e.OnProgress(i.data)}catch{}}));const r=u.gql`
1513
1581
  mutation CreateVersionLabel($input: CreateVersionLabelInput!, $sessionId: String) {
1514
1582
  CreateVersionLabel(input: $input, sessionId: $sessionId) {
1515
1583
  Success
@@ -1525,7 +1593,7 @@
1525
1593
  }
1526
1594
  }
1527
1595
  }
1528
- `,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 c.LogError(`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 Pe{static{d(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const s=u.gql`
1596
+ `,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 c.LogError(`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 Le{static{d(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const s=u.gql`
1529
1597
  query ListStorageObjects($input: ListStorageObjectsInput!) {
1530
1598
  ListStorageObjects(input: $input) {
1531
1599
  objects {
@@ -1542,18 +1610,18 @@
1542
1610
  prefixes
1543
1611
  }
1544
1612
  }
1545
- `,n={input:{AccountID:e,Prefix:t,Delimiter:r||"/"}},a=await this._dataProvider.ExecuteGQL(s,n);if(!a?.ListStorageObjects)throw new Error("Invalid response from server");return{objects:a.ListStorageObjects.objects.map(i=>({...i,lastModified:new Date(i.lastModified)})),prefixes:a.ListStorageObjects.prefixes}}catch(s){const n=s;throw c.LogError(`Error listing storage objects: ${n}`),n}}async DirectoryExists(e,t){try{const r=await this.ListObjects(e,t.endsWith("/")?t:`${t}/`,"/");return r.objects.length>0||r.prefixes.length>0}catch(r){const s=r;return c.LogError(`Error checking directory existence: ${s}`),!1}}async CreateDirectory(e,t){try{const r=u.gql`
1613
+ `,n={input:{AccountID:e,Prefix:t,Delimiter:r||"/"}},o=await this._dataProvider.ExecuteGQL(s,n);if(!o?.ListStorageObjects)throw new Error("Invalid response from server");return{objects:o.ListStorageObjects.objects.map(i=>({...i,lastModified:new Date(i.lastModified)})),prefixes:o.ListStorageObjects.prefixes}}catch(s){const n=s;throw c.LogError(`Error listing storage objects: ${n}`),n}}async DirectoryExists(e,t){try{const r=await this.ListObjects(e,t.endsWith("/")?t:`${t}/`,"/");return r.objects.length>0||r.prefixes.length>0}catch(r){const s=r;return c.LogError(`Error checking directory existence: ${s}`),!1}}async CreateDirectory(e,t){try{const r=u.gql`
1546
1614
  mutation CreateDirectory($input: CreateDirectoryInput!) {
1547
1615
  CreateDirectory(input: $input)
1548
1616
  }
1549
- `,s={input:{AccountID:e,Path:t}};return(await this._dataProvider.ExecuteGQL(r,s))?.CreateDirectory??!1}catch(r){const s=r;return c.LogError(`Error creating directory: ${s}`),!1}}async ObjectExists(e,t){try{const r=t.substring(0,t.lastIndexOf("/")+1),s=t.substring(t.lastIndexOf("/")+1);return(await this.ListObjects(e,r,"/")).objects.some(a=>a.name===s||a.fullPath===t)}catch(r){const s=r;return c.LogError(`Error checking object existence: ${s}`),!1}}async CreatePreAuthUploadUrl(e,t,r){try{const s=u.gql`
1617
+ `,s={input:{AccountID:e,Path:t}};return(await this._dataProvider.ExecuteGQL(r,s))?.CreateDirectory??!1}catch(r){const s=r;return c.LogError(`Error creating directory: ${s}`),!1}}async ObjectExists(e,t){try{const r=t.substring(0,t.lastIndexOf("/")+1),s=t.substring(t.lastIndexOf("/")+1);return(await this.ListObjects(e,r,"/")).objects.some(o=>o.name===s||o.fullPath===t)}catch(r){const s=r;return c.LogError(`Error checking object existence: ${s}`),!1}}async CreatePreAuthUploadUrl(e,t,r){try{const s=u.gql`
1550
1618
  mutation CreatePreAuthUploadUrl($input: CreatePreAuthUploadUrlInput!) {
1551
1619
  CreatePreAuthUploadUrl(input: $input) {
1552
1620
  UploadUrl
1553
1621
  ProviderKey
1554
1622
  }
1555
1623
  }
1556
- `,n={input:{AccountID:e,ObjectName:t,ContentType:r}},a=await this._dataProvider.ExecuteGQL(s,n);if(!a?.CreatePreAuthUploadUrl)throw new Error("Invalid response from server");return{uploadUrl:a.CreatePreAuthUploadUrl.UploadUrl,providerKey:a.CreatePreAuthUploadUrl.ProviderKey}}catch(s){const n=s;throw c.LogError(`Error creating pre-auth upload URL: ${n}`),n}}async CreatePreAuthDownloadUrl(e,t){try{const r=u.gql`
1624
+ `,n={input:{AccountID:e,ObjectName:t,ContentType:r}},o=await this._dataProvider.ExecuteGQL(s,n);if(!o?.CreatePreAuthUploadUrl)throw new Error("Invalid response from server");return{uploadUrl:o.CreatePreAuthUploadUrl.UploadUrl,providerKey:o.CreatePreAuthUploadUrl.ProviderKey}}catch(s){const n=s;throw c.LogError(`Error creating pre-auth upload URL: ${n}`),n}}async CreatePreAuthDownloadUrl(e,t){try{const r=u.gql`
1557
1625
  query CreatePreAuthDownloadUrl($input: CreatePreAuthDownloadUrlInput!) {
1558
1626
  CreatePreAuthDownloadUrl(input: $input)
1559
1627
  }
@@ -1581,7 +1649,7 @@
1581
1649
  destinationPath
1582
1650
  }
1583
1651
  }
1584
- `,a={input:{SourceAccountID:e,DestinationAccountID:t,SourcePath:r,DestinationPath:s}},i=await this._dataProvider.ExecuteGQL(n,a);if(!i?.CopyObjectBetweenAccounts)throw new Error("Invalid response from server");return{success:i.CopyObjectBetweenAccounts.success,message:i.CopyObjectBetweenAccounts.message,bytesTransferred:i.CopyObjectBetweenAccounts.bytesTransferred,sourceAccount:i.CopyObjectBetweenAccounts.sourceAccount,destinationAccount:i.CopyObjectBetweenAccounts.destinationAccount,sourcePath:i.CopyObjectBetweenAccounts.sourcePath,destinationPath:i.CopyObjectBetweenAccounts.destinationPath}}catch(n){const a=n;return c.LogError(`Error copying object between accounts: ${a}`),{success:!1,message:a.message,sourceAccount:"",destinationAccount:"",sourcePath:r,destinationPath:s}}}async SearchFiles(e,t,r){try{const s=u.gql`
1652
+ `,o={input:{SourceAccountID:e,DestinationAccountID:t,SourcePath:r,DestinationPath:s}},i=await this._dataProvider.ExecuteGQL(n,o);if(!i?.CopyObjectBetweenAccounts)throw new Error("Invalid response from server");return{success:i.CopyObjectBetweenAccounts.success,message:i.CopyObjectBetweenAccounts.message,bytesTransferred:i.CopyObjectBetweenAccounts.bytesTransferred,sourceAccount:i.CopyObjectBetweenAccounts.sourceAccount,destinationAccount:i.CopyObjectBetweenAccounts.destinationAccount,sourcePath:i.CopyObjectBetweenAccounts.sourcePath,destinationPath:i.CopyObjectBetweenAccounts.destinationPath}}catch(n){const o=n;return c.LogError(`Error copying object between accounts: ${o}`),{success:!1,message:o.message,sourceAccount:"",destinationAccount:"",sourcePath:r,destinationPath:s}}}async SearchFiles(e,t,r){try{const s=u.gql`
1585
1653
  query SearchAcrossAccounts($input: SearchAcrossAccountsInput!) {
1586
1654
  SearchAcrossAccounts(input: $input) {
1587
1655
  accountResults {
@@ -1609,7 +1677,7 @@
1609
1677
  failedAccounts
1610
1678
  }
1611
1679
  }
1612
- `,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){const n=s;return c.LogError(`Error searching across accounts: ${n}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}class Ae{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 u.gql`
1680
+ `,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:r?.maxResultsPerAccount,FileTypes:r?.fileTypes,SearchContent:r?.searchContent}},o=await this._dataProvider.ExecuteGQL(s,n);if(!o?.SearchAcrossAccounts)throw new Error("Invalid response from server");const i=o.SearchAcrossAccounts;return{accountResults:i.accountResults.map(a=>({accountId:a.accountID,accountName:a.accountName,success:a.success,errorMessage:a.errorMessage,results:a.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:a.totalMatches,hasMore:a.hasMore,nextPageToken:a.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(s){const n=s;return c.LogError(`Error searching across accounts: ${n}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}class Ae{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 u.gql`
1613
1681
  mutation SearchKnowledge($query: String!, $maxResults: Float, $filters: SearchFiltersInput, $minScore: Float, $scopeIDs: [ID!], $searchContext: SearchContextInput) {
1614
1682
  SearchKnowledge(query: $query, maxResults: $maxResults, filters: $filters, minScore: $minScore, scopeIDs: $scopeIDs, searchContext: $searchContext) {
1615
1683
  Success
@@ -1715,7 +1783,7 @@
1715
1783
  IsPersonal
1716
1784
  }
1717
1785
  }
1718
- `;return((await this._dataProvider.ExecuteGQL(e,{}))?.SearchScopes??[]).map(s=>({ID:s.ID,Name:s.Name,Description:s.Description??void 0,Icon:s.Icon??void 0,IsGlobal:!!s.IsGlobal,IsDefault:!!s.IsDefault,IsPersonal:!!s.IsPersonal}))}catch(e){return c.LogError(`GraphQLSearchClient.GetSearchScopes failed: ${e instanceof Error?e.message:String(e)}`),[]}}StreamSearch(e){return new A.Observable(t=>{const r=u.gql`
1786
+ `;return((await this._dataProvider.ExecuteGQL(e,{}))?.SearchScopes??[]).map(s=>({ID:s.ID,Name:s.Name,Description:s.Description??void 0,Icon:s.Icon??void 0,IsGlobal:!!s.IsGlobal,IsDefault:!!s.IsDefault,IsPersonal:!!s.IsPersonal}))}catch(e){return c.LogError(`GraphQLSearchClient.GetSearchScopes failed: ${e instanceof Error?e.message:String(e)}`),[]}}StreamSearch(e){return new L.Observable(t=>{const r=u.gql`
1719
1787
  mutation StreamScopedSearch(
1720
1788
  $query: String!,
1721
1789
  $maxResults: Float,
@@ -1736,7 +1804,7 @@
1736
1804
  StreamID
1737
1805
  ErrorMessage
1738
1806
  }
1739
- }`,s=this.prepareSearchVariables(e);let n=null;return(async()=>{try{const i=(await this._dataProvider.ExecuteGQL(r,s))?.StreamScopedSearch;if(!i?.Success){t.error(new Error(i?.ErrorMessage??"StreamScopedSearch failed to start"));return}const o=u.gql`
1807
+ }`,s=this.prepareSearchVariables(e);let n=null;return(async()=>{try{const i=(await this._dataProvider.ExecuteGQL(r,s))?.StreamScopedSearch;if(!i?.Success){t.error(new Error(i?.ErrorMessage??"StreamScopedSearch failed to start"));return}const a=u.gql`
1740
1808
  subscription SearchStream($streamID: ID!) {
1741
1809
  SearchStreamEvents(streamID: $streamID) {
1742
1810
  StreamID
@@ -1748,7 +1816,7 @@
1748
1816
  ElapsedMs
1749
1817
  ErrorMessage
1750
1818
  }
1751
- }`;n=this._dataProvider.subscribe(o,{streamID:i.StreamID}).subscribe({next:d(y=>{const l=y?.SearchStreamEvents;l&&(t.next(l),l.Phase==="final"?(t.complete(),n?.unsubscribe()):l.Phase==="error"&&(t.error(new Error(l.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 c.LogError(`Error executing search: ${t}`),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,SourceCounts:{Vector:0,FullText:0,Entity:0,Storage:0},Providers:[],ErrorMessage:`Error: ${t.message}`}}}class Ne{static{d(this,"GraphQLIntegrationClient")}constructor(e){this._dataProvider=e}async DiscoverObjects(e){try{const t=u.gql`
1819
+ }`;n=this._dataProvider.subscribe(a,{streamID:i.StreamID}).subscribe({next:d(y=>{const l=y?.SearchStreamEvents;l&&(t.next(l),l.Phase==="final"?(t.complete(),n?.unsubscribe()):l.Phase==="error"&&(t.error(new Error(l.ErrorMessage??"Stream error")),n?.unsubscribe()))},"next"),error:d(y=>t.error(y),"error")})}catch(o){t.error(o)}})(),()=>{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 c.LogError(`Error executing search: ${t}`),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,SourceCounts:{Vector:0,FullText:0,Entity:0,Storage:0},Providers:[],ErrorMessage:`Error: ${t.message}`}}}class Ne{static{d(this,"GraphQLIntegrationClient")}constructor(e){this._dataProvider=e}async DiscoverObjects(e){try{const t=u.gql`
1752
1820
  query IntegrationDiscoverObjects($companyIntegrationID: String!) {
1753
1821
  IntegrationDiscoverObjects(companyIntegrationID: $companyIntegrationID) {
1754
1822
  Success
@@ -1805,7 +1873,7 @@
1805
1873
  Warnings
1806
1874
  }
1807
1875
  }
1808
- `,a=(await this._dataProvider.ExecuteGQL(s,{companyIntegrationID:e,objects:t,platform:r}))?.IntegrationSchemaPreview;if(!a)throw new Error("Invalid response from server");return{Success:a.Success,Message:a.Message,Files:a.Files??[],Warnings:a.Warnings??[]}}catch(s){const n=s;return c.LogError(`Error generating schema preview: ${n}`),{Success:!1,Message:`Error: ${n.message}`,Files:[],Warnings:[]}}}async PreviewData(e,t,r=5){try{const s=u.gql`
1876
+ `,o=(await this._dataProvider.ExecuteGQL(s,{companyIntegrationID:e,objects:t,platform:r}))?.IntegrationSchemaPreview;if(!o)throw new Error("Invalid response from server");return{Success:o.Success,Message:o.Message,Files:o.Files??[],Warnings:o.Warnings??[]}}catch(s){const n=s;return c.LogError(`Error generating schema preview: ${n}`),{Success:!1,Message:`Error: ${n.message}`,Files:[],Warnings:[]}}}async PreviewData(e,t,r=5){try{const s=u.gql`
1809
1877
  query IntegrationPreviewData(
1810
1878
  $companyIntegrationID: String!,
1811
1879
  $objectName: String!,
@@ -1823,7 +1891,7 @@
1823
1891
  }
1824
1892
  }
1825
1893
  }
1826
- `,a=(await this._dataProvider.ExecuteGQL(s,{companyIntegrationID:e,objectName:t,limit:r}))?.IntegrationPreviewData;if(!a)throw new Error("Invalid response from server");return{Success:a.Success,Message:a.Message,Records:a.Records??[]}}catch(s){const n=s;return c.LogError(`Error previewing integration data: ${n}`),{Success:!1,Message:`Error: ${n.message}`,Records:[]}}}async GetDefaultConfig(e){try{const t=u.gql`
1894
+ `,o=(await this._dataProvider.ExecuteGQL(s,{companyIntegrationID:e,objectName:t,limit:r}))?.IntegrationPreviewData;if(!o)throw new Error("Invalid response from server");return{Success:o.Success,Message:o.Message,Records:o.Records??[]}}catch(s){const n=s;return c.LogError(`Error previewing integration data: ${n}`),{Success:!1,Message:`Error: ${n.message}`,Records:[]}}}async GetDefaultConfig(e){try{const t=u.gql`
1827
1895
  query IntegrationGetDefaultConfig($companyIntegrationID: String!) {
1828
1896
  IntegrationGetDefaultConfig(companyIntegrationID: $companyIntegrationID) {
1829
1897
  Success
@@ -1860,13 +1928,13 @@
1860
1928
  IntegrationUpdateEntityMaps(updates: $updates) { Success Message }
1861
1929
  }`;return(await this._dataProvider.ExecuteGQL(t,{updates:e}))?.IntegrationUpdateEntityMaps??{Success:!1,Message:"No response"}}catch(t){return{Success:!1,Message:t.message}}}async DeleteEntityMaps(e){try{const t=u.gql`mutation IntegrationDeleteEntityMaps($entityMapIDs: [String!]!) {
1862
1930
  IntegrationDeleteEntityMaps(entityMapIDs: $entityMapIDs) { Success Message }
1863
- }`;return(await this._dataProvider.ExecuteGQL(t,{entityMapIDs:e}))?.IntegrationDeleteEntityMaps??{Success:!1,Message:"No response"}}catch(t){return{Success:!1,Message:t.message}}}async ApplySchema(e,t,r="sqlserver",s=!1,n=!1){try{const a=u.gql`mutation IntegrationApplySchema(
1931
+ }`;return(await this._dataProvider.ExecuteGQL(t,{entityMapIDs:e}))?.IntegrationDeleteEntityMaps??{Success:!1,Message:"No response"}}catch(t){return{Success:!1,Message:t.message}}}async ApplySchema(e,t,r="sqlserver",s=!1,n=!1){try{const o=u.gql`mutation IntegrationApplySchema(
1864
1932
  $companyIntegrationID: String!, $objects: [SchemaPreviewObjectInput!]!, $platform: String!, $skipGitCommit: Boolean!, $skipRestart: Boolean!
1865
1933
  ) {
1866
1934
  IntegrationApplySchema(companyIntegrationID: $companyIntegrationID, objects: $objects, platform: $platform, skipGitCommit: $skipGitCommit, skipRestart: $skipRestart) {
1867
1935
  Success Message Steps { Name Status DurationMs Message } MigrationFilePath APIRestarted GitCommitSuccess
1868
1936
  }
1869
- }`;return(await this._dataProvider.ExecuteGQL(a,{companyIntegrationID:e,objects:t,platform:r,skipGitCommit:s,skipRestart:n}))?.IntegrationApplySchema??{Success:!1,Message:"No response"}}catch(a){return{Success:!1,Message:a.message}}}async ApplySchemaBatch(e,t="sqlserver",r=!1,s=!1){try{const n=u.gql`mutation IntegrationApplySchemaBatch(
1937
+ }`;return(await this._dataProvider.ExecuteGQL(o,{companyIntegrationID:e,objects:t,platform:r,skipGitCommit:s,skipRestart:n}))?.IntegrationApplySchema??{Success:!1,Message:"No response"}}catch(o){return{Success:!1,Message:o.message}}}async ApplySchemaBatch(e,t="sqlserver",r=!1,s=!1){try{const n=u.gql`mutation IntegrationApplySchemaBatch(
1870
1938
  $items: [ApplySchemaBatchItemInput!]!, $platform: String!, $skipGitCommit: Boolean!, $skipRestart: Boolean!
1871
1939
  ) {
1872
1940
  IntegrationApplySchemaBatch(items: $items, platform: $platform, skipGitCommit: $skipGitCommit, skipRestart: $skipRestart) {
@@ -1892,14 +1960,14 @@
1892
1960
  }
1893
1961
  }
1894
1962
  }
1895
- `,s=(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationListSourceObjects;if(!s)throw new Error("Invalid response from server");return{Success:s.Success,Message:s.Message,Data:s.Objects??[]}}catch(t){return this.handleError(t,[])}}async ApplyAllBatch(e,t=!0,r=!1,s="created",n="sqlserver",a=!1,i=!1){try{const o=u.gql`mutation($input: ApplyAllBatchInput!, $platform: String!, $skipGitCommit: Boolean!, $skipRestart: Boolean!) {
1963
+ `,s=(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationListSourceObjects;if(!s)throw new Error("Invalid response from server");return{Success:s.Success,Message:s.Message,Data:s.Objects??[]}}catch(t){return this.handleError(t,[])}}async ApplyAllBatch(e,t=!0,r=!1,s="created",n="sqlserver",o=!1,i=!1){try{const a=u.gql`mutation($input: ApplyAllBatchInput!, $platform: String!, $skipGitCommit: Boolean!, $skipRestart: Boolean!) {
1896
1964
  IntegrationApplyAllBatch(input: $input, platform: $platform, skipGitCommit: $skipGitCommit, skipRestart: $skipRestart) {
1897
1965
  Success Message SuccessCount FailureCount
1898
1966
  ConnectorResults { CompanyIntegrationID IntegrationName Success Message EntityMapsCreated { SourceObjectName EntityName EntityMapID FieldMapCount } SyncRunID Warnings }
1899
1967
  PipelineSteps { Name Status DurationMs Message }
1900
1968
  GitCommitSuccess APIRestarted
1901
1969
  }
1902
- }`,y={Connectors:e.map(f=>({CompanyIntegrationID:f.CompanyIntegrationID,SourceObjects:f.SourceObjects.map(I=>({SourceObjectID:I.SourceObjectID??null,SourceObjectName:I.SourceObjectName??null,Fields:I.Fields??null}))})),StartSync:t,FullSync:r,SyncScope:s},l=(await this._dataProvider.ExecuteGQL(o,{input:y,platform:n,skipGitCommit:a,skipRestart:i}))?.IntegrationApplyAllBatch;return l?{Success:l.Success,Message:l.Message,Steps:l.PipelineSteps,GitCommitSuccess:l.GitCommitSuccess,APIRestarted:l.APIRestarted,EntityMapsCreated:l.ConnectorResults?.[0]?.EntityMapsCreated,SyncRunID:l.ConnectorResults?.[0]?.SyncRunID,Warnings:l.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=u.gql`mutation IntegrationApplyAll(
1970
+ }`,y={Connectors:e.map(f=>({CompanyIntegrationID:f.CompanyIntegrationID,SourceObjects:f.SourceObjects.map(I=>({SourceObjectID:I.SourceObjectID??null,SourceObjectName:I.SourceObjectName??null,Fields:I.Fields??null}))})),StartSync:t,FullSync:r,SyncScope:s},l=(await this._dataProvider.ExecuteGQL(a,{input:y,platform:n,skipGitCommit:o,skipRestart:i}))?.IntegrationApplyAllBatch;return l?{Success:l.Success,Message:l.Message,Steps:l.PipelineSteps,GitCommitSuccess:l.GitCommitSuccess,APIRestarted:l.APIRestarted,EntityMapsCreated:l.ConnectorResults?.[0]?.EntityMapsCreated,SyncRunID:l.ConnectorResults?.[0]?.SyncRunID,Warnings:l.ConnectorResults?.flatMap(f=>f.Warnings??[])}:{Success:!1,Message:"No response"}}catch(a){return{Success:!1,Message:a.message}}}async ApplyAll(e,t,r="sqlserver",s=!1,n=!1){try{const o=u.gql`mutation IntegrationApplyAll(
1903
1971
  $input: ApplyAllInput!, $platform: String!, $skipGitCommit: Boolean!, $skipRestart: Boolean!
1904
1972
  ) {
1905
1973
  IntegrationApplyAll(input: $input, platform: $platform, skipGitCommit: $skipGitCommit, skipRestart: $skipRestart) {
@@ -1908,7 +1976,7 @@
1908
1976
  EntityMapsCreated { SourceObjectName EntityName EntityMapID FieldMapCount }
1909
1977
  SyncRunID GitCommitSuccess APIRestarted Warnings
1910
1978
  }
1911
- }`,i={CompanyIntegrationID:e,SourceObjectNames:t};return(await this._dataProvider.ExecuteGQL(a,{input:i,platform:r,skipGitCommit:s,skipRestart:n}))?.IntegrationApplyAll??{Success:!1,Message:"No response"}}catch(a){return{Success:!1,Message:a.message}}}async StartSync(e,t,r,s){try{const n=u.gql`mutation IntegrationStartSync(
1979
+ }`,i={CompanyIntegrationID:e,SourceObjectNames:t};return(await this._dataProvider.ExecuteGQL(o,{input:i,platform:r,skipGitCommit:s,skipRestart:n}))?.IntegrationApplyAll??{Success:!1,Message:"No response"}}catch(o){return{Success:!1,Message:o.message}}}async StartSync(e,t,r,s){try{const n=u.gql`mutation IntegrationStartSync(
1912
1980
  $companyIntegrationID: String!,
1913
1981
  $webhookURL: String,
1914
1982
  $fullSync: Boolean,
@@ -1941,5 +2009,5 @@
1941
2009
  IntegrationGetConnectorCapabilities(companyIntegrationID: $companyIntegrationID) {
1942
2010
  Success Message SupportsGet SupportsCreate SupportsUpdate SupportsDelete SupportsSearch
1943
2011
  }
1944
- }`;return(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationGetConnectorCapabilities??{Success:!1,Message:"No response"}}catch(t){return{Success:!1,Message:t.message}}}handleError(e,t){const r=e;return c.LogError(`Error in integration discovery: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Data:t}}}Object.defineProperty(exports,"gql",{enumerable:!0,get:d(function(){return u.gql},"get")}),exports.ActionItemInput=ce,exports.ActionItemOutput=le,exports.BrowserIndexedDBStorageProvider=O,exports.BrowserStorageProviderBase=V,exports.FieldMapper=P,exports.FireAndForgetHelper=$,exports.GetDataOutput=ye,exports.GraphQLAIClient=U,exports.GraphQLActionClient=pe,exports.GraphQLClassifyClient=ve,exports.GraphQLClusterClient=De,exports.GraphQLComponentRegistryClient=we,exports.GraphQLDataProvider=h,exports.GraphQLEncryptionClient=Re,exports.GraphQLFileStorageClient=Pe,exports.GraphQLIntegrationClient=Ne,exports.GraphQLListsClient=he,exports.GraphQLProviderConfigData=re,exports.GraphQLSearchClient=Ae,exports.GraphQLSystemUserClient=de,exports.GraphQLTestingClient=Ce,exports.GraphQLTransactionGroup=q,exports.GraphQLVersionHistoryClient=$e,exports.PACKAGE_VERSION=L,exports.RoleInput=ae,exports.RolesAndUsersInput=ie,exports.SimpleRemoteEntity=me,exports.SimpleRemoteEntityField=Se,exports.SimpleRemoteEntityOutput=ge,exports.SyncDataAction=k,exports.SyncDataResult=ue,exports.SyncRolesAndUsersResult=ne,exports.UserInput=oe,exports.setupGraphQLClient=se;
2012
+ }`;return(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationGetConnectorCapabilities??{Success:!1,Message:"No response"}}catch(t){return{Success:!1,Message:t.message}}}handleError(e,t){const r=e;return c.LogError(`Error in integration discovery: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Data:t}}}Object.defineProperty(exports,"gql",{enumerable:!0,get:d(function(){return u.gql},"get")}),exports.ActionItemInput=ce,exports.ActionItemOutput=le,exports.BrowserIndexedDBStorageProvider=O,exports.BrowserStorageProviderBase=V,exports.FieldMapper=P,exports.FireAndForgetHelper=$,exports.GetDataOutput=ye,exports.GraphQLAIClient=U,exports.GraphQLActionClient=pe,exports.GraphQLClassifyClient=Ce,exports.GraphQLClusterClient=De,exports.GraphQLComponentRegistryClient=$e,exports.GraphQLDataProvider=h,exports.GraphQLEncryptionClient=Re,exports.GraphQLFileStorageClient=Le,exports.GraphQLIntegrationClient=Ne,exports.GraphQLListsClient=he,exports.GraphQLLiveKitClient=ve,exports.GraphQLProviderConfigData=re,exports.GraphQLSearchClient=Ae,exports.GraphQLSystemUserClient=de,exports.GraphQLTestingClient=we,exports.GraphQLTransactionGroup=q,exports.GraphQLVersionHistoryClient=Pe,exports.PACKAGE_VERSION=M,exports.RoleInput=oe,exports.RolesAndUsersInput=ie,exports.SimpleRemoteEntity=me,exports.SimpleRemoteEntityField=Se,exports.SimpleRemoteEntityOutput=ge,exports.SyncDataAction=k,exports.SyncDataResult=ue,exports.SyncRolesAndUsersResult=ne,exports.UserInput=ae,exports.setupGraphQLClient=se;
1945
2013
  //# sourceMappingURL=index.cjs.map