@memberjunction/react-runtime 5.3.0 → 5.4.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.
@@ -1,4 +1,4 @@
1
- "use strict";(this.webpackChunkMJReactRuntime=this.webpackChunkMJReactRuntime||[]).push([[324],{324(e,t,r){r.r(t),r.d(t,{ActionItemInput:()=>M,ActionItemOutput:()=>G,BrowserIndexedDBStorageProvider:()=>w,BrowserStorageProviderBase:()=>R,FieldMapper:()=>g,GetDataOutput:()=>T,GraphQLAIClient:()=>I,GraphQLActionClient:()=>_,GraphQLComponentRegistryClient:()=>k,GraphQLDataProvider:()=>P,GraphQLEncryptionClient:()=>O,GraphQLFileStorageClient:()=>j,GraphQLProviderConfigData:()=>f,GraphQLSystemUserClient:()=>L,GraphQLTestingClient:()=>K,GraphQLTransactionGroup:()=>h,GraphQLVersionHistoryClient:()=>J,RoleInput:()=>v,RolesAndUsersInput:()=>N,SimpleRemoteEntity:()=>F,SimpleRemoteEntityField:()=>V,SimpleRemoteEntityOutput:()=>U,SyncDataAction:()=>x,SyncDataResult:()=>Q,SyncRolesAndUsersResult:()=>$,UserInput:()=>A,gql:()=>s.J1,setupGraphQLClient:()=>C});var s=r(215),a=r(454),n=r(429),o=r(600),i=r(49),u=r(226),c=r(497),l=r(718),d=r(292),m=r(196),y=Object.defineProperty,p=(e,t)=>y(e,"name",{value:t,configurable:!0});class g{static{p(this,"FieldMapper")}constructor(){this._fieldMap={__mj_CreatedAt:"_mj__CreatedAt",__mj_UpdatedAt:"_mj__UpdatedAt",__mj_DeletedAt:"_mj__DeletedAt"}}MapFields(e){if(e)for(const t in e)t in this._fieldMap&&(e[this._fieldMap[t]]=e[t],delete e[t]);return e}MapFieldName(e){return this._fieldMap[e]??e}ReverseMapFieldName(e){return Object.entries(this._fieldMap).find(([t,r])=>r===e)?.[0]??e}ReverseMapFields(e){const t=Object.fromEntries(Object.entries(this._fieldMap).map(([e,t])=>[t,e]));for(const r in e)r in t&&(e[t[r]]=e[r],delete e[r]);return e}}class h extends a.VH{static{p(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=s.J1`
1
+ "use strict";(this.webpackChunkMJReactRuntime=this.webpackChunkMJReactRuntime||[]).push([[324],{324(e,t,r){r.r(t),r.d(t,{ActionItemInput:()=>G,ActionItemOutput:()=>Q,BrowserIndexedDBStorageProvider:()=>C,BrowserStorageProviderBase:()=>D,FieldMapper:()=>g,FireAndForgetHelper:()=>I,GetDataOutput:()=>F,GraphQLAIClient:()=>S,GraphQLActionClient:()=>O,GraphQLComponentRegistryClient:()=>j,GraphQLDataProvider:()=>P,GraphQLEncryptionClient:()=>k,GraphQLFileStorageClient:()=>B,GraphQLProviderConfigData:()=>f,GraphQLSystemUserClient:()=>L,GraphQLTestingClient:()=>K,GraphQLTransactionGroup:()=>h,GraphQLVersionHistoryClient:()=>J,RoleInput:()=>A,RolesAndUsersInput:()=>b,SimpleRemoteEntity:()=>U,SimpleRemoteEntityField:()=>_,SimpleRemoteEntityOutput:()=>V,SyncDataAction:()=>M,SyncDataResult:()=>T,SyncRolesAndUsersResult:()=>v,UserInput:()=>N,gql:()=>s.J1,setupGraphQLClient:()=>$});var s=r(215),a=r(454),n=r(429),o=r(600),i=r(49),u=r(226),c=r(497),l=r(718),d=r(292),m=r(196),p=Object.defineProperty,y=(e,t)=>p(e,"name",{value:t,configurable:!0});class g{static{y(this,"FieldMapper")}constructor(){this._fieldMap={__mj_CreatedAt:"_mj__CreatedAt",__mj_UpdatedAt:"_mj__UpdatedAt",__mj_DeletedAt:"_mj__DeletedAt"}}MapFields(e){if(e)for(const t in e)t in this._fieldMap&&(e[this._fieldMap[t]]=e[t],delete e[t]);return e}MapFieldName(e){return this._fieldMap[e]??e}ReverseMapFieldName(e){return Object.entries(this._fieldMap).find(([t,r])=>r===e)?.[0]??e}ReverseMapFields(e){const t=Object.fromEntries(Object.entries(this._fieldMap).map(([e,t])=>[t,e]));for(const r in e)r in t&&(e[t[r]]=e[r],delete e[r]);return e}}class h extends a.VH{static{y(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=s.J1`
2
2
  mutation ExecuteTransactionGroup($group: TransactionInputType!) {
3
3
  ExecuteTransactionGroup(group: $group) {
4
4
  Success
@@ -6,7 +6,7 @@
6
6
  ResultsJSON
7
7
  }
8
8
  }
9
- `,t=[];for(const e of this.PendingTransactions)t.push({EntityName:e.BaseEntity.EntityInfo.Name,EntityObjectJSON:await e.BaseEntity.GetDataObjectJSON(),OperationType:e.OperationType});const r={group:{Items:t,Variables:this.Variables.map(e=>({Name:e.Name,ItemIndex:this.MapVariableEntityObjectToPosition(e),FieldName:e.FieldName,Type:e.Type}))}},n=await this._provider.ExecuteGQL(e,r);if(n&&n.ExecuteTransactionGroup){const e=n.ExecuteTransactionGroup,t=[];for(let r=0;r<this.PendingTransactions.length;r++){const s=e.ResultsJSON[r],n=(0,d.NG)(s),o=this.PendingTransactions[r];t.push(new a.qT(o,n,null!==n))}return t}throw new Error("Failed to execute transaction group")}}class I{static{p(this,"GraphQLAIClient")}static{this.FIRE_AND_FORGET_TIMEOUT_MS=9e5}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=s.J1`
9
+ `,t=[];for(const e of this.PendingTransactions)t.push({EntityName:e.BaseEntity.EntityInfo.Name,EntityObjectJSON:await e.BaseEntity.GetDataObjectJSON(),OperationType:e.OperationType});const r={group:{Items:t,Variables:this.Variables.map(e=>({Name:e.Name,ItemIndex:this.MapVariableEntityObjectToPosition(e),FieldName:e.FieldName,Type:e.Type}))}},n=await this._provider.ExecuteGQL(e,r);if(n&&n.ExecuteTransactionGroup){const e=n.ExecuteTransactionGroup,t=[];for(let r=0;r<this.PendingTransactions.length;r++){const s=e.ResultsJSON[r],n=(0,d.NG)(s),o=this.PendingTransactions[r];t.push(new a.qT(o,n,null!==n))}return t}throw new Error("Failed to execute transaction group")}}class I{static{y(this,"FireAndForgetHelper")}static async Execute(e){const t=e.operationLabel??e.mutationFieldName;let r,s;try{const{promise:n,resolve:o,reject:i}=I.createCompletionPromise();s=I.setupTimeout(i,e.timeoutMs,e.timeoutErrorMessage),r=I.subscribeToPubSub(e,o,s);const u=await I.executeMutation(e);if(!e.validateAck(u)){s&&clearTimeout(s);const r=u?.errorMessage??"Server rejected the request";return(0,a.ZI)(`[FireAndForget:${t}] Server rejected: ${r}`),e.createErrorResult(r)}return(0,a.b0)(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await n}catch(e){throw s&&clearTimeout(s),(0,a.ZI)(`[FireAndForget:${t}] Error: ${e.message}`),e}finally{s&&clearTimeout(s),r&&r.unsubscribe()}}static createCompletionPromise(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}static setupTimeout(e,t,r){const s=r??"The operation may still be running on the server but the client timed out after 15 minutes. Please refresh the page to check the latest status.";return setTimeout(()=>{e(new Error(s))},t??9e5)}static subscribeToPubSub(e,t,r){const s=e.dataProvider.sessionId,n=e.operationLabel??e.mutationFieldName;return e.dataProvider.PushStatusUpdates(s).subscribe(s=>{try{const o=JSON.parse(s);e.onMessage&&e.onMessage(o),e.isCompletionEvent(o)&&(clearTimeout(r),(0,a.b0)(`[FireAndForget:${n}] Completion event received`),t(e.extractResult(o)))}catch(e){console.error(`[FireAndForget:${n}] Failed to parse PubSub message:`,e)}})}static async executeMutation(e){return(await e.dataProvider.ExecuteGQL(e.mutation,e.variables))[e.mutationFieldName]}}class S{static{y(this,"GraphQLAIClient")}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=s.J1`
10
10
  mutation RunAIPrompt(
11
11
  $promptId: String!,
12
12
  $data: String,
@@ -65,85 +65,87 @@
65
65
  chatResult
66
66
  }
67
67
  }
68
- `,r=this.preparePromptVariables(e),a=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(a)}catch(e){return this.handlePromptError(e)}}preparePromptVariables(e){const t={promptId:e.promptId};return void 0!==e.data&&(t.data="object"==typeof e.data?JSON.stringify(e.data):e.data),void 0!==e.templateData&&(t.templateData="object"==typeof e.templateData?JSON.stringify(e.templateData):e.templateData),void 0!==e.messages&&(t.messages=JSON.stringify(e.messages)),void 0!==e.overrideModelId&&(t.overrideModelId=e.overrideModelId),void 0!==e.overrideVendorId&&(t.overrideVendorId=e.overrideVendorId),void 0!==e.configurationId&&(t.configurationId=e.configurationId),void 0!==e.skipValidation&&(t.skipValidation=e.skipValidation),void 0!==e.responseFormat&&(t.responseFormat=e.responseFormat),void 0!==e.temperature&&(t.temperature=e.temperature),void 0!==e.topP&&(t.topP=e.topP),void 0!==e.topK&&(t.topK=e.topK),void 0!==e.minP&&(t.minP=e.minP),void 0!==e.frequencyPenalty&&(t.frequencyPenalty=e.frequencyPenalty),void 0!==e.presencePenalty&&(t.presencePenalty=e.presencePenalty),void 0!==e.seed&&(t.seed=e.seed),void 0!==e.stopSequences&&(t.stopSequences=e.stopSequences),void 0!==e.includeLogProbs&&(t.includeLogProbs=e.includeLogProbs),void 0!==e.topLogProbs&&(t.topLogProbs=e.topLogProbs),void 0!==e.rerunFromPromptRunID&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),void 0!==e.systemPromptOverride&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,a;try{t.parsedResult&&(r=JSON.parse(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(a=JSON.parse(t.chatResult))}catch{a=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:a}}handlePromptError(e){const t=e;return(0,a.ZI)(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){let n;try{e.onProgress&&(n=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(t=>{try{(0,a.Mo)({message:"[GraphQLAIClient] Received statusUpdate message",verboseOnly:!0,additionalArgs:[t]});const r=JSON.parse(t);if((0,a.Mo)({message:"[GraphQLAIClient] Parsed message",verboseOnly:!0,additionalArgs:[r]}),"RunAIAgentResolver"===r.resolver&&"ExecutionProgress"===r.type&&"ok"===r.status&&r.data?.progress){(0,a.Mo)({message:"[GraphQLAIClient] Forwarding progress to callback",verboseOnly:!0,additionalArgs:[r.data.progress]});const t={...r.data.progress,metadata:{...r.data.progress.metadata||{},agentRunId:r.data.agentRunId}};e.onProgress(t)}else(0,a.Mo)({message:"[GraphQLAIClient] Message does not match filter criteria",verboseOnly:!0,additionalArgs:[{resolver:r.resolver,type:r.type,status:r.status,hasProgress:!!r.data?.progress}]})}catch(e){console.error("[GraphQLAIClient] Failed to parse progress message:",e,"Raw message:",t)}}));const o=s.J1`
69
- mutation RunAIAgent(
70
- $agentId: String!,
71
- $messages: String!,
72
- $sessionId: String!,
73
- $data: String,
74
- $payload: String,
75
- $templateData: String,
76
- $lastRunId: String,
77
- $autoPopulateLastRunPayload: Boolean,
78
- $configurationId: String,
79
- $conversationDetailId: String,
80
- $createArtifacts: Boolean,
81
- $createNotification: Boolean,
82
- $sourceArtifactId: String,
83
- $sourceArtifactVersionId: String
68
+ `,r=this.preparePromptVariables(e),a=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(a)}catch(e){return this.handlePromptError(e)}}preparePromptVariables(e){const t={promptId:e.promptId};return void 0!==e.data&&(t.data="object"==typeof e.data?JSON.stringify(e.data):e.data),void 0!==e.templateData&&(t.templateData="object"==typeof e.templateData?JSON.stringify(e.templateData):e.templateData),void 0!==e.messages&&(t.messages=JSON.stringify(e.messages)),void 0!==e.overrideModelId&&(t.overrideModelId=e.overrideModelId),void 0!==e.overrideVendorId&&(t.overrideVendorId=e.overrideVendorId),void 0!==e.configurationId&&(t.configurationId=e.configurationId),void 0!==e.skipValidation&&(t.skipValidation=e.skipValidation),void 0!==e.responseFormat&&(t.responseFormat=e.responseFormat),void 0!==e.temperature&&(t.temperature=e.temperature),void 0!==e.topP&&(t.topP=e.topP),void 0!==e.topK&&(t.topK=e.topK),void 0!==e.minP&&(t.minP=e.minP),void 0!==e.frequencyPenalty&&(t.frequencyPenalty=e.frequencyPenalty),void 0!==e.presencePenalty&&(t.presencePenalty=e.presencePenalty),void 0!==e.seed&&(t.seed=e.seed),void 0!==e.stopSequences&&(t.stopSequences=e.stopSequences),void 0!==e.includeLogProbs&&(t.includeLogProbs=e.includeLogProbs),void 0!==e.topLogProbs&&(t.topLogProbs=e.topLogProbs),void 0!==e.rerunFromPromptRunID&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),void 0!==e.systemPromptOverride&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,a;try{t.parsedResult&&(r=JSON.parse(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(a=JSON.parse(t.chatResult))}catch{a=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:a}}handlePromptError(e){const t=e;return(0,a.ZI)(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){try{const s=this.buildRunAIAgentMutation(),a=this.prepareAgentVariables(e,t,r);return a.fireAndForget=!0,await I.Execute({dataProvider:this._dataProvider,mutation:s,variables:a,mutationFieldName:"RunAIAgent",operationLabel:"RunAIAgent",validateAck:y(e=>!0===e?.success,"validateAck"),isCompletionEvent:y(e=>this.isAgentCompletionEvent(e),"isCompletionEvent"),extractResult:y(e=>this.extractAgentResult(e),"extractResult"),onMessage:e.onProgress?t=>this.forwardAgentProgress(t,e.onProgress):void 0,createErrorResult:y(e=>this.createAgentErrorResult(e),"createErrorResult")})}catch(e){return this.handleAgentError(e)}}buildRunAIAgentMutation(){return s.J1`
69
+ mutation RunAIAgent(
70
+ $agentId: String!,
71
+ $messages: String!,
72
+ $sessionId: String!,
73
+ $data: String,
74
+ $payload: String,
75
+ $templateData: String,
76
+ $lastRunId: String,
77
+ $autoPopulateLastRunPayload: Boolean,
78
+ $configurationId: String,
79
+ $conversationDetailId: String,
80
+ $createArtifacts: Boolean,
81
+ $createNotification: Boolean,
82
+ $sourceArtifactId: String,
83
+ $sourceArtifactVersionId: String,
84
+ $fireAndForget: Boolean
85
+ ) {
86
+ RunAIAgent(
87
+ agentId: $agentId,
88
+ messages: $messages,
89
+ sessionId: $sessionId,
90
+ data: $data,
91
+ payload: $payload,
92
+ templateData: $templateData,
93
+ lastRunId: $lastRunId,
94
+ autoPopulateLastRunPayload: $autoPopulateLastRunPayload,
95
+ configurationId: $configurationId,
96
+ conversationDetailId: $conversationDetailId,
97
+ createArtifacts: $createArtifacts,
98
+ createNotification: $createNotification,
99
+ sourceArtifactId: $sourceArtifactId,
100
+ sourceArtifactVersionId: $sourceArtifactVersionId,
101
+ fireAndForget: $fireAndForget
84
102
  ) {
85
- RunAIAgent(
86
- agentId: $agentId,
87
- messages: $messages,
88
- sessionId: $sessionId,
89
- data: $data,
90
- payload: $payload,
91
- templateData: $templateData,
92
- lastRunId: $lastRunId,
93
- autoPopulateLastRunPayload: $autoPopulateLastRunPayload,
94
- configurationId: $configurationId,
95
- conversationDetailId: $conversationDetailId,
96
- createArtifacts: $createArtifacts,
97
- createNotification: $createNotification,
98
- sourceArtifactId: $sourceArtifactId,
99
- sourceArtifactVersionId: $sourceArtifactVersionId
100
- ) {
101
- success
102
- errorMessage
103
- executionTimeMs
104
- result
105
- }
103
+ success
104
+ errorMessage
105
+ executionTimeMs
106
+ result
106
107
  }
107
- `,i=this.prepareAgentVariables(e,t,r),u=await this._dataProvider.ExecuteGQL(o,i);return this.processAgentResult(u.RunAIAgent?.result)}catch(e){return this.handleAgentError(e)}finally{n&&n.unsubscribe()}}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return void 0!==e.data&&(s.data="object"==typeof e.data?JSON.stringify(e.data):e.data),void 0!==e.payload&&(s.payload="object"==typeof e.payload?JSON.stringify(e.payload):e.payload),void 0!==e.lastRunId&&(s.lastRunId=e.lastRunId),void 0!==e.autoPopulateLastRunPayload&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),void 0!==e.configurationId&&(s.configurationId=e.configurationId),void 0!==e.conversationDetailId&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),void 0!==t&&(s.sourceArtifactId=t),void 0!==r&&(s.sourceArtifactVersionId=r),s}processAgentResult(e){return(0,d.NG)(e)}handleAgentError(e){const t=e?.message||String(e);(0,a.ZI)(`Error running AI agent: ${t}`);const r=t.includes("Failed to fetch")||t.includes("NetworkError");let s;return t.includes("timed out")||t.includes("timeout"),s=r?"Lost connection to the server. The agent may still be running. Please refresh to check the latest status.":t,{success:!1,agentRun:void 0,errorMessage:s}}async RunAIAgentFromConversationDetail(e){let t,r;try{let a,n;const o=new Promise((e,t)=>{a=e,n=t});r=setTimeout(()=>{n(new Error("The agent may still be running on the server but the connection timed out after 15 minutes. Please refresh the page to check the latest status."))},I.FIRE_AND_FORGET_TIMEOUT_MS),t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(t=>{try{const s=JSON.parse(t);if(e.onProgress&&"RunAIAgentResolver"===s.resolver&&"ExecutionProgress"===s.type&&"ok"===s.status&&s.data?.progress){const t={...s.data.progress,metadata:{...s.data.progress.metadata||{},agentRunId:s.data.agentRunId}};e.onProgress(t)}"RunAIAgentResolver"===s.resolver&&"StreamingContent"===s.type&&"ok"===s.status&&"complete"===s.data?.type&&s.data?.conversationDetailId===e.conversationDetailId&&(r&&clearTimeout(r),s.data.result?a((0,d.NG)(s.data.result)):a({success:!1!==s.data.success,agentRun:void 0}))}catch(e){console.error("[GraphQLAIClient] Failed to parse progress message:",e)}});const i=s.J1`
108
- mutation RunAIAgentFromConversationDetail(
109
- $conversationDetailId: String!,
110
- $agentId: String!,
111
- $sessionId: String!,
112
- $maxHistoryMessages: Int,
113
- $data: String,
114
- $payload: String,
115
- $lastRunId: String,
116
- $autoPopulateLastRunPayload: Boolean,
117
- $configurationId: String,
118
- $createArtifacts: Boolean,
119
- $createNotification: Boolean,
120
- $sourceArtifactId: String,
121
- $sourceArtifactVersionId: String,
122
- $fireAndForget: Boolean
108
+ }
109
+ `}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return void 0!==e.data&&(s.data="object"==typeof e.data?JSON.stringify(e.data):e.data),void 0!==e.payload&&(s.payload="object"==typeof e.payload?JSON.stringify(e.payload):e.payload),void 0!==e.lastRunId&&(s.lastRunId=e.lastRunId),void 0!==e.autoPopulateLastRunPayload&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),void 0!==e.configurationId&&(s.configurationId=e.configurationId),void 0!==e.conversationDetailId&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),void 0!==t&&(s.sourceArtifactId=t),void 0!==r&&(s.sourceArtifactVersionId=r),s}processAgentResult(e){return(0,d.NG)(e)}handleAgentError(e){const t=e?.message||String(e);(0,a.ZI)(`Error running AI agent: ${t}`);const r=t.includes("Failed to fetch")||t.includes("NetworkError");let s;return t.includes("timed out")||t.includes("timeout"),s=r?"Lost connection to the server. The agent may still be running. Please refresh to check the latest status.":t,{success:!1,agentRun:void 0,errorMessage:s}}async RunAIAgentFromConversationDetail(e){try{const t=this.buildConversationDetailMutation(),r=this.prepareConversationDetailVariables(e);return await I.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunAIAgentFromConversationDetail",operationLabel:"RunAIAgentFromConversationDetail",validateAck:y(e=>!0===e?.success,"validateAck"),isCompletionEvent:y(t=>this.isConversationDetailCompletionEvent(t,e.conversationDetailId),"isCompletionEvent"),extractResult:y(e=>this.extractAgentResult(e),"extractResult"),onMessage:e.onProgress?t=>this.forwardConversationDetailProgress(t,e.onProgress):void 0,createErrorResult:y(e=>this.createAgentErrorResult(e),"createErrorResult")})}catch(e){return this.handleAgentError(e)}}buildConversationDetailMutation(){return s.J1`
110
+ mutation RunAIAgentFromConversationDetail(
111
+ $conversationDetailId: String!,
112
+ $agentId: String!,
113
+ $sessionId: String!,
114
+ $maxHistoryMessages: Int,
115
+ $data: String,
116
+ $payload: String,
117
+ $lastRunId: String,
118
+ $autoPopulateLastRunPayload: Boolean,
119
+ $configurationId: String,
120
+ $createArtifacts: Boolean,
121
+ $createNotification: Boolean,
122
+ $sourceArtifactId: String,
123
+ $sourceArtifactVersionId: String,
124
+ $fireAndForget: Boolean
125
+ ) {
126
+ RunAIAgentFromConversationDetail(
127
+ conversationDetailId: $conversationDetailId,
128
+ agentId: $agentId,
129
+ sessionId: $sessionId,
130
+ maxHistoryMessages: $maxHistoryMessages,
131
+ data: $data,
132
+ payload: $payload,
133
+ lastRunId: $lastRunId,
134
+ autoPopulateLastRunPayload: $autoPopulateLastRunPayload,
135
+ configurationId: $configurationId,
136
+ createArtifacts: $createArtifacts,
137
+ createNotification: $createNotification,
138
+ sourceArtifactId: $sourceArtifactId,
139
+ sourceArtifactVersionId: $sourceArtifactVersionId,
140
+ fireAndForget: $fireAndForget
123
141
  ) {
124
- RunAIAgentFromConversationDetail(
125
- conversationDetailId: $conversationDetailId,
126
- agentId: $agentId,
127
- sessionId: $sessionId,
128
- maxHistoryMessages: $maxHistoryMessages,
129
- data: $data,
130
- payload: $payload,
131
- lastRunId: $lastRunId,
132
- autoPopulateLastRunPayload: $autoPopulateLastRunPayload,
133
- configurationId: $configurationId,
134
- createArtifacts: $createArtifacts,
135
- createNotification: $createNotification,
136
- sourceArtifactId: $sourceArtifactId,
137
- sourceArtifactVersionId: $sourceArtifactVersionId,
138
- fireAndForget: $fireAndForget
139
- ) {
140
- success
141
- errorMessage
142
- executionTimeMs
143
- result
144
- }
142
+ success
143
+ errorMessage
144
+ executionTimeMs
145
+ result
145
146
  }
146
- `,u={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId,fireAndForget:!0};void 0!==e.maxHistoryMessages&&(u.maxHistoryMessages=e.maxHistoryMessages),void 0!==e.data&&(u.data="object"==typeof e.data?JSON.stringify(e.data):e.data),void 0!==e.payload&&(u.payload="object"==typeof e.payload?JSON.stringify(e.payload):e.payload),void 0!==e.lastRunId&&(u.lastRunId=e.lastRunId),void 0!==e.autoPopulateLastRunPayload&&(u.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),void 0!==e.configurationId&&(u.configurationId=e.configurationId),void 0!==e.createArtifacts&&(u.createArtifacts=e.createArtifacts),void 0!==e.createNotification&&(u.createNotification=e.createNotification),void 0!==e.sourceArtifactId&&(u.sourceArtifactId=e.sourceArtifactId),void 0!==e.sourceArtifactVersionId&&(u.sourceArtifactVersionId=e.sourceArtifactVersionId);const c=(await this._dataProvider.ExecuteGQL(i,u)).RunAIAgentFromConversationDetail;return c?.success?await o:(r&&clearTimeout(r),{success:!1,agentRun:void 0,errorMessage:c?.errorMessage||"Server rejected the agent execution request"})}catch(e){return r&&clearTimeout(r),this.handleAgentError(e)}finally{r&&clearTimeout(r),t&&t.unsubscribe()}}async ExecuteSimplePrompt(e){try{const t=s.J1`
147
+ }
148
+ `}prepareConversationDetailVariables(e){const t={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId,fireAndForget:!0};return void 0!==e.maxHistoryMessages&&(t.maxHistoryMessages=e.maxHistoryMessages),void 0!==e.data&&(t.data="object"==typeof e.data?JSON.stringify(e.data):e.data),void 0!==e.payload&&(t.payload="object"==typeof e.payload?JSON.stringify(e.payload):e.payload),void 0!==e.lastRunId&&(t.lastRunId=e.lastRunId),void 0!==e.autoPopulateLastRunPayload&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),void 0!==e.configurationId&&(t.configurationId=e.configurationId),void 0!==e.createArtifacts&&(t.createArtifacts=e.createArtifacts),void 0!==e.createNotification&&(t.createNotification=e.createNotification),void 0!==e.sourceArtifactId&&(t.sourceArtifactId=e.sourceArtifactId),void 0!==e.sourceArtifactVersionId&&(t.sourceArtifactVersionId=e.sourceArtifactVersionId),t}isAgentCompletionEvent(e){const t=e.data;return"RunAIAgentResolver"===e.resolver&&"StreamingContent"===e.type&&"complete"===t?.type}isConversationDetailCompletionEvent(e,t){const r=e.data;return"RunAIAgentResolver"===e.resolver&&"StreamingContent"===e.type&&"complete"===r?.type&&r?.conversationDetailId===t}extractAgentResult(e){const t=e.data,r=t.result;return r?(0,d.NG)(r):{success:t.success,agentRun:void 0}}forwardAgentProgress(e,t){if("RunAIAgentResolver"!==e.resolver||"ExecutionProgress"!==e.type||"ok"!==e.status)return;const r=e.data?.progress;r&&t({step:r.currentStep,percentage:r.percentage,message:r.message,metadata:r})}forwardConversationDetailProgress(e,t){if("RunAIAgentResolver"!==e.resolver||"ExecutionProgress"!==e.type||"ok"!==e.status)return;const r=e.data?.progress;r&&t({currentStep:r.currentStep,percentage:r.percentage,message:r.message,metadata:r})}createAgentErrorResult(e){return{success:!1,agentRun:void 0,errorMessage:e}}async ExecuteSimplePrompt(e){try{const t=s.J1`
147
149
  mutation ExecuteSimplePrompt(
148
150
  $systemPrompt: String!,
149
151
  $messages: String,
@@ -181,9 +183,9 @@
181
183
  error
182
184
  }
183
185
  }
184
- `,r={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this._dataProvider.ExecuteGQL(t,r);if(!a?.EmbedText)throw new Error("Invalid response from server");const n=a.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?n.embeddings:n.embeddings[0],modelName:n.modelName,vectorDimensions:n.vectorDimensions,error:n.error}}catch(t){const r=t;return(0,a.ZI)(`Error generating embeddings: ${r}`),{embeddings:(Array.isArray(e.textToEmbed),[]),modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}}const S="default";class R{static{p(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||S;let r=this._storage.get(t);return r||(r=new Map,this._storage.set(t,r)),r}async GetItem(e,t){return this.getCategoryMap(t||S).get(e)??null}async SetItem(e,t,r){this.getCategoryMap(r||S).set(e,t)}async Remove(e,t){this.getCategoryMap(t||S).delete(e)}async ClearCategory(e){const t=e||S;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||S);return t?Array.from(t.keys()):[]}}const D=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"],E="Metadata_KVPairs";class w extends R{static{p(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=(0,m.P2)("MJ_Metadata",3,{upgrade(e){try{e.objectStoreNames.contains(E)&&e.deleteObjectStore(E);for(const t of D)e.objectStoreNames.contains(t)||e.createObjectStore(t)}catch(e){(0,a.Q1)({error:e,message:e?.message})}}}),this.dbPromise.then(()=>{this._dbReady=!0}).catch(e=>{(0,a.Q1)({error:e,message:"IndexedDB initialization failed: "+e?.message})})}isKnownCategory(e){const t=`mj:${e}`;return D.includes(t)}getStoreName(e){const t=e||S;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||S;return this.isKnownCategory(r)?e:`[${r}]:${e}`}async SetItem(e,t,r){try{const s=await this.dbPromise,a=this.getStoreName(r),n=this.getStoreKey(e,r),o=s.transaction(a,"readwrite");await o.objectStore(a).put(t,n),await o.done}catch(s){(0,a.Q1)({error:s,message:s?.message}),await super.SetItem(e,t,r)}}async GetItem(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),a=this.getStoreKey(e,t);return await r.transaction(s).objectStore(s).get(a)??null}catch(r){return(0,a.Q1)({error:r,message:r?.message}),await super.GetItem(e,t)}}async Remove(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),a=this.getStoreKey(e,t),n=r.transaction(s,"readwrite");await n.objectStore(s).delete(a),await n.done}catch(r){(0,a.Q1)({error:r,message:r?.message}),await super.Remove(e,t)}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||S,s=this.getStoreName(e);if(this.isKnownCategory(r)){const e=t.transaction(s,"readwrite");await e.objectStore(s).clear(),await e.done}else{const e=`[${r}]:`,s=t.transaction("mj:default","readwrite"),a=s.objectStore("mj:default"),n=await a.getAllKeys();for(const t of n)"string"==typeof t&&t.startsWith(e)&&await a.delete(t);await s.done}}catch(t){(0,a.Q1)({error:t,message:t?.message}),await super.ClearCategory(e)}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||S,s=this.getStoreName(e),a=await t.transaction(s,"readonly").objectStore(s).getAllKeys();if(this.isKnownCategory(r))return a.map(e=>String(e));const n=`[${r}]:`;return a.map(e=>String(e)).filter(e=>e.startsWith(n)).map(e=>e.slice(n.length))}catch(t){return(0,a.Q1)({error:t,message:t?.message}),await super.GetCategoryKeys(e)}}}class f extends a.dZ{static{p(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}constructor(e,t,r,s,a,n,o,i,u){super({Token:e,URL:t,WSURL:r,MJAPIKey:i,UserAPIKey:u,RefreshTokenFunction:s},a,n,o)}}class P extends a.Dn{static{p(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._innerCurrentUserQueryString=`CurrentUser {\n ${this.userInfoString()}\n MJUserRoles_UserIDArray {\n ${this.userRoleInfoString()}\n }\n }\n `,this._currentUserQuery=s.J1`query CurrentUserAndRoles {
186
+ `,r={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this._dataProvider.ExecuteGQL(t,r);if(!a?.EmbedText)throw new Error("Invalid response from server");const n=a.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?n.embeddings:n.embeddings[0],modelName:n.modelName,vectorDimensions:n.vectorDimensions,error:n.error}}catch(t){const r=t;return(0,a.ZI)(`Error generating embeddings: ${r}`),{embeddings:(Array.isArray(e.textToEmbed),[]),modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}}const R="default";class D{static{y(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||R;let r=this._storage.get(t);return r||(r=new Map,this._storage.set(t,r)),r}async GetItem(e,t){return this.getCategoryMap(t||R).get(e)??null}async SetItem(e,t,r){this.getCategoryMap(r||R).set(e,t)}async Remove(e,t){this.getCategoryMap(t||R).delete(e)}async ClearCategory(e){const t=e||R;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||R);return t?Array.from(t.keys()):[]}}const E=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"],w="Metadata_KVPairs";class C extends D{static{y(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=(0,m.P2)("MJ_Metadata",3,{upgrade(e){try{e.objectStoreNames.contains(w)&&e.deleteObjectStore(w);for(const t of E)e.objectStoreNames.contains(t)||e.createObjectStore(t)}catch(e){(0,a.Q1)({error:e,message:e?.message})}}}),this.dbPromise.then(()=>{this._dbReady=!0}).catch(e=>{(0,a.Q1)({error:e,message:"IndexedDB initialization failed: "+e?.message})})}isKnownCategory(e){const t=`mj:${e}`;return E.includes(t)}getStoreName(e){const t=e||R;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||R;return this.isKnownCategory(r)?e:`[${r}]:${e}`}async SetItem(e,t,r){try{const s=await this.dbPromise,a=this.getStoreName(r),n=this.getStoreKey(e,r),o=s.transaction(a,"readwrite");await o.objectStore(a).put(t,n),await o.done}catch(s){(0,a.Q1)({error:s,message:s?.message}),await super.SetItem(e,t,r)}}async GetItem(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),a=this.getStoreKey(e,t);return await r.transaction(s).objectStore(s).get(a)??null}catch(r){return(0,a.Q1)({error:r,message:r?.message}),await super.GetItem(e,t)}}async Remove(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),a=this.getStoreKey(e,t),n=r.transaction(s,"readwrite");await n.objectStore(s).delete(a),await n.done}catch(r){(0,a.Q1)({error:r,message:r?.message}),await super.Remove(e,t)}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||R,s=this.getStoreName(e);if(this.isKnownCategory(r)){const e=t.transaction(s,"readwrite");await e.objectStore(s).clear(),await e.done}else{const e=`[${r}]:`,s=t.transaction("mj:default","readwrite"),a=s.objectStore("mj:default"),n=await a.getAllKeys();for(const t of n)"string"==typeof t&&t.startsWith(e)&&await a.delete(t);await s.done}}catch(t){(0,a.Q1)({error:t,message:t?.message}),await super.ClearCategory(e)}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||R,s=this.getStoreName(e),a=await t.transaction(s,"readonly").objectStore(s).getAllKeys();if(this.isKnownCategory(r))return a.map(e=>String(e));const n=`[${r}]:`;return a.map(e=>String(e)).filter(e=>e.startsWith(n)).map(e=>e.slice(n.length))}catch(t){return(0,a.Q1)({error:t,message:t?.message}),await super.GetCategoryKeys(e)}}}class f extends a.dZ{static{y(this,"GraphQLProviderConfigData")}get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get MJAPIKey(){return this.Data.MJAPIKey}set MJAPIKey(e){this.Data.MJAPIKey=e}get UserAPIKey(){return this.Data.UserAPIKey}set UserAPIKey(e){this.Data.UserAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}constructor(e,t,r,s,a,n,o,i,u){super({Token:e,URL:t,WSURL:r,MJAPIKey:i,UserAPIKey:u,RefreshTokenFunction:s},a,n,o)}}class P extends a.Dn{static{y(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._innerCurrentUserQueryString=`CurrentUser {\n ${this.userInfoString()}\n MJUserRoles_UserIDArray {\n ${this.userRoleInfoString()}\n }\n }\n `,this._currentUserQuery=s.J1`query CurrentUserAndRoles {
185
187
  ${this._innerCurrentUserQueryString}
186
- }`,this._wsClient=null,this._wsClientCreatedAt=null,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=18e5,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=3e5,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=6e5,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,P._instance||(P._instance=this)}static get Instance(){return P._instance}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new I(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return(0,l.A)()}get LocalStoragePrefix(){if(void 0===this._configData||void 0===this._configData.URL)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)):(P.Instance._configData=e,void 0===P.Instance._sessionId&&(P.Instance._sessionId=await this.GetPreferredUUID(s)),P.Instance._client||(P.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,P.Instance._sessionId,e.MJAPIKey,e.UserAPIKey)),await P.Instance.SaveStoredSessionID(P.Instance._sessionId),this._sessionId=P.Instance._sessionId,this._client=P.Instance._client),super.Config(e)}catch(e){throw(0,a.ZI)(e),e}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),r=t.MJUserRoles_UserIDArray.map(e=>this.ConvertBackToMJFields(e));return t.MJUserRoles_UserIDArray=r,new a.oq(this,{...t,UserRoles:r})}}async RunReport(e,t){const r=s.J1`
188
+ }`,this._wsClient=null,this._wsClientCreatedAt=null,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=18e5,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=3e5,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=6e5,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,P._instance||(P._instance=this)}static get Instance(){return P._instance}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new S(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return(0,l.A)()}get LocalStoragePrefix(){if(void 0===this._configData||void 0===this._configData.URL)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)):(P.Instance._configData=e,void 0===P.Instance._sessionId&&(P.Instance._sessionId=await this.GetPreferredUUID(s)),P.Instance._client||(P.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,P.Instance._sessionId,e.MJAPIKey,e.UserAPIKey)),await P.Instance.SaveStoredSessionID(P.Instance._sessionId),this._sessionId=P.Instance._sessionId,this._client=P.Instance._client),super.Config(e)}catch(e){throw(0,a.ZI)(e),e}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),r=t.MJUserRoles_UserIDArray.map(e=>this.ConvertBackToMJFields(e));return t.MJUserRoles_UserIDArray=r,new a.oq(this,{...t,UserRoles:r})}}async RunReport(e,t){const r=s.J1`
187
189
  query GetReportDataQuery ($ReportID: String!) {
188
190
  GetReportData(ReportID: $ReportID) {
189
191
  Success
@@ -232,7 +234,7 @@
232
234
  }
233
235
  }
234
236
  }
235
- `,a=(await this.ExecuteGQL(r,{input:t}))?.RunQueriesWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const n=a.results.map(e=>{if(("stale"===e.status||"no_validation"===e.status)&&e.Results){const t=JSON.parse(e.Results);return{queryIndex:e.queryIndex,queryId:e.queryId,status:e.status,results:t,maxUpdatedAt:e.maxUpdatedAt,rowCount:e.rowCount,errorMessage:e.errorMessage}}return{queryIndex:e.queryIndex,queryId:e.queryId,status:e.status,maxUpdatedAt:e.maxUpdatedAt,rowCount:e.rowCount,errorMessage:e.errorMessage}});return{success:a.success,results:n,errorMessage:a.errorMessage}}catch(e){return(0,a.ZI)(`Error in RunQueriesWithCacheCheck: ${e}`),{success:!1,results:[],errorMessage:e instanceof Error?e.message:String(e)}}}async InternalRunView(e,t){try{let r="",n="";if(!e)throw"No parameters passed to RunView";{const o={};let i,u;if(e.ViewEntity)u=e.ViewEntity,i=u.Entity;else{const{entityName:r,v:s}=await this.getEntityNameAndUserView(e,t);u=s,i=r}const c=this.Entities.find(e=>e.Name===i);if(!c)throw new Error(`Entity ${i} not found in metadata`);let l=!1;const d=(0,a.I)(c);e.ViewID?(r=`Run${d}ViewByID`,n="RunViewByIDInput",o.ViewID=e.ViewID):e.ViewName?(r=`Run${d}ViewByName`,n="RunViewByNameInput",o.ViewName=e.ViewName):(l=!0,r=`Run${d}DynamicView`,n="RunDynamicViewInput",o.EntityName=e.EntityName),o.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",o.OrderBy=e.OrderBy?e.OrderBy:"",o.UserSearchString=e.UserSearchString?e.UserSearchString:"",o.Fields=e.Fields,o.IgnoreMaxRows=!!e.IgnoreMaxRows&&e.IgnoreMaxRows,void 0!==e.MaxRows&&(o.MaxRows=e.MaxRows),void 0!==e.StartRow&&(o.StartRow=e.StartRow),o.ForceAuditLog=!!e.ForceAuditLog&&e.ForceAuditLog,o.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(o.AuditLogDescription=e.AuditLogDescription),l||(o.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",o.ExcludeDataFromAllPriorViewRuns=!!e.ExcludeDataFromAllPriorViewRuns&&e.ExcludeDataFromAllPriorViewRuns,o.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",o.SaveViewResults=!!e.SaveViewResults&&e.SaveViewResults),e.Aggregates&&e.Aggregates.length>0&&(o.Aggregates=e.Aggregates.map(e=>({expression:e.expression,alias:e.alias})));const m=this.getViewRunTimeFieldList(c,u,e,l),y=e.Aggregates&&e.Aggregates.length>0?"\n AggregateResults {\n alias\n expression\n value\n error\n }\n AggregateExecutionTime":"",p=s.J1`
237
+ `,a=(await this.ExecuteGQL(r,{input:t}))?.RunQueriesWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const n=a.results.map(e=>{if(("stale"===e.status||"no_validation"===e.status)&&e.Results){const t=JSON.parse(e.Results);return{queryIndex:e.queryIndex,queryId:e.queryId,status:e.status,results:t,maxUpdatedAt:e.maxUpdatedAt,rowCount:e.rowCount,errorMessage:e.errorMessage}}return{queryIndex:e.queryIndex,queryId:e.queryId,status:e.status,maxUpdatedAt:e.maxUpdatedAt,rowCount:e.rowCount,errorMessage:e.errorMessage}});return{success:a.success,results:n,errorMessage:a.errorMessage}}catch(e){return(0,a.ZI)(`Error in RunQueriesWithCacheCheck: ${e}`),{success:!1,results:[],errorMessage:e instanceof Error?e.message:String(e)}}}async InternalRunView(e,t){try{let r="",n="";if(!e)throw"No parameters passed to RunView";{const o={};let i,u;if(e.ViewEntity)u=e.ViewEntity,i=u.Entity;else{const{entityName:r,v:s}=await this.getEntityNameAndUserView(e,t);u=s,i=r}const c=this.Entities.find(e=>e.Name===i);if(!c)throw new Error(`Entity ${i} not found in metadata`);let l=!1;const d=(0,a.I)(c);e.ViewID?(r=`Run${d}ViewByID`,n="RunViewByIDInput",o.ViewID=e.ViewID):e.ViewName?(r=`Run${d}ViewByName`,n="RunViewByNameInput",o.ViewName=e.ViewName):(l=!0,r=`Run${d}DynamicView`,n="RunDynamicViewInput",o.EntityName=e.EntityName),o.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",o.OrderBy=e.OrderBy?e.OrderBy:"",o.UserSearchString=e.UserSearchString?e.UserSearchString:"",o.Fields=e.Fields,o.IgnoreMaxRows=!!e.IgnoreMaxRows&&e.IgnoreMaxRows,void 0!==e.MaxRows&&(o.MaxRows=e.MaxRows),void 0!==e.StartRow&&(o.StartRow=e.StartRow),o.ForceAuditLog=!!e.ForceAuditLog&&e.ForceAuditLog,o.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(o.AuditLogDescription=e.AuditLogDescription),l||(o.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",o.ExcludeDataFromAllPriorViewRuns=!!e.ExcludeDataFromAllPriorViewRuns&&e.ExcludeDataFromAllPriorViewRuns,o.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",o.SaveViewResults=!!e.SaveViewResults&&e.SaveViewResults),e.Aggregates&&e.Aggregates.length>0&&(o.Aggregates=e.Aggregates.map(e=>({expression:e.expression,alias:e.alias})));const m=this.getViewRunTimeFieldList(c,u,e,l),p=e.Aggregates&&e.Aggregates.length>0?"\n AggregateResults {\n alias\n expression\n value\n error\n }\n AggregateExecutionTime":"",y=s.J1`
236
238
  query RunViewQuery ($input: ${n}!) {
237
239
  ${r}(input: $input) {
238
240
  Results {
@@ -243,9 +245,9 @@
243
245
  TotalRowCount
244
246
  ExecutionTime
245
247
  Success
246
- ErrorMessage${y}
248
+ ErrorMessage${p}
247
249
  }
248
- }`;o.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:i,queryName:r,aggregateCount:o.Aggregates.length,aggregates:o.Aggregates});const g=await this.ExecuteGQL(p,{input:o});if(g&&g[r]){const e=g[r].AggregateResults;o.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:i,aggregateResultCount:e?.length||0,aggregateResults:e,aggregateExecutionTime:g[r].AggregateExecutionTime});const t=g[r].Results;if(t&&t.length>0){const e=c.Fields.filter(e=>e.CodeName!==e.Name&&void 0!==e.CodeName);t.forEach(t=>{this.ConvertBackToMJFields(t),e.forEach(e=>{t[e.Name]=t[e.CodeName]})})}return g[r]}}return null}catch(e){throw(0,a.ZI)(e),e}}async InternalRunViews(e,t){try{let r=[],n=[],o=[];for(const s of e){let e="",i="";const u={};let c=null,l=null;if(s.ViewEntity)l=s.ViewEntity,c=l.Get("Entity");else{const{entityName:e,v:r}=await this.getEntityNameAndUserView(s,t);l=r,c=e}const d=this.Entities.find(e=>e.Name===c);if(!d)throw new Error(`Entity ${c} not found in metadata`);n.push(d);let m=!1;const y=(0,a.I)(d);s.ViewID?(e=`Run${y}ViewByID`,i="RunViewByIDInput",u.ViewID=s.ViewID):s.ViewName?(e=`Run${y}ViewByName`,i="RunViewByNameInput",u.ViewName=s.ViewName):(m=!0,e=`Run${y}DynamicView`,i="RunDynamicViewInput",u.EntityName=s.EntityName),u.ExtraFilter=s.ExtraFilter||"",u.OrderBy=s.OrderBy||"",u.UserSearchString=s.UserSearchString||"",u.Fields=s.Fields,u.IgnoreMaxRows=s.IgnoreMaxRows||!1,void 0!==s.MaxRows&&(u.MaxRows=s.MaxRows),void 0!==s.StartRow&&(u.StartRow=s.StartRow),u.ForceAuditLog=s.ForceAuditLog||!1,u.ResultType=s.ResultType||"simple",s.AuditLogDescription&&s.AuditLogDescription.length>0&&(u.AuditLogDescription=s.AuditLogDescription),m||(u.ExcludeUserViewRunID=s.ExcludeUserViewRunID||"",u.ExcludeDataFromAllPriorViewRuns=s.ExcludeDataFromAllPriorViewRuns||!1,u.OverrideExcludeFilter=s.OverrideExcludeFilter||"",u.SaveViewResults=s.SaveViewResults||!1),s.Aggregates&&s.Aggregates.length>0&&(u.Aggregates=s.Aggregates.map(e=>({expression:e.expression,alias:e.alias}))),r.push(u),o.push(...this.getViewRunTimeFieldList(d,l,s,m))}const i=e.some(e=>e.Aggregates&&e.Aggregates.length>0)?"\n AggregateResults {\n alias\n expression\n value\n error\n }\n AggregateExecutionTime":"",u=s.J1`
250
+ }`;o.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:i,queryName:r,aggregateCount:o.Aggregates.length,aggregates:o.Aggregates});const g=await this.ExecuteGQL(y,{input:o});if(g&&g[r]){const e=g[r].AggregateResults;o.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:i,aggregateResultCount:e?.length||0,aggregateResults:e,aggregateExecutionTime:g[r].AggregateExecutionTime});const t=g[r].Results;if(t&&t.length>0){const e=c.Fields.filter(e=>e.CodeName!==e.Name&&void 0!==e.CodeName);t.forEach(t=>{this.ConvertBackToMJFields(t),e.forEach(e=>{t[e.Name]=t[e.CodeName]})})}return g[r]}}return null}catch(e){throw(0,a.ZI)(e),e}}async InternalRunViews(e,t){try{let r=[],n=[],o=[];for(const s of e){let e="",i="";const u={};let c=null,l=null;if(s.ViewEntity)l=s.ViewEntity,c=l.Get("Entity");else{const{entityName:e,v:r}=await this.getEntityNameAndUserView(s,t);l=r,c=e}const d=this.Entities.find(e=>e.Name===c);if(!d)throw new Error(`Entity ${c} not found in metadata`);n.push(d);let m=!1;const p=(0,a.I)(d);s.ViewID?(e=`Run${p}ViewByID`,i="RunViewByIDInput",u.ViewID=s.ViewID):s.ViewName?(e=`Run${p}ViewByName`,i="RunViewByNameInput",u.ViewName=s.ViewName):(m=!0,e=`Run${p}DynamicView`,i="RunDynamicViewInput",u.EntityName=s.EntityName),u.ExtraFilter=s.ExtraFilter||"",u.OrderBy=s.OrderBy||"",u.UserSearchString=s.UserSearchString||"",u.Fields=s.Fields,u.IgnoreMaxRows=s.IgnoreMaxRows||!1,void 0!==s.MaxRows&&(u.MaxRows=s.MaxRows),void 0!==s.StartRow&&(u.StartRow=s.StartRow),u.ForceAuditLog=s.ForceAuditLog||!1,u.ResultType=s.ResultType||"simple",s.AuditLogDescription&&s.AuditLogDescription.length>0&&(u.AuditLogDescription=s.AuditLogDescription),m||(u.ExcludeUserViewRunID=s.ExcludeUserViewRunID||"",u.ExcludeDataFromAllPriorViewRuns=s.ExcludeDataFromAllPriorViewRuns||!1,u.OverrideExcludeFilter=s.OverrideExcludeFilter||"",u.SaveViewResults=s.SaveViewResults||!1),s.Aggregates&&s.Aggregates.length>0&&(u.Aggregates=s.Aggregates.map(e=>({expression:e.expression,alias:e.alias}))),r.push(u),o.push(...this.getViewRunTimeFieldList(d,l,s,m))}const i=e.some(e=>e.Aggregates&&e.Aggregates.length>0)?"\n AggregateResults {\n alias\n expression\n value\n error\n }\n AggregateExecutionTime":"",u=s.J1`
249
251
  query RunViewsQuery ($input: [RunViewGenericInput!]!) {
250
252
  RunViews(input: $input) {
251
253
  Results {
@@ -420,14 +422,14 @@
420
422
  ErrorMessage
421
423
  Result
422
424
  }
423
- }`,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)}throw new Error("GraphQL query failed")}catch(e){throw(0,a.ZI)(e),e}}static async ExecuteGQL(e,t,r=!0){return P.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("JWT_EXPIRED"===s.response.errors[0]?.extensions?.code?.toUpperCase().trim()){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw(0,a.ZI)("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}throw s}throw(0,a.ZI)(s),s}}async RefreshToken(){const e=P.Instance&&P.Instance._configData===this._configData;if(e&&P.Instance._refreshPromise)return P.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(P.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&P.Instance&&(P.Instance._refreshPromise=null)}}async performTokenRefresh(){if(!this._configData.Data.RefreshTokenFunction)throw new Error("No refresh token function provided");{const e=await this._configData.Data.RefreshTokenFunction();if(!e)throw new Error("Refresh token function returned null or undefined token");{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,P.Instance&&P.Instance._configData===this._configData&&(P.Instance._client=t)}}}static async RefreshToken(){return P.Instance.RefreshToken()}CreateNewGraphQLClient(e,t,r,a,n){const o={"x-session-id":r};return t&&(o.authorization="Bearer "+t),a&&(o["x-mj-api-key"]=a),n&&(o["x-api-key"]=n),new s.l4(e,{headers:o})}userInfoString(){return this.infoString(new a.oq(null,null))}userRoleInfoString(){return this.infoString(new a.St(null))}infoString(e){let t="";const r=Object.keys(e);for(const e of r)e.startsWith("__mj_")?t+=e.replace("__mj_","_mj__")+"\n ":e.startsWith("_")||(t+=e+"\n ");return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new w:this._localStorageProvider=new a.KW),this._localStorageProvider}get Metadata(){return this}getOrCreateWSClient(){const e=Date.now();return this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&0===this._activeSubscriptionCount&&this.disposeWSClient(),this._wsClient||(this._wsClient=(0,c.UU)({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token},keepAlive:3e4,retryAttempts:3,shouldRetry:p(()=>!0,"shouldRetry")}),this._wsClientCreatedAt=e,this._subscriptionCleanupTimer||(this._subscriptionCleanupTimer=setInterval(()=>{this.cleanupStaleSubscriptions()},this.SUBSCRIPTION_CLEANUP_INTERVAL_MS))),this._wsClient}disposeWSClient(){if(this._wsClient){try{this._wsClient.dispose()}catch(e){console.error("[GraphQLDataProvider] Error disposing WebSocket client:",e)}this._wsClient=null,this._wsClientCreatedAt=null}}completeAllSubjects(){this._pushStatusSubjects.forEach((e,t)=>{try{e.subject.complete(),e.subscription.unsubscribe()}catch(e){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,e)}}),this._pushStatusSubjects.clear()}cleanupStaleSubscriptions(){if(!this._isCleaningUp){this._isCleaningUp=!0;try{const e=Date.now(),t=(this._pushStatusSubjects.size,Array.from(this._pushStatusSubjects.entries())),r=[];t.forEach(([t,s])=>{const a=e-s.lastRequestedAt,n=e-s.lastEmissionAt;0===s.activeSubscribers&&a>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&n>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${t} for cleanup: activeSubscribers=${s.activeSubscribers}, timeSinceRequested=${Math.round(a/1e3)}s, timeSinceEmission=${Math.round(n/1e3)}s`),r.push(t))}),r.forEach(e=>{const t=this._pushStatusSubjects.get(e);if(t)try{t.subject.complete(),t.subscription.unsubscribe(),this._pushStatusSubjects.delete(e),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${e}`)}catch(t){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${e}:`,t)}}),r.length>0&&console.log(`[GraphQLDataProvider] Cleaned up ${r.length} stale subscription(s)`),0===this._pushStatusSubjects.size&&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 o.c(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const a=s.subscribe({query:e,variables:t},{next:p(e=>{r.next(e.data)},"next"),error:p(async e=>{const t=e;if("JWT_EXPIRED"===t?.extensions?.code||t?.message?.includes("token has expired")||t?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] WebSocket JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),r.complete()}catch(e){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",e),r.error(e)}}else r.error(e)},"error"),complete:p(()=>{r.complete()},"complete")});return()=>{this._activeSubscriptionCount--,a()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),r=this._pushStatusSubjects.get(e);if(r)return r.lastRequestedAt=t,new o.c(t=>{r.activeSubscribers++;const s=r.subject.subscribe(t);return()=>{const t=this._pushStatusSubjects.get(e);t&&t.activeSubscribers>0&&t.activeSubscribers--,s.unsubscribe()}});const a=s.J1`subscription StatusUpdates($sessionId: String!) {
425
+ }`,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)}throw new Error("GraphQL query failed")}catch(e){throw(0,a.ZI)(e),e}}static async ExecuteGQL(e,t,r=!0){return P.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("JWT_EXPIRED"===s.response.errors[0]?.extensions?.code?.toUpperCase().trim()){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw(0,a.ZI)("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}throw s}throw(0,a.ZI)(s),s}}async RefreshToken(){const e=P.Instance&&P.Instance._configData===this._configData;if(e&&P.Instance._refreshPromise)return P.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(P.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&P.Instance&&(P.Instance._refreshPromise=null)}}async performTokenRefresh(){if(!this._configData.Data.RefreshTokenFunction)throw new Error("No refresh token function provided");{const e=await this._configData.Data.RefreshTokenFunction();if(!e)throw new Error("Refresh token function returned null or undefined token");{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,P.Instance&&P.Instance._configData===this._configData&&(P.Instance._client=t)}}}static async RefreshToken(){return P.Instance.RefreshToken()}CreateNewGraphQLClient(e,t,r,a,n){const o={"x-session-id":r};return t&&(o.authorization="Bearer "+t),a&&(o["x-mj-api-key"]=a),n&&(o["x-api-key"]=n),new s.l4(e,{headers:o})}userInfoString(){return this.infoString(new a.oq(null,null))}userRoleInfoString(){return this.infoString(new a.St(null))}infoString(e){let t="";const r=Object.keys(e);for(const e of r)e.startsWith("__mj_")?t+=e.replace("__mj_","_mj__")+"\n ":e.startsWith("_")||(t+=e+"\n ");return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new C:this._localStorageProvider=new a.KW),this._localStorageProvider}get Metadata(){return this}getOrCreateWSClient(){const e=Date.now();return this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&0===this._activeSubscriptionCount&&this.disposeWSClient(),this._wsClient||(this._wsClient=(0,c.UU)({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token},keepAlive:3e4,retryAttempts:3,shouldRetry:y(()=>!0,"shouldRetry")}),this._wsClientCreatedAt=e,this._subscriptionCleanupTimer||(this._subscriptionCleanupTimer=setInterval(()=>{this.cleanupStaleSubscriptions()},this.SUBSCRIPTION_CLEANUP_INTERVAL_MS))),this._wsClient}disposeWSClient(){if(this._wsClient){try{this._wsClient.dispose()}catch(e){console.error("[GraphQLDataProvider] Error disposing WebSocket client:",e)}this._wsClient=null,this._wsClientCreatedAt=null}}completeAllSubjects(){this._pushStatusSubjects.forEach((e,t)=>{try{e.subject.complete(),e.subscription.unsubscribe()}catch(e){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,e)}}),this._pushStatusSubjects.clear()}cleanupStaleSubscriptions(){if(!this._isCleaningUp){this._isCleaningUp=!0;try{const e=Date.now(),t=(this._pushStatusSubjects.size,Array.from(this._pushStatusSubjects.entries())),r=[];t.forEach(([t,s])=>{const a=e-s.lastRequestedAt,n=e-s.lastEmissionAt;0===s.activeSubscribers&&a>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&n>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${t} for cleanup: activeSubscribers=${s.activeSubscribers}, timeSinceRequested=${Math.round(a/1e3)}s, timeSinceEmission=${Math.round(n/1e3)}s`),r.push(t))}),r.forEach(e=>{const t=this._pushStatusSubjects.get(e);if(t)try{t.subject.complete(),t.subscription.unsubscribe(),this._pushStatusSubjects.delete(e),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${e}`)}catch(t){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${e}:`,t)}}),r.length>0&&console.log(`[GraphQLDataProvider] Cleaned up ${r.length} stale subscription(s)`),0===this._pushStatusSubjects.size&&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 o.c(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const a=s.subscribe({query:e,variables:t},{next:y(e=>{r.next(e.data)},"next"),error:y(async e=>{const t=e;if("JWT_EXPIRED"===t?.extensions?.code||t?.message?.includes("token has expired")||t?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] WebSocket JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),r.complete()}catch(e){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",e),r.error(e)}}else r.error(e)},"error"),complete:y(()=>{r.complete()},"complete")});return()=>{this._activeSubscriptionCount--,a()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),r=this._pushStatusSubjects.get(e);if(r)return r.lastRequestedAt=t,new o.c(t=>{r.activeSubscribers++;const s=r.subject.subscribe(t);return()=>{const t=this._pushStatusSubjects.get(e);t&&t.activeSubscribers>0&&t.activeSubscribers--,s.unsubscribe()}});const a=s.J1`subscription StatusUpdates($sessionId: String!) {
424
426
  statusUpdates(sessionId: $sessionId) {
425
427
  date
426
428
  message
427
429
  sessionId
428
430
  }
429
431
  }
430
- `,n=new i.B,c=this.getOrCreateWSClient(),l=new u.yU;return l.add(new o.c(t=>{const r=c.subscribe({query:a,variables:{sessionId:e}},{next:p(r=>{const s=this._pushStatusSubjects.get(e);s&&(s.lastEmissionAt=Date.now()),t.next(r.data.statusUpdates.message)},"next"),error:p(async e=>{const r=e;if("JWT_EXPIRED"===r?.extensions?.code||r?.message?.includes("token has expired")||r?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),t.complete()}catch(e){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",e),t.error(e)}}else t.error(e)},"error"),complete:p(()=>{t.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,r()}}).subscribe({next:p(e=>n.next(e),"next"),error:p(t=>{n.error(t),this._pushStatusSubjects.delete(e)},"error"),complete:p(()=>{n.complete(),this._pushStatusSubjects.delete(e)},"complete")})),this._pushStatusSubjects.set(e,{subject:n,subscription:l,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new o.c(t=>{const r=this._pushStatusSubjects.get(e);r&&r.activeSubscribers++;const s=n.subscribe(t);return()=>{const t=this._pushStatusSubjects.get(e);t&&t.activeSubscribers>0&&t.activeSubscribers--,s.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}async FindISAChildEntity(e,t,r){if(!e.IsParentType)return null;try{const r=await this.ExecuteGQL("query FindISAChildEntity($EntityName: String!, $RecordID: String!) {\n FindISAChildEntity(EntityName: $EntityName, RecordID: $RecordID) {\n Success\n ChildEntityName\n ErrorMessage\n }\n }",{EntityName:e.Name,RecordID:t});return r?.FindISAChildEntity?.Success&&r.FindISAChildEntity.ChildEntityName?{ChildEntityName:r.FindISAChildEntity.ChildEntityName}:null}catch(t){return(0,a.ZI)(`FindISAChildEntity failed for ${e.Name}: ${t}`),null}}async FindISAChildEntities(e,t,r){if(!e.IsParentType)return[];try{const r=await this.ExecuteGQL("query FindISAChildEntities($EntityName: String!, $RecordID: String!) {\n FindISAChildEntities(EntityName: $EntityName, RecordID: $RecordID) {\n Success\n ChildEntityNames\n ErrorMessage\n }\n }",{EntityName:e.Name,RecordID:t});return r?.FindISAChildEntities?.Success&&r.FindISAChildEntities.ChildEntityNames?r.FindISAChildEntities.ChildEntityNames.map(e=>({ChildEntityName:e})):[]}catch(t){return(0,a.ZI)(`FindISAChildEntities failed for ${e.Name}: ${t}`),[]}}}async function C(e){const t=new P;return(0,a.YE)(t),await t.Config(e),await a.jF.Instance.Startup(),d.rt.Instance.RaiseEvent({event:d.UK.LoggedIn,eventCode:null,component:this,args:null}),t}p(C,"setupGraphQLClient");class ${static{p(this,"SyncRolesAndUsersResult")}}class v{static{p(this,"RoleInput")}}class A{static{p(this,"UserInput")}}class N{static{p(this,"RolesAndUsersInput")}}var b,x=((b=x||{}).Create="Create",b.Update="Update",b.CreateOrUpdate="CreateOrUpdate",b.Delete="Delete",b.DeleteWithFilter="DeleteWithFilter",b);class M{static{p(this,"ActionItemInput")}}class Q{static{p(this,"SyncDataResult")}constructor(){this.Results=[]}}class G{static{p(this,"ActionItemOutput")}}class L{static{p(this,"GraphQLSystemUserClient")}get Client(){return this._client}constructor(e,t,r,a){const n={"x-session-id":r};this._sessionId=r,t&&(n.authorization="Bearer "+t),a&&(n["x-mj-api-key"]=a),this._client=new s.l4(e,{headers:n})}async GetData(e,t){try{const r=await this.Client.request("query GetData($input: GetDataInputType!) {\n GetData(input: $input) {\n Success\n ErrorMessages\n Queries\n Results\n }\n }",{input:{Queries:e,Token:t}});return r&&r.GetData?{Success:r.GetData.Success,Results:r.GetData.Results.map(e=>e?(0,d.NG)(e):null),ErrorMessages:r.GetData.ErrorMessages,Queries:r.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:r.GetData?.ErrorMessages??["Unknown error"],Queries:r.GetData?.Queries??e}}catch(t){let r=t instanceof Error?t.message:String(t);const s=r.match(/Error: ([^:]+)\./);if(s&&(r=s[1]+"."),(0,a.l9)()){const e=`GraphQLSystemUserClient::GetData - Error getting data - ${t}`;(0,a.ZI)(e)}return{Success:!1,Results:[],ErrorMessages:[r],Queries:e}}}async GetAllRemoteEntities(){try{const e=await this.Client.request("query GetAllEntities {\n GetAllEntities {\n Success\n ErrorMessage\n Results {\n ID\n Name\n Description\n SchemaName\n BaseView\n BaseTable\n CodeName\n ClassName\n Fields {\n ID\n Name\n Description\n Type\n AllowsNull\n MaxLength\n }\n }\n }\n }");return e&&e.GetAllEntities?e.GetAllEntities:{Success:!1,Results:[],ErrorMessage:e.GetAllEntities?.ErrorMessage??"Unknown error"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::GetAllRemoteEntities - Error getting remote entities - ${e}`),{Success:!1,Results:[],ErrorMessage:e}}}async SyncData(e){try{const t=await this.Client.request("mutation SyncData($items: [ActionItemInputType!]!) {\n SyncData(items: $items) {\n Success\n Results {\n Success\n ErrorMessage\n EntityName\n Type\n PrimaryKey {\n KeyValuePairs {\n FieldName\n Value \n }\n }\n AlternateKey {\n KeyValuePairs {\n FieldName\n Value \n }\n }\n DeleteFilter\n RecordJSON\n }\n }\n }",{items:e});return t&&t.SyncData?t.SyncData:{Success:!1,Results:[]}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::SyncData - Error syncing data - ${e}`),{Success:!1,Results:[]}}}async SyncRolesAndUsers(e){try{const t=await this.Client.request("mutation SyncRolesAndUsers($data: RolesAndUsersInputType!) {\n SyncRolesAndUsers(data: $data) {\n Success\n }\n }",{data:e});return t&&t.SyncRolesAndUsers?t.SyncRolesAndUsers:{Success:!1}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::SyncRolesAndUsers - Error syncing roles and users - ${e}`),{Success:!1}}}async RunViewByName(e){try{const t=await this.Client.request("query RunViewByNameSystemUser($input: RunViewByNameInput!) {\n RunViewByNameSystemUser(input: $input) {\n Results {\n PrimaryKey {\n FieldName\n Value\n }\n EntityID\n Data\n }\n UserViewRunID\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n Success\n }\n }",{input:e});return t&&t.RunViewByNameSystemUser?t.RunViewByNameSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by name"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::RunViewByNameSystemUser - Error running view by name - ${e}`),{Results:[],Success:!1,ErrorMessage:e.toString()}}}async RunViewByID(e){try{const t=await this.Client.request("query RunViewByIDSystemUser($input: RunViewByIDInput!) {\n RunViewByIDSystemUser(input: $input) {\n Results {\n PrimaryKey {\n FieldName\n Value\n }\n EntityID\n Data\n }\n UserViewRunID\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n Success\n }\n }",{input:e});return t&&t.RunViewByIDSystemUser?t.RunViewByIDSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by ID"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::RunViewByIDSystemUser - Error running view by ID - ${e}`),{Results:[],Success:!1,ErrorMessage:e.toString()}}}async RunDynamicView(e){try{const t=await this.Client.request("query RunDynamicViewSystemUser($input: RunDynamicViewInput!) {\n RunDynamicViewSystemUser(input: $input) {\n Results {\n PrimaryKey {\n FieldName\n Value\n }\n EntityID\n Data\n }\n UserViewRunID\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n Success\n }\n }",{input:e});return t&&t.RunDynamicViewSystemUser?t.RunDynamicViewSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute dynamic view"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::RunDynamicViewSystemUser - Error running dynamic view - ${e}`),{Results:[],Success:!1,ErrorMessage:e.toString()}}}async RunViews(e){try{const t=await this.Client.request("query RunViewsSystemUser($input: [RunViewGenericInput!]!) {\n RunViewsSystemUser(input: $input) {\n Results {\n PrimaryKey {\n FieldName\n Value\n }\n EntityID\n Data\n }\n UserViewRunID\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n Success\n }\n }",{input:e});return t&&t.RunViewsSystemUser?t.RunViewsSystemUser:[]}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::RunViewsSystemUser - Error running views - ${e}`),[]}}async GetQueryData(e){try{if(void 0!==e.Parameters&&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) {\n GetQueryDataSystemUser(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {\n QueryID\n QueryName\n Success\n Results\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n AppliedParameters\n }\n }",r={QueryID:e.QueryID};void 0!==e.CategoryID&&(r.CategoryID=e.CategoryID),void 0!==e.CategoryPath&&(r.CategoryPath=e.CategoryPath),void 0!==e.Parameters&&(r.Parameters=e.Parameters),void 0!==e.MaxRows&&(r.MaxRows=e.MaxRows),void 0!==e.StartRow&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataSystemUser?{...s.GetQueryDataSystemUser,Results:s.GetQueryDataSystemUser.Results?(0,d.NG)(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(0,a.ZI)(`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(void 0!==e.Parameters&&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) {\n GetQueryDataByNameSystemUser(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {\n QueryID\n QueryName\n Success\n Results\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n AppliedParameters\n }\n }",r={QueryName:e.QueryName};void 0!==e.CategoryID&&(r.CategoryID=e.CategoryID),void 0!==e.CategoryPath&&(r.CategoryPath=e.CategoryPath),void 0!==e.Parameters&&(r.Parameters=e.Parameters),void 0!==e.MaxRows&&(r.MaxRows=e.MaxRows),void 0!==e.StartRow&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataByNameSystemUser?{...s.GetQueryDataByNameSystemUser,Results:s.GetQueryDataByNameSystemUser.Results?(0,d.NG)(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(0,a.ZI)(`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 t=await this.Client.request("mutation CreateQuerySystemUser($input: CreateQuerySystemUserInput!) {\n CreateQuerySystemUser(input: $input) {\n Success\n ErrorMessage\n ID\n Name\n Description\n CategoryID\n Category\n SQL\n Status\n QualityRank\n EmbeddingVector\n EmbeddingModelID\n EmbeddingModelName\n Fields {\n ID\n QueryID\n Name\n Description\n Sequence\n SQLBaseType\n SQLFullType\n SourceEntityID\n SourceEntity\n SourceFieldName\n IsComputed\n ComputationDescription\n IsSummary\n SummaryDescription\n }\n Parameters {\n ID\n QueryID\n Name\n Description\n Type\n IsRequired\n DefaultValue\n SampleValue\n ValidationFilters\n }\n Entities {\n ID\n QueryID\n EntityID\n Entity\n }\n Permissions {\n ID\n QueryID\n RoleID\n Role\n }\n }\n }",{input:e});return t&&t.CreateQuerySystemUser?t.CreateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to create query"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::CreateQuery - Error creating query - ${e}`),{Success:!1,ErrorMessage:e.toString()}}}async UpdateQuery(e){try{const t=await this.Client.request("mutation UpdateQuerySystemUser($input: UpdateQuerySystemUserInput!) {\n UpdateQuerySystemUser(input: $input) {\n Success\n ErrorMessage\n ID\n Name\n Description\n CategoryID\n Category\n SQL\n Status\n QualityRank\n EmbeddingVector\n EmbeddingModelID\n EmbeddingModelName\n Fields {\n ID\n QueryID\n Name\n Description\n Sequence\n SQLBaseType\n SQLFullType\n SourceEntityID\n SourceEntity\n SourceFieldName\n IsComputed\n ComputationDescription\n IsSummary\n SummaryDescription\n }\n Parameters {\n ID\n QueryID\n Name\n Description\n Type\n IsRequired\n DefaultValue\n SampleValue\n ValidationFilters\n }\n Entities {\n ID\n QueryID\n EntityID\n Entity\n }\n Permissions {\n ID\n QueryID\n RoleID\n Role\n }\n }\n }",{input:e});return t&&t.UpdateQuerySystemUser?t.UpdateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to update query"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::UpdateQuery - Error updating query - ${e}`),{Success:!1,ErrorMessage:e.toString()}}}async DeleteQuery(e,t){try{if(!e||""===e.trim())return(0,a.ZI)("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) {\n DeleteQuerySystemResolver(ID: $ID, options: $options) {\n Success\n ErrorMessage\n ID\n Name\n }\n }",s={ID:e};void 0!==t&&(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(e){let t="";if(e instanceof Error){if(t=e.message,"cause"in e&&e.cause){const r=e.cause;t+=` | Cause: ${r.message||r}`,"code"in r&&(t+=` | Code: ${r.code}`)}if("response"in e){const r=e.response;r?.status&&(t+=` | HTTP Status: ${r.status}`),r?.errors&&(t+=` | GraphQL Errors: ${JSON.stringify(r.errors)}`)}e.stack&&console.error("DeleteQuery stack trace:",e.stack)}else t=String(e);return(0,a.ZI)(`GraphQLSystemUserClient::DeleteQuery - Error deleting query - ${t}`),{Success:!1,ErrorMessage:t}}}async RunAIPrompt(e){try{const t=s.J1`
432
+ `,n=new i.B,c=this.getOrCreateWSClient(),l=new u.yU;return l.add(new o.c(t=>{const r=c.subscribe({query:a,variables:{sessionId:e}},{next:y(r=>{const s=this._pushStatusSubjects.get(e);s&&(s.lastEmissionAt=Date.now()),t.next(r.data.statusUpdates.message)},"next"),error:y(async e=>{const r=e;if("JWT_EXPIRED"===r?.extensions?.code||r?.message?.includes("token has expired")||r?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),t.complete()}catch(e){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",e),t.error(e)}}else t.error(e)},"error"),complete:y(()=>{t.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,r()}}).subscribe({next:y(e=>n.next(e),"next"),error:y(t=>{n.error(t),this._pushStatusSubjects.delete(e)},"error"),complete:y(()=>{n.complete(),this._pushStatusSubjects.delete(e)},"complete")})),this._pushStatusSubjects.set(e,{subject:n,subscription:l,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new o.c(t=>{const r=this._pushStatusSubjects.get(e);r&&r.activeSubscribers++;const s=n.subscribe(t);return()=>{const t=this._pushStatusSubjects.get(e);t&&t.activeSubscribers>0&&t.activeSubscribers--,s.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}async FindISAChildEntity(e,t,r){if(!e.IsParentType)return null;try{const r=await this.ExecuteGQL("query FindISAChildEntity($EntityName: String!, $RecordID: String!) {\n FindISAChildEntity(EntityName: $EntityName, RecordID: $RecordID) {\n Success\n ChildEntityName\n ErrorMessage\n }\n }",{EntityName:e.Name,RecordID:t});return r?.FindISAChildEntity?.Success&&r.FindISAChildEntity.ChildEntityName?{ChildEntityName:r.FindISAChildEntity.ChildEntityName}:null}catch(t){return(0,a.ZI)(`FindISAChildEntity failed for ${e.Name}: ${t}`),null}}async FindISAChildEntities(e,t,r){if(!e.IsParentType)return[];try{const r=await this.ExecuteGQL("query FindISAChildEntities($EntityName: String!, $RecordID: String!) {\n FindISAChildEntities(EntityName: $EntityName, RecordID: $RecordID) {\n Success\n ChildEntityNames\n ErrorMessage\n }\n }",{EntityName:e.Name,RecordID:t});return r?.FindISAChildEntities?.Success&&r.FindISAChildEntities.ChildEntityNames?r.FindISAChildEntities.ChildEntityNames.map(e=>({ChildEntityName:e})):[]}catch(t){return(0,a.ZI)(`FindISAChildEntities failed for ${e.Name}: ${t}`),[]}}}async function $(e){const t=Date.now();console.log(`[DIAG][${t}] setupGraphQLClient() ENTER`);const r=new P;console.log(`[DIAG][${t}] setupGraphQLClient() calling SetProvider() (Metadata.Provider will be set BEFORE Config completes)`),(0,a.YE)(r),console.log(`[DIAG][${t}] setupGraphQLClient() SetProvider() done. Metadata.Provider is now set. Starting async Config()...`);const s=Date.now();await r.Config(e),console.log(`[DIAG][${t}] setupGraphQLClient() provider.Config() completed in ${Date.now()-s}ms. Provider is now fully ready.`);const n=Date.now();return console.log(`[DIAG][${t}] setupGraphQLClient() calling StartupManager.Startup()...`),await a.jF.Instance.Startup(),console.log(`[DIAG][${t}] setupGraphQLClient() StartupManager.Startup() completed in ${Date.now()-n}ms`),d.rt.Instance.RaiseEvent({event:d.UK.LoggedIn,eventCode:null,component:this,args:null}),console.log(`[DIAG][${t}] setupGraphQLClient() EXIT - total time: ${Date.now()-t}ms`),r}y($,"setupGraphQLClient");class v{static{y(this,"SyncRolesAndUsersResult")}}class A{static{y(this,"RoleInput")}}class N{static{y(this,"UserInput")}}class b{static{y(this,"RolesAndUsersInput")}}var x,M=((x=M||{}).Create="Create",x.Update="Update",x.CreateOrUpdate="CreateOrUpdate",x.Delete="Delete",x.DeleteWithFilter="DeleteWithFilter",x);class G{static{y(this,"ActionItemInput")}}class T{static{y(this,"SyncDataResult")}constructor(){this.Results=[]}}class Q{static{y(this,"ActionItemOutput")}}class L{static{y(this,"GraphQLSystemUserClient")}get Client(){return this._client}constructor(e,t,r,a){const n={"x-session-id":r};this._sessionId=r,t&&(n.authorization="Bearer "+t),a&&(n["x-mj-api-key"]=a),this._client=new s.l4(e,{headers:n})}async GetData(e,t){try{const r=await this.Client.request("query GetData($input: GetDataInputType!) {\n GetData(input: $input) {\n Success\n ErrorMessages\n Queries\n Results\n }\n }",{input:{Queries:e,Token:t}});return r&&r.GetData?{Success:r.GetData.Success,Results:r.GetData.Results.map(e=>e?(0,d.NG)(e):null),ErrorMessages:r.GetData.ErrorMessages,Queries:r.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:r.GetData?.ErrorMessages??["Unknown error"],Queries:r.GetData?.Queries??e}}catch(t){let r=t instanceof Error?t.message:String(t);const s=r.match(/Error: ([^:]+)\./);if(s&&(r=s[1]+"."),(0,a.l9)()){const e=`GraphQLSystemUserClient::GetData - Error getting data - ${t}`;(0,a.ZI)(e)}return{Success:!1,Results:[],ErrorMessages:[r],Queries:e}}}async GetAllRemoteEntities(){try{const e=await this.Client.request("query GetAllEntities {\n GetAllEntities {\n Success\n ErrorMessage\n Results {\n ID\n Name\n Description\n SchemaName\n BaseView\n BaseTable\n CodeName\n ClassName\n Fields {\n ID\n Name\n Description\n Type\n AllowsNull\n MaxLength\n }\n }\n }\n }");return e&&e.GetAllEntities?e.GetAllEntities:{Success:!1,Results:[],ErrorMessage:e.GetAllEntities?.ErrorMessage??"Unknown error"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::GetAllRemoteEntities - Error getting remote entities - ${e}`),{Success:!1,Results:[],ErrorMessage:e}}}async SyncData(e){try{const t=await this.Client.request("mutation SyncData($items: [ActionItemInputType!]!) {\n SyncData(items: $items) {\n Success\n Results {\n Success\n ErrorMessage\n EntityName\n Type\n PrimaryKey {\n KeyValuePairs {\n FieldName\n Value \n }\n }\n AlternateKey {\n KeyValuePairs {\n FieldName\n Value \n }\n }\n DeleteFilter\n RecordJSON\n }\n }\n }",{items:e});return t&&t.SyncData?t.SyncData:{Success:!1,Results:[]}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::SyncData - Error syncing data - ${e}`),{Success:!1,Results:[]}}}async SyncRolesAndUsers(e){try{const t=await this.Client.request("mutation SyncRolesAndUsers($data: RolesAndUsersInputType!) {\n SyncRolesAndUsers(data: $data) {\n Success\n }\n }",{data:e});return t&&t.SyncRolesAndUsers?t.SyncRolesAndUsers:{Success:!1}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::SyncRolesAndUsers - Error syncing roles and users - ${e}`),{Success:!1}}}async RunViewByName(e){try{const t=await this.Client.request("query RunViewByNameSystemUser($input: RunViewByNameInput!) {\n RunViewByNameSystemUser(input: $input) {\n Results {\n PrimaryKey {\n FieldName\n Value\n }\n EntityID\n Data\n }\n UserViewRunID\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n Success\n }\n }",{input:e});return t&&t.RunViewByNameSystemUser?t.RunViewByNameSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by name"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::RunViewByNameSystemUser - Error running view by name - ${e}`),{Results:[],Success:!1,ErrorMessage:e.toString()}}}async RunViewByID(e){try{const t=await this.Client.request("query RunViewByIDSystemUser($input: RunViewByIDInput!) {\n RunViewByIDSystemUser(input: $input) {\n Results {\n PrimaryKey {\n FieldName\n Value\n }\n EntityID\n Data\n }\n UserViewRunID\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n Success\n }\n }",{input:e});return t&&t.RunViewByIDSystemUser?t.RunViewByIDSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by ID"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::RunViewByIDSystemUser - Error running view by ID - ${e}`),{Results:[],Success:!1,ErrorMessage:e.toString()}}}async RunDynamicView(e){try{const t=await this.Client.request("query RunDynamicViewSystemUser($input: RunDynamicViewInput!) {\n RunDynamicViewSystemUser(input: $input) {\n Results {\n PrimaryKey {\n FieldName\n Value\n }\n EntityID\n Data\n }\n UserViewRunID\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n Success\n }\n }",{input:e});return t&&t.RunDynamicViewSystemUser?t.RunDynamicViewSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute dynamic view"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::RunDynamicViewSystemUser - Error running dynamic view - ${e}`),{Results:[],Success:!1,ErrorMessage:e.toString()}}}async RunViews(e){try{const t=await this.Client.request("query RunViewsSystemUser($input: [RunViewGenericInput!]!) {\n RunViewsSystemUser(input: $input) {\n Results {\n PrimaryKey {\n FieldName\n Value\n }\n EntityID\n Data\n }\n UserViewRunID\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n Success\n }\n }",{input:e});return t&&t.RunViewsSystemUser?t.RunViewsSystemUser:[]}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::RunViewsSystemUser - Error running views - ${e}`),[]}}async GetQueryData(e){try{if(void 0!==e.Parameters&&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) {\n GetQueryDataSystemUser(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {\n QueryID\n QueryName\n Success\n Results\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n AppliedParameters\n }\n }",r={QueryID:e.QueryID};void 0!==e.CategoryID&&(r.CategoryID=e.CategoryID),void 0!==e.CategoryPath&&(r.CategoryPath=e.CategoryPath),void 0!==e.Parameters&&(r.Parameters=e.Parameters),void 0!==e.MaxRows&&(r.MaxRows=e.MaxRows),void 0!==e.StartRow&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataSystemUser?{...s.GetQueryDataSystemUser,Results:s.GetQueryDataSystemUser.Results?(0,d.NG)(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(0,a.ZI)(`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(void 0!==e.Parameters&&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) {\n GetQueryDataByNameSystemUser(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {\n QueryID\n QueryName\n Success\n Results\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n AppliedParameters\n }\n }",r={QueryName:e.QueryName};void 0!==e.CategoryID&&(r.CategoryID=e.CategoryID),void 0!==e.CategoryPath&&(r.CategoryPath=e.CategoryPath),void 0!==e.Parameters&&(r.Parameters=e.Parameters),void 0!==e.MaxRows&&(r.MaxRows=e.MaxRows),void 0!==e.StartRow&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataByNameSystemUser?{...s.GetQueryDataByNameSystemUser,Results:s.GetQueryDataByNameSystemUser.Results?(0,d.NG)(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(0,a.ZI)(`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 t=await this.Client.request("mutation CreateQuerySystemUser($input: CreateQuerySystemUserInput!) {\n CreateQuerySystemUser(input: $input) {\n Success\n ErrorMessage\n ID\n Name\n Description\n CategoryID\n Category\n SQL\n Status\n QualityRank\n EmbeddingVector\n EmbeddingModelID\n EmbeddingModelName\n Fields {\n ID\n QueryID\n Name\n Description\n Sequence\n SQLBaseType\n SQLFullType\n SourceEntityID\n SourceEntity\n SourceFieldName\n IsComputed\n ComputationDescription\n IsSummary\n SummaryDescription\n }\n Parameters {\n ID\n QueryID\n Name\n Description\n Type\n IsRequired\n DefaultValue\n SampleValue\n ValidationFilters\n }\n Entities {\n ID\n QueryID\n EntityID\n Entity\n }\n Permissions {\n ID\n QueryID\n RoleID\n Role\n }\n }\n }",{input:e});return t&&t.CreateQuerySystemUser?t.CreateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to create query"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::CreateQuery - Error creating query - ${e}`),{Success:!1,ErrorMessage:e.toString()}}}async UpdateQuery(e){try{const t=await this.Client.request("mutation UpdateQuerySystemUser($input: UpdateQuerySystemUserInput!) {\n UpdateQuerySystemUser(input: $input) {\n Success\n ErrorMessage\n ID\n Name\n Description\n CategoryID\n Category\n SQL\n Status\n QualityRank\n EmbeddingVector\n EmbeddingModelID\n EmbeddingModelName\n Fields {\n ID\n QueryID\n Name\n Description\n Sequence\n SQLBaseType\n SQLFullType\n SourceEntityID\n SourceEntity\n SourceFieldName\n IsComputed\n ComputationDescription\n IsSummary\n SummaryDescription\n }\n Parameters {\n ID\n QueryID\n Name\n Description\n Type\n IsRequired\n DefaultValue\n SampleValue\n ValidationFilters\n }\n Entities {\n ID\n QueryID\n EntityID\n Entity\n }\n Permissions {\n ID\n QueryID\n RoleID\n Role\n }\n }\n }",{input:e});return t&&t.UpdateQuerySystemUser?t.UpdateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to update query"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::UpdateQuery - Error updating query - ${e}`),{Success:!1,ErrorMessage:e.toString()}}}async DeleteQuery(e,t){try{if(!e||""===e.trim())return(0,a.ZI)("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) {\n DeleteQuerySystemResolver(ID: $ID, options: $options) {\n Success\n ErrorMessage\n ID\n Name\n }\n }",s={ID:e};void 0!==t&&(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(e){let t="";if(e instanceof Error){if(t=e.message,"cause"in e&&e.cause){const r=e.cause;t+=` | Cause: ${r.message||r}`,"code"in r&&(t+=` | Code: ${r.code}`)}if("response"in e){const r=e.response;r?.status&&(t+=` | HTTP Status: ${r.status}`),r?.errors&&(t+=` | GraphQL Errors: ${JSON.stringify(r.errors)}`)}e.stack&&console.error("DeleteQuery stack trace:",e.stack)}else t=String(e);return(0,a.ZI)(`GraphQLSystemUserClient::DeleteQuery - Error deleting query - ${t}`),{Success:!1,ErrorMessage:t}}}async RunAIPrompt(e){try{const t=s.J1`
431
433
  query RunAIPromptSystemUser(
432
434
  $promptId: String!,
433
435
  $data: String,
@@ -551,7 +553,7 @@
551
553
  error
552
554
  }
553
555
  }
554
- `,r={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this.Client.request(t,r);if(!a?.EmbedTextSystemUser)return{embeddings:(Array.isArray(e.textToEmbed),[]),modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const n=a.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?n.embeddings:n.embeddings[0],modelName:n.modelName,vectorDimensions:n.vectorDimensions,error:n.error}}catch(t){return(0,a.ZI)(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:(Array.isArray(e.textToEmbed),[]),modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}}class T{static{p(this,"GetDataOutput")}}class U{static{p(this,"SimpleRemoteEntityOutput")}}class F{static{p(this,"SimpleRemoteEntity")}}class V{static{p(this,"SimpleRemoteEntityField")}}class _{static{p(this,"GraphQLActionClient")}constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),a=this.createActionVariables(e,s,r),n=await this.executeActionMutation(a);return this.processActionResult(n,t)}catch(e){return this.handleActionError(e,t)}}serializeActionParameters(e){if(e)return e.map(e=>{let t=e.Value;return null!=t&&"object"==typeof t&&(t=JSON.stringify(t)),{...e,Value:t}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=s.J1`
556
+ `,r={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this.Client.request(t,r);if(!a?.EmbedTextSystemUser)return{embeddings:(Array.isArray(e.textToEmbed),[]),modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const n=a.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?n.embeddings:n.embeddings[0],modelName:n.modelName,vectorDimensions:n.vectorDimensions,error:n.error}}catch(t){return(0,a.ZI)(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:(Array.isArray(e.textToEmbed),[]),modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}}class F{static{y(this,"GetDataOutput")}}class V{static{y(this,"SimpleRemoteEntityOutput")}}class U{static{y(this,"SimpleRemoteEntity")}}class _{static{y(this,"SimpleRemoteEntityField")}}class O{static{y(this,"GraphQLActionClient")}constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),a=this.createActionVariables(e,s,r),n=await this.executeActionMutation(a);return this.processActionResult(n,t)}catch(e){return this.handleActionError(e,t)}}serializeActionParameters(e){if(e)return e.map(e=>{let t=e.Value;return null!=t&&"object"==typeof t&&(t=JSON.stringify(t)),{...e,Value:t}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=s.J1`
555
557
  mutation RunAction($input: RunActionInput!) {
556
558
  RunAction(input: $input) {
557
559
  Success
@@ -568,7 +570,7 @@
568
570
  ResultData
569
571
  }
570
572
  }
571
- `;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(e){(0,a.ZI)(`Failed to parse entity action result data: ${e}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return(0,a.ZI)(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}}class O{static{p(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(e){return this.handleCreateAPIKeyError(e)}}createAPIKeyVariables(e){return{input:{Label:e.Label,Description:e.Description,ExpiresAt:e.ExpiresAt?.toISOString(),ScopeIDs:e.ScopeIDs}}}async executeCreateAPIKeyMutation(e){const t=s.J1`
573
+ `;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(e){(0,a.ZI)(`Failed to parse entity action result data: ${e}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return(0,a.ZI)(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}}class k{static{y(this,"GraphQLEncryptionClient")}constructor(e){this._dataProvider=e}async CreateAPIKey(e){try{const t=this.createAPIKeyVariables(e),r=await this.executeCreateAPIKeyMutation(t);return this.processCreateAPIKeyResult(r)}catch(e){return this.handleCreateAPIKeyError(e)}}createAPIKeyVariables(e){return{input:{Label:e.Label,Description:e.Description,ExpiresAt:e.ExpiresAt?.toISOString(),ScopeIDs:e.ScopeIDs}}}async executeCreateAPIKeyMutation(e){const t=s.J1`
572
574
  mutation CreateAPIKey($input: CreateAPIKeyInput!) {
573
575
  CreateAPIKey(input: $input) {
574
576
  Success
@@ -584,61 +586,65 @@
584
586
  Error
585
587
  }
586
588
  }
587
- `,r=await this._dataProvider.ExecuteGQL(t,{apiKeyId:e});return r?.RevokeAPIKey?{Success:r.RevokeAPIKey.Success,Error:r.RevokeAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}catch(e){const t=e;return(0,a.ZI)(`Error revoking API key: ${t.message}`),{Success:!1,Error:`Error: ${t.message}`}}}}class K{static{p(this,"GraphQLTestingClient")}constructor(e){this._dataProvider=e}async RunTest(e){let t;try{e.onProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(t=>{try{const r=JSON.parse(t);"RunTestResolver"===r.resolver&&"TestExecutionProgress"===r.type&&"ok"===r.status&&r.data?.progress&&e.onProgress(r.data.progress)}catch(e){console.error("[GraphQLTestingClient] Failed to parse progress message:",e)}}));const r=s.J1`
588
- mutation RunTest(
589
- $testId: String!,
590
- $verbose: Boolean,
591
- $environment: String,
592
- $tags: String,
593
- $variables: String
594
- ) {
595
- RunTest(
596
- testId: $testId,
597
- verbose: $verbose,
598
- environment: $environment,
599
- tags: $tags,
600
- variables: $variables
601
- ) {
602
- success
603
- errorMessage
604
- executionTimeMs
605
- result
606
- }
589
+ `,r=await this._dataProvider.ExecuteGQL(t,{apiKeyId:e});return r?.RevokeAPIKey?{Success:r.RevokeAPIKey.Success,Error:r.RevokeAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}catch(e){const t=e;return(0,a.ZI)(`Error revoking API key: ${t.message}`),{Success:!1,Error:`Error: ${t.message}`}}}}class K{static{y(this,"GraphQLTestingClient")}constructor(e){this._dataProvider=e}async RunTest(e){try{const t=this.buildRunTestMutation(),r=this.buildRunTestVariables(e);return await I.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTest",operationLabel:"RunTest",validateAck:y(e=>!0===e?.success,"validateAck"),isCompletionEvent:y(t=>this.isTestCompletionEvent(t,e.testId),"isCompletionEvent"),extractResult:y(e=>this.extractTestResult(e),"extractResult"),onMessage:e.onProgress?t=>this.forwardTestProgress(t,e.onProgress):void 0,createErrorResult:y(e=>({success:!1,errorMessage:e,result:null}),"createErrorResult")})}catch(e){return this.handleError(e,"RunTest")}}async RunTestSuite(e){try{const t=this.buildRunTestSuiteMutation(),r=this.buildRunTestSuiteVariables(e);return await I.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTestSuite",operationLabel:"RunTestSuite",validateAck:y(e=>!0===e?.success,"validateAck"),isCompletionEvent:y(t=>this.isSuiteCompletionEvent(t,e.suiteId),"isCompletionEvent"),extractResult:y(e=>this.extractSuiteResult(e),"extractResult"),onMessage:e.onProgress?t=>this.forwardTestProgress(t,e.onProgress):void 0,createErrorResult:y(e=>({success:!1,errorMessage:e,result:null}),"createErrorResult")})}catch(e){return this.handleError(e,"RunTestSuite")}}async IsTestRunning(e){try{const t=s.J1`
590
+ query IsTestRunning($testId: String!) {
591
+ IsTestRunning(testId: $testId)
607
592
  }
608
- `,a=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,n=e.variables?JSON.stringify(e.variables):void 0,o={testId:e.testId,verbose:e.verbose,environment:e.environment,tags:a,variables:n},i=await this._dataProvider.ExecuteGQL(r,o);return this.processTestResult(i.RunTest)}catch(e){return this.handleError(e,"RunTest")}finally{t&&t.unsubscribe()}}async RunTestSuite(e){let t;try{e.onProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(t=>{try{const r=JSON.parse(t);"RunTestResolver"===r.resolver&&"TestExecutionProgress"===r.type&&"ok"===r.status&&r.data?.progress&&e.onProgress(r.data.progress)}catch(e){console.error("[GraphQLTestingClient] Failed to parse progress message:",e)}}));const r=s.J1`
609
- mutation RunTestSuite(
610
- $suiteId: String!,
611
- $verbose: Boolean,
612
- $environment: String,
613
- $parallel: Boolean,
614
- $tags: String,
615
- $variables: String,
616
- $selectedTestIds: String,
617
- $sequenceStart: Int,
618
- $sequenceEnd: Int
593
+ `;return(await this._dataProvider.ExecuteGQL(t,{testId:e})).IsTestRunning}catch(e){return(0,a.ZI)(`Error checking test running status: ${e.message}`),!1}}buildRunTestMutation(){return s.J1`
594
+ mutation RunTest(
595
+ $testId: String!,
596
+ $verbose: Boolean,
597
+ $environment: String,
598
+ $tags: String,
599
+ $variables: String,
600
+ $fireAndForget: Boolean
601
+ ) {
602
+ RunTest(
603
+ testId: $testId,
604
+ verbose: $verbose,
605
+ environment: $environment,
606
+ tags: $tags,
607
+ variables: $variables,
608
+ fireAndForget: $fireAndForget
619
609
  ) {
620
- RunTestSuite(
621
- suiteId: $suiteId,
622
- verbose: $verbose,
623
- environment: $environment,
624
- parallel: $parallel,
625
- tags: $tags,
626
- variables: $variables,
627
- selectedTestIds: $selectedTestIds,
628
- sequenceStart: $sequenceStart,
629
- sequenceEnd: $sequenceEnd
630
- ) {
631
- success
632
- errorMessage
633
- executionTimeMs
634
- result
635
- }
610
+ success
611
+ errorMessage
612
+ executionTimeMs
613
+ result
636
614
  }
637
- `,a=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,n=e.variables?JSON.stringify(e.variables):void 0,o=e.selectedTestIds&&e.selectedTestIds.length>0?JSON.stringify(e.selectedTestIds):void 0,i={suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel,tags:a,variables:n,selectedTestIds:o,sequenceStart:e.sequenceStart,sequenceEnd:e.sequenceEnd},u=await this._dataProvider.ExecuteGQL(r,i);return this.processSuiteResult(u.RunTestSuite)}catch(e){return this.handleError(e,"RunTestSuite")}finally{t&&t.unsubscribe()}}async IsTestRunning(e){try{const t=s.J1`
638
- query IsTestRunning($testId: String!) {
639
- IsTestRunning(testId: $testId)
615
+ }
616
+ `}buildRunTestSuiteMutation(){return s.J1`
617
+ mutation RunTestSuite(
618
+ $suiteId: String!,
619
+ $verbose: Boolean,
620
+ $environment: String,
621
+ $parallel: Boolean,
622
+ $tags: String,
623
+ $variables: String,
624
+ $selectedTestIds: String,
625
+ $sequenceStart: Int,
626
+ $sequenceEnd: Int,
627
+ $fireAndForget: Boolean
628
+ ) {
629
+ RunTestSuite(
630
+ suiteId: $suiteId,
631
+ verbose: $verbose,
632
+ environment: $environment,
633
+ parallel: $parallel,
634
+ tags: $tags,
635
+ variables: $variables,
636
+ selectedTestIds: $selectedTestIds,
637
+ sequenceStart: $sequenceStart,
638
+ sequenceEnd: $sequenceEnd,
639
+ fireAndForget: $fireAndForget
640
+ ) {
641
+ success
642
+ errorMessage
643
+ executionTimeMs
644
+ result
640
645
  }
641
- `;return(await this._dataProvider.ExecuteGQL(t,{testId:e})).IsTestRunning}catch(e){return(0,a.ZI)(`Error checking test running status: ${e.message}`),!1}}processTestResult(e){if(!e)throw new Error("Invalid response from server");let t;try{t=(0,d.NG)(e.result)}catch{t=e.result}return{success:e.success,errorMessage:e.errorMessage,executionTimeMs:e.executionTimeMs,result:t}}processSuiteResult(e){if(!e)throw new Error("Invalid response from server");let t;try{t=(0,d.NG)(e.result)}catch{t=e.result}return{success:e.success,errorMessage:e.errorMessage,executionTimeMs:e.executionTimeMs,result:t}}handleError(e,t){const r=e.message;return(0,a.ZI)(`${t} failed: ${r}`),{success:!1,errorMessage:r,result:null}}}class k{static{p(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=s.J1`
646
+ }
647
+ `}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"RunTestResolver"===e.resolver&&"FireAndForgetComplete"===e.type&&"complete"===r?.type&&r?.testId===t}isSuiteCompletionEvent(e,t){const r=e.data;return"RunTestResolver"===e.resolver&&"FireAndForgetSuiteComplete"===e.type&&"complete"===r?.type&&r?.suiteId===t}extractTestResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?(0,d.NG)(t.result):null}}extractSuiteResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?(0,d.NG)(t.result):null}}forwardTestProgress(e,t){if("RunTestResolver"===e.resolver&&"TestExecutionProgress"===e.type&&"ok"===e.status){const r=e.data?.progress;r&&t(r)}}handleError(e,t){const r=e.message;return(0,a.ZI)(`${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 j{static{y(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=s.J1`
642
648
  query GetRegistryComponent(
643
649
  $registryName: String!,
644
650
  $namespace: String!,
@@ -659,7 +665,7 @@
659
665
  specification
660
666
  }
661
667
  }
662
- `,r={registryName:e.registryName,namespace:e.namespace,name:e.name};void 0!==e.version&&(r.version=e.version),void 0!==e.hash&&(r.hash=e.hash);const n=await this._dataProvider.ExecuteGQL(t,r);if(n&&n.GetRegistryComponent){const e=n.GetRegistryComponent;if(e.notModified&&!e.specification)return null;if(e.specification){if("object"==typeof e.specification)return e.specification;try{return JSON.parse(e.specification)}catch(e){return(0,a.ZI)(`Failed to parse component specification: ${e}`),null}}return null}return null}catch(e){throw(0,a.ZI)(e),new Error(`Failed to get registry component: ${e instanceof Error?e.message:"Unknown error"}`)}}async GetRegistryComponentWithHash(e){try{const t=s.J1`
668
+ `,r={registryName:e.registryName,namespace:e.namespace,name:e.name};void 0!==e.version&&(r.version=e.version),void 0!==e.hash&&(r.hash=e.hash);const n=Date.now();console.log(`[DIAG][${n}] GetRegistryComponent() calling ExecuteGQL for ${e.registryName}/${e.name}`,{variables:r,dataProviderType:this._dataProvider?.constructor?.name});const o=Date.now(),i=await this._dataProvider.ExecuteGQL(t,r);if(console.log(`[DIAG][${n}] GetRegistryComponent() ExecuteGQL returned in ${Date.now()-o}ms`,{resultExists:!!i,hasGetRegistryComponent:!!i&&!!i.GetRegistryComponent,resultKeys:i?Object.keys(i):[],rawResult:i?JSON.stringify(i).substring(0,500):"null"}),i&&i.GetRegistryComponent){const e=i.GetRegistryComponent;if(console.log(`[DIAG][${n}] GetRegistryComponent() response details:`,{notModified:e.notModified,hasSpecification:!!e.specification,specType:e.specification?typeof e.specification:"N/A",specLength:e.specification?"string"==typeof e.specification?e.specification.length:JSON.stringify(e.specification).length:0,hash:e.hash,message:e.message}),e.notModified&&!e.specification)return console.log(`[DIAG][${n}] GetRegistryComponent() returning null - notModified with no spec`),null;if(e.specification){if("object"==typeof e.specification)return console.log(`[DIAG][${n}] GetRegistryComponent() returning spec as object`),e.specification;try{const t=JSON.parse(e.specification);return console.log(`[DIAG][${n}] GetRegistryComponent() returning parsed spec`,{name:t.name,hasCode:!!t.code,codeLength:t.code?.length}),t}catch(e){return console.error(`[DIAG][${n}] GetRegistryComponent() JSON PARSE FAILED:`,e),(0,a.ZI)(`Failed to parse component specification: ${e}`),null}}return console.warn(`[DIAG][${n}] GetRegistryComponent() response has GetRegistryComponent but no specification - returning null`),null}return console.warn(`[DIAG][${n}] GetRegistryComponent() result missing GetRegistryComponent field - returning null`,{resultExists:!!i,resultKeys:i?Object.keys(i):[]}),null}catch(e){throw console.error("[DIAG] GetRegistryComponent() CAUGHT ERROR:",e),(0,a.ZI)(e),new Error(`Failed to get registry component: ${e instanceof Error?e.message:"Unknown error"}`)}}async GetRegistryComponentWithHash(e){try{const t=s.J1`
663
669
  query GetRegistryComponent(
664
670
  $registryName: String!,
665
671
  $namespace: String!,
@@ -722,7 +728,7 @@
722
728
  error
723
729
  }
724
730
  }
725
- `,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(e){return(0,a.ZI)(e),{success:!1,error:e instanceof Error?e.message:"Unknown error"}}}}class J{static{p(this,"GraphQLVersionHistoryClient")}constructor(e){this._dataProvider=e}async CreateLabel(e){let t;try{e.OnProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(t=>{try{const r=JSON.parse(t);"VersionHistoryResolver"===r.resolver&&"CreateLabelProgress"===r.type&&"ok"===r.status&&r.data&&e.OnProgress(r.data)}catch{}}));const r=s.J1`
731
+ `,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(e){return(0,a.ZI)(e),{success:!1,error:e instanceof Error?e.message:"Unknown error"}}}}class J{static{y(this,"GraphQLVersionHistoryClient")}constructor(e){this._dataProvider=e}async CreateLabel(e){let t;try{e.OnProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(t=>{try{const r=JSON.parse(t);"VersionHistoryResolver"===r.resolver&&"CreateLabelProgress"===r.type&&"ok"===r.status&&r.data&&e.OnProgress(r.data)}catch{}}));const r=s.J1`
726
732
  mutation CreateVersionLabel($input: CreateVersionLabelInput!, $sessionId: String) {
727
733
  CreateVersionLabel(input: $input, sessionId: $sessionId) {
728
734
  Success
@@ -738,7 +744,7 @@
738
744
  }
739
745
  }
740
746
  }
741
- `,a={input:this.buildInput(e),sessionId:this._dataProvider.sessionId},n=await this._dataProvider.ExecuteGQL(r,a);return this.processResult(n)}catch(e){const t=e instanceof Error?e.message:String(e);return(0,a.ZI)(`GraphQLVersionHistoryClient.CreateLabel error: ${t}`),{Success:!1,Error:t}}finally{t&&t.unsubscribe()}}buildInput(e){const t={Name:e.Name};return null!=e.Description&&(t.Description=e.Description),null!=e.Scope&&(t.Scope=e.Scope),null!=e.EntityName&&(t.EntityName=e.EntityName),null!=e.ParentID&&(t.ParentID=e.ParentID),null!=e.ExternalSystemID&&(t.ExternalSystemID=e.ExternalSystemID),null!=e.IncludeDependencies&&(t.IncludeDependencies=e.IncludeDependencies),null!=e.MaxDepth&&(t.MaxDepth=e.MaxDepth),null!=e.ExcludeEntities&&(t.ExcludeEntities=e.ExcludeEntities),e.RecordKeys&&e.RecordKeys.length>0&&(t.RecordKeys=e.RecordKeys.map(e=>({Key:e.Key,Value:e.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(e=>({EntityName:e.EntityName??"",RecordID:e.RecordID??"",ErrorMessage:e.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 j{static{p(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const a=s.J1`
747
+ `,a={input:this.buildInput(e),sessionId:this._dataProvider.sessionId},n=await this._dataProvider.ExecuteGQL(r,a);return this.processResult(n)}catch(e){const t=e instanceof Error?e.message:String(e);return(0,a.ZI)(`GraphQLVersionHistoryClient.CreateLabel error: ${t}`),{Success:!1,Error:t}}finally{t&&t.unsubscribe()}}buildInput(e){const t={Name:e.Name};return null!=e.Description&&(t.Description=e.Description),null!=e.Scope&&(t.Scope=e.Scope),null!=e.EntityName&&(t.EntityName=e.EntityName),null!=e.ParentID&&(t.ParentID=e.ParentID),null!=e.ExternalSystemID&&(t.ExternalSystemID=e.ExternalSystemID),null!=e.IncludeDependencies&&(t.IncludeDependencies=e.IncludeDependencies),null!=e.MaxDepth&&(t.MaxDepth=e.MaxDepth),null!=e.ExcludeEntities&&(t.ExcludeEntities=e.ExcludeEntities),e.RecordKeys&&e.RecordKeys.length>0&&(t.RecordKeys=e.RecordKeys.map(e=>({Key:e.Key,Value:e.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(e=>({EntityName:e.EntityName??"",RecordID:e.RecordID??"",ErrorMessage:e.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 B{static{y(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const a=s.J1`
742
748
  query ListStorageObjects($input: ListStorageObjectsInput!) {
743
749
  ListStorageObjects(input: $input) {
744
750
  objects {