@memberjunction/graphql-dataprovider 5.43.0 → 5.45.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0});import{gql as c,GraphQLClient as k}from"graphql-request";import{gql as ht}from"graphql-request";import{TransactionGroupBase as ne,TransactionResult as ae,LogError as u,LogStatus as M,LogErrorEx as P,ProviderBase as oe,UserInfo as q,getGraphQLTypeNameBase as T,ProviderType as ie,BaseEntityResult as G,EntityFieldTSType as N,TransactionItem as K,CompositeKey as ce,UserRoleInfo as ue,InMemoryLocalStorageProvider as le,BaseEntity as de,ProviderConfigDataBase as ye,SetProvider as me,StartupManager as ge,IsPlatformSQL as Se,IsVerboseLoggingEnabled as pe}from"@memberjunction/core";import{SafeJSONParse as D,CleanAndParseJSON as he,GetGlobalObjectStore as B,MJGlobal as j,MJEventType as J}from"@memberjunction/global";import{ViewInfo as W}from"@memberjunction/core-entities";import{BehaviorSubject as Ie,Observable as x,Subject as fe,Subscription as Re}from"rxjs";import{createClient as Ee}from"graphql-ws";import{v4 as De}from"uuid";import{openDB as ve}from"@tempfix/idb";class A{static{l(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(A.DB_PREFIX)?A.GQL_PREFIX+e.substring(A.DB_PREFIX.length):e}ReverseMapFieldName(e){return e.startsWith(A.GQL_PREFIX)?A.DB_PREFIX+e.substring(A.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 z extends ne{static{l(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=c`
1
+ var se=Object.defineProperty;var d=(g,e)=>se(g,"name",{value:e,configurable:!0});import{gql as c,GraphQLClient as k}from"graphql-request";import{gql as ht}from"graphql-request";import{TransactionGroupBase as ne,TransactionResult as ae,LogError as l,LogStatus as A,LogErrorEx as P,ProviderBase as oe,UserInfo as q,getGraphQLTypeNameBase as T,ProviderType as ie,BaseEntityResult as U,EntityFieldTSType as N,TransactionItem as K,CompositeKey as ce,UserRoleInfo as ue,InMemoryLocalStorageProvider as le,BaseEntity as de,ProviderConfigDataBase as ye,SetProvider as me,StartupManager as ge,IsPlatformSQL as Se,IsVerboseLoggingEnabled as pe}from"@memberjunction/core";import{SafeJSONParse as D,CleanAndParseJSON as he,GetGlobalObjectStore as B,MJGlobal as j,MJEventType as J}from"@memberjunction/global";import{ViewInfo as W}from"@memberjunction/core-entities";import{BehaviorSubject as Ie,Observable as x,Subject as fe,Subscription as Re}from"rxjs";import{createClient as Ee}from"graphql-ws";import{v4 as De}from"uuid";import{openDB as ve}from"@tempfix/idb";class M{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(M.DB_PREFIX)?M.GQL_PREFIX+e.substring(M.DB_PREFIX.length):e}ReverseMapFieldName(e){return e.startsWith(M.GQL_PREFIX)?M.DB_PREFIX+e.substring(M.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 z extends ne{static{d(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=c`
2
2
  mutation ExecuteTransactionGroup($group: TransactionInputType!) {
3
3
  ExecuteTransactionGroup(group: $group) {
4
4
  Success
@@ -6,7 +6,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
6
6
  ResultsJSON
7
7
  }
8
8
  }
9
- `,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const r={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const n=s.ExecuteTransactionGroup,a=[];for(let i=0;i<this.PendingTransactions.length;i++){const o=n.ResultsJSON[i],y=D(o),d=this.PendingTransactions[i];a.push(new ae(d,y,y!==null))}return a}else throw new Error("Failed to execute transaction group")}}const Ce=720*1e3,we=6;class ${static{l(this,"FireAndForgetHelper")}static async Execute(e){const t=e.operationLabel??e.mutationFieldName,r=e.timeoutMs??Ce,s=e.maxStallReconciles??we;let n,a=!1,i=0;const{promise:o,resolve:y,reject:d}=$.createCompletionPromise(),f=l(R=>{a||(a=!0,S.clear(),R())},"finish"),I=l(R=>f(()=>y(R)),"settleResolve"),m=l(R=>f(()=>d(R)),"settleReject"),p=l(async()=>{if(a)return;if(!e.onStall){m(new Error($.timeoutMessage(e.timeoutErrorMessage,r)));return}let R;try{M(`[FireAndForget:${t}] Idle window elapsed, reconciling against server run record`),R=await e.onStall()}catch(E){m(E);return}a||(R==="continue"?++i>s?m(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 R?(M(`[FireAndForget:${t}] Reconciliation recovered a completed run`),I(R.resolve)):m(R.reject))},"onStall"),S=$.createIdleTimer(r,()=>{p()});try{S.reset(),n=$.subscribeToPubSub(e,{onActivity:l(()=>{i=0,S.reset()},"onActivity"),onCompletion:l(E=>I(E),"onCompletion"),onStreamEnd:l(()=>{p()},"onStreamEnd")});const R=await $.executeMutation(e);if(!e.validateAck(R)){S.clear();const E=R?.errorMessage??"Server rejected the request";return u(`[FireAndForget:${t}] Server rejected: ${E}`),e.createErrorResult(E)}return M(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await o}catch(R){throw u(`[FireAndForget:${t}] Error: ${R.message}`),R}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:l(()=>{r&&clearTimeout(r),r=setTimeout(t,e)},"reset"),clear:l(()=>{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:l(n=>{t.onActivity();try{const a=JSON.parse(n);e.onMessage&&e.onMessage(a),e.isCompletionEvent(a)&&(M(`[FireAndForget:${s}] Completion event received`),t.onCompletion(e.extractResult(a)))}catch(a){console.error(`[FireAndForget:${s}] Failed to parse PubSub message:`,a)}},"next"),error:l(()=>t.onStreamEnd(),"error"),complete:l(()=>t.onStreamEnd(),"complete")})}static async executeMutation(e){return(await e.dataProvider.ExecuteGQL(e.mutation,e.variables))[e.mutationFieldName]}}class H{static{l(this,"GraphQLAIClient")}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=c`
9
+ `,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const r={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const n=s.ExecuteTransactionGroup,a=[];for(let i=0;i<this.PendingTransactions.length;i++){const o=n.ResultsJSON[i],y=D(o),u=this.PendingTransactions[i];a.push(new ae(u,y,y!==null))}return a}else throw new Error("Failed to execute transaction group")}}const Ce=720*1e3,we=6;class ${static{d(this,"FireAndForgetHelper")}static async Execute(e){const t=e.operationLabel??e.mutationFieldName,r=e.timeoutMs??Ce,s=e.maxStallReconciles??we;let n,a=!1,i=0;const{promise:o,resolve:y,reject:u}=$.createCompletionPromise(),h=d(R=>{a||(a=!0,S.clear(),R())},"finish"),f=d(R=>h(()=>y(R)),"settleResolve"),m=d(R=>h(()=>u(R)),"settleReject"),p=d(async()=>{if(a)return;if(!e.onStall){m(new Error($.timeoutMessage(e.timeoutErrorMessage,r)));return}let R;try{A(`[FireAndForget:${t}] Idle window elapsed, reconciling against server run record`),R=await e.onStall()}catch(E){m(E);return}a||(R==="continue"?++i>s?m(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 R?(A(`[FireAndForget:${t}] Reconciliation recovered a completed run`),f(R.resolve)):m(R.reject))},"onStall"),S=$.createIdleTimer(r,()=>{p()});try{S.reset(),n=$.subscribeToPubSub(e,{onActivity:d(()=>{i=0,S.reset()},"onActivity"),onCompletion:d(E=>f(E),"onCompletion"),onStreamEnd:d(()=>{p()},"onStreamEnd")});const R=await $.executeMutation(e);if(!e.validateAck(R)){S.clear();const E=R?.errorMessage??"Server rejected the request";return l(`[FireAndForget:${t}] Server rejected: ${E}`),e.createErrorResult(E)}return A(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await o}catch(R){throw l(`[FireAndForget:${t}] Error: ${R.message}`),R}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)&&(A(`[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 H{static{d(this,"GraphQLAIClient")}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=c`
10
10
  mutation RunAIPrompt(
11
11
  $promptId: String!,
12
12
  $data: String,
@@ -65,7 +65,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
65
65
  chatResult
66
66
  }
67
67
  }
68
- `,r=this.preparePromptVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(s)}catch(t){return this.handlePromptError(t)}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,n;try{t.parsedResult&&(r=he(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 u(`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:l(i=>i?.success===!0,"validateAck"),isCompletionEvent:l(i=>this.isAgentCompletionEvent(i),"isCompletionEvent"),extractResult:l(i=>this.extractAgentResult(i),"extractResult"),onMessage:l(i=>{this.captureAgentRunId(i,a),e.onProgress&&this.forwardAgentProgress(i,e.onProgress)},"onMessage"),onStall:l(()=>this.reconcileAgentRun(a.id?`ID='${a.id}'`:void 0),"onStall"),createErrorResult:l(i=>this.createAgentErrorResult(i),"createErrorResult")})}catch(s){return this.handleAgentError(s)}}buildRunAIAgentMutation(){return c`
68
+ `,r=this.preparePromptVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(s)}catch(t){return this.handlePromptError(t)}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,n;try{t.parsedResult&&(r=he(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(n=JSON.parse(t.chatResult))}catch{n=t.chatResult}return{success:t.success,output:t.output,parsedResult:r,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:s,chatResult:n}}handlePromptError(e){const t=e;return l(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){try{const s=this.buildRunAIAgentMutation(),n=this.prepareAgentVariables(e,t,r);n.fireAndForget=!0;const a={};return await $.Execute({dataProvider:this._dataProvider,mutation:s,variables:n,mutationFieldName:"RunAIAgent",operationLabel:"RunAIAgent",validateAck:d(i=>i?.success===!0,"validateAck"),isCompletionEvent:d(i=>this.isAgentCompletionEvent(i),"isCompletionEvent"),extractResult:d(i=>this.extractAgentResult(i),"extractResult"),onMessage:d(i=>{this.captureAgentRunId(i,a),e.onProgress&&this.forwardAgentProgress(i,e.onProgress)},"onMessage"),onStall:d(()=>this.reconcileAgentRun(a.id?`ID='${a.id}'`:void 0),"onStall"),createErrorResult:d(i=>this.createAgentErrorResult(i),"createErrorResult")})}catch(s){return this.handleAgentError(s)}}buildRunAIAgentMutation(){return c`
69
69
  mutation RunAIAgent(
70
70
  $agentId: String!,
71
71
  $messages: String!,
@@ -81,7 +81,9 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
81
81
  $createNotification: Boolean,
82
82
  $sourceArtifactId: String,
83
83
  $sourceArtifactVersionId: String,
84
- $fireAndForget: Boolean
84
+ $fireAndForget: Boolean,
85
+ $planMode: Boolean,
86
+ $requestedSkillIDs: [String!]
85
87
  ) {
86
88
  RunAIAgent(
87
89
  agentId: $agentId,
@@ -98,7 +100,9 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
98
100
  createNotification: $createNotification,
99
101
  sourceArtifactId: $sourceArtifactId,
100
102
  sourceArtifactVersionId: $sourceArtifactVersionId,
101
- fireAndForget: $fireAndForget
103
+ fireAndForget: $fireAndForget,
104
+ planMode: $planMode,
105
+ requestedSkillIDs: $requestedSkillIDs
102
106
  ) {
103
107
  success
104
108
  errorMessage
@@ -106,7 +110,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
106
110
  result
107
111
  }
108
112
  }
109
- `}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),t!==void 0&&(s.sourceArtifactId=t),r!==void 0&&(s.sourceArtifactVersionId=r),s}processAgentResult(e){return D(e)}handleAgentError(e){const r=e?.message||String(e);u(`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:l(s=>s?.success===!0,"validateAck"),isCompletionEvent:l(s=>this.isConversationDetailCompletionEvent(s,e.conversationDetailId),"isCompletionEvent"),extractResult:l(s=>this.extractAgentResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardConversationDetailProgress(s,e.onProgress):void 0,onStall:l(()=>this.reconcileAgentRun(`ConversationDetailID='${e.conversationDetailId}'`),"onStall"),createErrorResult:l(s=>this.createAgentErrorResult(s),"createErrorResult")})}catch(t){return this.handleAgentError(t)}}buildConversationDetailMutation(){return c`
113
+ `}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),e.planMode!==void 0&&(s.planMode=e.planMode),e.requestedSkillIDs!==void 0&&(s.requestedSkillIDs=e.requestedSkillIDs),s}processAgentResult(e){return D(e)}handleAgentError(e){const r=e?.message||String(e);l(`Error running AI agent: ${r}`);const s=r.includes("Failed to fetch")||r.includes("NetworkError"),n=r.includes("timed out")||r.includes("timeout");let a;return s?a="Lost connection to the server. The agent may still be running. Please refresh to check the latest status.":a=r,{success:!1,agentRun:void 0,errorMessage:a}}async RunAIAgentFromConversationDetail(e){try{const t=this.buildConversationDetailMutation(),r=this.prepareConversationDetailVariables(e);return await $.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunAIAgentFromConversationDetail",operationLabel:"RunAIAgentFromConversationDetail",validateAck:d(s=>s?.success===!0,"validateAck"),isCompletionEvent:d(s=>this.isConversationDetailCompletionEvent(s,e.conversationDetailId),"isCompletionEvent"),extractResult:d(s=>this.extractAgentResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardConversationDetailProgress(s,e.onProgress):void 0,onStall:d(()=>this.reconcileAgentRun(`ConversationDetailID='${e.conversationDetailId}'`),"onStall"),createErrorResult:d(s=>this.createAgentErrorResult(s),"createErrorResult")})}catch(t){return this.handleAgentError(t)}}buildConversationDetailMutation(){return c`
110
114
  mutation RunAIAgentFromConversationDetail(
111
115
  $conversationDetailId: String!,
112
116
  $agentId: String!,
@@ -117,6 +121,8 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
117
121
  $lastRunId: String,
118
122
  $autoPopulateLastRunPayload: Boolean,
119
123
  $configurationId: String,
124
+ $planMode: Boolean,
125
+ $requestedSkillIDs: [String!],
120
126
  $createArtifacts: Boolean,
121
127
  $createNotification: Boolean,
122
128
  $sourceArtifactId: String,
@@ -133,6 +139,8 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
133
139
  lastRunId: $lastRunId,
134
140
  autoPopulateLastRunPayload: $autoPopulateLastRunPayload,
135
141
  configurationId: $configurationId,
142
+ planMode: $planMode,
143
+ requestedSkillIDs: $requestedSkillIDs,
136
144
  createArtifacts: $createArtifacts,
137
145
  createNotification: $createNotification,
138
146
  sourceArtifactId: $sourceArtifactId,
@@ -145,7 +153,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
145
153
  result
146
154
  }
147
155
  }
148
- `}prepareConversationDetailVariables(e){const t={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId,fireAndForget:!0};return e.maxHistoryMessages!==void 0&&(t.maxHistoryMessages=e.maxHistoryMessages),e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(t.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.createArtifacts!==void 0&&(t.createArtifacts=e.createArtifacts),e.createNotification!==void 0&&(t.createNotification=e.createNotification),e.sourceArtifactId!==void 0&&(t.sourceArtifactId=e.sourceArtifactId),e.sourceArtifactVersionId!==void 0&&(t.sourceArtifactVersionId=e.sourceArtifactVersionId),t}isAgentCompletionEvent(e){const t=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&t?.type==="complete"}isConversationDetailCompletionEvent(e,t){const r=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&r?.type==="complete"&&r?.conversationDetailId===t}captureAgentRunId(e,t){const r=e.data,s=r?.agentRunId??r?.runId;s&&s!=="unknown"&&(t.id=s)}async reconcileAgentRun(e){if(!e)return"continue";const t=await this._dataProvider.RunView({EntityName:"MJ: AI Agent Runs",ExtraFilter:e,OrderBy:"__mj_CreatedAt DESC",ResultType:"entity_object",BypassCache:!0}),r=t.Success?t.Results?.[0]:void 0;return!r||r.Status==="Running"?"continue":{resolve:{success:r.Status==="Completed"||r.Status==="Paused"||r.Status==="AwaitingFeedback",agentRun:r,payload:r.Result?D(r.Result)??void 0:void 0,errorMessage:r.ErrorMessage??void 0}}}extractAgentResult(e){const t=e.data,r=t.result;return r?D(r):{success:t.success,agentRun:void 0}}forwardAgentProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const s=e.data?.progress;s&&t({step:s.currentStep,percentage:s.percentage,message:s.message,metadata:s})}forwardConversationDetailProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const r=e.data,s=r?.progress;s&&t({currentStep:s.currentStep,percentage:s.percentage,message:s.message,metadata:{...s,agentRun:r?.agentRun,agentRunId:r?.agentRunId}})}createAgentErrorResult(e){return{success:!1,agentRun:void 0,errorMessage:e}}async ExecuteSimplePrompt(e){try{const t=c`
156
+ `}prepareConversationDetailVariables(e){const t={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId,fireAndForget:!0};return e.maxHistoryMessages!==void 0&&(t.maxHistoryMessages=e.maxHistoryMessages),e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(t.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.planMode!==void 0&&(t.planMode=e.planMode),e.requestedSkillIDs!==void 0&&(t.requestedSkillIDs=e.requestedSkillIDs),e.createArtifacts!==void 0&&(t.createArtifacts=e.createArtifacts),e.createNotification!==void 0&&(t.createNotification=e.createNotification),e.sourceArtifactId!==void 0&&(t.sourceArtifactId=e.sourceArtifactId),e.sourceArtifactVersionId!==void 0&&(t.sourceArtifactVersionId=e.sourceArtifactVersionId),t}isAgentCompletionEvent(e){const t=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&t?.type==="complete"}isConversationDetailCompletionEvent(e,t){const r=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&r?.type==="complete"&&r?.conversationDetailId===t}captureAgentRunId(e,t){const r=e.data,s=r?.agentRunId??r?.runId;s&&s!=="unknown"&&(t.id=s)}async reconcileAgentRun(e){if(!e)return"continue";const t=await this._dataProvider.RunView({EntityName:"MJ: AI Agent Runs",ExtraFilter:e,OrderBy:"__mj_CreatedAt DESC",ResultType:"entity_object",BypassCache:!0}),r=t.Success?t.Results?.[0]:void 0;return!r||r.Status==="Running"?"continue":{resolve:{success:r.Status==="Completed"||r.Status==="Paused"||r.Status==="AwaitingFeedback",agentRun:r,payload:r.Result?D(r.Result)??void 0:void 0,errorMessage:r.ErrorMessage??void 0}}}extractAgentResult(e){const t=e.data,r=t.result;return r?D(r):{success:t.success,agentRun:void 0}}forwardAgentProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const s=e.data?.progress;s&&t({step:s.currentStep,percentage:s.percentage,message:s.message,metadata:s})}forwardConversationDetailProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const r=e.data,s=r?.progress;s&&t({currentStep:s.currentStep,percentage:s.percentage,message:s.message,metadata:{...s,agentRun:r?.agentRun,agentRunId:r?.agentRunId}})}createAgentErrorResult(e){return{success:!1,agentRun:void 0,errorMessage:e}}async ExecuteSimplePrompt(e){try{const t=c`
149
157
  mutation ExecuteSimplePrompt(
150
158
  $systemPrompt: String!,
151
159
  $messages: String,
@@ -168,7 +176,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
168
176
  executionTimeMs
169
177
  }
170
178
  }
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 u(`Error executing simple prompt: ${r}`),{success:!1,modelName:"Unknown",error:r.message||"Unknown error occurred"}}}async EmbedText(e){try{const t=c`
179
+ `,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.ExecuteSimplePrompt)throw new Error("Invalid response from server");const n=s.ExecuteSimplePrompt;let a;if(n.resultObject)try{a=JSON.parse(n.resultObject)}catch{a=n.resultObject}return{success:n.success,result:n.result,resultObject:a,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){const r=t;return l(`Error executing simple prompt: ${r}`),{success:!1,modelName:"Unknown",error:r.message||"Unknown error occurred"}}}async EmbedText(e){try{const t=c`
172
180
  mutation EmbedText(
173
181
  $textToEmbed: [String!]!,
174
182
  $modelSize: String!
@@ -183,7 +191,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
183
191
  error
184
192
  }
185
193
  }
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 u(`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=c`
194
+ `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this._dataProvider.ExecuteGQL(t,s);if(!n?.EmbedText)throw new Error("Invalid response from server");const a=n.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?a.embeddings:a.embeddings[0],modelName:a.modelName,vectorDimensions:a.vectorDimensions,error:a.error}}catch(t){const r=t;return l(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}async RunAutotagPipeline(e){try{const t=c`
187
195
  mutation RunAutotagPipeline($contentSourceIDs: [String!], $forceReprocess: Boolean) {
188
196
  RunAutotagPipeline(contentSourceIDs: $contentSourceIDs, forceReprocess: $forceReprocess) {
189
197
  Success
@@ -192,7 +200,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
192
200
  PipelineRunID
193
201
  }
194
202
  }
195
- `,r={};e?.contentSourceIDs?.length&&(r.contentSourceIDs=e.contentSourceIDs),e?.forceReprocess&&(r.forceReprocess=!0);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.RunAutotagPipeline)throw new Error("Invalid response from server");return s.RunAutotagPipeline}catch(t){const r=t;return u("GraphQLAIClient.RunAutotagPipeline failed",void 0,r),{Success:!1,Status:"Error",ErrorMessage:r.message||"Unknown error"}}}async PauseClassificationPipeline(e){try{const t=c`
203
+ `,r={};e?.contentSourceIDs?.length&&(r.contentSourceIDs=e.contentSourceIDs),e?.forceReprocess&&(r.forceReprocess=!0);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.RunAutotagPipeline)throw new Error("Invalid response from server");return s.RunAutotagPipeline}catch(t){const r=t;return l("GraphQLAIClient.RunAutotagPipeline failed",void 0,r),{Success:!1,Status:"Error",ErrorMessage:r.message||"Unknown error"}}}async PauseClassificationPipeline(e){try{const t=c`
196
204
  mutation PauseClassificationPipeline($processRunID: String!) {
197
205
  PauseClassificationPipeline(processRunID: $processRunID) {
198
206
  Success
@@ -201,7 +209,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
201
209
  PipelineRunID
202
210
  }
203
211
  }
204
- `,r=await this._dataProvider.ExecuteGQL(t,{processRunID:e});if(!r?.PauseClassificationPipeline)throw new Error("Invalid response from server");return r.PauseClassificationPipeline}catch(t){const r=t;return u("GraphQLAIClient.PauseClassificationPipeline failed",void 0,r),{Success:!1,Status:"Error",ErrorMessage:r.message||"Unknown error"}}}async ResumeClassificationPipeline(e){try{const t=c`
212
+ `,r=await this._dataProvider.ExecuteGQL(t,{processRunID:e});if(!r?.PauseClassificationPipeline)throw new Error("Invalid response from server");return r.PauseClassificationPipeline}catch(t){const r=t;return l("GraphQLAIClient.PauseClassificationPipeline failed",void 0,r),{Success:!1,Status:"Error",ErrorMessage:r.message||"Unknown error"}}}async ResumeClassificationPipeline(e){try{const t=c`
205
213
  mutation ResumeClassificationPipeline($processRunID: String!) {
206
214
  ResumeClassificationPipeline(processRunID: $processRunID) {
207
215
  Success
@@ -210,7 +218,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
210
218
  PipelineRunID
211
219
  }
212
220
  }
213
- `,r=await this._dataProvider.ExecuteGQL(t,{processRunID:e});if(!r?.ResumeClassificationPipeline)throw new Error("Invalid response from server");return r.ResumeClassificationPipeline}catch(t){const r=t;return u("GraphQLAIClient.ResumeClassificationPipeline failed",void 0,r),{Success:!1,Status:"Error",ErrorMessage:r.message||"Unknown error"}}}async PromoteTagSuggestion(e){try{const t=c`
221
+ `,r=await this._dataProvider.ExecuteGQL(t,{processRunID:e});if(!r?.ResumeClassificationPipeline)throw new Error("Invalid response from server");return r.ResumeClassificationPipeline}catch(t){const r=t;return l("GraphQLAIClient.ResumeClassificationPipeline failed",void 0,r),{Success:!1,Status:"Error",ErrorMessage:r.message||"Unknown error"}}}async PromoteTagSuggestion(e){try{const t=c`
214
222
  mutation PromoteTagSuggestion($suggestionID: String!, $strategy: String!, $targetTagID: String) {
215
223
  PromoteTagSuggestion(suggestionID: $suggestionID, strategy: $strategy, targetTagID: $targetTagID) {
216
224
  Success
@@ -219,14 +227,14 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
219
227
  ErrorMessage
220
228
  }
221
229
  }
222
- `,r={suggestionID:e.suggestionID,strategy:e.strategy};e.targetTagID&&(r.targetTagID=e.targetTagID);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.PromoteTagSuggestion)throw new Error("Invalid response from server");return s.PromoteTagSuggestion}catch(t){const r=t;return u("GraphQLAIClient.PromoteTagSuggestion failed",void 0,r),{Success:!1,ErrorMessage:r.message||"Unknown error"}}}async RejectTagSuggestion(e){try{const t=c`
230
+ `,r={suggestionID:e.suggestionID,strategy:e.strategy};e.targetTagID&&(r.targetTagID=e.targetTagID);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.PromoteTagSuggestion)throw new Error("Invalid response from server");return s.PromoteTagSuggestion}catch(t){const r=t;return l("GraphQLAIClient.PromoteTagSuggestion failed",void 0,r),{Success:!1,ErrorMessage:r.message||"Unknown error"}}}async RejectTagSuggestion(e){try{const t=c`
223
231
  mutation RejectTagSuggestion($suggestionID: String!, $reviewerNotes: String) {
224
232
  RejectTagSuggestion(suggestionID: $suggestionID, reviewerNotes: $reviewerNotes) {
225
233
  Success
226
234
  ErrorMessage
227
235
  }
228
236
  }
229
- `,r={suggestionID:e.suggestionID};e.reviewerNotes&&(r.reviewerNotes=e.reviewerNotes);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.RejectTagSuggestion)throw new Error("Invalid response from server");return s.RejectTagSuggestion}catch(t){const r=t;return u("GraphQLAIClient.RejectTagSuggestion failed",void 0,r),{Success:!1,ErrorMessage:r.message||"Unknown error"}}}async RebuildTagEmbeddings(){try{const e=c`
237
+ `,r={suggestionID:e.suggestionID};e.reviewerNotes&&(r.reviewerNotes=e.reviewerNotes);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.RejectTagSuggestion)throw new Error("Invalid response from server");return s.RejectTagSuggestion}catch(t){const r=t;return l("GraphQLAIClient.RejectTagSuggestion failed",void 0,r),{Success:!1,ErrorMessage:r.message||"Unknown error"}}}async RebuildTagEmbeddings(){try{const e=c`
230
238
  mutation RebuildTagEmbeddings {
231
239
  RebuildTagEmbeddings {
232
240
  Success
@@ -235,7 +243,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
235
243
  ErrorMessage
236
244
  }
237
245
  }
238
- `,t=await this._dataProvider.ExecuteGQL(e,{});if(!t?.RebuildTagEmbeddings)throw new Error("Invalid response from server");return t.RebuildTagEmbeddings}catch(e){const t=e;return u("GraphQLAIClient.RebuildTagEmbeddings failed",void 0,t),{Success:!1,Refreshed:0,Total:0,ErrorMessage:t.message||"Unknown error"}}}async RunTagHealth(e){try{const t=c`
246
+ `,t=await this._dataProvider.ExecuteGQL(e,{});if(!t?.RebuildTagEmbeddings)throw new Error("Invalid response from server");return t.RebuildTagEmbeddings}catch(e){const t=e;return l("GraphQLAIClient.RebuildTagEmbeddings failed",void 0,t),{Success:!1,Refreshed:0,Total:0,ErrorMessage:t.message||"Unknown error"}}}async RunTagHealth(e){try{const t=c`
239
247
  mutation RunTagHealth(
240
248
  $minCoOccurrence: Int,
241
249
  $minNameSimilarity: Float,
@@ -258,7 +266,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
258
266
  ErrorMessage
259
267
  }
260
268
  }
261
- `,r={};e?.minCoOccurrence!=null&&(r.minCoOccurrence=e.minCoOccurrence),e?.minNameSimilarity!=null&&(r.minNameSimilarity=e.minNameSimilarity),e?.minEmbeddingSimilarity!=null&&(r.minEmbeddingSimilarity=e.minEmbeddingSimilarity),e?.maxUsage!=null&&(r.maxUsage=e.maxUsage),e?.maxImplicitChildren!=null&&(r.maxImplicitChildren=e.maxImplicitChildren);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.RunTagHealth)throw new Error("Invalid response from server");return s.RunTagHealth}catch(t){const r=t;return u("GraphQLAIClient.RunTagHealth failed",void 0,r),{Success:!1,MergeCount:0,LowUsageCount:0,WideNodeCount:0,DurationMs:0,ErrorMessage:r.message||"Unknown error"}}}async VectorizeEntity(e){try{const t=c`
269
+ `,r={};e?.minCoOccurrence!=null&&(r.minCoOccurrence=e.minCoOccurrence),e?.minNameSimilarity!=null&&(r.minNameSimilarity=e.minNameSimilarity),e?.minEmbeddingSimilarity!=null&&(r.minEmbeddingSimilarity=e.minEmbeddingSimilarity),e?.maxUsage!=null&&(r.maxUsage=e.maxUsage),e?.maxImplicitChildren!=null&&(r.maxImplicitChildren=e.maxImplicitChildren);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.RunTagHealth)throw new Error("Invalid response from server");return s.RunTagHealth}catch(t){const r=t;return l("GraphQLAIClient.RunTagHealth failed",void 0,r),{Success:!1,MergeCount:0,LowUsageCount:0,WideNodeCount:0,DurationMs:0,ErrorMessage:r.message||"Unknown error"}}}async VectorizeEntity(e){try{const t=c`
262
270
  mutation VectorizeEntity(
263
271
  $entityDocumentID: String!,
264
272
  $entityID: String!,
@@ -275,7 +283,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
275
283
  PipelineRunID
276
284
  }
277
285
  }
278
- `,r={entityDocumentID:e.entityDocumentID,entityID:e.entityID};e.batchSize!==void 0&&(r.batchSize=e.batchSize);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.VectorizeEntity)throw new Error("Invalid response from server");return s.VectorizeEntity}catch(t){const r=t;return u("GraphQLAIClient.VectorizeEntity failed",void 0,r),{Success:!1,Status:"Error",ErrorMessage:r.message||"Unknown error"}}}async FetchEntityVectors(e){try{const t=c`
286
+ `,r={entityDocumentID:e.entityDocumentID,entityID:e.entityID};e.batchSize!==void 0&&(r.batchSize=e.batchSize);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.VectorizeEntity)throw new Error("Invalid response from server");return s.VectorizeEntity}catch(t){const r=t;return l("GraphQLAIClient.VectorizeEntity failed",void 0,r),{Success:!1,Status:"Error",ErrorMessage:r.message||"Unknown error"}}}async FetchEntityVectors(e){try{const t=c`
279
287
  query FetchEntityVectors(
280
288
  $entityDocumentID: String!,
281
289
  $maxRecords: Int,
@@ -297,12 +305,12 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
297
305
  }
298
306
  }
299
307
  }
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 u("GraphQLAIClient.FetchEntityVectors failed",void 0,r),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,ErrorMessage:r.message||"Unknown error"}}}}const F="5.43.0",w="default";class X{static{l(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 $e="MJ_Metadata",Pe=0;function Ae(){try{const g=F.split("."),e=parseInt(g[0],10),t=parseInt(g[1],10);if(!Number.isFinite(e)||!Number.isFinite(t))throw new Error(`Could not parse major.minor from version "${F}"`);return e*1e3+t+Pe}catch(g){return P({error:g,message:"Failed to derive IDB version from PACKAGE_VERSION; using fallback 99999"}),99999}}l(Ae,"computeIdbVersion");const Me=Ae(),Y=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"];class Z extends X{static{l(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=ve($e,Me,{upgrade:l((e,t,r)=>{try{M(`[IDBCache] Upgrading IndexedDB schema v${t} \u2192 v${r} (package ${F}). Dropping all stores; caches will repopulate on first use.`);for(const s of Array.from(e.objectStoreNames))e.deleteObjectStore(s);for(const s of Y)e.objectStoreNames.contains(s)||e.createObjectStore(s)}catch(s){P({error:s,message:s?.message})}},"upgrade"),blocked:l((e,t)=>{M(`[IDBCache] Upgrade from v${e} to v${t} blocked by another tab. Close other tabs to allow the upgrade to proceed.`)},"blocked")}),this.dbPromise.then(e=>{this._dbReady=!0,e.onversionchange=()=>{M("[IDBCache] DB schema upgraded in another tab \u2014 closing local connection."),e.close(),this._dbReady=!1}}).catch(e=>{P({error:e,message:"IndexedDB initialization failed: "+e?.message})})}get IsReady(){return this._dbReady}isKnownCategory(e){const t=`mj:${e}`;return Y.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){P({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 P({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),d=i.map(I=>y.get(I)),f=await Promise.all(d);await o.done;for(let I=0;I<a.length;I++){const m=f[I];r.set(a[I],m===void 0?null:m)}return r}catch(s){P({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){P({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){P({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 P({error:t,message:t?.message}),[]}}}const b=new A,Ne=c`subscription RemoteOperationProgress($channelId: ID!) {
308
+ `,r={entityDocumentID:e.entityDocumentID};e.maxRecords!==void 0&&(r.maxRecords=e.maxRecords),e.filter!==void 0&&(r.filter=e.filter);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.FetchEntityVectors)throw new Error("Invalid response from server");return s.FetchEntityVectors}catch(t){const r=t;return l("GraphQLAIClient.FetchEntityVectors failed",void 0,r),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,ErrorMessage:r.message||"Unknown error"}}}}const F="5.45.0",w="default";class X{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 $e="MJ_Metadata",Pe=0;function Me(){try{const g=F.split("."),e=parseInt(g[0],10),t=parseInt(g[1],10);if(!Number.isFinite(e)||!Number.isFinite(t))throw new Error(`Could not parse major.minor from version "${F}"`);return e*1e3+t+Pe}catch(g){return P({error:g,message:"Failed to derive IDB version from PACKAGE_VERSION; using fallback 99999"}),99999}}d(Me,"computeIdbVersion");const Ae=Me(),Y=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"];class Z extends X{static{d(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=ve($e,Ae,{upgrade:d((e,t,r)=>{try{A(`[IDBCache] Upgrading IndexedDB schema v${t} \u2192 v${r} (package ${F}). Dropping all stores; caches will repopulate on first use.`);for(const s of Array.from(e.objectStoreNames))e.deleteObjectStore(s);for(const s of Y)e.objectStoreNames.contains(s)||e.createObjectStore(s)}catch(s){P({error:s,message:s?.message})}},"upgrade"),blocked:d((e,t)=>{A(`[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=()=>{A("[IDBCache] DB schema upgraded in another tab \u2014 closing local connection."),e.close(),this._dbReady=!1}}).catch(e=>{P({error:e,message:"IndexedDB initialization failed: "+e?.message})})}get IsReady(){return this._dbReady}isKnownCategory(e){const t=`mj:${e}`;return Y.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){P({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 P({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(f=>this.getStoreKey(f,t)),o=s.transaction(n,"readonly"),y=o.objectStore(n),u=i.map(f=>y.get(f)),h=await Promise.all(u);await o.done;for(let f=0;f<a.length;f++){const m=h[f];r.set(a[f],m===void 0?null:m)}return r}catch(s){P({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){P({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){P({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 P({error:t,message:t?.message}),[]}}}const b=new M,Ne=c`subscription RemoteOperationProgress($channelId: ID!) {
301
309
  RemoteOperationProgress(channelId: $channelId) {
302
310
  ChannelId
303
311
  ProgressJSON
304
312
  }
305
- }`;class be extends ye{static{l(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,d){super({Token:e,URL:t,WSURL:r,MJAPIKey:o,UserAPIKey:y,RefreshTokenFunction:s,OnAuthenticationError:d},n,a,i)}}class h extends oe{static{l(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._dynamicHeaders=new Map,this._innerCurrentUserQueryString=`CurrentUser {
313
+ }`;class be extends ye{static{d(this,"GraphQLProviderConfigData")}get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get MJAPIKey(){return this.Data.MJAPIKey}set MJAPIKey(e){this.Data.MJAPIKey=e}get UserAPIKey(){return this.Data.UserAPIKey}set UserAPIKey(e){this.Data.UserAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}get OnAuthenticationError(){return this.Data.OnAuthenticationError}set OnAuthenticationError(e){this.Data.OnAuthenticationError=e}constructor(e,t,r,s,n,a,i,o,y,u){super({Token:e,URL:t,WSURL:r,MJAPIKey:o,UserAPIKey:y,RefreshTokenFunction:s,OnAuthenticationError:u},n,a,i)}}class I extends oe{static{d(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._dynamicHeaders=new Map,this._innerCurrentUserQueryString=`CurrentUser {
306
314
  ${this.userInfoString()}
307
315
  MJUserRoles_UserIDArray {
308
316
  ${this.userRoleInfoString()}
@@ -311,7 +319,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
311
319
  `,this._currentUserQuery=c`query CurrentUserAndRoles {
312
320
  ${this._innerCurrentUserQueryString}
313
321
  CurrentUserTenantContext
314
- }`,this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject=new Ie("unknown"),this._isDisposingSocketIntentionally=!1,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=1800*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=300*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=600*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,this._cacheInvalidationSubscription=null;const e=B();if(e&&e[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=B();return e?e[h._globalStoreKey]:void 0}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new H(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 De()}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 u(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 q(this,{...t,UserRoles:r});return e.CurrentUserTenantContext&&typeof e.CurrentUserTenantContext=="object"&&(s.TenantContext=e.CurrentUserTenantContext),s}}async RunReport(e,t){const r=c`
322
+ }`,this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject=new Ie("unknown"),this._isDisposingSocketIntentionally=!1,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=1800*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=300*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=600*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,this._cacheInvalidationSubscription=null;const e=B();if(e&&e[I._globalStoreKey])return e[I._globalStoreKey];e&&(e[I._globalStoreKey]=this)}static{this.VerboseCacheInvalidationLogging=!1}static{this._globalStoreKey="___SINGLETON__GraphQLDataProvider"}static get Instance(){const e=B();return e?e[I._globalStoreKey]:void 0}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new H(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 De()}get LocalStoragePrefix(){if(this._configData===void 0||this._configData.URL===void 0)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const r=this.LocalStoragePrefix+"sessionId";await t.SetItem(r,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,r,s){try{return this._configData=e,r?(this._sessionId=await this.GetPreferredUUID(s),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey,e.UserAPIKey),await this.SaveStoredSessionID(this._sessionId)):(I.Instance._configData=e,I.Instance._sessionId===void 0&&(I.Instance._sessionId=await this.GetPreferredUUID(s)),I.Instance._client||(I.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,I.Instance._sessionId,e.MJAPIKey,e.UserAPIKey)),await I.Instance.SaveStoredSessionID(I.Instance._sessionId),this._sessionId=I.Instance._sessionId,this._client=I.Instance._client),super.Config(e)}catch(n){throw l(n),n}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}SetDynamicHeader(e,t){this._dynamicHeaders.set(e,t),this._client&&this._client.setHeader(e,t),I.Instance&&I.Instance!==this&&I.Instance._configData===this._configData&&(I.Instance._dynamicHeaders.set(e,t),I.Instance._client&&I.Instance._client.setHeader(e,t))}RemoveDynamicHeader(e){this._dynamicHeaders.delete(e),this._client&&this._client.setHeader(e,""),I.Instance&&I.Instance!==this&&I.Instance._configData===this._configData&&(I.Instance._dynamicHeaders.delete(e),I.Instance._client&&I.Instance._client.setHeader(e,""))}GetDynamicHeaders(){return this._dynamicHeaders}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),r=t.MJUserRoles_UserIDArray.map(n=>this.ConvertBackToMJFields(n));t.MJUserRoles_UserIDArray=r;const s=new q(this,{...t,UserRoles:r});return e.CurrentUserTenantContext&&typeof e.CurrentUserTenantContext=="object"&&(s.TenantContext=e.CurrentUserTenantContext),s}}async RunReport(e,t){const r=c`
315
323
  query GetReportDataQuery ($ReportID: String!) {
316
324
  GetReportData(ReportID: $ReportID) {
317
325
  Success
@@ -320,7 +328,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
320
328
  ExecutionTime
321
329
  ErrorMessage
322
330
  }
323
- }`,s=await this.ExecuteGQL(r,{ReportID:e.ReportID});if(s&&s.GetReportData)return{ReportID:e.ReportID,Success:s.GetReportData.Success,Results:JSON.parse(s.GetReportData.Results),RowCount:s.GetReportData.RowCount,ExecutionTime:s.GetReportData.ExecutionTime,ErrorMessage:s.GetReportData.ErrorMessage}}async InternalRunQuery(e,t){if(e.SQL)return this.RunAdhocQuery(e.SQL,e.MaxRows,void 0,e.StartRow);if(e.QueryID)return this.RunQueryByID(e.QueryID,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);throw new Error("No SQL, QueryID, or QueryName provided to RunQuery")}async RunAdhocQuery(e,t,r,s){const n=c`
331
+ }`,s=await this.ExecuteGQL(r,{ReportID:e.ReportID});if(s&&s.GetReportData)return{ReportID:e.ReportID,Success:s.GetReportData.Success,Results:JSON.parse(s.GetReportData.Results),RowCount:s.GetReportData.RowCount,ExecutionTime:s.GetReportData.ExecutionTime,ErrorMessage:s.GetReportData.ErrorMessage}}async InternalRunQuery(e,t){if(e.SQL)return this.RunAdhocQuery(e.SQL,e.MaxRows,void 0,e.StartRow);if(e.QueryID)return this.RunQueryByID(e.QueryID,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow,e.Enrichment);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow,e.Enrichment);throw new Error("No SQL, QueryID, or QueryName provided to RunQuery")}async RunAdhocQuery(e,t,r,s){const n=c`
324
332
  query ExecuteAdhocQuery($input: AdhocQueryInput!) {
325
333
  ExecuteAdhocQuery(input: $input) {
326
334
  ${this.QueryReturnFieldList}
@@ -332,19 +340,19 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
332
340
  ${this.QueryReturnFieldList}
333
341
  }
334
342
  }
335
- `,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=c`
336
- query GetQueryDataQuery($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
337
- GetQueryData(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
343
+ `,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,Enrichment:a.Enrichment})),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,o){const y=c`
344
+ query GetQueryDataQuery($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int, $Enrichment: JSONObject) {
345
+ GetQueryData(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow, Enrichment: $Enrichment) {
338
346
  ${this.QueryReturnFieldList}
339
347
  }
340
348
  }
341
- `,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 d=await this.ExecuteGQL(o,y);if(d&&d.GetQueryData)return this.TransformQueryPayload(d.GetQueryData)}async RunQueryByName(e,t,r,s,n,a,i){const o=c`
342
- query GetQueryDataByNameQuery($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
343
- GetQueryDataByName(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
349
+ `,u={QueryID:e};t!==void 0&&(u.CategoryID=t),r!==void 0&&(u.CategoryPath=r),n!==void 0&&(u.Parameters=n),a!==void 0&&(u.MaxRows=a),i!==void 0&&(u.StartRow=i),o!==void 0&&(u.Enrichment=o);const h=await this.ExecuteGQL(y,u);if(h&&h.GetQueryData)return this.TransformQueryPayload(h.GetQueryData)}async RunQueryByName(e,t,r,s,n,a,i,o){const y=c`
350
+ query GetQueryDataByNameQuery($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int, $Enrichment: JSONObject) {
351
+ GetQueryDataByName(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow, Enrichment: $Enrichment) {
344
352
  ${this.QueryReturnFieldList}
345
353
  }
346
354
  }
347
- `,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 d=await this.ExecuteGQL(o,y);if(d&&d.GetQueryDataByName)return this.TransformQueryPayload(d.GetQueryDataByName)}get QueryReturnFieldList(){return`
355
+ `,u={QueryName:e};t!==void 0&&(u.CategoryID=t),r!==void 0&&(u.CategoryPath=r),n!==void 0&&(u.Parameters=n),a!==void 0&&(u.MaxRows=a),i!==void 0&&(u.StartRow=i),o!==void 0&&(u.Enrichment=o);const h=await this.ExecuteGQL(y,u);if(h&&h.GetQueryDataByName)return this.TransformQueryPayload(h.GetQueryDataByName)}get QueryReturnFieldList(){return`
348
356
  Success
349
357
  QueryID
350
358
  QueryName
@@ -353,7 +361,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
353
361
  TotalRowCount
354
362
  ExecutionTime
355
363
  ErrorMessage
356
- 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 u(`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=c`
364
+ AppliedParameters`}TransformQueryPayload(e){try{return{QueryID:e.QueryID,QueryName:e.QueryName,Success:e.Success,Results:JSON.parse(e.Results),RowCount:e.RowCount,TotalRowCount:e.TotalRowCount,ExecutionTime:e.ExecutionTime,ErrorMessage:e.ErrorMessage,AppliedParameters:e.AppliedParameters?JSON.parse(e.AppliedParameters):void 0}}catch(t){return l(`Error transforming query payload: ${t}`),null}}async RunQueriesWithCacheCheck(e,t){try{const r=e.map(o=>({params:{QueryID:o.params.QueryID||null,QueryName:o.params.QueryName||null,CategoryID:o.params.CategoryID||null,CategoryPath:o.params.CategoryPath||null,Parameters:o.params.Parameters||null,MaxRows:o.params.MaxRows??null,StartRow:o.params.StartRow??null,ForceAuditLog:o.params.ForceAuditLog||!1,AuditLogDescription:o.params.AuditLogDescription||null,Enrichment:o.params.Enrichment||null},cacheStatus:o.cacheStatus?{maxUpdatedAt:o.cacheStatus.maxUpdatedAt,rowCount:o.cacheStatus.rowCount}:null})),s=c`
357
365
  query RunQueriesWithCacheCheckQuery($input: [RunQueryWithCacheCheckInput!]!) {
358
366
  RunQueriesWithCacheCheck(input: $input) {
359
367
  success
@@ -369,7 +377,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
369
377
  }
370
378
  }
371
379
  }
372
- `,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 u(`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:R}=await this.getEntityNameAndUserView(e,t);i=R,a=S}const o=this.EntityByName(a);if(!o)throw new Error(`Entity ${a} not found in metadata`);let y=!1;const d=T(o);e.ViewID?(r=`Run${d}ViewByID`,s="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(r=`Run${d}ViewByName`,s="RunViewByNameInput",n.ViewName=e.ViewName):(y=!0,r=`Run${d}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?`
380
+ `,a=(await this.ExecuteGQL(s,{input:r}))?.RunQueriesWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map(o=>{if((o.status==="stale"||o.status==="no_validation")&&o.Results){const y=JSON.parse(o.Results);return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,results:y,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}});return{success:a.success,results:i,errorMessage:a.errorMessage}}catch(r){return l(`Error in RunQueriesWithCacheCheck: ${r}`),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async InternalRunView(e,t){try{let r="",s="";if(e){const n={};let a,i;if(e.ViewEntity)i=e.ViewEntity,a=i.Entity;else{const{entityName:S,v:R}=await this.getEntityNameAndUserView(e,t);i=R,a=S}const o=this.EntityByName(a);if(!o)throw new Error(`Entity ${a} not found in metadata`);let y=!1;const u=T(o);e.ViewID?(r=`Run${u}ViewByID`,s="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(r=`Run${u}ViewByName`,s="RunViewByNameInput",n.ViewName=e.ViewName):(y=!0,r=`Run${u}DynamicView`,s="RunDynamicViewInput",n.EntityName=e.EntityName),n.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",n.OrderBy=e.OrderBy?e.OrderBy:"",n.UserSearchString=e.UserSearchString?e.UserSearchString:"",n.Fields=e.Fields,n.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,e.MaxRows!==void 0&&(n.MaxRows=e.MaxRows),e.StartRow!==void 0&&(n.StartRow=e.StartRow),n.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,n.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(n.AuditLogDescription=e.AuditLogDescription),e.BypassCache!==void 0&&(n.BypassCache=e.BypassCache),y||(n.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",n.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,n.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",n.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1),e.Aggregates&&e.Aggregates.length>0&&(n.Aggregates=e.Aggregates.map(S=>({expression:S.expression,alias:S.alias})));const h=this.getViewRunTimeFieldList(o,i,e,y),f=e.Aggregates&&e.Aggregates.length>0?`
373
381
  AggregateResults {
374
382
  alias
375
383
  expression
@@ -380,7 +388,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
380
388
  query RunViewQuery ($input: ${s}!) {
381
389
  ${r}(input: $input) {
382
390
  Results {
383
- ${f.join(`
391
+ ${h.join(`
384
392
  `)}
385
393
  }
386
394
  UserViewRunID
@@ -388,9 +396,9 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
388
396
  TotalRowCount
389
397
  ExecutionTime
390
398
  Success
391
- ErrorMessage${I}
399
+ ErrorMessage${f}
392
400
  }
393
- }`;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(m,{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 R=p[r].Results;if(R&&R.length>0){const C=o.Fields.filter(v=>v.CodeName!==v.Name&&v.CodeName!==void 0);R.forEach(v=>{this.ConvertBackToMJFields(v),C.forEach(L=>{v[L.Name]=v[L.CodeName]})})}return p[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw u(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],n=[];for(const d of e){let f="",I="";const m={};let p=null,S=null;if(d.ViewEntity)S=d.ViewEntity,p=S.Get("Entity");else{const{entityName:v,v:L}=await this.getEntityNameAndUserView(d,t);S=L,p=v}const R=this.EntityByName(p);if(!R)throw new Error(`Entity ${p} not found in metadata`);s.push(R);let E=!1;const C=T(R);d.ViewID?(f=`Run${C}ViewByID`,I="RunViewByIDInput",m.ViewID=d.ViewID):d.ViewName?(f=`Run${C}ViewByName`,I="RunViewByNameInput",m.ViewName=d.ViewName):(E=!0,f=`Run${C}DynamicView`,I="RunDynamicViewInput",m.EntityName=d.EntityName),m.ExtraFilter=d.ExtraFilter||"",m.OrderBy=d.OrderBy||"",m.UserSearchString=d.UserSearchString||"",m.Fields=d.Fields,m.IgnoreMaxRows=d.IgnoreMaxRows||!1,d.MaxRows!==void 0&&(m.MaxRows=d.MaxRows),d.StartRow!==void 0&&(m.StartRow=d.StartRow),d.AfterKey&&(m.AfterKey={KeyValuePairs:d.AfterKey.KeyValuePairs}),m.ForceAuditLog=d.ForceAuditLog||!1,m.ResultType=d.ResultType||"simple",d.AuditLogDescription&&d.AuditLogDescription.length>0&&(m.AuditLogDescription=d.AuditLogDescription),d.BypassCache!==void 0&&(m.BypassCache=d.BypassCache),E||(m.ExcludeUserViewRunID=d.ExcludeUserViewRunID||"",m.ExcludeDataFromAllPriorViewRuns=d.ExcludeDataFromAllPriorViewRuns||!1,m.OverrideExcludeFilter=d.OverrideExcludeFilter||"",m.SaveViewResults=d.SaveViewResults||!1),d.Aggregates&&d.Aggregates.length>0&&(m.Aggregates=d.Aggregates.map(v=>({expression:v.expression,alias:v.alias}))),r.push(m),n.push(...this.getViewRunTimeFieldList(R,S,d,E))}const i=e.some(d=>d.Aggregates&&d.Aggregates.length>0)?`
401
+ }`;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(m,{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 R=p[r].Results;if(R&&R.length>0){const C=o.Fields.filter(v=>v.CodeName!==v.Name&&v.CodeName!==void 0);R.forEach(v=>{this.ConvertBackToMJFields(v),C.forEach(L=>{v[L.Name]=v[L.CodeName]})})}return p[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw l(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],n=[];for(const u of e){let h="",f="";const m={};let p=null,S=null;if(u.ViewEntity)S=u.ViewEntity,p=S.Get("Entity");else{const{entityName:v,v:L}=await this.getEntityNameAndUserView(u,t);S=L,p=v}const R=this.EntityByName(p);if(!R)throw new Error(`Entity ${p} not found in metadata`);s.push(R);let E=!1;const C=T(R);u.ViewID?(h=`Run${C}ViewByID`,f="RunViewByIDInput",m.ViewID=u.ViewID):u.ViewName?(h=`Run${C}ViewByName`,f="RunViewByNameInput",m.ViewName=u.ViewName):(E=!0,h=`Run${C}DynamicView`,f="RunDynamicViewInput",m.EntityName=u.EntityName),m.ExtraFilter=u.ExtraFilter||"",m.OrderBy=u.OrderBy||"",m.UserSearchString=u.UserSearchString||"",m.Fields=u.Fields,m.IgnoreMaxRows=u.IgnoreMaxRows||!1,u.MaxRows!==void 0&&(m.MaxRows=u.MaxRows),u.StartRow!==void 0&&(m.StartRow=u.StartRow),u.AfterKey&&(m.AfterKey={KeyValuePairs:u.AfterKey.KeyValuePairs}),m.ForceAuditLog=u.ForceAuditLog||!1,m.ResultType=u.ResultType||"simple",u.AuditLogDescription&&u.AuditLogDescription.length>0&&(m.AuditLogDescription=u.AuditLogDescription),u.BypassCache!==void 0&&(m.BypassCache=u.BypassCache),E||(m.ExcludeUserViewRunID=u.ExcludeUserViewRunID||"",m.ExcludeDataFromAllPriorViewRuns=u.ExcludeDataFromAllPriorViewRuns||!1,m.OverrideExcludeFilter=u.OverrideExcludeFilter||"",m.SaveViewResults=u.SaveViewResults||!1),u.Aggregates&&u.Aggregates.length>0&&(m.Aggregates=u.Aggregates.map(v=>({expression:v.expression,alias:v.alias}))),r.push(m),n.push(...this.getViewRunTimeFieldList(R,S,u,E))}const i=e.some(u=>u.Aggregates&&u.Aggregates.length>0)?`
394
402
  AggregateResults {
395
403
  alias
396
404
  expression
@@ -415,7 +423,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
415
423
  Success
416
424
  ErrorMessage${i}
417
425
  }
418
- }`,y=await this.ExecuteGQL(o,{input:r});if(y&&y.RunViews){const d=y.RunViews;for(const[f,I]of d.entries())I.Results=I.Results.map(m=>{let p=JSON.parse(m.Data);return this.ConvertBackToMJFields(p),p});return d}return null}catch(r){throw u(r),r}}async RunViewsWithCacheCheck(e,t){try{const r=e.map(o=>({params:{EntityName:o.params.EntityName||"",ExtraFilter:o.params.ExtraFilter||"",OrderBy:o.params.OrderBy||"",Fields:o.params.Fields,UserSearchString:o.params.UserSearchString||"",IgnoreMaxRows:o.params.IgnoreMaxRows||!1,MaxRows:o.params.MaxRows,StartRow:o.params.StartRow,AfterKey:o.params.AfterKey?{KeyValuePairs:o.params.AfterKey.KeyValuePairs}:null,ForceAuditLog:o.params.ForceAuditLog||!1,AuditLogDescription:o.params.AuditLogDescription||"",ResultType:o.params.ResultType||"simple"},cacheStatus:o.cacheStatus?{maxUpdatedAt:o.cacheStatus.maxUpdatedAt,rowCount:o.cacheStatus.rowCount}:null})),s=c`
426
+ }`,y=await this.ExecuteGQL(o,{input:r});if(y&&y.RunViews){const u=y.RunViews;for(const[h,f]of u.entries())f.Results=f.Results.map(m=>{let p=JSON.parse(m.Data);return this.ConvertBackToMJFields(p),p});return u}return null}catch(r){throw l(r),r}}async RunViewsWithCacheCheck(e,t){try{const r=e.map(o=>({params:{EntityName:o.params.EntityName||"",ExtraFilter:o.params.ExtraFilter||"",OrderBy:o.params.OrderBy||"",Fields:o.params.Fields,UserSearchString:o.params.UserSearchString||"",IgnoreMaxRows:o.params.IgnoreMaxRows||!1,MaxRows:o.params.MaxRows,StartRow:o.params.StartRow,AfterKey:o.params.AfterKey?{KeyValuePairs:o.params.AfterKey.KeyValuePairs}:null,ForceAuditLog:o.params.ForceAuditLog||!1,AuditLogDescription:o.params.AuditLogDescription||"",ResultType:o.params.ResultType||"simple"},cacheStatus:o.cacheStatus?{maxUpdatedAt:o.cacheStatus.maxUpdatedAt,rowCount:o.cacheStatus.rowCount}:null})),s=c`
419
427
  query RunViewsWithCacheCheckQuery($input: [RunViewWithCacheCheckInput!]!) {
420
428
  RunViewsWithCacheCheck(input: $input) {
421
429
  success
@@ -448,7 +456,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
448
456
  }
449
457
  }
450
458
  }
451
- `,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 d=e[y];if(o.status==="differential"&&o.differentialData){const f=o.differentialData.updatedRows.map(I=>{const m=JSON.parse(I.Data);return this.ConvertBackToMJFields(m),m});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 m=JSON.parse(I.Data);return this.ConvertBackToMJFields(m),m});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 u(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 W.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await W.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(b.MapFieldName(a))})}else if(s)e.Fields.forEach(a=>{a.IsBinaryFieldType||n.push(b.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(b.MapFieldName(a.EntityField.CodeName))})}return n}get ProviderType(){return ie.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 u(r),r}}async GetRecordDependencies(e,t){try{const r=c`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
459
+ `,a=(await this.ExecuteGQL(s,{input:r}))?.RunViewsWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map((o,y)=>{const u=e[y];if(o.status==="differential"&&o.differentialData){const h=o.differentialData.updatedRows.map(f=>{const m=JSON.parse(f.Data);return this.ConvertBackToMJFields(m),m});return{viewIndex:o.viewIndex,status:o.status,results:void 0,differentialData:{updatedRows:h,deletedRecordIDs:o.differentialData.deletedRecordIDs},maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}if(o.status==="stale"&&o.Results){const h=o.Results.map(f=>{const m=JSON.parse(f.Data);return this.ConvertBackToMJFields(m),m});return{viewIndex:o.viewIndex,status:o.status,results:h,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}return{viewIndex:o.viewIndex,status:o.status,results:void 0,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}});return{success:a.success,results:i,errorMessage:a.errorMessage}}catch(r){return l(r),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async getEntityNameAndUserView(e,t){let r,s;if(e.EntityName)r=e.EntityName;else if(e.ViewID)s=await W.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await W.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(b.MapFieldName(a))})}else if(s)e.Fields.forEach(a=>{a.IsBinaryFieldType||n.push(b.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(b.MapFieldName(a.EntityField.CodeName))})}return n}get ProviderType(){return ie.Network}async GetRecordChanges(e,t){try{const r={EntityName:"MJ: Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},s=await this.RunView(r);return s?s.Results.sort((n,a)=>n.ChangedAt>a.ChangedAt?-1:1):null}catch(r){throw l(r),r}}async GetRecordDependencies(e,t){try{const r=c`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
452
460
  GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
453
461
  EntityName
454
462
  RelatedEntityName
@@ -460,7 +468,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
460
468
  }
461
469
  }
462
470
  }
463
- }`,s={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}};return(await this.ExecuteGQL(r,s))?.GetRecordDependencies}catch(r){throw u(r),r}}ensureKeyValuePairValueIsString(e){return e.map(t=>({FieldName:t.FieldName,Value:t.Value.toString()}))}async GetRecordDuplicates(e,t){if(!e)return null;const r=c`query GetRecordDuplicatesQuery ($params: PotentialDuplicateRequestType!) {
471
+ }`,s={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}};return(await this.ExecuteGQL(r,s))?.GetRecordDependencies}catch(r){throw l(r),r}}ensureKeyValuePairValueIsString(e){return e.map(t=>({FieldName:t.FieldName,Value:t.Value.toString()}))}async GetRecordDuplicates(e,t){if(!e)return null;const r=c`query GetRecordDuplicatesQuery ($params: PotentialDuplicateRequestType!) {
464
472
  GetRecordDuplicates(params: $params) {
465
473
  Status
466
474
  ErrorMessage
@@ -498,7 +506,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
498
506
  }
499
507
  }
500
508
  }
501
- }`,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&&u(`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=c`mutation ExecuteRemoteOperation($operationKey: String!, $inputJSON: String!, $invokeMode: String!, $progressChannelId: String) {
509
+ }`,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&&l(`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=c`mutation ExecuteRemoteOperation($operationKey: String!, $inputJSON: String!, $invokeMode: String!, $progressChannelId: String) {
502
510
  ExecuteRemoteOperation(input: { operationKey: $operationKey, inputJSON: $inputJSON, invokeMode: $invokeMode, progressChannelId: $progressChannelId }) {
503
511
  success
504
512
  resultCode
@@ -506,7 +514,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
506
514
  handle
507
515
  errorMessage
508
516
  }
509
- }`;let n,a;r.onProgress&&(n=this.GenerateUUID(),a=this.subscribe(Ne,{channelId:n}).subscribe({next:l(i=>{const o=i?.RemoteOperationProgress?.ProgressJSON;if(o)try{r.onProgress(JSON.parse(o))}catch{}},"next"),error:l(()=>{},"error")}),await new Promise(i=>setTimeout(i,400)));try{const o=(await this.ExecuteGQL(s,{operationKey:e,inputJSON:JSON.stringify(t??null),invokeMode:r.mode??"attached",progressChannelId:n??null}))?.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(i){return{Success:!1,ResultCode:"TRANSPORT_ERROR",ErrorMessage:i instanceof Error?i.message:String(i)}}finally{a?.unsubscribe()}}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=c`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
517
+ }`;let n,a;r.onProgress&&(n=this.GenerateUUID(),a=this.subscribe(Ne,{channelId:n}).subscribe({next:d(i=>{const o=i?.RemoteOperationProgress?.ProgressJSON;if(o)try{r.onProgress(JSON.parse(o))}catch{}},"next"),error:d(()=>{},"error")}),await new Promise(i=>setTimeout(i,400)));try{const o=(await this.ExecuteGQL(s,{operationKey:e,inputJSON:JSON.stringify(t??null),invokeMode:r.mode??"attached",progressChannelId:n??null}))?.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(i){return{Success:!1,ResultCode:"TRANSPORT_ERROR",ErrorMessage:i instanceof Error?i.message:String(i)}}finally{a?.unsubscribe()}}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=c`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
510
518
  MergeRecords(request: $request) {
511
519
  Success
512
520
  OverallStatus
@@ -523,32 +531,32 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
523
531
  Message
524
532
  }
525
533
  }
526
- }`,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 u(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 G;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 G;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(m=>({FieldName:m.CodeName,Value:m.Value})),e.RegisterResultHistoryEntry(s);const i=T(e.EntityInfo),o=`${a}${i}`,y=e.Fields.filter(m=>!m.ReadOnly||m.IsPrimaryKey&&e.IsSaved),d=` ${o}(input: $input) {
534
+ }`,a={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(o=>({FieldName:o.FieldName,Value:o.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(o=>o.Copy())};return(await this.ExecuteGQL(n,{request:a}))?.MergeRecords}catch(n){return l(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){if(r?.IsParentEntitySave){const n=new U;return n.StartedAt=new Date,n.EndedAt=new Date,n.Type=e.IsSaved?"update":"create",n.Success=!0,n.NewValues=e.GetAll(),e.RegisterResultHistoryEntry(n),n.NewValues}const s=new U;try{e.RegisterTransactionPreprocessing();const n={input:{}},a=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(m=>({FieldName:m.CodeName,Value:m.Value})),e.RegisterResultHistoryEntry(s);const i=T(e.EntityInfo),o=`${a}${i}`,y=e.Fields.filter(m=>!m.ReadOnly||m.IsPrimaryKey&&e.IsSaved),u=` ${o}(input: $input) {
527
535
  ${e.Fields.map(m=>b.MapFieldName(m.CodeName)).join(`
528
536
  `)}
529
- }`,f=c`mutation ${a}${i} ($input: ${o}Input!) {
530
- ${d}
537
+ }`,h=c`mutation ${a}${i} ($input: ${o}Input!) {
538
+ ${u}
531
539
  }
532
- `;for(let m=0;m<y.length;m++){const p=y[m];let S=e.Get(p.Name);if(S)switch(p.EntityFieldInfo.TSType){case N.Date:S=S.getTime();break;case N.Boolean:typeof S!="boolean"&&(S=parseInt(S)!==0);break;case N.Number:if(typeof S!="number"){const R=Number(S);isNaN(R)||(S=R)}break}S===null&&p.EntityFieldInfo.AllowsNull===!1&&(p.EntityFieldInfo.DefaultValue!==null?S=p.EntityFieldInfo.DefaultValue:p.FieldType===N.Number||p.FieldType===N.Boolean?S=0:S=""),n.input[b.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 m=[];e.Fields.forEach(p=>{let S=null;p.OldValue!==null&&p.OldValue!==void 0&&(p.EntityFieldInfo.TSType===N.Date?S=p.OldValue.getTime().toString():p.EntityFieldInfo.TSType===N.Boolean?S=p.OldValue===!0?"1":"0":typeof p.OldValue!="string"?S=p.OldValue.toString():S=p.OldValue),m.push({Key:b.MapFieldName(p.CodeName),Value:S})}),n.input.OldValues___=m}if(e.TransactionGroup){const m=[{varName:"input",inputType:o+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new K(e,s.Type==="create"?"Create":"Update",d,n,{mutationName:o,mutationInputTypes:m},(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 m=await this.ExecuteGQL(f,n);if(m&&m[o])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(m[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,u(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 m=e.Fields.find(R=>R.Name.trim().toLowerCase()===t.KeyValuePairs[I].FieldName.trim().toLowerCase()).EntityFieldInfo,p=t.GetValueByIndex(I),S=m.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${m.CodeName}: ${S}!`,a.length>0&&(a+=", "),a+=`${m.CodeName}: $${m.CodeName}`,m.TSType===N.Number){if(isNaN(t.GetValueByIndex(I)))throw new Error(`Primary Key value ${p} (${m.Name}) is not a valid number`);n[m.CodeName]=parseInt(p)}else n[m.CodeName]=p}const o=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",y=T(e.EntityInfo),d=c`query Single${y}${o.length>0?"Full":""} (${i}) {
540
+ `;for(let m=0;m<y.length;m++){const p=y[m];let S=e.Get(p.Name);if(S)switch(p.EntityFieldInfo.TSType){case N.Date:S=S.getTime();break;case N.Boolean:typeof S!="boolean"&&(S=parseInt(S)!==0);break;case N.Number:if(typeof S!="number"){const R=Number(S);isNaN(R)||(S=R)}break}S===null&&p.EntityFieldInfo.AllowsNull===!1&&(p.EntityFieldInfo.DefaultValue!==null?S=p.EntityFieldInfo.DefaultValue:p.FieldType===N.Number||p.FieldType===N.Boolean?S=0:S=""),n.input[b.MapFieldName(p.CodeName)]=S}const f=e.RestoreContext;if(f&&(n.input.RestoreContext___={SourceChangeID:f.SourceChangeID,Reason:f.Reason}),a.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const m=[];e.Fields.forEach(p=>{let S=null;p.OldValue!==null&&p.OldValue!==void 0&&(p.EntityFieldInfo.TSType===N.Date?S=p.OldValue.getTime().toString():p.EntityFieldInfo.TSType===N.Boolean?S=p.OldValue===!0?"1":"0":typeof p.OldValue!="string"?S=p.OldValue.toString():S=p.OldValue),m.push({Key:b.MapFieldName(p.CodeName),Value:S})}),n.input.OldValues___=m}if(e.TransactionGroup){const m=[{varName:"input",inputType:o+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new K(e,s.Type==="create"?"Create":"Update",u,n,{mutationName:o,mutationInputTypes:m},(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 m=await this.ExecuteGQL(h,n);if(m&&m[o])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(m[o]),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(n){return s.Success=!1,s.EndedAt=new Date,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,l(n),null}}async Load(e,t,r=null,s){try{const n={};let a="",i="";for(let f=0;f<t.KeyValuePairs.length;f++){const m=e.Fields.find(R=>R.Name.trim().toLowerCase()===t.KeyValuePairs[f].FieldName.trim().toLowerCase()).EntityFieldInfo,p=t.GetValueByIndex(f),S=m.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${m.CodeName}: ${S}!`,a.length>0&&(a+=", "),a+=`${m.CodeName}: $${m.CodeName}`,m.TSType===N.Number){if(isNaN(t.GetValueByIndex(f)))throw new Error(`Primary Key value ${p} (${m.Name}) is not a valid number`);n[m.CodeName]=parseInt(p)}else n[m.CodeName]=p}const o=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",y=T(e.EntityInfo),u=c`query Single${y}${o.length>0?"Full":""} (${i}) {
533
541
  ${y}(${a}) {
534
- ${e.Fields.filter(I=>!I.EntityFieldInfo.IsBinaryFieldType).map(I=>I.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?I.CodeName.replace("__mj_","_mj__"):I.CodeName).join(`
542
+ ${e.Fields.filter(f=>!f.EntityFieldInfo.IsBinaryFieldType).map(f=>f.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?f.CodeName.replace("__mj_","_mj__"):f.CodeName).join(`
535
543
  `)}
536
544
  ${o}
537
545
  }
538
546
  }
539
- `,f=await this.ExecuteGQL(d,n);return f&&f[y]?this.ConvertBackToMJFields(f[y]):null}catch(n){return u(n),null}}ConvertBackToMJFields(e){return b.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+=`
547
+ `,h=await this.ExecuteGQL(u,n);return h&&h[y]?this.ConvertBackToMJFields(h[y]):null}catch(n){return l(n),null}}ConvertBackToMJFields(e){return b.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+=`
540
548
  ${i} {
541
549
  ${a.Fields.map(o=>o.CodeName).join(`
542
550
  `)}
543
551
  }
544
- `}return r}async Delete(e,t,r){const s=new G;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(R=>R.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+=`
545
- `),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"+T(e.EntityInfo),I=c`${f}(${i}, options___: $options___) {
552
+ `}return r}async Delete(e,t,r){const s=new U;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(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(R=>R.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+=`
553
+ `),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 h="Delete"+T(e.EntityInfo),f=c`${h}(${i}, options___: $options___) {
546
554
  ${y}
547
555
  }
548
- `,m=c`mutation ${f} (${o}, $options___: DeleteOptionsInput!) {
549
- ${I}
556
+ `,m=c`mutation ${h} (${o}, $options___: DeleteOptionsInput!) {
557
+ ${f}
550
558
  }
551
- `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new K(e,"Delete",I,n,{mutationName:f,mutationInputTypes:a},(p,S)=>{if(s.EndedAt=new Date,S&&p){let R=!0;for(const E of e.PrimaryKey.KeyValuePairs)E.Value!==p[E.FieldName]&&(R=!1);R?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const p=await this.ExecuteGQL(m,n);if(p&&p[f]){const S=p[f];for(let R of e.PrimaryKey.KeyValuePairs){let E=S[R.FieldName],C=R.Value;if(typeof C=="number"&&(C=C.toString()),typeof E=="number"&&(E=E.toString()),C!==E)throw new Error(`Primary key value mismatch in server Delete response. Field: ${R.FieldName}, Original: ${C}, Returned: ${E}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(n){return s.EndedAt=new Date,s.Success=!1,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,u(n),!1}}async GetDatasetByName(e,t){const r=c`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
559
+ `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new K(e,"Delete",f,n,{mutationName:h,mutationInputTypes:a},(p,S)=>{if(s.EndedAt=new Date,S&&p){let R=!0;for(const E of e.PrimaryKey.KeyValuePairs)E.Value!==p[E.FieldName]&&(R=!1);R?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const p=await this.ExecuteGQL(m,n);if(p&&p[h]){const S=p[h];for(let R of e.PrimaryKey.KeyValuePairs){let E=S[R.FieldName],C=R.Value;if(typeof C=="number"&&(C=C.toString()),typeof E=="number"&&(E=E.toString()),C!==E)throw new Error(`Primary key value mismatch in server Delete response. Field: ${R.FieldName}, Original: ${C}, Returned: ${E}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(n){return s.EndedAt=new Date,s.Success=!1,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,l(n),!1}}async GetDatasetByName(e,t){const r=c`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
552
560
  GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
553
561
  DatasetID
554
562
  DatasetName
@@ -557,7 +565,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
557
565
  LatestUpdateDate
558
566
  Results
559
567
  }
560
- }`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetByName&&s.GetDatasetByName.Success?{DatasetID:s.GetDatasetByName.DatasetID,DatasetName:s.GetDatasetByName.DatasetName,Success:s.GetDatasetByName.Success,Status:s.GetDatasetByName.Status,LatestUpdateDate:new Date(s.GetDatasetByName.LatestUpdateDate),Results:JSON.parse(s.GetDatasetByName.Results)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,Results:null}}static{this._datasetStatusQueue=[]}static{this._datasetStatusTimer=null}static{this._datasetStatusCoalesceMs=10}async GetDatasetStatusByName(e,t){return h._datasetStatusCoalesceMs>0&&!t?this.enqueueDatasetStatusCheck(e):this.executeDatasetStatusByName(e,t)}enqueueDatasetStatusCheck(e){return new Promise((t,r)=>{h._datasetStatusQueue.push({datasetName:e,resolve:t,reject:r}),h._datasetStatusTimer||(h._datasetStatusTimer=setTimeout(()=>this.flushDatasetStatusQueue(),h._datasetStatusCoalesceMs))})}async flushDatasetStatusQueue(){h._datasetStatusTimer=null;const e=h._datasetStatusQueue.splice(0);if(e.length===0)return;if(e.length===1){try{const r=await this.executeDatasetStatusByName(e[0].datasetName,e[0].itemFilters);e[0].resolve(r)}catch(r){e[0].reject(r)}return}const t=e.map(r=>r.datasetName);M(`\u26A1 [Coalesce] Batching ${t.length} dataset status checks into 1 request: [${t.join(", ")}]`);try{const r=c`query GetMultipleDatasetStatusByName($DatasetNames: [String!]!) {
568
+ }`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetByName&&s.GetDatasetByName.Success?{DatasetID:s.GetDatasetByName.DatasetID,DatasetName:s.GetDatasetByName.DatasetName,Success:s.GetDatasetByName.Success,Status:s.GetDatasetByName.Status,LatestUpdateDate:new Date(s.GetDatasetByName.LatestUpdateDate),Results:JSON.parse(s.GetDatasetByName.Results)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,Results:null}}static{this._datasetStatusQueue=[]}static{this._datasetStatusTimer=null}static{this._datasetStatusCoalesceMs=10}async GetDatasetStatusByName(e,t){return I._datasetStatusCoalesceMs>0&&!t?this.enqueueDatasetStatusCheck(e):this.executeDatasetStatusByName(e,t)}enqueueDatasetStatusCheck(e){return new Promise((t,r)=>{I._datasetStatusQueue.push({datasetName:e,resolve:t,reject:r}),I._datasetStatusTimer||(I._datasetStatusTimer=setTimeout(()=>this.flushDatasetStatusQueue(),I._datasetStatusCoalesceMs))})}async flushDatasetStatusQueue(){I._datasetStatusTimer=null;const e=I._datasetStatusQueue.splice(0);if(e.length===0)return;if(e.length===1){try{const r=await this.executeDatasetStatusByName(e[0].datasetName,e[0].itemFilters);e[0].resolve(r)}catch(r){e[0].reject(r)}return}const t=e.map(r=>r.datasetName);A(`\u26A1 [Coalesce] Batching ${t.length} dataset status checks into 1 request: [${t.join(", ")}]`);try{const r=c`query GetMultipleDatasetStatusByName($DatasetNames: [String!]!) {
561
569
  GetMultipleDatasetStatusByName(DatasetNames: $DatasetNames) {
562
570
  DatasetID
563
571
  DatasetName
@@ -566,7 +574,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
566
574
  LatestUpdateDate
567
575
  EntityUpdateDates
568
576
  }
569
- }`,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){u(`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=c`query GetDatasetStatusByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
577
+ }`,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){l(`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=c`query GetDatasetStatusByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
570
578
  GetDatasetStatusByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
571
579
  DatasetID
572
580
  DatasetName
@@ -609,22 +617,22 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
609
617
  ErrorMessages
610
618
  Results
611
619
  }
612
- }`,r=await this.ExecuteGQL(t,{DataContextID:e});if(r&&r.GetDataContextData){if(r.GetDataContextData.Success)return r.GetDataContextData.Results.map(s=>JSON.parse(s));throw new Error(r.GetDataContextData.ErrorMessages.join(", "))}else throw new Error("GraphQL query failed")}catch(t){throw u(t),t}}async GetDataContextItemData(e){try{const t=c`query GetDataContextItemData ($DataContextItemID: String!) {
620
+ }`,r=await this.ExecuteGQL(t,{DataContextID:e});if(r&&r.GetDataContextData){if(r.GetDataContextData.Success)return r.GetDataContextData.Results.map(s=>JSON.parse(s));throw new Error(r.GetDataContextData.ErrorMessages.join(", "))}else throw new Error("GraphQL query failed")}catch(t){throw l(t),t}}async GetDataContextItemData(e){try{const t=c`query GetDataContextItemData ($DataContextItemID: String!) {
613
621
  GetDataContextItemData(DataContextItemID: $DataContextItemID) {
614
622
  Success
615
623
  ErrorMessage
616
624
  Result
617
625
  }
618
- }`,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 u(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 u("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw u(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 k(e,{headers:a});for(const[o,y]of this._dynamicHeaders)i.setHeader(o,y);return i}userInfoString(){return this.infoString(new q(null,null))}userRoleInfoString(){return this.infoString(new ue(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
626
+ }`,r=await this.ExecuteGQL(t,{DataContextItemID:e});if(r&&r.GetDataContextItemData){if(r.GetDataContextItemData.Success)return JSON.parse(r.GetDataContextItemData.Result);throw new Error(r.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw l(t),t}}static async ExecuteGQL(e,t,r=!0){return I.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(console.error("[GraphQL] ExecuteGQL error caught:",{hasResponse:!!s?.response,hasErrors:!!s?.response?.errors,errorCount:s?.response?.errors?.length,firstError:s?.response?.errors?.[0],errorCode:s?.response?.errors?.[0]?.extensions?.code,errorMessage:s?.response?.errors?.[0]?.message,fullError:s}),s&&s.response&&s.response.errors?.length>0)if(s.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw l("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw l(s),s}}async RefreshToken(){const e=I.Instance&&I.Instance._configData===this._configData;if(e&&I.Instance._refreshPromise)return I.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(I.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&I.Instance&&(I.Instance._refreshPromise=null)}}async performTokenRefresh(){if(this._configData.Data.RefreshTokenFunction)try{const e=await this._configData.Data.RefreshTokenFunction();if(e){this._configData.Token=e;const t=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey,this._configData.UserAPIKey);this._client=t,I.Instance&&I.Instance._configData===this._configData&&(I.Instance._client=t)}else{const t=new Error("Refresh token function returned null or undefined token");throw this.notifyAuthenticationError(t),t}}catch(e){const t=e instanceof Error?e:new Error(String(e));throw this.notifyAuthenticationError(t),e}else{const e=new Error("No refresh token function provided");throw this.notifyAuthenticationError(e),e}}notifyAuthenticationError(e){try{const t=this._configData?.OnAuthenticationError;t&&t(e)}catch(t){console.error("[GraphQLDataProvider] Error in OnAuthenticationError callback:",t)}}static async RefreshToken(){return I.Instance.RefreshToken()}static async clearClientCache(e=new Set){const t=[];for(let r=0;r<localStorage.length;r++){const s=localStorage.key(r);s&&!e.has(s)&&t.push(s)}t.forEach(r=>localStorage.removeItem(r)),await new Promise(r=>{const s=indexedDB.deleteDatabase("MJ_Metadata");s.onsuccess=()=>r(),s.onerror=()=>r(),s.onblocked=()=>r()})}CreateNewGraphQLClient(e,t,r,s,n){const a={"x-session-id":r};t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),n&&(a["x-api-key"]=n);const i=new k(e,{headers:a});for(const[o,y]of this._dynamicHeaders)i.setHeader(o,y);return i}userInfoString(){return this.infoString(new q(null,null))}userRoleInfoString(){return this.infoString(new ue(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
619
627
  `:s.startsWith("_")||(t+=s+`
620
- `);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new Z:this._localStorageProvider=new le),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=Ee({url:this.ConfigData.WSURL,connectionParams:l(()=>({Authorization:"Bearer "+this.ConfigData.Token,...this.ConfigData.MJAPIKey?{"x-mj-api-key":this.ConfigData.MJAPIKey}:{},...this.ConfigData.UserAPIKey?{"x-mj-user-api-key":this.ConfigData.UserAPIKey}:{}}),"connectionParams"),keepAlive:3e4,retryAttempts:3,shouldRetry:l(()=>!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 x(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=s.subscribe({query:e,variables:t},{next:l(a=>{r.next(a.data)},"next"),error:l(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:l(()=>{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 x(o=>{r.activeSubscribers++;const y=r.subject.subscribe(o);return()=>{const d=this._pushStatusSubjects.get(e);d&&d.activeSubscribers>0&&d.activeSubscribers--,y.unsubscribe()}});const s=c`subscription StatusUpdates($sessionId: String!) {
628
+ `);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new Z:this._localStorageProvider=new le),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=Ee({url:this.ConfigData.WSURL,connectionParams:d(()=>({Authorization:"Bearer "+this.ConfigData.Token,...this.ConfigData.MJAPIKey?{"x-mj-api-key":this.ConfigData.MJAPIKey}:{},...this.ConfigData.UserAPIKey?{"x-mj-user-api-key":this.ConfigData.UserAPIKey}:{}}),"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 x(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 x(o=>{r.activeSubscribers++;const y=r.subject.subscribe(o);return()=>{const u=this._pushStatusSubjects.get(e);u&&u.activeSubscribers>0&&u.activeSubscribers--,y.unsubscribe()}});const s=c`subscription StatusUpdates($sessionId: String!) {
621
629
  statusUpdates(sessionId: $sessionId) {
622
630
  date
623
631
  message
624
632
  sessionId
625
633
  }
626
634
  }
627
- `,n=new fe,a=this.getOrCreateWSClient(),i=new Re;return i.add(new x(o=>{const y=a.subscribe({query:s,variables:{sessionId:e}},{next:l(d=>{const f=this._pushStatusSubjects.get(e);f&&(f.lastEmissionAt=Date.now()),o.next(d.data.statusUpdates.message)},"next"),error:l(async d=>{const f=d;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(m){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",m),o.error(m)}}else o.error(d)},"error"),complete:l(()=>{o.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,y()}}).subscribe({next:l(o=>n.next(o),"next"),error:l(o=>{n.error(o),this._pushStatusSubjects.delete(e)},"error"),complete:l(()=>{n.complete(),this._pushStatusSubjects.delete(e)},"complete")})),this._pushStatusSubjects.set(e,{subject:n,subscription:i,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new x(o=>{const y=this._pushStatusSubjects.get(e);y&&y.activeSubscribers++;const d=n.subscribe(o);return()=>{const f=this._pushStatusSubjects.get(e);f&&f.activeSubscribers>0&&f.activeSubscribers--,d.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.UnsubscribeFromCacheInvalidation(),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}ClientToolRequests(e){return this.subscribe(`
635
+ `,n=new fe,a=this.getOrCreateWSClient(),i=new Re;return i.add(new x(o=>{const y=a.subscribe({query:s,variables:{sessionId:e}},{next:d(u=>{const h=this._pushStatusSubjects.get(e);h&&(h.lastEmissionAt=Date.now()),o.next(u.data.statusUpdates.message)},"next"),error:d(async u=>{const h=u;if(h?.extensions?.code==="JWT_EXPIRED"||h?.message?.includes("token has expired")||h?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),o.complete()}catch(m){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",m),o.error(m)}}else o.error(u)},"error"),complete:d(()=>{o.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,y()}}).subscribe({next:d(o=>n.next(o),"next"),error:d(o=>{n.error(o),this._pushStatusSubjects.delete(e)},"error"),complete:d(()=>{n.complete(),this._pushStatusSubjects.delete(e)},"complete")})),this._pushStatusSubjects.set(e,{subject:n,subscription:i,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new x(o=>{const y=this._pushStatusSubjects.get(e);y&&y.activeSubscribers++;const u=n.subscribe(o);return()=>{const h=this._pushStatusSubjects.get(e);h&&h.activeSubscribers>0&&h.activeSubscribers--,u.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.UnsubscribeFromCacheInvalidation(),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}ClientToolRequests(e){return this.subscribe(`
628
636
  subscription ClientToolRequest($sessionID: String!) {
629
637
  ClientToolRequest(sessionID: $sessionID) {
630
638
  AgentRunID
@@ -646,26 +654,26 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
646
654
  OriginSessionID
647
655
  RecordData
648
656
  }
649
- }`,t=this.subscribe(e);this._cacheInvalidationSubscription=t.subscribe({next:l(r=>{const s=r?.cacheInvalidation;if(!s)return;if(s.OriginSessionID&&s.OriginSessionID===this.sessionId){h.VerboseCacheInvalidationLogging&&console.debug(`[GraphQLDataProvider] Skipping self-originated cache invalidation for "${s.EntityName}" (action: ${s.Action})`);return}h.VerboseCacheInvalidationLogging&&console.debug(`[GraphQLDataProvider] Cache invalidation received: ${s.Action} for "${s.EntityName}" from server ${s.SourceServerID?.substring(0,8)||"unknown"}`);const n={type:"remote-invalidate",entityName:s.EntityName,baseEntity:null,provider:this,payload:{primaryKeyValues:s.PrimaryKeyValues,action:s.Action,sourceServerId:s.SourceServerID,timestamp:s.Timestamp,recordData:s.RecordData}};j.Instance.RaiseEvent({event:J.ComponentEvent,eventCode:de.BaseEventCode,args:n,component:this})},"next"),error:l(r=>{console.error("[GraphQLDataProvider] Cache invalidation subscription error:",r),this._cacheInvalidationSubscription=null},"error"),complete:l(()=>{console.log("[GraphQLDataProvider] Cache invalidation subscription completed, will re-establish on next WebSocket creation"),this._cacheInvalidationSubscription=null},"complete")})}UnsubscribeFromCacheInvalidation(){this._cacheInvalidationSubscription&&(this._cacheInvalidationSubscription.unsubscribe(),this._cacheInvalidationSubscription=null)}async FindISAChildEntity(e,t,r){if(!e.IsParentType)return null;const s=`query FindISAChildEntity($EntityName: String!, $RecordID: String!) {
657
+ }`,t=this.subscribe(e);this._cacheInvalidationSubscription=t.subscribe({next:d(r=>{const s=r?.cacheInvalidation;if(!s)return;if(s.OriginSessionID&&s.OriginSessionID===this.sessionId){I.VerboseCacheInvalidationLogging&&console.debug(`[GraphQLDataProvider] Skipping self-originated cache invalidation for "${s.EntityName}" (action: ${s.Action})`);return}I.VerboseCacheInvalidationLogging&&console.debug(`[GraphQLDataProvider] Cache invalidation received: ${s.Action} for "${s.EntityName}" from server ${s.SourceServerID?.substring(0,8)||"unknown"}`);const n={type:"remote-invalidate",entityName:s.EntityName,baseEntity:null,provider:this,payload:{primaryKeyValues:s.PrimaryKeyValues,action:s.Action,sourceServerId:s.SourceServerID,timestamp:s.Timestamp,recordData:s.RecordData}};j.Instance.RaiseEvent({event:J.ComponentEvent,eventCode:de.BaseEventCode,args:n,component:this})},"next"),error:d(r=>{console.error("[GraphQLDataProvider] Cache invalidation subscription error:",r),this._cacheInvalidationSubscription=null},"error"),complete:d(()=>{console.log("[GraphQLDataProvider] Cache invalidation subscription completed, will re-establish on next WebSocket creation"),this._cacheInvalidationSubscription=null},"complete")})}UnsubscribeFromCacheInvalidation(){this._cacheInvalidationSubscription&&(this._cacheInvalidationSubscription.unsubscribe(),this._cacheInvalidationSubscription=null)}async FindISAChildEntity(e,t,r){if(!e.IsParentType)return null;const s=`query FindISAChildEntity($EntityName: String!, $RecordID: String!) {
650
658
  FindISAChildEntity(EntityName: $EntityName, RecordID: $RecordID) {
651
659
  Success
652
660
  ChildEntityName
653
661
  ErrorMessage
654
662
  }
655
- }`;try{const n=await this.ExecuteGQL(s,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntity?.Success&&n.FindISAChildEntity.ChildEntityName?{ChildEntityName:n.FindISAChildEntity.ChildEntityName}:null}catch(n){return u(`FindISAChildEntity failed for ${e.Name}: ${n}`),null}}async FindISAChildEntities(e,t,r){if(!e.IsParentType)return[];const s=`query FindISAChildEntities($EntityName: String!, $RecordID: String!) {
663
+ }`;try{const n=await this.ExecuteGQL(s,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntity?.Success&&n.FindISAChildEntity.ChildEntityName?{ChildEntityName:n.FindISAChildEntity.ChildEntityName}:null}catch(n){return l(`FindISAChildEntity failed for ${e.Name}: ${n}`),null}}async FindISAChildEntities(e,t,r){if(!e.IsParentType)return[];const s=`query FindISAChildEntities($EntityName: String!, $RecordID: String!) {
656
664
  FindISAChildEntities(EntityName: $EntityName, RecordID: $RecordID) {
657
665
  Success
658
666
  ChildEntityNames
659
667
  ErrorMessage
660
668
  }
661
- }`;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 u(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function Te(g){const e=new h;return me(e),await e.Config(g),await e.preValidateAndRefresh(),j.Instance.RaiseEvent({event:J.LoggedIn,eventCode:null,component:this,args:null}),await ge.Instance.Startup(),e}l(Te,"setupGraphQLClient");class xe{static{l(this,"SyncRolesAndUsersResult")}}class Le{static{l(this,"RoleInput")}}class Fe{static{l(this,"UserInput")}}class Qe{static{l(this,"RolesAndUsersInput")}}var ee=(g=>(g.Create="Create",g.Update="Update",g.CreateOrUpdate="CreateOrUpdate",g.Delete="Delete",g.DeleteWithFilter="DeleteWithFilter",g))(ee||{});class Ue{static{l(this,"ActionItemInput")}}class Ge{static{l(this,"SyncDataResult")}constructor(){this.Results=[]}}class Ve{static{l(this,"ActionItemOutput")}}class _e{static{l(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 k(e,{headers:n})}resolvePlatformSQL(e){if(e!=null)return Se(e)?e.default:e}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
669
+ }`;try{const n=await this.ExecuteGQL(s,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntities?.Success&&n.FindISAChildEntities.ChildEntityNames?n.FindISAChildEntities.ChildEntityNames.map(a=>({ChildEntityName:a})):[]}catch(n){return l(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function Te(g){const e=new I;return me(e),await e.Config(g),await e.preValidateAndRefresh(),j.Instance.RaiseEvent({event:J.LoggedIn,eventCode:null,component:this,args:null}),await ge.Instance.Startup(),e}d(Te,"setupGraphQLClient");class xe{static{d(this,"SyncRolesAndUsersResult")}}class Le{static{d(this,"RoleInput")}}class Fe{static{d(this,"UserInput")}}class Qe{static{d(this,"RolesAndUsersInput")}}var ee=(g=>(g.Create="Create",g.Update="Update",g.CreateOrUpdate="CreateOrUpdate",g.Delete="Delete",g.DeleteWithFilter="DeleteWithFilter",g))(ee||{});class Ge{static{d(this,"ActionItemInput")}}class Ue{static{d(this,"SyncDataResult")}constructor(){this.Results=[]}}class Ve{static{d(this,"ActionItemOutput")}}class _e{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 k(e,{headers:n})}resolvePlatformSQL(e){if(e!=null)return Se(e)?e.default:e}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
662
670
  GetData(input: $input) {
663
671
  Success
664
672
  ErrorMessages
665
673
  Queries
666
674
  Results
667
675
  }
668
- }`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(n=>n?D(n):null),ErrorMessages:s.GetData.ErrorMessages,Queries:s.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:s.GetData?.ErrorMessages??["Unknown error"],Queries:s.GetData?.Queries??e}}catch(r){let s=r instanceof Error?r.message:String(r);const n=s.match(/Error: ([^:]+)\./);if(n&&(s=n[1]+"."),pe()){const a=`GraphQLSystemUserClient::GetData - Error getting data - ${r}`;u(a)}return{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
676
+ }`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(n=>n?D(n):null),ErrorMessages:s.GetData.ErrorMessages,Queries:s.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:s.GetData?.ErrorMessages??["Unknown error"],Queries:s.GetData?.Queries??e}}catch(r){let s=r instanceof Error?r.message:String(r);const n=s.match(/Error: ([^:]+)\./);if(n&&(s=n[1]+"."),pe()){const a=`GraphQLSystemUserClient::GetData - Error getting data - ${r}`;l(a)}return{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
669
677
  GetAllEntities {
670
678
  Success
671
679
  ErrorMessage
@@ -688,7 +696,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
688
696
  }
689
697
  }
690
698
  }
691
- }`);return t&&t.GetAllEntities?t.GetAllEntities:{Success:!1,Results:[],ErrorMessage:t.GetAllEntities?.ErrorMessage??"Unknown error"}}catch(e){return u(`GraphQLSystemUserClient::GetAllRemoteEntities - Error getting remote entities - ${e}`),{Success:!1,Results:[],ErrorMessage:e}}}async SyncData(e){try{const r=await this.Client.request(`mutation SyncData($items: [ActionItemInputType!]!) {
699
+ }`);return t&&t.GetAllEntities?t.GetAllEntities:{Success:!1,Results:[],ErrorMessage:t.GetAllEntities?.ErrorMessage??"Unknown error"}}catch(e){return l(`GraphQLSystemUserClient::GetAllRemoteEntities - Error getting remote entities - ${e}`),{Success:!1,Results:[],ErrorMessage:e}}}async SyncData(e){try{const r=await this.Client.request(`mutation SyncData($items: [ActionItemInputType!]!) {
692
700
  SyncData(items: $items) {
693
701
  Success
694
702
  Results {
@@ -712,11 +720,11 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
712
720
  RecordJSON
713
721
  }
714
722
  }
715
- }`,{items:e});return r&&r.SyncData?r.SyncData:{Success:!1,Results:[]}}catch(t){return u(`GraphQLSystemUserClient::SyncData - Error syncing data - ${t}`),{Success:!1,Results:[]}}}async SyncRolesAndUsers(e){try{const r=await this.Client.request(`mutation SyncRolesAndUsers($data: RolesAndUsersInputType!) {
723
+ }`,{items:e});return r&&r.SyncData?r.SyncData:{Success:!1,Results:[]}}catch(t){return l(`GraphQLSystemUserClient::SyncData - Error syncing data - ${t}`),{Success:!1,Results:[]}}}async SyncRolesAndUsers(e){try{const r=await this.Client.request(`mutation SyncRolesAndUsers($data: RolesAndUsersInputType!) {
716
724
  SyncRolesAndUsers(data: $data) {
717
725
  Success
718
726
  }
719
- }`,{data:e});return r&&r.SyncRolesAndUsers?r.SyncRolesAndUsers:{Success:!1}}catch(t){return u(`GraphQLSystemUserClient::SyncRolesAndUsers - Error syncing roles and users - ${t}`),{Success:!1}}}async RunViewByName(e){try{const t=`query RunViewByNameSystemUser($input: RunViewByNameInput!) {
727
+ }`,{data:e});return r&&r.SyncRolesAndUsers?r.SyncRolesAndUsers:{Success:!1}}catch(t){return l(`GraphQLSystemUserClient::SyncRolesAndUsers - Error syncing roles and users - ${t}`),{Success:!1}}}async RunViewByName(e){try{const t=`query RunViewByNameSystemUser($input: RunViewByNameInput!) {
720
728
  RunViewByNameSystemUser(input: $input) {
721
729
  Results {
722
730
  PrimaryKey {
@@ -733,7 +741,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
733
741
  ErrorMessage
734
742
  Success
735
743
  }
736
- }`,r={...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)},s=await this.Client.request(t,{input:r});return s&&s.RunViewByNameSystemUser?s.RunViewByNameSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by name"}}catch(t){return u(`GraphQLSystemUserClient::RunViewByNameSystemUser - Error running view by name - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViewByID(e){try{const t=`query RunViewByIDSystemUser($input: RunViewByIDInput!) {
744
+ }`,r={...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)},s=await this.Client.request(t,{input:r});return s&&s.RunViewByNameSystemUser?s.RunViewByNameSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by name"}}catch(t){return l(`GraphQLSystemUserClient::RunViewByNameSystemUser - Error running view by name - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViewByID(e){try{const t=`query RunViewByIDSystemUser($input: RunViewByIDInput!) {
737
745
  RunViewByIDSystemUser(input: $input) {
738
746
  Results {
739
747
  PrimaryKey {
@@ -750,7 +758,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
750
758
  ErrorMessage
751
759
  Success
752
760
  }
753
- }`,r={...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)},s=await this.Client.request(t,{input:r});return s&&s.RunViewByIDSystemUser?s.RunViewByIDSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by ID"}}catch(t){return u(`GraphQLSystemUserClient::RunViewByIDSystemUser - Error running view by ID - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunDynamicView(e){try{const t=`query RunDynamicViewSystemUser($input: RunDynamicViewInput!) {
761
+ }`,r={...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)},s=await this.Client.request(t,{input:r});return s&&s.RunViewByIDSystemUser?s.RunViewByIDSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by ID"}}catch(t){return l(`GraphQLSystemUserClient::RunViewByIDSystemUser - Error running view by ID - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunDynamicView(e){try{const t=`query RunDynamicViewSystemUser($input: RunDynamicViewInput!) {
754
762
  RunDynamicViewSystemUser(input: $input) {
755
763
  Results {
756
764
  PrimaryKey {
@@ -767,7 +775,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
767
775
  ErrorMessage
768
776
  Success
769
777
  }
770
- }`,r={...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)},s=await this.Client.request(t,{input:r});return s&&s.RunDynamicViewSystemUser?s.RunDynamicViewSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute dynamic view"}}catch(t){return u(`GraphQLSystemUserClient::RunDynamicViewSystemUser - Error running dynamic view - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViews(e){try{const t=`query RunViewsSystemUser($input: [RunViewGenericInput!]!) {
778
+ }`,r={...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)},s=await this.Client.request(t,{input:r});return s&&s.RunDynamicViewSystemUser?s.RunDynamicViewSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute dynamic view"}}catch(t){return l(`GraphQLSystemUserClient::RunDynamicViewSystemUser - Error running dynamic view - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViews(e){try{const t=`query RunViewsSystemUser($input: [RunViewGenericInput!]!) {
771
779
  RunViewsSystemUser(input: $input) {
772
780
  Results {
773
781
  PrimaryKey {
@@ -784,8 +792,8 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
784
792
  ErrorMessage
785
793
  Success
786
794
  }
787
- }`,r=e.map(n=>({...n,ExtraFilter:this.resolvePlatformSQL(n.ExtraFilter),OrderBy:this.resolvePlatformSQL(n.OrderBy)})),s=await this.Client.request(t,{input:r});return s&&s.RunViewsSystemUser?s.RunViewsSystemUser:[]}catch(t){return u(`GraphQLSystemUserClient::RunViewsSystemUser - Error running views - ${t}`),[]}}async GetQueryData(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataSystemUser($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
788
- GetQueryDataSystemUser(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
795
+ }`,r=e.map(n=>({...n,ExtraFilter:this.resolvePlatformSQL(n.ExtraFilter),OrderBy:this.resolvePlatformSQL(n.OrderBy)})),s=await this.Client.request(t,{input:r});return s&&s.RunViewsSystemUser?s.RunViewsSystemUser:[]}catch(t){return l(`GraphQLSystemUserClient::RunViewsSystemUser - Error running views - ${t}`),[]}}async GetQueryData(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataSystemUser($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int, $Enrichment: JSONObject) {
796
+ GetQueryDataSystemUser(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow, Enrichment: $Enrichment) {
789
797
  QueryID
790
798
  QueryName
791
799
  Success
@@ -796,8 +804,8 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
796
804
  ErrorMessage
797
805
  AppliedParameters
798
806
  }
799
- }`,r={QueryID:e.QueryID};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataSystemUser?{...s.GetQueryDataSystemUser,Results:s.GetQueryDataSystemUser.Results?D(s.GetQueryDataSystemUser.Results):null}:{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return u(`GraphQLSystemUserClient::GetQueryDataSystemUser - Error executing query - ${t}`),{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async GetQueryDataByName(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataByNameSystemUser($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
800
- GetQueryDataByNameSystemUser(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
807
+ }`,r={QueryID:e.QueryID};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow),e.Enrichment!==void 0&&(r.Enrichment=e.Enrichment);const s=await this.Client.request(t,r);return s&&s.GetQueryDataSystemUser?{...s.GetQueryDataSystemUser,Results:s.GetQueryDataSystemUser.Results?D(s.GetQueryDataSystemUser.Results):null}:{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return l(`GraphQLSystemUserClient::GetQueryDataSystemUser - Error executing query - ${t}`),{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async GetQueryDataByName(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataByNameSystemUser($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int, $Enrichment: JSONObject) {
808
+ GetQueryDataByNameSystemUser(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow, Enrichment: $Enrichment) {
801
809
  QueryID
802
810
  QueryName
803
811
  Success
@@ -808,8 +816,8 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
808
816
  ErrorMessage
809
817
  AppliedParameters
810
818
  }
811
- }`,r={QueryName:e.QueryName};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataByNameSystemUser?{...s.GetQueryDataByNameSystemUser,Results:s.GetQueryDataByNameSystemUser.Results?D(s.GetQueryDataByNameSystemUser.Results):null}:{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return u(`GraphQLSystemUserClient::GetQueryDataByNameSystemUser - Error executing query - ${t}`),{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async CreateQuery(e){try{const r=await this.Client.request(`mutation CreateQuerySystemUser($input: CreateQuerySystemUserInput!) {
812
- CreateQuerySystemUser(input: $input) {
819
+ }`,r={QueryName:e.QueryName};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow),e.Enrichment!==void 0&&(r.Enrichment=e.Enrichment);const s=await this.Client.request(t,r);return s&&s.GetQueryDataByNameSystemUser?{...s.GetQueryDataByNameSystemUser,Results:s.GetQueryDataByNameSystemUser.Results?D(s.GetQueryDataByNameSystemUser.Results):null}:{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return l(`GraphQLSystemUserClient::GetQueryDataByNameSystemUser - Error executing query - ${t}`),{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async CreateQuery(e){try{const r=await this.Client.request(`mutation CreateQueryExtended($input: CreateQuerySystemUserInput!) {
820
+ CreateQueryExtended(input: $input) {
813
821
  Success
814
822
  ErrorMessage
815
823
  Query {
@@ -867,8 +875,8 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
867
875
  }
868
876
  }
869
877
  }
870
- }`,{input:e});return r&&r.CreateQuerySystemUser?r.CreateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to create query"}}catch(t){return u(`GraphQLSystemUserClient::CreateQuery - Error creating query - ${t}`),{Success:!1,ErrorMessage:t.toString()}}}async UpdateQuery(e){try{const r=await this.Client.request(`mutation UpdateQuerySystemUser($input: UpdateQuerySystemUserInput!) {
871
- UpdateQuerySystemUser(input: $input) {
878
+ }`,{input:e});return r&&r.CreateQueryExtended?r.CreateQueryExtended:{Success:!1,ErrorMessage:"Failed to create query"}}catch(t){return l(`GraphQLSystemUserClient::CreateQuery - Error creating query - ${t}`),{Success:!1,ErrorMessage:t.toString()}}}async UpdateQuery(e){try{const r=await this.Client.request(`mutation UpdateQueryExtended($input: UpdateQuerySystemUserInput!) {
879
+ UpdateQueryExtended(input: $input) {
872
880
  Success
873
881
  ErrorMessage
874
882
  Query {
@@ -926,14 +934,14 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
926
934
  }
927
935
  }
928
936
  }
929
- }`,{input:e});return r&&r.UpdateQuerySystemUser?r.UpdateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to update query"}}catch(t){return u(`GraphQLSystemUserClient::UpdateQuery - Error updating query - ${t}`),{Success:!1,ErrorMessage:t.toString()}}}async DeleteQuery(e,t){try{if(!e||e.trim()==="")return u("GraphQLSystemUserClient::DeleteQuery - Invalid query ID: ID cannot be null or empty"),{Success:!1,ErrorMessage:"Invalid query ID: ID cannot be null or empty"};const r=`mutation DeleteQuerySystemResolver($ID: String!, $options: DeleteOptionsInput) {
930
- DeleteQuerySystemResolver(ID: $ID, options: $options) {
937
+ }`,{input:e});return r&&r.UpdateQueryExtended?r.UpdateQueryExtended:{Success:!1,ErrorMessage:"Failed to update query"}}catch(t){return l(`GraphQLSystemUserClient::UpdateQuery - Error updating query - ${t}`),{Success:!1,ErrorMessage:t.toString()}}}async DeleteQuery(e,t){try{if(!e||e.trim()==="")return l("GraphQLSystemUserClient::DeleteQuery - Invalid query ID: ID cannot be null or empty"),{Success:!1,ErrorMessage:"Invalid query ID: ID cannot be null or empty"};const r=`mutation DeleteQueryExtended($ID: String!, $options: DeleteOptionsInput) {
938
+ DeleteQueryExtended(ID: $ID, options: $options) {
931
939
  Success
932
940
  ErrorMessage
933
941
  ID
934
942
  Name
935
943
  }
936
- }`,s={ID:e};t!==void 0&&(s.options={SkipEntityAIActions:t.SkipEntityAIActions??!1,SkipEntityActions:t.SkipEntityActions??!1,ReplayOnly:t.ReplayOnly??!1,IsParentEntityDelete:t.IsParentEntityDelete??!1});const n=await this.Client.request(r,s);return n&&n.DeleteQuerySystemResolver?n.DeleteQuerySystemResolver:{Success:!1,ErrorMessage:"Failed to delete query"}}catch(r){let s="";if(r instanceof Error){if(s=r.message,"cause"in r&&r.cause){const n=r.cause;s+=` | Cause: ${n.message||n}`,"code"in n&&(s+=` | Code: ${n.code}`)}if("response"in r){const n=r.response;n?.status&&(s+=` | HTTP Status: ${n.status}`),n?.errors&&(s+=` | GraphQL Errors: ${JSON.stringify(n.errors)}`)}r.stack&&console.error("DeleteQuery stack trace:",r.stack)}else s=String(r);return u(`GraphQLSystemUserClient::DeleteQuery - Error deleting query - ${s}`),{Success:!1,ErrorMessage:s}}}async RunAIPrompt(e){try{const t=c`
944
+ }`,s={ID:e};t!==void 0&&(s.options={SkipEntityAIActions:t.SkipEntityAIActions??!1,SkipEntityActions:t.SkipEntityActions??!1,ReplayOnly:t.ReplayOnly??!1,IsParentEntityDelete:t.IsParentEntityDelete??!1});const n=await this.Client.request(r,s);return n&&n.DeleteQueryExtended?n.DeleteQueryExtended:{Success:!1,ErrorMessage:"Failed to delete query"}}catch(r){let s="";if(r instanceof Error){if(s=r.message,"cause"in r&&r.cause){const n=r.cause;s+=` | Cause: ${n.message||n}`,"code"in n&&(s+=` | Code: ${n.code}`)}if("response"in r){const n=r.response;n?.status&&(s+=` | HTTP Status: ${n.status}`),n?.errors&&(s+=` | GraphQL Errors: ${JSON.stringify(n.errors)}`)}r.stack&&console.error("DeleteQuery stack trace:",r.stack)}else s=String(r);return l(`GraphQLSystemUserClient::DeleteQuery - Error deleting query - ${s}`),{Success:!1,ErrorMessage:s}}}async RunAIPrompt(e){try{const t=c`
937
945
  query RunAIPromptSystemUser(
938
946
  $promptId: String!,
939
947
  $data: String,
@@ -992,7 +1000,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
992
1000
  chatResult
993
1001
  }
994
1002
  }
995
- `,r=this.preparePromptVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIPromptSystemUser?this.processPromptResult(s.RunAIPromptSystemUser):{success:!1,error:"Failed to execute AI prompt as system user"}}catch(t){return u(`GraphQLSystemUserClient::RunAIPrompt - Error running AI prompt - ${t}`),{success:!1,error:t.toString()}}}async RunAIAgent(e){try{const t=c`
1003
+ `,r=this.preparePromptVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIPromptSystemUser?this.processPromptResult(s.RunAIPromptSystemUser):{success:!1,error:"Failed to execute AI prompt as system user"}}catch(t){return l(`GraphQLSystemUserClient::RunAIPrompt - Error running AI prompt - ${t}`),{success:!1,error:t.toString()}}}async RunAIAgent(e){try{const t=c`
996
1004
  query RunAIAgentSystemUser(
997
1005
  $agentId: String!,
998
1006
  $messages: String!,
@@ -1019,7 +1027,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1019
1027
  result
1020
1028
  }
1021
1029
  }
1022
- `,r=this.prepareAgentVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIAgentSystemUser?this.processAgentResult(s.RunAIAgentSystemUser.result):{success:!1,agentRun:void 0}}catch(t){return u(`GraphQLSystemUserClient::RunAIAgent - Error running AI agent - ${t}`),{success:!1,agentRun:void 0}}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}prepareAgentVariables(e){const t={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._sessionId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),t}processPromptResult(e){let t,r,s;try{e.parsedResult&&(t=JSON.parse(e.parsedResult))}catch{t=e.parsedResult}try{e.validationResult&&(r=JSON.parse(e.validationResult))}catch{r=e.validationResult}try{e.chatResult&&(s=JSON.parse(e.chatResult))}catch{s=e.chatResult}return{success:e.success,output:e.output,parsedResult:t,error:e.error,executionTimeMs:e.executionTimeMs,tokensUsed:e.tokensUsed,promptRunId:e.promptRunId,rawResult:e.rawResult,validationResult:r,chatResult:s}}processAgentResult(e){return D(e)}async TestQuerySQL(e){try{const r=await this.Client.request(`query TestQuerySQL($input: TestQuerySQLInput!) {
1030
+ `,r=this.prepareAgentVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIAgentSystemUser?this.processAgentResult(s.RunAIAgentSystemUser.result):{success:!1,agentRun:void 0}}catch(t){return l(`GraphQLSystemUserClient::RunAIAgent - Error running AI agent - ${t}`),{success:!1,agentRun:void 0}}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}prepareAgentVariables(e){const t={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._sessionId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),t}processPromptResult(e){let t,r,s;try{e.parsedResult&&(t=JSON.parse(e.parsedResult))}catch{t=e.parsedResult}try{e.validationResult&&(r=JSON.parse(e.validationResult))}catch{r=e.validationResult}try{e.chatResult&&(s=JSON.parse(e.chatResult))}catch{s=e.chatResult}return{success:e.success,output:e.output,parsedResult:t,error:e.error,executionTimeMs:e.executionTimeMs,tokensUsed:e.tokensUsed,promptRunId:e.promptRunId,rawResult:e.rawResult,validationResult:r,chatResult:s}}processAgentResult(e){return D(e)}async TestQuerySQL(e){try{const r=await this.Client.request(`query TestQuerySQL($input: TestQuerySQLInput!) {
1023
1031
  TestQuerySQL(input: $input) {
1024
1032
  Success
1025
1033
  Results
@@ -1028,7 +1036,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1028
1036
  ErrorMessage
1029
1037
  AppliedParameters
1030
1038
  }
1031
- }`,{input:e});return r&&r.TestQuerySQL?{Success:r.TestQuerySQL.Success,Results:r.TestQuerySQL.Results?D(r.TestQuerySQL.Results):null,RowCount:r.TestQuerySQL.RowCount,ExecutionTime:r.TestQuerySQL.ExecutionTime,ErrorMessage:r.TestQuerySQL.ErrorMessage,AppliedParameters:r.TestQuerySQL.AppliedParameters?D(r.TestQuerySQL.AppliedParameters):void 0}:{Success:!1,Results:null,RowCount:0,ExecutionTime:0,ErrorMessage:"TestQuerySQL execution failed"}}catch(t){return u(`GraphQLSystemUserClient::TestQuerySQL - Error testing query SQL - ${t}`),{Success:!1,Results:null,RowCount:0,ExecutionTime:0,ErrorMessage:t instanceof Error?t.message:String(t)}}}async ExecuteSimplePrompt(e){try{const t=c`
1039
+ }`,{input:e});return r&&r.TestQuerySQL?{Success:r.TestQuerySQL.Success,Results:r.TestQuerySQL.Results?D(r.TestQuerySQL.Results):null,RowCount:r.TestQuerySQL.RowCount,ExecutionTime:r.TestQuerySQL.ExecutionTime,ErrorMessage:r.TestQuerySQL.ErrorMessage,AppliedParameters:r.TestQuerySQL.AppliedParameters?D(r.TestQuerySQL.AppliedParameters):void 0}:{Success:!1,Results:null,RowCount:0,ExecutionTime:0,ErrorMessage:"TestQuerySQL execution failed"}}catch(t){return l(`GraphQLSystemUserClient::TestQuerySQL - Error testing query SQL - ${t}`),{Success:!1,Results:null,RowCount:0,ExecutionTime:0,ErrorMessage:t instanceof Error?t.message:String(t)}}}async ExecuteSimplePrompt(e){try{const t=c`
1032
1040
  query ExecuteSimplePromptSystemUser(
1033
1041
  $systemPrompt: String!,
1034
1042
  $messages: String,
@@ -1051,7 +1059,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1051
1059
  executionTimeMs
1052
1060
  }
1053
1061
  }
1054
- `,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 u(`GraphQLSystemUserClient::ExecuteSimplePrompt - Error executing simple prompt - ${t}`),{success:!1,modelName:"Unknown",error:t.toString()}}}async EmbedText(e){try{const t=c`
1062
+ `,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this.Client.request(t,r);if(!s?.ExecuteSimplePromptSystemUser)return{success:!1,modelName:"Unknown",error:"Failed to execute simple prompt as system user"};const n=s.ExecuteSimplePromptSystemUser;let a;if(n.resultObject)try{a=JSON.parse(n.resultObject)}catch{a=n.resultObject}return{success:n.success,result:n.result,resultObject:a,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){return l(`GraphQLSystemUserClient::ExecuteSimplePrompt - Error executing simple prompt - ${t}`),{success:!1,modelName:"Unknown",error:t.toString()}}}async EmbedText(e){try{const t=c`
1055
1063
  query EmbedTextSystemUser(
1056
1064
  $textToEmbed: [String!]!,
1057
1065
  $modelSize: String!
@@ -1066,7 +1074,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1066
1074
  error
1067
1075
  }
1068
1076
  }
1069
- `,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 u(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}async SearchKnowledge(e){try{const t=c`
1077
+ `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this.Client.request(t,s);if(!n?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const a=n.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?a.embeddings:a.embeddings[0],modelName:a.modelName,vectorDimensions:a.vectorDimensions,error:a.error}}catch(t){return l(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}async SearchKnowledge(e){try{const t=c`
1070
1078
  mutation SearchKnowledgeAsSystemUser($query: String!, $maxResults: Float, $filters: SearchFiltersInput, $minScore: Float) {
1071
1079
  SearchKnowledgeAsSystemUser(query: $query, maxResults: $maxResults, filters: $filters, minScore: $minScore) {
1072
1080
  Success
@@ -1113,7 +1121,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1113
1121
  ErrorMessage
1114
1122
  }
1115
1123
  }
1116
- `,r={query:e.Query};if(e.MaxResults!==void 0&&(r.maxResults=e.MaxResults),e.MinScore!==void 0&&(r.minScore=e.MinScore),e.Filters!==void 0){const n={};e.Filters.EntityNames?.length&&(n.EntityNames=e.Filters.EntityNames),e.Filters.SourceTypes?.length&&(n.SourceTypes=e.Filters.SourceTypes),e.Filters.Tags?.length&&(n.Tags=e.Filters.Tags),r.filters=n}const s=await this.Client.request(t,r);return s?.SearchKnowledgeAsSystemUser?this.mapSearchResponse(s.SearchKnowledgeAsSystemUser):this.searchErrorResponse("Invalid response from server")}catch(t){return u(`GraphQLSystemUserClient::SearchKnowledge - Error executing search - ${t}`),this.searchErrorResponse(t instanceof Error?t.message:String(t))}}async PreviewSearch(e){try{const t=c`
1124
+ `,r={query:e.Query};if(e.MaxResults!==void 0&&(r.maxResults=e.MaxResults),e.MinScore!==void 0&&(r.minScore=e.MinScore),e.Filters!==void 0){const n={};e.Filters.EntityNames?.length&&(n.EntityNames=e.Filters.EntityNames),e.Filters.SourceTypes?.length&&(n.SourceTypes=e.Filters.SourceTypes),e.Filters.Tags?.length&&(n.Tags=e.Filters.Tags),r.filters=n}const s=await this.Client.request(t,r);return s?.SearchKnowledgeAsSystemUser?this.mapSearchResponse(s.SearchKnowledgeAsSystemUser):this.searchErrorResponse("Invalid response from server")}catch(t){return l(`GraphQLSystemUserClient::SearchKnowledge - Error executing search - ${t}`),this.searchErrorResponse(t instanceof Error?t.message:String(t))}}async PreviewSearch(e){try{const t=c`
1117
1125
  mutation PreviewSearchAsSystemUser($query: String!, $maxResults: Float) {
1118
1126
  PreviewSearchAsSystemUser(query: $query, maxResults: $maxResults) {
1119
1127
  Success
@@ -1160,7 +1168,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1160
1168
  ErrorMessage
1161
1169
  }
1162
1170
  }
1163
- `,r={query:e.Query};e.MaxResults!==void 0&&(r.maxResults=e.MaxResults);const s=await this.Client.request(t,r);return s?.PreviewSearchAsSystemUser?this.mapSearchResponse(s.PreviewSearchAsSystemUser):this.searchErrorResponse("Invalid response from server")}catch(t){return u(`GraphQLSystemUserClient::PreviewSearch - Error executing preview search - ${t}`),this.searchErrorResponse(t instanceof Error?t.message:String(t))}}mapSearchResponse(e){return{Success:e.Success,Results:(e.Results||[]).map(t=>({ID:t.ID,EntityName:t.EntityName,RecordID:t.RecordID,SourceType:t.SourceType,ResultType:t.ResultType,Title:t.Title,Snippet:t.Snippet,Score:t.Score,ScoreBreakdown:this.mapScoreBreakdown(t.ScoreBreakdown),Tags:t.Tags||[],EntityIcon:t.EntityIcon,RecordName:t.RecordName,MatchedAt:t.MatchedAt,RawMetadata:t.RawMetadata,ProviderId:t.ProviderId,ProviderLabel:t.ProviderLabel,ProviderIcon:t.ProviderIcon})),TotalCount:e.TotalCount,ElapsedMs:e.ElapsedMs,SourceCounts:this.mapSourceCounts(e.SourceCounts),Providers:(e.Providers||[]).map(t=>({ID:t.ID,Name:t.Name,DisplayName:t.DisplayName,Icon:t.Icon,SourceType:t.SourceType,Priority:t.Priority})),ErrorMessage:e.ErrorMessage}}mapScoreBreakdown(e){if(!e)return{};const t={};return e.Vector!==void 0&&(t.Vector=e.Vector),e.FullText!==void 0&&(t.FullText=e.FullText),e.Entity!==void 0&&(t.Entity=e.Entity),e.Storage!==void 0&&(t.Storage=e.Storage),t}mapSourceCounts(e){return e?{Vector:e.Vector??0,FullText:e.FullText??0,Entity:e.Entity??0,Storage:e.Storage??0}:{Vector:0,FullText:0,Entity:0,Storage:0}}searchErrorResponse(e){return{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,SourceCounts:{Vector:0,FullText:0,Entity:0,Storage:0},Providers:[],ErrorMessage:`Error: ${e}`}}async CheckEntityPermissionsSystemUser(e,t){try{const r=c`
1171
+ `,r={query:e.Query};e.MaxResults!==void 0&&(r.maxResults=e.MaxResults);const s=await this.Client.request(t,r);return s?.PreviewSearchAsSystemUser?this.mapSearchResponse(s.PreviewSearchAsSystemUser):this.searchErrorResponse("Invalid response from server")}catch(t){return l(`GraphQLSystemUserClient::PreviewSearch - Error executing preview search - ${t}`),this.searchErrorResponse(t instanceof Error?t.message:String(t))}}mapSearchResponse(e){return{Success:e.Success,Results:(e.Results||[]).map(t=>({ID:t.ID,EntityName:t.EntityName,RecordID:t.RecordID,SourceType:t.SourceType,ResultType:t.ResultType,Title:t.Title,Snippet:t.Snippet,Score:t.Score,ScoreBreakdown:this.mapScoreBreakdown(t.ScoreBreakdown),Tags:t.Tags||[],EntityIcon:t.EntityIcon,RecordName:t.RecordName,MatchedAt:t.MatchedAt,RawMetadata:t.RawMetadata,ProviderId:t.ProviderId,ProviderLabel:t.ProviderLabel,ProviderIcon:t.ProviderIcon})),TotalCount:e.TotalCount,ElapsedMs:e.ElapsedMs,SourceCounts:this.mapSourceCounts(e.SourceCounts),Providers:(e.Providers||[]).map(t=>({ID:t.ID,Name:t.Name,DisplayName:t.DisplayName,Icon:t.Icon,SourceType:t.SourceType,Priority:t.Priority})),ErrorMessage:e.ErrorMessage}}mapScoreBreakdown(e){if(!e)return{};const t={};return e.Vector!==void 0&&(t.Vector=e.Vector),e.FullText!==void 0&&(t.FullText=e.FullText),e.Entity!==void 0&&(t.Entity=e.Entity),e.Storage!==void 0&&(t.Storage=e.Storage),t}mapSourceCounts(e){return e?{Vector:e.Vector??0,FullText:e.FullText??0,Entity:e.Entity??0,Storage:e.Storage??0}:{Vector:0,FullText:0,Entity:0,Storage:0}}searchErrorResponse(e){return{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,SourceCounts:{Vector:0,FullText:0,Entity:0,Storage:0},Providers:[],ErrorMessage:`Error: ${e}`}}async CheckEntityPermissionsSystemUser(e,t){try{const r=c`
1164
1172
  query CheckEntityPermissionsSystemUser($EntityNames: [String!]!, $UserEmail: String!) {
1165
1173
  CheckEntityPermissionsSystemUser(EntityNames: $EntityNames, UserEmail: $UserEmail) {
1166
1174
  Success
@@ -1171,7 +1179,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1171
1179
  ErrorMessage
1172
1180
  }
1173
1181
  }
1174
- `,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 u(`GraphQLSystemUserClient::CheckEntityPermissionsSystemUser - Error checking entity permissions - ${r}`),{Success:!1,Results:[],ErrorMessage:r instanceof Error?r.message:String(r)}}}}class Oe{static{l(this,"GetDataOutput")}}class ke{static{l(this,"SimpleRemoteEntityOutput")}}class qe{static{l(this,"SimpleRemoteEntity")}}class Ke{static{l(this,"SimpleRemoteEntityField")}}class Be{static{l(this,"GraphQLActionClient")}constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),n=this.createActionVariables(e,s,r),a=await this.executeActionMutation(n);return this.processActionResult(a,t)}catch(s){return this.handleActionError(s,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{...t,Value:r}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=c`
1182
+ `,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 l(`GraphQLSystemUserClient::CheckEntityPermissionsSystemUser - Error checking entity permissions - ${r}`),{Success:!1,Results:[],ErrorMessage:r instanceof Error?r.message:String(r)}}}}class Oe{static{d(this,"GetDataOutput")}}class ke{static{d(this,"SimpleRemoteEntityOutput")}}class qe{static{d(this,"SimpleRemoteEntity")}}class Ke{static{d(this,"SimpleRemoteEntityField")}}class Be{static{d(this,"GraphQLActionClient")}constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),n=this.createActionVariables(e,s,r),a=await this.executeActionMutation(n);return this.processActionResult(a,t)}catch(s){return this.handleActionError(s,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{...t,Value:r}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=c`
1175
1183
  mutation RunAction($input: RunActionInput!) {
1176
1184
  RunAction(input: $input) {
1177
1185
  Success
@@ -1180,7 +1188,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1180
1188
  ResultData
1181
1189
  }
1182
1190
  }
1183
- `;return await this._dataProvider.ExecuteGQL(t,e)}processActionResult(e,t){if(!e?.RunAction)throw new Error("Invalid response from server");let r;try{e.RunAction.ResultData&&(r=JSON.parse(e.RunAction.ResultData))}catch(s){u(`Failed to parse action result data: ${s}`)}return{Success:e.RunAction.Success,Message:e.RunAction.Message,Result:r,LogEntry:null,Params:t||[],RunParams:null}}handleActionError(e,t){const r=e;return u(`Error running action: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Result:null,LogEntry:null,Params:t||[],RunParams:null}}async RunEntityAction(e){try{const t=this.createEntityActionInput(e),r=await this.executeEntityActionMutation(t);return this.processEntityActionResult(r)}catch(t){return this.handleEntityActionError(t)}}createEntityActionInput(e){const t={EntityActionID:e.EntityAction.ID,InvocationType:e.InvocationType.Name,ListID:e.ListID,ViewID:e.ViewID};return e.Params&&(t.Params=this.convertActionParams(e.Params)),e.EntityObject&&this.addEntityInformation(t,e.EntityObject),t}convertActionParams(e){return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{Name:t.Name,Value:r,Type:t.Type}})}addEntityInformation(e,t){e.EntityName=t.EntityInfo?.Name,t.PrimaryKey&&(e.PrimaryKey=this.convertPrimaryKey(t.PrimaryKey))}convertPrimaryKey(e){return{KeyValuePairs:e.KeyValuePairs.map(t=>this.convertKeyValuePair(t))}}convertKeyValuePair(e){return{FieldName:e.FieldName,Value:e.Value!==null&&e.Value!==void 0?typeof e.Value=="object"?JSON.stringify(e.Value):e.Value.toString():null}}async executeEntityActionMutation(e){const t=c`
1191
+ `;return await this._dataProvider.ExecuteGQL(t,e)}processActionResult(e,t){if(!e?.RunAction)throw new Error("Invalid response from server");let r;try{e.RunAction.ResultData&&(r=JSON.parse(e.RunAction.ResultData))}catch(s){l(`Failed to parse action result data: ${s}`)}return{Success:e.RunAction.Success,Message:e.RunAction.Message,Result:r,LogEntry:null,Params:t||[],RunParams:null}}handleActionError(e,t){const r=e;return l(`Error running action: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Result:null,LogEntry:null,Params:t||[],RunParams:null}}async RunEntityAction(e){try{const t=this.createEntityActionInput(e),r=await this.executeEntityActionMutation(t);return this.processEntityActionResult(r)}catch(t){return this.handleEntityActionError(t)}}createEntityActionInput(e){const t={EntityActionID:e.EntityAction.ID,InvocationType:e.InvocationType.Name,ListID:e.ListID,ViewID:e.ViewID};return e.Params&&(t.Params=this.convertActionParams(e.Params)),e.EntityObject&&this.addEntityInformation(t,e.EntityObject),t}convertActionParams(e){return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{Name:t.Name,Value:r,Type:t.Type}})}addEntityInformation(e,t){e.EntityName=t.EntityInfo?.Name,t.PrimaryKey&&(e.PrimaryKey=this.convertPrimaryKey(t.PrimaryKey))}convertPrimaryKey(e){return{KeyValuePairs:e.KeyValuePairs.map(t=>this.convertKeyValuePair(t))}}convertKeyValuePair(e){return{FieldName:e.FieldName,Value:e.Value!==null&&e.Value!==void 0?typeof e.Value=="object"?JSON.stringify(e.Value):e.Value.toString():null}}async executeEntityActionMutation(e){const t=c`
1184
1192
  mutation RunEntityAction($input: EntityActionInput!) {
1185
1193
  RunEntityAction(input: $input) {
1186
1194
  Success
@@ -1188,7 +1196,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1188
1196
  ResultData
1189
1197
  }
1190
1198
  }
1191
- `;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(r){u(`Failed to parse entity action result data: ${r}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return u(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}}class je{static{l(this,"GraphQLListsClient")}constructor(e){this.dataProvider=e}async PreviewListDelta(e){const t=c`
1199
+ `;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(r){l(`Failed to parse entity action result data: ${r}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return l(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}}class je{static{d(this,"GraphQLListsClient")}constructor(e){this.dataProvider=e}async PreviewListDelta(e){const t=c`
1192
1200
  query PreviewListDelta($input: ComputeDeltaInput!) {
1193
1201
  PreviewListDelta(input: $input) {
1194
1202
  ...ListDeltaFields
@@ -1202,28 +1210,28 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1202
1210
  }
1203
1211
  }
1204
1212
  ${Q}
1205
- `,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 U(r?.ApplyListDelta)}async MaterializeFromView(e,t){const r=c`
1213
+ `,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 G(r?.ApplyListDelta)}async MaterializeFromView(e,t){const r=c`
1206
1214
  mutation MaterializeListFromView($viewId: String!, $options: MaterializeOptionsInput!) {
1207
1215
  MaterializeListFromView(viewId: $viewId, options: $options) {
1208
1216
  ...ApplyResultFields
1209
1217
  }
1210
1218
  }
1211
1219
  ${Q}
1212
- `,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 U(s?.MaterializeListFromView)}async AddViewResultsToList(e,t){const r=c`
1220
+ `,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 G(s?.MaterializeListFromView)}async AddViewResultsToList(e,t){const r=c`
1213
1221
  mutation AddViewResultsToList($viewId: String!, $listId: String!) {
1214
1222
  AddViewResultsToList(viewId: $viewId, listId: $listId) {
1215
1223
  ...ApplyResultFields
1216
1224
  }
1217
1225
  }
1218
1226
  ${Q}
1219
- `,s=await this.dataProvider.ExecuteGQL(r,{viewId:e,listId:t});return U(s?.AddViewResultsToList)}async RefreshFromSource(e){const t=c`
1227
+ `,s=await this.dataProvider.ExecuteGQL(r,{viewId:e,listId:t});return G(s?.AddViewResultsToList)}async RefreshFromSource(e){const t=c`
1220
1228
  mutation RefreshListFromSource($listId: String!, $mode: String!, $confirmDrops: Boolean!) {
1221
1229
  RefreshListFromSource(listId: $listId, mode: $mode, confirmDrops: $confirmDrops) {
1222
1230
  ...ApplyResultFields
1223
1231
  }
1224
1232
  }
1225
1233
  ${Q}
1226
- `,r=await this.dataProvider.ExecuteGQL(t,{listId:e.ListId,mode:e.Mode,confirmDrops:e.ConfirmDrops});return U(r?.RefreshListFromSource)}async ComposeLists(e){const t=c`
1234
+ `,r=await this.dataProvider.ExecuteGQL(t,{listId:e.ListId,mode:e.Mode,confirmDrops:e.ConfirmDrops});return G(r?.RefreshListFromSource)}async ComposeLists(e){const t=c`
1227
1235
  mutation ComposeLists($input: ComposeListsInput!) {
1228
1236
  ComposeLists(input: $input) {
1229
1237
  ...ListDeltaFields
@@ -1338,7 +1346,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1338
1346
  Message
1339
1347
  PermissionID
1340
1348
  }
1341
- `;function Je(g){return g.kind==="user"?{Kind:"user",UserID:g.userId}:{Kind:"role",RoleID:g.roleId}}l(Je,"serializeShareTarget");function _(g){if(!g||typeof g!="object")throw new Error("GraphQLListsClient: empty/invalid ShareResult response");const e=g;return{Success:e.Success,ResultCode:e.ResultCode,Message:e.Message,PermissionID:e.PermissionID??void 0}}l(_,"parseShareResult");function We(g){const e=g,t=e.Target.Kind==="user"?{kind:"user",userId:e.Target.UserID}:{kind:"role",roleId:e.Target.RoleID};return{PermissionID:e.PermissionID,ListID:e.ListID,Target:t,PermissionLevel:e.PermissionLevel,Status:e.Status,SharedByUserID:e.SharedByUserID??null,CreatedAt:new Date(e.CreatedAt)}}l(We,"parseShareSummary");function O(g){switch(g.kind){case"list":return{Kind:"list",ListID:g.listId};case"view":return{Kind:"view",ViewID:g.viewId};case"adhoc":return{Kind:"adhoc",EntityName:g.entityName,ExtraFilter:g.extraFilter}}}l(O,"serializeListSource");function re(g){if(!g||typeof g!="object")throw new Error("GraphQLListsClient: empty/invalid ListDelta response from server");const e=g;return{TargetListId:e.TargetListId,EntityName:e.EntityName,ToAdd:e.ToAdd,ToRemove:e.ToRemove,Unchanged:e.Unchanged,Counts:e.Counts,Warnings:e.Warnings.map(ze),DeltaToken:e.DeltaToken}}l(re,"parseListDelta");function ze(g){let e;if(g.DetailsJSON)try{e=JSON.parse(g.DetailsJSON)}catch(t){u(`GraphQLListsClient: failed to parse warning details JSON: ${t}`)}return{Code:g.Code,Message:g.Message,Details:e}}l(ze,"parseWarning");function U(g){if(!g||typeof g!="object")throw new Error("GraphQLListsClient: empty/invalid ApplyResult response from server");const e=g;return{Success:e.Success,ResultCode:e.ResultCode,Message:e.Message,CreatedListId:e.CreatedListId??void 0,TargetListId:e.TargetListId??void 0,Counts:e.AddedCount!=null||e.RemovedCount!=null||e.FailedCount!=null?{Added:e.AddedCount??0,Removed:e.RemovedCount??0,Failed:e.FailedCount??0}:void 0,Errors:e.Errors??void 0}}l(U,"parseApplyResult");class He{static{l(this,"GraphQLEncryptionClient")}constructor(e){this._dataProvider=e}async CreateAPIKey(e){try{const t=this.createAPIKeyVariables(e),r=await this.executeCreateAPIKeyMutation(t);return this.processCreateAPIKeyResult(r)}catch(t){return this.handleCreateAPIKeyError(t)}}createAPIKeyVariables(e){return{input:{Label:e.Label,Description:e.Description,ExpiresAt:e.ExpiresAt?.toISOString(),ScopeIDs:e.ScopeIDs}}}async executeCreateAPIKeyMutation(e){const t=c`
1349
+ `;function Je(g){return g.kind==="user"?{Kind:"user",UserID:g.userId}:{Kind:"role",RoleID:g.roleId}}d(Je,"serializeShareTarget");function _(g){if(!g||typeof g!="object")throw new Error("GraphQLListsClient: empty/invalid ShareResult response");const e=g;return{Success:e.Success,ResultCode:e.ResultCode,Message:e.Message,PermissionID:e.PermissionID??void 0}}d(_,"parseShareResult");function We(g){const e=g,t=e.Target.Kind==="user"?{kind:"user",userId:e.Target.UserID}:{kind:"role",roleId:e.Target.RoleID};return{PermissionID:e.PermissionID,ListID:e.ListID,Target:t,PermissionLevel:e.PermissionLevel,Status:e.Status,SharedByUserID:e.SharedByUserID??null,CreatedAt:new Date(e.CreatedAt)}}d(We,"parseShareSummary");function O(g){switch(g.kind){case"list":return{Kind:"list",ListID:g.listId};case"view":return{Kind:"view",ViewID:g.viewId};case"adhoc":return{Kind:"adhoc",EntityName:g.entityName,ExtraFilter:g.extraFilter}}}d(O,"serializeListSource");function re(g){if(!g||typeof g!="object")throw new Error("GraphQLListsClient: empty/invalid ListDelta response from server");const e=g;return{TargetListId:e.TargetListId,EntityName:e.EntityName,ToAdd:e.ToAdd,ToRemove:e.ToRemove,Unchanged:e.Unchanged,Counts:e.Counts,Warnings:e.Warnings.map(ze),DeltaToken:e.DeltaToken}}d(re,"parseListDelta");function ze(g){let e;if(g.DetailsJSON)try{e=JSON.parse(g.DetailsJSON)}catch(t){l(`GraphQLListsClient: failed to parse warning details JSON: ${t}`)}return{Code:g.Code,Message:g.Message,Details:e}}d(ze,"parseWarning");function G(g){if(!g||typeof g!="object")throw new Error("GraphQLListsClient: empty/invalid ApplyResult response from server");const e=g;return{Success:e.Success,ResultCode:e.ResultCode,Message:e.Message,CreatedListId:e.CreatedListId??void 0,TargetListId:e.TargetListId??void 0,Counts:e.AddedCount!=null||e.RemovedCount!=null||e.FailedCount!=null?{Added:e.AddedCount??0,Removed:e.RemovedCount??0,Failed:e.FailedCount??0}:void 0,Errors:e.Errors??void 0}}d(G,"parseApplyResult");class He{static{d(this,"GraphQLEncryptionClient")}constructor(e){this._dataProvider=e}async CreateAPIKey(e){try{const t=this.createAPIKeyVariables(e),r=await this.executeCreateAPIKeyMutation(t);return this.processCreateAPIKeyResult(r)}catch(t){return this.handleCreateAPIKeyError(t)}}createAPIKeyVariables(e){return{input:{Label:e.Label,Description:e.Description,ExpiresAt:e.ExpiresAt?.toISOString(),ScopeIDs:e.ScopeIDs}}}async executeCreateAPIKeyMutation(e){const t=c`
1342
1350
  mutation CreateAPIKey($input: CreateAPIKeyInput!) {
1343
1351
  CreateAPIKey(input: $input) {
1344
1352
  Success
@@ -1347,14 +1355,14 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1347
1355
  Error
1348
1356
  }
1349
1357
  }
1350
- `;return await this._dataProvider.ExecuteGQL(t,e)}processCreateAPIKeyResult(e){const t=e;return t?.CreateAPIKey?{Success:t.CreateAPIKey.Success,RawKey:t.CreateAPIKey.RawKey,APIKeyID:t.CreateAPIKey.APIKeyID,Error:t.CreateAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}handleCreateAPIKeyError(e){const t=e;return u(`Error creating API key: ${t.message}`),{Success:!1,Error:`Error: ${t.message}`}}async RevokeAPIKey(e){try{const t=c`
1358
+ `;return await this._dataProvider.ExecuteGQL(t,e)}processCreateAPIKeyResult(e){const t=e;return t?.CreateAPIKey?{Success:t.CreateAPIKey.Success,RawKey:t.CreateAPIKey.RawKey,APIKeyID:t.CreateAPIKey.APIKeyID,Error:t.CreateAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}handleCreateAPIKeyError(e){const t=e;return l(`Error creating API key: ${t.message}`),{Success:!1,Error:`Error: ${t.message}`}}async RevokeAPIKey(e){try{const t=c`
1351
1359
  mutation RevokeAPIKey($apiKeyId: String!) {
1352
1360
  RevokeAPIKey(apiKeyId: $apiKeyId) {
1353
1361
  Success
1354
1362
  Error
1355
1363
  }
1356
1364
  }
1357
- `,s=await this._dataProvider.ExecuteGQL(t,{apiKeyId:e});return s?.RevokeAPIKey?{Success:s.RevokeAPIKey.Success,Error:s.RevokeAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}catch(t){const r=t;return u(`Error revoking API key: ${r.message}`),{Success:!1,Error:`Error: ${r.message}`}}}}class Xe{static{l(this,"GraphQLClusterClient")}constructor(e){this._dataProvider=e}async RunClusterAnalysis(e){try{const t=c`
1365
+ `,s=await this._dataProvider.ExecuteGQL(t,{apiKeyId:e});return s?.RevokeAPIKey?{Success:s.RevokeAPIKey.Success,Error:s.RevokeAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}catch(t){const r=t;return l(`Error revoking API key: ${r.message}`),{Success:!1,Error:`Error: ${r.message}`}}}}class Xe{static{d(this,"GraphQLClusterClient")}constructor(e){this._dataProvider=e}async RunClusterAnalysis(e){try{const t=c`
1358
1366
  mutation RunClusterAnalysis($input: RunClusterAnalysisInput!) {
1359
1367
  RunClusterAnalysis(input: $input) {
1360
1368
  Success
@@ -1370,7 +1378,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1370
1378
  AnalysisID
1371
1379
  }
1372
1380
  }
1373
- `,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 u("GraphQLClusterClient.RunClusterAnalysis failed",void 0,r),this.errorResult(r.message||"Unknown error occurred")}}parseResult(e){const t=this.parseMetrics(e),r=D(e.ClustersJSON)??[],s=D(e.PointsJSON)??[];return{Success:e.Success,ErrorMessage:e.ErrorMessage,Metrics:t,Clusters:r,Points:s,AnalysisID:e.AnalysisID}}parseMetrics(e){const t=D(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 Ye{static{l(this,"GraphQLLiveKitClient")}constructor(e){this._dataProvider=e}async MintClientToken(e){try{const t=c`
1381
+ `,s=(await this._dataProvider.ExecuteGQL(t,{input:e}))?.RunClusterAnalysis;if(!s)throw new Error("Invalid response from server");return this.parseResult(s)}catch(t){const r=t;return l("GraphQLClusterClient.RunClusterAnalysis failed",void 0,r),this.errorResult(r.message||"Unknown error occurred")}}parseResult(e){const t=this.parseMetrics(e),r=D(e.ClustersJSON)??[],s=D(e.PointsJSON)??[];return{Success:e.Success,ErrorMessage:e.ErrorMessage,Metrics:t,Clusters:r,Points:s,AnalysisID:e.AnalysisID}}parseMetrics(e){const t=D(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 Ye{static{d(this,"GraphQLLiveKitClient")}constructor(e){this._dataProvider=e}async MintClientToken(e){try{const t=c`
1374
1382
  mutation MintLiveKitClientToken($input: MintLiveKitClientTokenInput!) {
1375
1383
  MintLiveKitClientToken(input: $input) {
1376
1384
  Success
@@ -1381,7 +1389,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1381
1389
  RoomName
1382
1390
  }
1383
1391
  }
1384
- `,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 u("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=c`
1392
+ `,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 l("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=c`
1385
1393
  mutation StartLiveKitAgentRoomSession($input: StartLiveKitAgentRoomSessionInput!) {
1386
1394
  StartLiveKitAgentRoomSession(input: $input) {
1387
1395
  Success
@@ -1393,19 +1401,19 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1393
1401
  Identity
1394
1402
  }
1395
1403
  }
1396
- `,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 u("GraphQLLiveKitClient.StartAgentRoomSession failed",void 0,r),{Success:!1,ErrorMessage:r.message||"Unknown error",SessionBridgeID:"",RoomName:"",ServerUrl:"",ClientToken:"",Identity:""}}}async StopAgentRoomSession(e){try{const t=c`
1404
+ `,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 l("GraphQLLiveKitClient.StartAgentRoomSession failed",void 0,r),{Success:!1,ErrorMessage:r.message||"Unknown error",SessionBridgeID:"",RoomName:"",ServerUrl:"",ClientToken:"",Identity:""}}}async StopAgentRoomSession(e){try{const t=c`
1397
1405
  mutation StopLiveKitAgentRoomSession($sessionBridgeID: String!) {
1398
1406
  StopLiveKitAgentRoomSession(sessionBridgeID: $sessionBridgeID)
1399
1407
  }
1400
- `;return(await this._dataProvider.ExecuteGQL(t,{sessionBridgeID:e}))?.StopLiveKitAgentRoomSession===!0}catch(t){return u("GraphQLLiveKitClient.StopAgentRoomSession failed",void 0,t),!1}}async EndRoom(e){try{const t=c`
1408
+ `;return(await this._dataProvider.ExecuteGQL(t,{sessionBridgeID:e}))?.StopLiveKitAgentRoomSession===!0}catch(t){return l("GraphQLLiveKitClient.StopAgentRoomSession failed",void 0,t),!1}}async EndRoom(e){try{const t=c`
1401
1409
  mutation EndLiveKitRoom($roomName: String!) {
1402
1410
  EndLiveKitRoom(roomName: $roomName)
1403
1411
  }
1404
- `;return(await this._dataProvider.ExecuteGQL(t,{roomName:e}))?.EndLiveKitRoom===!0}catch(t){return u("GraphQLLiveKitClient.EndRoom failed",void 0,t),!1}}async InviteUsers(e,t){try{const r=c`
1412
+ `;return(await this._dataProvider.ExecuteGQL(t,{roomName:e}))?.EndLiveKitRoom===!0}catch(t){return l("GraphQLLiveKitClient.EndRoom failed",void 0,t),!1}}async InviteUsers(e,t){try{const r=c`
1405
1413
  mutation InviteUsersToLiveKitRoom($roomName: String!, $userIDs: [String!]!) {
1406
1414
  InviteUsersToLiveKitRoom(roomName: $roomName, userIDs: $userIDs)
1407
1415
  }
1408
- `;return(await this._dataProvider.ExecuteGQL(r,{roomName:e,userIDs:t}))?.InviteUsersToLiveKitRoom===!0}catch(r){return u("GraphQLLiveKitClient.InviteUsers failed",void 0,r),!1}}async GetRealtimeModelVoices(){try{const e=c`
1416
+ `;return(await this._dataProvider.ExecuteGQL(r,{roomName:e,userIDs:t}))?.InviteUsersToLiveKitRoom===!0}catch(r){return l("GraphQLLiveKitClient.InviteUsers failed",void 0,r),!1}}async GetRealtimeModelVoices(){try{const e=c`
1409
1417
  query GetRealtimeModelVoices {
1410
1418
  GetRealtimeModelVoices {
1411
1419
  ModelID
@@ -1416,7 +1424,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1416
1424
  }
1417
1425
  }
1418
1426
  }
1419
- `;return(await this._dataProvider.ExecuteGQL(e,{}))?.GetRealtimeModelVoices??[]}catch(e){return u("GraphQLLiveKitClient.GetRealtimeModelVoices failed",void 0,e),[]}}async StartRecording(e,t){return this.runRecordingMutation(c`
1427
+ `;return(await this._dataProvider.ExecuteGQL(e,{}))?.GetRealtimeModelVoices??[]}catch(e){return l("GraphQLLiveKitClient.GetRealtimeModelVoices failed",void 0,e),[]}}async StartRecording(e,t){return this.runRecordingMutation(c`
1420
1428
  mutation StartLiveKitRecording($input: LiveKitRecordingInput!) {
1421
1429
  StartLiveKitRecording(input: $input) {
1422
1430
  Success
@@ -1432,9 +1440,10 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1432
1440
  ErrorMessage
1433
1441
  EgressID
1434
1442
  Status
1443
+ RecordingFileID
1435
1444
  }
1436
1445
  }
1437
- `,{egressID:e},"StopLiveKitRecording",e)}async runRecordingMutation(e,t,r,s){try{const a=(await this._dataProvider.ExecuteGQL(e,t))?.[r];if(!a)throw new Error("Invalid response from server");return a}catch(n){const a=n;return u(`GraphQLLiveKitClient.${r} failed`,void 0,a),{Success:!1,ErrorMessage:a.message||"Unknown error",EgressID:s,Status:""}}}}class Ze{static{l(this,"GraphQLClassifyClient")}constructor(e){this._dataProvider=e}async GenerateSeedTaxonomy(e){try{const t=c`
1446
+ `,{egressID:e},"StopLiveKitRecording",e)}async runRecordingMutation(e,t,r,s){try{const a=(await this._dataProvider.ExecuteGQL(e,t))?.[r];if(!a)throw new Error("Invalid response from server");return a}catch(n){const a=n;return l(`GraphQLLiveKitClient.${r} failed`,void 0,a),{Success:!1,ErrorMessage:a.message||"Unknown error",EgressID:s,Status:""}}}}class Ze{static{d(this,"GraphQLClassifyClient")}constructor(e){this._dataProvider=e}async GenerateSeedTaxonomy(e){try{const t=c`
1438
1447
  mutation GenerateSeedTaxonomy($sourceID: String!, $sampleSize: Int!) {
1439
1448
  GenerateSeedTaxonomy(sourceID: $sourceID, sampleSize: $sampleSize) {
1440
1449
  Success
@@ -1444,11 +1453,11 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1444
1453
  NodesJSON
1445
1454
  }
1446
1455
  }
1447
- `,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 u("GraphQLClassifyClient.GenerateSeedTaxonomy failed",void 0,r),this.errorResult(r.message||"Unknown error occurred")}}parseResult(e){const t=D(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 et{static{l(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:l(n=>n?.success===!0,"validateAck"),isCompletionEvent:l(n=>this.isTestCompletionEvent(n,e.testId),"isCompletionEvent"),extractResult:l(n=>this.extractTestResult(n),"extractResult"),onMessage:l(n=>{this.captureTestRunId(n,s),e.onProgress&&this.forwardTestProgress(n,e.onProgress)},"onMessage"),onStall:l(()=>this.reconcileTestRun(s),"onStall"),createErrorResult:l(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:l(s=>s?.success===!0,"validateAck"),isCompletionEvent:l(s=>this.isSuiteCompletionEvent(s,e.suiteId),"isCompletionEvent"),extractResult:l(s=>this.extractSuiteResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardTestProgress(s,e.onProgress):void 0,createErrorResult:l(s=>({success:!1,errorMessage:s,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTestSuite")}}async IsTestRunning(e){try{const t=c`
1456
+ `,s=(await this._dataProvider.ExecuteGQL(t,{sourceID:e.SourceID,sampleSize:e.SampleSize}))?.GenerateSeedTaxonomy;if(!s)throw new Error("Invalid response from server");return this.parseResult(s)}catch(t){const r=t;return l("GraphQLClassifyClient.GenerateSeedTaxonomy failed",void 0,r),this.errorResult(r.message||"Unknown error occurred")}}parseResult(e){const t=D(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 et{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=c`
1448
1457
  query IsTestRunning($testId: String!) {
1449
1458
  IsTestRunning(testId: $testId)
1450
1459
  }
1451
- `;return(await this._dataProvider.ExecuteGQL(t,{testId:e})).IsTestRunning}catch(t){return u(`Error checking test running status: ${t.message}`),!1}}buildRunTestMutation(){return c`
1460
+ `;return(await this._dataProvider.ExecuteGQL(t,{testId:e})).IsTestRunning}catch(t){return l(`Error checking test running status: ${t.message}`),!1}}buildRunTestMutation(){return c`
1452
1461
  mutation RunTest(
1453
1462
  $testId: String!,
1454
1463
  $verbose: Boolean,
@@ -1502,7 +1511,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1502
1511
  result
1503
1512
  }
1504
1513
  }
1505
- `}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?D(t.result):null}}extractSuiteResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?D(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 u(`${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 tt{static{l(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=c`
1514
+ `}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?D(t.result):null}}extractSuiteResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?D(t.result):null}}forwardTestProgress(e,t){if(e.resolver==="RunTestResolver"&&e.type==="TestExecutionProgress"&&e.status==="ok"){const s=e.data?.progress;s&&t(s)}}handleError(e,t){const r=e.message;return l(`${t} failed: ${r}`),{success:!1,errorMessage:r.includes("Failed to fetch")||r.includes("NetworkError")?"Lost connection to the server. The test may still be running. Please refresh to check the latest status.":r,result:null}}}class tt{static{d(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=c`
1506
1515
  query GetRegistryComponent(
1507
1516
  $registryName: String!,
1508
1517
  $namespace: String!,
@@ -1523,7 +1532,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1523
1532
  specification
1524
1533
  }
1525
1534
  }
1526
- `,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 u(`Failed to parse component specification: ${a}`),null}}return null}return null}catch(t){throw u(t),new Error(`Failed to get registry component: ${t instanceof Error?t.message:"Unknown error"}`)}}async GetRegistryComponentWithHash(e){try{const t=c`
1535
+ `,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const n=s.GetRegistryComponent;if(n.notModified&&!n.specification)return null;if(n.specification){if(typeof n.specification=="object")return n.specification;try{return JSON.parse(n.specification)}catch(a){return l(`Failed to parse component specification: ${a}`),null}}return null}return null}catch(t){throw l(t),new Error(`Failed to get registry component: ${t instanceof Error?t.message:"Unknown error"}`)}}async GetRegistryComponentWithHash(e){try{const t=c`
1527
1536
  query GetRegistryComponent(
1528
1537
  $registryName: String!,
1529
1538
  $namespace: String!,
@@ -1544,7 +1553,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1544
1553
  specification
1545
1554
  }
1546
1555
  }
1547
- `,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){u(`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 u(t),new Error(`Failed to get registry component with hash: ${t instanceof Error?t.message:"Unknown error"}`)}}async SearchRegistryComponents(e){try{const t=c`
1556
+ `,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const n=s.GetRegistryComponent;let a;if(n.specification)try{a=JSON.parse(n.specification)}catch(i){l(`Failed to parse component specification in GetRegistryComponentWithHash: ${i}`),a=void 0}return{specification:a,hash:n.hash,notModified:n.notModified,message:n.message}}return{specification:void 0,hash:"",notModified:!1,message:"Component not found"}}catch(t){throw l(t),new Error(`Failed to get registry component with hash: ${t instanceof Error?t.message:"Unknown error"}`)}}async SearchRegistryComponents(e){try{const t=c`
1548
1557
  query SearchRegistryComponents($params: SearchRegistryComponentsInput!) {
1549
1558
  SearchRegistryComponents(params: $params) {
1550
1559
  components
@@ -1553,7 +1562,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1553
1562
  limit
1554
1563
  }
1555
1564
  }
1556
- `,r=await this._dataProvider.ExecuteGQL(t,{params:e});if(r&&r.SearchRegistryComponents){const s=r.SearchRegistryComponents;return{components:s.components.map(n=>JSON.parse(n)),total:s.total,offset:s.offset,limit:s.limit}}return{components:[],total:0,offset:0,limit:e.limit||10}}catch(t){throw u(t),new Error(`Failed to search registry components: ${t instanceof Error?t.message:"Unknown error"}`)}}async ResolveComponentDependencies(e,t){try{const r=c`
1565
+ `,r=await this._dataProvider.ExecuteGQL(t,{params:e});if(r&&r.SearchRegistryComponents){const s=r.SearchRegistryComponents;return{components:s.components.map(n=>JSON.parse(n)),total:s.total,offset:s.offset,limit:s.limit}}return{components:[],total:0,offset:0,limit:e.limit||10}}catch(t){throw l(t),new Error(`Failed to search registry components: ${t instanceof Error?t.message:"Unknown error"}`)}}async ResolveComponentDependencies(e,t){try{const r=c`
1557
1566
  query ResolveComponentDependencies(
1558
1567
  $registryId: String!,
1559
1568
  $componentId: String!
@@ -1578,7 +1587,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1578
1587
  }
1579
1588
  }
1580
1589
  }
1581
- `,s=await this._dataProvider.ExecuteGQL(r,{registryId:e,componentId:t});return s&&s.ResolveComponentDependencies?s.ResolveComponentDependencies:null}catch(r){throw u(r),new Error(`Failed to resolve component dependencies: ${r instanceof Error?r.message:"Unknown error"}`)}}async ComponentExists(e){try{return await this.GetRegistryComponent(e)!==null}catch{return!1}}async GetLatestVersion(e,t,r){try{return(await this.GetRegistryComponent({registryName:e,namespace:t,name:r,version:"latest"}))?.version||null}catch(s){return u(s),null}}async SendComponentFeedback(e){try{const t=c`
1590
+ `,s=await this._dataProvider.ExecuteGQL(r,{registryId:e,componentId:t});return s&&s.ResolveComponentDependencies?s.ResolveComponentDependencies:null}catch(r){throw l(r),new Error(`Failed to resolve component dependencies: ${r instanceof Error?r.message:"Unknown error"}`)}}async ComponentExists(e){try{return await this.GetRegistryComponent(e)!==null}catch{return!1}}async GetLatestVersion(e,t,r){try{return(await this.GetRegistryComponent({registryName:e,namespace:t,name:r,version:"latest"}))?.version||null}catch(s){return l(s),null}}async SendComponentFeedback(e){try{const t=c`
1582
1591
  mutation SendComponentFeedback($feedback: ComponentFeedbackInput!) {
1583
1592
  SendComponentFeedback(feedback: $feedback) {
1584
1593
  success
@@ -1586,7 +1595,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1586
1595
  error
1587
1596
  }
1588
1597
  }
1589
- `,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return u(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}}class rt{static{l(this,"GraphQLVersionHistoryClient")}constructor(e){this._dataProvider=e}async CreateLabel(e){let t;try{e.OnProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(a=>{try{const i=JSON.parse(a);i.resolver==="VersionHistoryResolver"&&i.type==="CreateLabelProgress"&&i.status==="ok"&&i.data&&e.OnProgress(i.data)}catch{}}));const r=c`
1598
+ `,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return l(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}}class rt{static{d(this,"GraphQLVersionHistoryClient")}constructor(e){this._dataProvider=e}async CreateLabel(e){let t;try{e.OnProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(a=>{try{const i=JSON.parse(a);i.resolver==="VersionHistoryResolver"&&i.type==="CreateLabelProgress"&&i.status==="ok"&&i.data&&e.OnProgress(i.data)}catch{}}));const r=c`
1590
1599
  mutation CreateVersionLabel($input: CreateVersionLabelInput!, $sessionId: String) {
1591
1600
  CreateVersionLabel(input: $input, sessionId: $sessionId) {
1592
1601
  Success
@@ -1602,7 +1611,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1602
1611
  }
1603
1612
  }
1604
1613
  }
1605
- `,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 u(`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 st{static{l(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const s=c`
1614
+ `,s={input:this.buildInput(e),sessionId:this._dataProvider.sessionId},n=await this._dataProvider.ExecuteGQL(r,s);return this.processResult(n)}catch(r){const s=r instanceof Error?r.message:String(r);return l(`GraphQLVersionHistoryClient.CreateLabel error: ${s}`),{Success:!1,Error:s}}finally{t&&t.unsubscribe()}}buildInput(e){const t={Name:e.Name};return e.Description!=null&&(t.Description=e.Description),e.Scope!=null&&(t.Scope=e.Scope),e.EntityName!=null&&(t.EntityName=e.EntityName),e.ParentID!=null&&(t.ParentID=e.ParentID),e.ExternalSystemID!=null&&(t.ExternalSystemID=e.ExternalSystemID),e.IncludeDependencies!=null&&(t.IncludeDependencies=e.IncludeDependencies),e.MaxDepth!=null&&(t.MaxDepth=e.MaxDepth),e.ExcludeEntities!=null&&(t.ExcludeEntities=e.ExcludeEntities),e.RecordKeys&&e.RecordKeys.length>0&&(t.RecordKeys=e.RecordKeys.map(r=>({Key:r.Key,Value:r.Value}))),t}processResult(e){const t=e?.CreateVersionLabel;if(!t)return{Success:!1,Error:"Invalid response from server."};const r=Array.isArray(t.CaptureErrors)?t.CaptureErrors.map(s=>({EntityName:s.EntityName??"",RecordID:s.RecordID??"",ErrorMessage:s.ErrorMessage??""})):void 0;return{Success:t.Success,LabelID:t.LabelID,LabelName:t.LabelName,ItemsCaptured:t.ItemsCaptured,SyntheticSnapshotsCreated:t.SyntheticSnapshotsCreated,Error:t.Error,CaptureErrors:r}}}class st{static{d(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const s=c`
1606
1615
  query ListStorageObjects($input: ListStorageObjectsInput!) {
1607
1616
  ListStorageObjects(input: $input) {
1608
1617
  objects {
@@ -1619,34 +1628,34 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1619
1628
  prefixes
1620
1629
  }
1621
1630
  }
1622
- `,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 u(`Error listing storage objects: ${n}`),n}}async DirectoryExists(e,t){try{const r=await this.ListObjects(e,t.endsWith("/")?t:`${t}/`,"/");return r.objects.length>0||r.prefixes.length>0}catch(r){return u(`Error checking directory existence: ${r}`),!1}}async CreateDirectory(e,t){try{const r=c`
1631
+ `,n={input:{AccountID:e,Prefix:t,Delimiter:r||"/"}},a=await this._dataProvider.ExecuteGQL(s,n);if(!a?.ListStorageObjects)throw new Error("Invalid response from server");return{objects:a.ListStorageObjects.objects.map(i=>({...i,lastModified:new Date(i.lastModified)})),prefixes:a.ListStorageObjects.prefixes}}catch(s){const n=s;throw l(`Error listing storage objects: ${n}`),n}}async DirectoryExists(e,t){try{const r=await this.ListObjects(e,t.endsWith("/")?t:`${t}/`,"/");return r.objects.length>0||r.prefixes.length>0}catch(r){return l(`Error checking directory existence: ${r}`),!1}}async CreateDirectory(e,t){try{const r=c`
1623
1632
  mutation CreateDirectory($input: CreateDirectoryInput!) {
1624
1633
  CreateDirectory(input: $input)
1625
1634
  }
1626
- `,s={input:{AccountID:e,Path:t}};return(await this._dataProvider.ExecuteGQL(r,s))?.CreateDirectory??!1}catch(r){return u(`Error creating directory: ${r}`),!1}}async ObjectExists(e,t){try{const r=t.substring(0,t.lastIndexOf("/")+1),s=t.substring(t.lastIndexOf("/")+1);return(await this.ListObjects(e,r,"/")).objects.some(a=>a.name===s||a.fullPath===t)}catch(r){return u(`Error checking object existence: ${r}`),!1}}async CreatePreAuthUploadUrl(e,t,r){try{const s=c`
1635
+ `,s={input:{AccountID:e,Path:t}};return(await this._dataProvider.ExecuteGQL(r,s))?.CreateDirectory??!1}catch(r){return l(`Error creating directory: ${r}`),!1}}async ObjectExists(e,t){try{const r=t.substring(0,t.lastIndexOf("/")+1),s=t.substring(t.lastIndexOf("/")+1);return(await this.ListObjects(e,r,"/")).objects.some(a=>a.name===s||a.fullPath===t)}catch(r){return l(`Error checking object existence: ${r}`),!1}}async CreatePreAuthUploadUrl(e,t,r){try{const s=c`
1627
1636
  mutation CreatePreAuthUploadUrl($input: CreatePreAuthUploadUrlInput!) {
1628
1637
  CreatePreAuthUploadUrl(input: $input) {
1629
1638
  UploadUrl
1630
1639
  ProviderKey
1631
1640
  }
1632
1641
  }
1633
- `,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 u(`Error creating pre-auth upload URL: ${n}`),n}}async CreatePreAuthDownloadUrl(e,t){try{const r=c`
1642
+ `,n={input:{AccountID:e,ObjectName:t,ContentType:r}},a=await this._dataProvider.ExecuteGQL(s,n);if(!a?.CreatePreAuthUploadUrl)throw new Error("Invalid response from server");return{uploadUrl:a.CreatePreAuthUploadUrl.UploadUrl,providerKey:a.CreatePreAuthUploadUrl.ProviderKey}}catch(s){const n=s;throw l(`Error creating pre-auth upload URL: ${n}`),n}}async CreatePreAuthDownloadUrl(e,t){try{const r=c`
1634
1643
  query CreatePreAuthDownloadUrl($input: CreatePreAuthDownloadUrlInput!) {
1635
1644
  CreatePreAuthDownloadUrl(input: $input)
1636
1645
  }
1637
- `,s={input:{AccountID:e,ObjectName:t}},n=await this._dataProvider.ExecuteGQL(r,s);if(n?.CreatePreAuthDownloadUrl===void 0)throw new Error("Invalid response from server");return n.CreatePreAuthDownloadUrl}catch(r){const s=r;throw u(`Error creating pre-auth download URL: ${s}`),s}}async DeleteObject(e,t){try{const r=c`
1646
+ `,s={input:{AccountID:e,ObjectName:t}},n=await this._dataProvider.ExecuteGQL(r,s);if(n?.CreatePreAuthDownloadUrl===void 0)throw new Error("Invalid response from server");return n.CreatePreAuthDownloadUrl}catch(r){const s=r;throw l(`Error creating pre-auth download URL: ${s}`),s}}async DeleteObject(e,t){try{const r=c`
1638
1647
  mutation DeleteStorageObject($input: DeleteStorageObjectInput!) {
1639
1648
  DeleteStorageObject(input: $input)
1640
1649
  }
1641
- `,s={input:{AccountID:e,ObjectName:t}};return(await this._dataProvider.ExecuteGQL(r,s))?.DeleteStorageObject??!1}catch(r){return u(`Error deleting storage object: ${r}`),!1}}async MoveObject(e,t,r){try{const s=c`
1650
+ `,s={input:{AccountID:e,ObjectName:t}};return(await this._dataProvider.ExecuteGQL(r,s))?.DeleteStorageObject??!1}catch(r){return l(`Error deleting storage object: ${r}`),!1}}async MoveObject(e,t,r){try{const s=c`
1642
1651
  mutation MoveStorageObject($input: MoveStorageObjectInput!) {
1643
1652
  MoveStorageObject(input: $input)
1644
1653
  }
1645
- `,n={input:{AccountID:e,OldName:t,NewName:r}};return(await this._dataProvider.ExecuteGQL(s,n))?.MoveStorageObject??!1}catch(s){return u(`Error moving storage object: ${s}`),!1}}async CopyObject(e,t,r){try{const s=c`
1654
+ `,n={input:{AccountID:e,OldName:t,NewName:r}};return(await this._dataProvider.ExecuteGQL(s,n))?.MoveStorageObject??!1}catch(s){return l(`Error moving storage object: ${s}`),!1}}async CopyObject(e,t,r){try{const s=c`
1646
1655
  mutation CopyStorageObject($input: CopyStorageObjectInput!) {
1647
1656
  CopyStorageObject(input: $input)
1648
1657
  }
1649
- `,n={input:{AccountID:e,SourceName:t,DestinationName:r}};return(await this._dataProvider.ExecuteGQL(s,n))?.CopyStorageObject??!1}catch(s){return u(`Error copying storage object: ${s}`),!1}}async CopyObjectBetweenAccounts(e,t,r,s){try{const n=c`
1658
+ `,n={input:{AccountID:e,SourceName:t,DestinationName:r}};return(await this._dataProvider.ExecuteGQL(s,n))?.CopyStorageObject??!1}catch(s){return l(`Error copying storage object: ${s}`),!1}}async CopyObjectBetweenAccounts(e,t,r,s){try{const n=c`
1650
1659
  mutation CopyObjectBetweenAccounts($input: CopyObjectBetweenAccountsInput!) {
1651
1660
  CopyObjectBetweenAccounts(input: $input) {
1652
1661
  success
@@ -1658,7 +1667,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1658
1667
  destinationPath
1659
1668
  }
1660
1669
  }
1661
- `,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 u(`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=c`
1670
+ `,a={input:{SourceAccountID:e,DestinationAccountID:t,SourcePath:r,DestinationPath:s}},i=await this._dataProvider.ExecuteGQL(n,a);if(!i?.CopyObjectBetweenAccounts)throw new Error("Invalid response from server");return{success:i.CopyObjectBetweenAccounts.success,message:i.CopyObjectBetweenAccounts.message,bytesTransferred:i.CopyObjectBetweenAccounts.bytesTransferred,sourceAccount:i.CopyObjectBetweenAccounts.sourceAccount,destinationAccount:i.CopyObjectBetweenAccounts.destinationAccount,sourcePath:i.CopyObjectBetweenAccounts.sourcePath,destinationPath:i.CopyObjectBetweenAccounts.destinationPath}}catch(n){const a=n;return l(`Error copying object between accounts: ${a}`),{success:!1,message:a.message,sourceAccount:"",destinationAccount:"",sourcePath:r,destinationPath:s}}}async SearchFiles(e,t,r){try{const s=c`
1662
1671
  query SearchAcrossAccounts($input: SearchAcrossAccountsInput!) {
1663
1672
  SearchAcrossAccounts(input: $input) {
1664
1673
  accountResults {
@@ -1686,7 +1695,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1686
1695
  failedAccounts
1687
1696
  }
1688
1697
  }
1689
- `,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:r?.maxResultsPerAccount,FileTypes:r?.fileTypes,SearchContent:r?.searchContent}},a=await this._dataProvider.ExecuteGQL(s,n);if(!a?.SearchAcrossAccounts)throw new Error("Invalid response from server");const i=a.SearchAcrossAccounts;return{accountResults:i.accountResults.map(o=>({accountId:o.accountID,accountName:o.accountName,success:o.success,errorMessage:o.errorMessage,results:o.results.map(y=>({path:y.path,name:y.name,size:y.size,contentType:y.contentType,lastModified:new Date(y.lastModified),relevance:y.relevance,excerpt:y.excerpt,matchInFilename:y.matchInFilename,objectId:y.objectId})),totalMatches:o.totalMatches,hasMore:o.hasMore,nextPageToken:o.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(s){return u(`Error searching across accounts: ${s}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}class nt{static{l(this,"GraphQLSearchClient")}constructor(e){this._dataProvider=e}async ExecuteSearch(e){try{const t=this.buildSearchKnowledgeMutation(),r=this.prepareSearchVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processSearchKnowledgeResult(s)}catch(t){return this.handleSearchError(t)}}async PreviewSearch(e,t){try{const r=this.buildPreviewSearchMutation(),s=this.preparePreviewVariables(e,t),n=await this._dataProvider.ExecuteGQL(r,s);return this.processPreviewSearchResult(n)}catch(r){return this.handleSearchError(r)}}buildSearchKnowledgeMutation(){return c`
1698
+ `,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:r?.maxResultsPerAccount,FileTypes:r?.fileTypes,SearchContent:r?.searchContent}},a=await this._dataProvider.ExecuteGQL(s,n);if(!a?.SearchAcrossAccounts)throw new Error("Invalid response from server");const i=a.SearchAcrossAccounts;return{accountResults:i.accountResults.map(o=>({accountId:o.accountID,accountName:o.accountName,success:o.success,errorMessage:o.errorMessage,results:o.results.map(y=>({path:y.path,name:y.name,size:y.size,contentType:y.contentType,lastModified:new Date(y.lastModified),relevance:y.relevance,excerpt:y.excerpt,matchInFilename:y.matchInFilename,objectId:y.objectId})),totalMatches:o.totalMatches,hasMore:o.hasMore,nextPageToken:o.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(s){return l(`Error searching across accounts: ${s}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}class nt{static{d(this,"GraphQLSearchClient")}constructor(e){this._dataProvider=e}async ExecuteSearch(e){try{const t=this.buildSearchKnowledgeMutation(),r=this.prepareSearchVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processSearchKnowledgeResult(s)}catch(t){return this.handleSearchError(t)}}async PreviewSearch(e,t){try{const r=this.buildPreviewSearchMutation(),s=this.preparePreviewVariables(e,t),n=await this._dataProvider.ExecuteGQL(r,s);return this.processPreviewSearchResult(n)}catch(r){return this.handleSearchError(r)}}buildSearchKnowledgeMutation(){return c`
1690
1699
  mutation SearchKnowledge($query: String!, $maxResults: Float, $filters: SearchFiltersInput, $minScore: Float, $scopeIDs: [ID!], $searchContext: SearchContextInput) {
1691
1700
  SearchKnowledge(query: $query, maxResults: $maxResults, filters: $filters, minScore: $minScore, scopeIDs: $scopeIDs, searchContext: $searchContext) {
1692
1701
  Success
@@ -1792,7 +1801,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1792
1801
  IsPersonal
1793
1802
  }
1794
1803
  }
1795
- `;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 u(`GraphQLSearchClient.GetSearchScopes failed: ${e instanceof Error?e.message:String(e)}`),[]}}StreamSearch(e){return new x(t=>{const r=c`
1804
+ `;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 l(`GraphQLSearchClient.GetSearchScopes failed: ${e instanceof Error?e.message:String(e)}`),[]}}StreamSearch(e){return new x(t=>{const r=c`
1796
1805
  mutation StreamScopedSearch(
1797
1806
  $query: String!,
1798
1807
  $maxResults: Float,
@@ -1825,7 +1834,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1825
1834
  ElapsedMs
1826
1835
  ErrorMessage
1827
1836
  }
1828
- }`;n=this._dataProvider.subscribe(o,{streamID:i.StreamID}).subscribe({next:l(y=>{const d=y?.SearchStreamEvents;d&&(t.next(d),d.Phase==="final"?(t.complete(),n?.unsubscribe()):d.Phase==="error"&&(t.error(new Error(d.ErrorMessage??"Stream error")),n?.unsubscribe()))},"next"),error:l(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 u(`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 at{static{l(this,"GraphQLIntegrationClient")}constructor(e){this._dataProvider=e}async DiscoverObjects(e){try{const t=c`
1837
+ }`;n=this._dataProvider.subscribe(o,{streamID:i.StreamID}).subscribe({next:d(y=>{const u=y?.SearchStreamEvents;u&&(t.next(u),u.Phase==="final"?(t.complete(),n?.unsubscribe()):u.Phase==="error"&&(t.error(new Error(u.ErrorMessage??"Stream error")),n?.unsubscribe()))},"next"),error:d(y=>t.error(y),"error")})}catch(a){t.error(a)}})(),()=>{n?.unsubscribe()}})}prepareFilters(e){const t={};return e.EntityNames!==void 0&&e.EntityNames.length>0&&(t.EntityNames=e.EntityNames),e.SourceTypes!==void 0&&e.SourceTypes.length>0&&(t.SourceTypes=e.SourceTypes),e.Tags!==void 0&&e.Tags.length>0&&(t.Tags=e.Tags),t}preparePreviewVariables(e,t){const r={query:e};return t!==void 0&&(r.maxResults=t),r}processSearchKnowledgeResult(e){if(!e?.SearchKnowledge)throw new Error("Invalid response from server");const t=e.SearchKnowledge;return this.mapSearchResponse(t)}processPreviewSearchResult(e){if(!e?.PreviewSearch)throw new Error("Invalid response from server");const t=e.PreviewSearch;return this.mapSearchResponse(t)}mapSearchResponse(e){return{Success:e.Success,Results:(e.Results||[]).map(t=>this.mapResultItem(t)),TotalCount:e.TotalCount,ElapsedMs:e.ElapsedMs,SourceCounts:this.mapSourceCounts(e.SourceCounts),Providers:(e.Providers||[]).map(t=>({ID:t.ID,Name:t.Name,DisplayName:t.DisplayName,Icon:t.Icon,SourceType:t.SourceType,Priority:t.Priority})),ErrorMessage:e.ErrorMessage}}mapResultItem(e){return{ID:e.ID,EntityName:e.EntityName,RecordID:e.RecordID,SourceType:e.SourceType,ResultType:e.ResultType,Title:e.Title,Snippet:e.Snippet,Score:e.Score,ScoreBreakdown:this.mapScoreBreakdown(e.ScoreBreakdown),Tags:e.Tags||[],EntityIcon:e.EntityIcon,RecordName:e.RecordName,MatchedAt:e.MatchedAt,RawMetadata:e.RawMetadata,ProviderId:e.ProviderId,ProviderLabel:e.ProviderLabel,ProviderIcon:e.ProviderIcon}}mapScoreBreakdown(e){if(!e)return{};const t={};return e.Vector!==void 0&&(t.Vector=e.Vector),e.FullText!==void 0&&(t.FullText=e.FullText),e.Entity!==void 0&&(t.Entity=e.Entity),e.Storage!==void 0&&(t.Storage=e.Storage),t}mapSourceCounts(e){return e?{Vector:e.Vector??0,FullText:e.FullText??0,Entity:e.Entity??0,Storage:e.Storage??0}:{Vector:0,FullText:0,Entity:0,Storage:0}}handleSearchError(e){const t=e;return l(`Error executing search: ${t}`),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,SourceCounts:{Vector:0,FullText:0,Entity:0,Storage:0},Providers:[],ErrorMessage:`Error: ${t.message}`}}}class at{static{d(this,"GraphQLIntegrationClient")}constructor(e){this._dataProvider=e}async DiscoverObjects(e){try{const t=c`
1829
1838
  query IntegrationDiscoverObjects($companyIntegrationID: String!) {
1830
1839
  IntegrationDiscoverObjects(companyIntegrationID: $companyIntegrationID) {
1831
1840
  Success
@@ -1861,7 +1870,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1861
1870
  ServerVersion
1862
1871
  }
1863
1872
  }
1864
- `,s=(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationTestConnection;if(!s)throw new Error("Invalid response from server");return{Success:s.Success,Message:s.Message,ServerVersion:s.ServerVersion??null}}catch(t){const r=t;return u(`Error testing integration connection: ${r}`),{Success:!1,Message:`Error: ${r.message}`,ServerVersion:null}}}async SchemaPreview(e,t,r="sqlserver"){try{const s=c`
1873
+ `,s=(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationTestConnection;if(!s)throw new Error("Invalid response from server");return{Success:s.Success,Message:s.Message,ServerVersion:s.ServerVersion??null}}catch(t){const r=t;return l(`Error testing integration connection: ${r}`),{Success:!1,Message:`Error: ${r.message}`,ServerVersion:null}}}async SchemaPreview(e,t,r="sqlserver"){try{const s=c`
1865
1874
  query IntegrationSchemaPreview(
1866
1875
  $companyIntegrationID: String!,
1867
1876
  $objects: [SchemaPreviewObjectInput!]!,
@@ -1882,7 +1891,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1882
1891
  Warnings
1883
1892
  }
1884
1893
  }
1885
- `,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 u(`Error generating schema preview: ${n}`),{Success:!1,Message:`Error: ${n.message}`,Files:[],Warnings:[]}}}async PreviewData(e,t,r=5){try{const s=c`
1894
+ `,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 l(`Error generating schema preview: ${n}`),{Success:!1,Message:`Error: ${n.message}`,Files:[],Warnings:[]}}}async PreviewData(e,t,r=5){try{const s=c`
1886
1895
  query IntegrationPreviewData(
1887
1896
  $companyIntegrationID: String!,
1888
1897
  $objectName: String!,
@@ -1900,7 +1909,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1900
1909
  }
1901
1910
  }
1902
1911
  }
1903
- `,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 u(`Error previewing integration data: ${n}`),{Success:!1,Message:`Error: ${n.message}`,Records:[]}}}async GetDefaultConfig(e){try{const t=c`
1912
+ `,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 l(`Error previewing integration data: ${n}`),{Success:!1,Message:`Error: ${n.message}`,Records:[]}}}async GetDefaultConfig(e){try{const t=c`
1904
1913
  query IntegrationGetDefaultConfig($companyIntegrationID: String!) {
1905
1914
  IntegrationGetDefaultConfig(companyIntegrationID: $companyIntegrationID) {
1906
1915
  Success
@@ -1919,7 +1928,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1919
1928
  }
1920
1929
  }
1921
1930
  }
1922
- `,s=(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationGetDefaultConfig;if(!s)throw new Error("Invalid response from server");return{Success:s.Success,Message:s.Message,DefaultSchemaName:s.DefaultSchemaName,DefaultObjects:s.DefaultObjects??[]}}catch(t){const r=t;return u(`Error getting default config: ${r}`),{Success:!1,Message:`Error: ${r.message}`}}}async CreateConnection(e){try{const t=c`mutation IntegrationCreateConnection($input: CreateConnectionInput!) {
1931
+ `,s=(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationGetDefaultConfig;if(!s)throw new Error("Invalid response from server");return{Success:s.Success,Message:s.Message,DefaultSchemaName:s.DefaultSchemaName,DefaultObjects:s.DefaultObjects??[]}}catch(t){const r=t;return l(`Error getting default config: ${r}`),{Success:!1,Message:`Error: ${r.message}`}}}async CreateConnection(e){try{const t=c`mutation IntegrationCreateConnection($input: CreateConnectionInput!) {
1923
1932
  IntegrationCreateConnection(input: $input) { Success Message CompanyIntegrationID CredentialID }
1924
1933
  }`;return(await this._dataProvider.ExecuteGQL(t,{input:e}))?.IntegrationCreateConnection??{Success:!1,Message:"No response"}}catch(t){return{Success:!1,Message:t.message}}}async UpdateConnection(e,t,r,s){try{const n=c`mutation IntegrationUpdateConnection(
1925
1934
  $companyIntegrationID: String!, $credentialValues: String, $configuration: String, $externalSystemID: String
@@ -1976,7 +1985,7 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
1976
1985
  PipelineSteps { Name Status DurationMs Message }
1977
1986
  GitCommitSuccess APIRestarted
1978
1987
  }
1979
- }`,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},d=(await this._dataProvider.ExecuteGQL(o,{input:y,platform:n,skipGitCommit:a,skipRestart:i}))?.IntegrationApplyAllBatch;return d?{Success:d.Success,Message:d.Message,Steps:d.PipelineSteps,GitCommitSuccess:d.GitCommitSuccess,APIRestarted:d.APIRestarted,EntityMapsCreated:d.ConnectorResults?.[0]?.EntityMapsCreated,SyncRunID:d.ConnectorResults?.[0]?.SyncRunID,Warnings:d.ConnectorResults?.flatMap(f=>f.Warnings??[])}:{Success:!1,Message:"No response"}}catch(o){return{Success:!1,Message:o.message}}}async ApplyAll(e,t,r="sqlserver",s=!1,n=!1){try{const a=c`mutation IntegrationApplyAll(
1988
+ }`,y={Connectors:e.map(h=>({CompanyIntegrationID:h.CompanyIntegrationID,SourceObjects:h.SourceObjects.map(f=>({SourceObjectID:f.SourceObjectID??null,SourceObjectName:f.SourceObjectName??null,Fields:f.Fields??null}))})),StartSync:t,FullSync:r,SyncScope:s},u=(await this._dataProvider.ExecuteGQL(o,{input:y,platform:n,skipGitCommit:a,skipRestart:i}))?.IntegrationApplyAllBatch;return u?{Success:u.Success,Message:u.Message,Steps:u.PipelineSteps,GitCommitSuccess:u.GitCommitSuccess,APIRestarted:u.APIRestarted,EntityMapsCreated:u.ConnectorResults?.[0]?.EntityMapsCreated,SyncRunID:u.ConnectorResults?.[0]?.SyncRunID,Warnings:u.ConnectorResults?.flatMap(h=>h.Warnings??[])}:{Success:!1,Message:"No response"}}catch(o){return{Success:!1,Message:o.message}}}async ApplyAll(e,t,r="sqlserver",s=!1,n=!1){try{const a=c`mutation IntegrationApplyAll(
1980
1989
  $input: ApplyAllInput!, $platform: String!, $skipGitCommit: Boolean!, $skipRestart: Boolean!
1981
1990
  ) {
1982
1991
  IntegrationApplyAll(input: $input, platform: $platform, skipGitCommit: $skipGitCommit, skipRestart: $skipRestart) {
@@ -2018,5 +2027,5 @@ var se=Object.defineProperty;var l=(g,e)=>se(g,"name",{value:e,configurable:!0})
2018
2027
  IntegrationGetConnectorCapabilities(companyIntegrationID: $companyIntegrationID) {
2019
2028
  Success Message SupportsGet SupportsCreate SupportsUpdate SupportsDelete SupportsSearch
2020
2029
  }
2021
- }`;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 u(`Error in integration discovery: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Data:t}}}export{Ue as ActionItemInput,Ve as ActionItemOutput,Z as BrowserIndexedDBStorageProvider,X as BrowserStorageProviderBase,A as FieldMapper,$ as FireAndForgetHelper,Oe as GetDataOutput,H as GraphQLAIClient,Be as GraphQLActionClient,Ze as GraphQLClassifyClient,Xe as GraphQLClusterClient,tt as GraphQLComponentRegistryClient,h as GraphQLDataProvider,He as GraphQLEncryptionClient,st as GraphQLFileStorageClient,at as GraphQLIntegrationClient,je as GraphQLListsClient,Ye as GraphQLLiveKitClient,be as GraphQLProviderConfigData,nt as GraphQLSearchClient,_e as GraphQLSystemUserClient,et as GraphQLTestingClient,z as GraphQLTransactionGroup,rt as GraphQLVersionHistoryClient,F as PACKAGE_VERSION,Le as RoleInput,Qe as RolesAndUsersInput,qe as SimpleRemoteEntity,Ke as SimpleRemoteEntityField,ke as SimpleRemoteEntityOutput,ee as SyncDataAction,Ge as SyncDataResult,xe as SyncRolesAndUsersResult,Fe as UserInput,ht as gql,Te as setupGraphQLClient};
2030
+ }`;return(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationGetConnectorCapabilities??{Success:!1,Message:"No response"}}catch(t){return{Success:!1,Message:t.message}}}handleError(e,t){const r=e;return l(`Error in integration discovery: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Data:t}}}export{Ge as ActionItemInput,Ve as ActionItemOutput,Z as BrowserIndexedDBStorageProvider,X as BrowserStorageProviderBase,M as FieldMapper,$ as FireAndForgetHelper,Oe as GetDataOutput,H as GraphQLAIClient,Be as GraphQLActionClient,Ze as GraphQLClassifyClient,Xe as GraphQLClusterClient,tt as GraphQLComponentRegistryClient,I as GraphQLDataProvider,He as GraphQLEncryptionClient,st as GraphQLFileStorageClient,at as GraphQLIntegrationClient,je as GraphQLListsClient,Ye as GraphQLLiveKitClient,be as GraphQLProviderConfigData,nt as GraphQLSearchClient,_e as GraphQLSystemUserClient,et as GraphQLTestingClient,z as GraphQLTransactionGroup,rt as GraphQLVersionHistoryClient,F as PACKAGE_VERSION,Le as RoleInput,Qe as RolesAndUsersInput,qe as SimpleRemoteEntity,Ke as SimpleRemoteEntityField,ke as SimpleRemoteEntityOutput,ee as SyncDataAction,Ue as SyncDataResult,xe as SyncRolesAndUsersResult,Fe as UserInput,ht as gql,Te as setupGraphQLClient};
2022
2031
  //# sourceMappingURL=index.mjs.map