@memberjunction/graphql-dataprovider 5.16.0 → 5.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +161 -96
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +169 -1
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +169 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +163 -98
- package/dist/index.mjs.map +1 -1
- package/package.json +7 -7
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var G=Object.defineProperty;var g=(h,e)=>G(h,"name",{value:e,configurable:!0});var u=require("graphql-request"),c=require("@memberjunction/core"),R=require("@memberjunction/global"),N=require("@memberjunction/core-entities"),b=require("rxjs"),q=require("graphql-ws"),V=require("uuid"),_=require("@tempfix/idb");class v{static{g(this,"FieldMapper")}static{this.DB_PREFIX="__mj_"}static{this.GQL_PREFIX="_mj__"}constructor(){}MapFields(e){if(e)for(const t in e){const r=this.MapFieldName(t);r!==t&&(e[r]=e[t],delete e[t])}return e}MapFieldName(e){return e.startsWith(v.DB_PREFIX)?v.GQL_PREFIX+e.substring(v.DB_PREFIX.length):e}ReverseMapFieldName(e){return e.startsWith(v.GQL_PREFIX)?v.DB_PREFIX+e.substring(v.GQL_PREFIX.length):e}ReverseMapFields(e){for(const t in e){const r=this.ReverseMapFieldName(t);r!==t&&(e[r]=e[t],delete e[t])}return e}}class M extends c.TransactionGroupBase{static{g(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=u.gql`
|
|
2
2
|
mutation ExecuteTransactionGroup($group: TransactionInputType!) {
|
|
3
3
|
ExecuteTransactionGroup(group: $group) {
|
|
4
4
|
Success
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
ResultsJSON
|
|
7
7
|
}
|
|
8
8
|
}
|
|
9
|
-
`,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const r={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const n=s.ExecuteTransactionGroup,a=[];for(let i=0;i<this.PendingTransactions.length;i++){const o=n.ResultsJSON[i],
|
|
9
|
+
`,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const r={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const n=s.ExecuteTransactionGroup,a=[];for(let i=0;i<this.PendingTransactions.length;i++){const o=n.ResultsJSON[i],l=R.SafeJSONParse(o),d=this.PendingTransactions[i];a.push(new c.TransactionResult(d,l,l!==null))}return a}else throw new Error("Failed to execute transaction group")}}const O=900*1e3;class P{static{g(this,"FireAndForgetHelper")}static async Execute(e){const t=e.operationLabel??e.mutationFieldName;let r,s;try{const{promise:n,resolve:a,reject:i}=P.createCompletionPromise();s=P.setupTimeout(i,e.timeoutMs,e.timeoutErrorMessage),r=P.subscribeToPubSub(e,a,s);const o=await P.executeMutation(e);if(!e.validateAck(o)){s&&clearTimeout(s);const l=o?.errorMessage??"Server rejected the request";return c.LogError(`[FireAndForget:${t}] Server rejected: ${l}`),e.createErrorResult(l)}return c.LogStatus(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await n}catch(n){s&&clearTimeout(s);const a=n;throw c.LogError(`[FireAndForget:${t}] Error: ${a.message}`),n}finally{s&&clearTimeout(s),r&&r.unsubscribe()}}static createCompletionPromise(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}static setupTimeout(e,t,r){const s=t??O,n=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(n))},s)}static subscribeToPubSub(e,t,r){const s=e.dataProvider.sessionId,n=e.operationLabel??e.mutationFieldName;return e.dataProvider.PushStatusUpdates(s).subscribe(a=>{try{const i=JSON.parse(a);e.onMessage&&e.onMessage(i),e.isCompletionEvent(i)&&(clearTimeout(r),c.LogStatus(`[FireAndForget:${n}] Completion event received`),t(e.extractResult(i)))}catch(i){console.error(`[FireAndForget:${n}] Failed to parse PubSub message:`,i)}})}static async executeMutation(e){return(await e.dataProvider.ExecuteGQL(e.mutation,e.variables))[e.mutationFieldName]}}class x{static{g(this,"GraphQLAIClient")}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=u.gql`
|
|
10
10
|
mutation RunAIPrompt(
|
|
11
11
|
$promptId: String!,
|
|
12
12
|
$data: String,
|
|
@@ -65,7 +65,7 @@
|
|
|
65
65
|
chatResult
|
|
66
66
|
}
|
|
67
67
|
}
|
|
68
|
-
`,r=this.preparePromptVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(s)}catch(t){return this.handlePromptError(t)}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,n;try{t.parsedResult&&(r=JSON.parse(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(n=JSON.parse(t.chatResult))}catch{n=t.chatResult}return{success:t.success,output:t.output,parsedResult:r,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:s,chatResult:n}}handlePromptError(e){const t=e;return
|
|
68
|
+
`,r=this.preparePromptVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(s)}catch(t){return this.handlePromptError(t)}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,n;try{t.parsedResult&&(r=JSON.parse(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(n=JSON.parse(t.chatResult))}catch{n=t.chatResult}return{success:t.success,output:t.output,parsedResult:r,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:s,chatResult:n}}handlePromptError(e){const t=e;return c.LogError(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){try{const s=this.buildRunAIAgentMutation(),n=this.prepareAgentVariables(e,t,r);return n.fireAndForget=!0,await P.Execute({dataProvider:this._dataProvider,mutation:s,variables:n,mutationFieldName:"RunAIAgent",operationLabel:"RunAIAgent",validateAck:g(a=>a?.success===!0,"validateAck"),isCompletionEvent:g(a=>this.isAgentCompletionEvent(a),"isCompletionEvent"),extractResult:g(a=>this.extractAgentResult(a),"extractResult"),onMessage:e.onProgress?a=>this.forwardAgentProgress(a,e.onProgress):void 0,createErrorResult:g(a=>this.createAgentErrorResult(a),"createErrorResult")})}catch(s){return this.handleAgentError(s)}}buildRunAIAgentMutation(){return u.gql`
|
|
69
69
|
mutation RunAIAgent(
|
|
70
70
|
$agentId: String!,
|
|
71
71
|
$messages: String!,
|
|
@@ -106,7 +106,7 @@
|
|
|
106
106
|
result
|
|
107
107
|
}
|
|
108
108
|
}
|
|
109
|
-
`}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),t!==void 0&&(s.sourceArtifactId=t),r!==void 0&&(s.sourceArtifactVersionId=r),s}processAgentResult(e){return R.SafeJSONParse(e)}handleAgentError(e){const r=e?.message||String(e);
|
|
109
|
+
`}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),t!==void 0&&(s.sourceArtifactId=t),r!==void 0&&(s.sourceArtifactVersionId=r),s}processAgentResult(e){return R.SafeJSONParse(e)}handleAgentError(e){const r=e?.message||String(e);c.LogError(`Error running AI agent: ${r}`);const s=r.includes("Failed to fetch")||r.includes("NetworkError"),n=r.includes("timed out")||r.includes("timeout");let a;return s?a="Lost connection to the server. The agent may still be running. Please refresh to check the latest status.":a=r,{success:!1,agentRun:void 0,errorMessage:a}}async RunAIAgentFromConversationDetail(e){try{const t=this.buildConversationDetailMutation(),r=this.prepareConversationDetailVariables(e);return await P.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunAIAgentFromConversationDetail",operationLabel:"RunAIAgentFromConversationDetail",validateAck:g(s=>s?.success===!0,"validateAck"),isCompletionEvent:g(s=>this.isConversationDetailCompletionEvent(s,e.conversationDetailId),"isCompletionEvent"),extractResult:g(s=>this.extractAgentResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardConversationDetailProgress(s,e.onProgress):void 0,createErrorResult:g(s=>this.createAgentErrorResult(s),"createErrorResult")})}catch(t){return this.handleAgentError(t)}}buildConversationDetailMutation(){return u.gql`
|
|
110
110
|
mutation RunAIAgentFromConversationDetail(
|
|
111
111
|
$conversationDetailId: String!,
|
|
112
112
|
$agentId: String!,
|
|
@@ -145,7 +145,7 @@
|
|
|
145
145
|
result
|
|
146
146
|
}
|
|
147
147
|
}
|
|
148
|
-
`}prepareConversationDetailVariables(e){const t={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId,fireAndForget:!0};return e.maxHistoryMessages!==void 0&&(t.maxHistoryMessages=e.maxHistoryMessages),e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(t.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.createArtifacts!==void 0&&(t.createArtifacts=e.createArtifacts),e.createNotification!==void 0&&(t.createNotification=e.createNotification),e.sourceArtifactId!==void 0&&(t.sourceArtifactId=e.sourceArtifactId),e.sourceArtifactVersionId!==void 0&&(t.sourceArtifactVersionId=e.sourceArtifactVersionId),t}isAgentCompletionEvent(e){const t=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&t?.type==="complete"}isConversationDetailCompletionEvent(e,t){const r=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&r?.type==="complete"&&r?.conversationDetailId===t}extractAgentResult(e){const t=e.data,r=t.result;return r?R.SafeJSONParse(r):{success:t.success,agentRun:void 0}}forwardAgentProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const s=e.data?.progress;s&&t({step:s.currentStep,percentage:s.percentage,message:s.message,metadata:s})}forwardConversationDetailProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const r=e.data,s=r?.progress;s&&t({currentStep:s.currentStep,percentage:s.percentage,message:s.message,metadata:{...s,agentRun:r?.agentRun,agentRunId:r?.agentRunId}})}createAgentErrorResult(e){return{success:!1,agentRun:void 0,errorMessage:e}}async ExecuteSimplePrompt(e){try{const t=
|
|
148
|
+
`}prepareConversationDetailVariables(e){const t={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId,fireAndForget:!0};return e.maxHistoryMessages!==void 0&&(t.maxHistoryMessages=e.maxHistoryMessages),e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(t.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.createArtifacts!==void 0&&(t.createArtifacts=e.createArtifacts),e.createNotification!==void 0&&(t.createNotification=e.createNotification),e.sourceArtifactId!==void 0&&(t.sourceArtifactId=e.sourceArtifactId),e.sourceArtifactVersionId!==void 0&&(t.sourceArtifactVersionId=e.sourceArtifactVersionId),t}isAgentCompletionEvent(e){const t=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&t?.type==="complete"}isConversationDetailCompletionEvent(e,t){const r=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&r?.type==="complete"&&r?.conversationDetailId===t}extractAgentResult(e){const t=e.data,r=t.result;return r?R.SafeJSONParse(r):{success:t.success,agentRun:void 0}}forwardAgentProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const s=e.data?.progress;s&&t({step:s.currentStep,percentage:s.percentage,message:s.message,metadata:s})}forwardConversationDetailProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const r=e.data,s=r?.progress;s&&t({currentStep:s.currentStep,percentage:s.percentage,message:s.message,metadata:{...s,agentRun:r?.agentRun,agentRunId:r?.agentRunId}})}createAgentErrorResult(e){return{success:!1,agentRun:void 0,errorMessage:e}}async ExecuteSimplePrompt(e){try{const t=u.gql`
|
|
149
149
|
mutation ExecuteSimplePrompt(
|
|
150
150
|
$systemPrompt: String!,
|
|
151
151
|
$messages: String,
|
|
@@ -168,7 +168,7 @@
|
|
|
168
168
|
executionTimeMs
|
|
169
169
|
}
|
|
170
170
|
}
|
|
171
|
-
`,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.ExecuteSimplePrompt)throw new Error("Invalid response from server");const n=s.ExecuteSimplePrompt;let a;if(n.resultObject)try{a=JSON.parse(n.resultObject)}catch{a=n.resultObject}return{success:n.success,result:n.result,resultObject:a,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){const r=t;return
|
|
171
|
+
`,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.ExecuteSimplePrompt)throw new Error("Invalid response from server");const n=s.ExecuteSimplePrompt;let a;if(n.resultObject)try{a=JSON.parse(n.resultObject)}catch{a=n.resultObject}return{success:n.success,result:n.result,resultObject:a,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){const r=t;return c.LogError(`Error executing simple prompt: ${r}`),{success:!1,modelName:"Unknown",error:r.message||"Unknown error occurred"}}}async EmbedText(e){try{const t=u.gql`
|
|
172
172
|
mutation EmbedText(
|
|
173
173
|
$textToEmbed: [String!]!,
|
|
174
174
|
$modelSize: String!
|
|
@@ -183,16 +183,16 @@
|
|
|
183
183
|
error
|
|
184
184
|
}
|
|
185
185
|
}
|
|
186
|
-
`,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this._dataProvider.ExecuteGQL(t,s);if(!n?.EmbedText)throw new Error("Invalid response from server");const a=n.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?a.embeddings:a.embeddings[0],modelName:a.modelName,vectorDimensions:a.vectorDimensions,error:a.error}}catch(t){const r=t;return
|
|
186
|
+
`,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this._dataProvider.ExecuteGQL(t,s);if(!n?.EmbedText)throw new Error("Invalid response from server");const a=n.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?a.embeddings:a.embeddings[0],modelName:a.modelName,vectorDimensions:a.vectorDimensions,error:a.error}}catch(t){const r=t;return c.LogError(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}}const $="default";class L{static{g(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||$;let r=this._storage.get(t);return r||(r=new Map,this._storage.set(t,r)),r}async GetItem(e,t){return this.getCategoryMap(t||$).get(e)??null}async SetItem(e,t,r){this.getCategoryMap(r||$).set(e,t)}async Remove(e,t){this.getCategoryMap(t||$).delete(e)}async ClearCategory(e){const t=e||$;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||$);return t?Array.from(t.keys()):[]}}const k="MJ_Metadata",B=3,T=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"],Q="Metadata_KVPairs";class F extends L{static{g(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=_.openDB(k,B,{upgrade(e){try{e.objectStoreNames.contains(Q)&&e.deleteObjectStore(Q);for(const t of T)e.objectStoreNames.contains(t)||e.createObjectStore(t)}catch(t){c.LogErrorEx({error:t,message:t?.message})}}}),this.dbPromise.then(()=>{this._dbReady=!0}).catch(e=>{c.LogErrorEx({error:e,message:"IndexedDB initialization failed: "+e?.message})})}isKnownCategory(e){const t=`mj:${e}`;return T.includes(t)}getStoreName(e){const t=e||$;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||$;return this.isKnownCategory(r)?e:`[${r}]:${e}`}async SetItem(e,t,r){try{const s=await this.dbPromise,n=this.getStoreName(r),a=this.getStoreKey(e,r),i=s.transaction(n,"readwrite");await i.objectStore(n).put(t,a),await i.done}catch(s){c.LogErrorEx({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),n=this.getStoreKey(e,t);return await r.transaction(s).objectStore(s).get(n)??null}catch(r){return c.LogErrorEx({error:r,message:r?.message}),await super.GetItem(e,t)}}async Remove(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t),a=r.transaction(s,"readwrite");await a.objectStore(s).delete(n),await a.done}catch(r){c.LogErrorEx({error:r,message:r?.message}),await super.Remove(e,t)}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||$,s=this.getStoreName(e);if(this.isKnownCategory(r)){const n=t.transaction(s,"readwrite");await n.objectStore(s).clear(),await n.done}else{const n=`[${r}]:`,a=t.transaction("mj:default","readwrite"),i=a.objectStore("mj:default"),o=await i.getAllKeys();for(const l of o)typeof l=="string"&&l.startsWith(n)&&await i.delete(l);await a.done}}catch(t){c.LogErrorEx({error:t,message:t?.message}),await super.ClearCategory(e)}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||$,s=this.getStoreName(e),i=await t.transaction(s,"readonly").objectStore(s).getAllKeys();if(this.isKnownCategory(r))return i.map(l=>String(l));const o=`[${r}]:`;return i.map(l=>String(l)).filter(l=>l.startsWith(o)).map(l=>l.slice(o.length))}catch(t){return c.LogErrorEx({error:t,message:t?.message}),await super.GetCategoryKeys(e)}}}class K extends c.ProviderConfigDataBase{static{g(this,"GraphQLProviderConfigData")}get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get MJAPIKey(){return this.Data.MJAPIKey}set MJAPIKey(e){this.Data.MJAPIKey=e}get UserAPIKey(){return this.Data.UserAPIKey}set UserAPIKey(e){this.Data.UserAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}get OnAuthenticationError(){return this.Data.OnAuthenticationError}set OnAuthenticationError(e){this.Data.OnAuthenticationError=e}constructor(e,t,r,s,n,a,i,o,l,d){super({Token:e,URL:t,WSURL:r,MJAPIKey:o,UserAPIKey:l,RefreshTokenFunction:s,OnAuthenticationError:d},n,a,i)}}class S extends c.ProviderBase{static{g(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._dynamicHeaders=new Map,this._innerCurrentUserQueryString=`CurrentUser {
|
|
187
187
|
${this.userInfoString()}
|
|
188
188
|
MJUserRoles_UserIDArray {
|
|
189
189
|
${this.userRoleInfoString()}
|
|
190
190
|
}
|
|
191
191
|
}
|
|
192
|
-
`,this._currentUserQuery=
|
|
192
|
+
`,this._currentUserQuery=u.gql`query CurrentUserAndRoles {
|
|
193
193
|
${this._innerCurrentUserQueryString}
|
|
194
194
|
CurrentUserTenantContext
|
|
195
|
-
}`,this._wsClient=null,this._wsClientCreatedAt=null,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=1800*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=300*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=600*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,this._cacheInvalidationSubscription=null;const e=R.GetGlobalObjectStore();if(e&&e[
|
|
195
|
+
}`,this._wsClient=null,this._wsClientCreatedAt=null,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=1800*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=300*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=600*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,this._cacheInvalidationSubscription=null;const e=R.GetGlobalObjectStore();if(e&&e[S._globalStoreKey])return e[S._globalStoreKey];e&&(e[S._globalStoreKey]=this)}static{this._globalStoreKey="___SINGLETON__GraphQLDataProvider"}static get Instance(){const e=R.GetGlobalObjectStore();return e?e[S._globalStoreKey]:void 0}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new x(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}async InternalExecuteQueryFromSpec(e,t){throw new Error("ExecuteQueryFromSpec is not supported by this provider.")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return V.v4()}get LocalStoragePrefix(){if(this._configData===void 0||this._configData.URL===void 0)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const r=this.LocalStoragePrefix+"sessionId";await t.SetItem(r,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,r,s){try{return this._configData=e,r?(this._sessionId=await this.GetPreferredUUID(s),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey,e.UserAPIKey),await this.SaveStoredSessionID(this._sessionId)):(S.Instance._configData=e,S.Instance._sessionId===void 0&&(S.Instance._sessionId=await this.GetPreferredUUID(s)),S.Instance._client||(S.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,S.Instance._sessionId,e.MJAPIKey,e.UserAPIKey)),await S.Instance.SaveStoredSessionID(S.Instance._sessionId),this._sessionId=S.Instance._sessionId,this._client=S.Instance._client),super.Config(e)}catch(n){throw c.LogError(n),n}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}SetDynamicHeader(e,t){this._dynamicHeaders.set(e,t),this._client&&this._client.setHeader(e,t),S.Instance&&S.Instance!==this&&S.Instance._configData===this._configData&&(S.Instance._dynamicHeaders.set(e,t),S.Instance._client&&S.Instance._client.setHeader(e,t))}RemoveDynamicHeader(e){this._dynamicHeaders.delete(e),this._client&&this._client.setHeader(e,""),S.Instance&&S.Instance!==this&&S.Instance._configData===this._configData&&(S.Instance._dynamicHeaders.delete(e),S.Instance._client&&S.Instance._client.setHeader(e,""))}GetDynamicHeaders(){return this._dynamicHeaders}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),r=t.MJUserRoles_UserIDArray.map(n=>this.ConvertBackToMJFields(n));t.MJUserRoles_UserIDArray=r;const s=new c.UserInfo(this,{...t,UserRoles:r});return e.CurrentUserTenantContext&&typeof e.CurrentUserTenantContext=="object"&&(s.TenantContext=e.CurrentUserTenantContext),s}}async RunReport(e,t){const r=u.gql`
|
|
196
196
|
query GetReportDataQuery ($ReportID: String!) {
|
|
197
197
|
GetReportData(ReportID: $ReportID) {
|
|
198
198
|
Success
|
|
@@ -201,31 +201,31 @@
|
|
|
201
201
|
ExecutionTime
|
|
202
202
|
ErrorMessage
|
|
203
203
|
}
|
|
204
|
-
}`,s=await this.ExecuteGQL(r,{ReportID:e.ReportID});if(s&&s.GetReportData)return{ReportID:e.ReportID,Success:s.GetReportData.Success,Results:JSON.parse(s.GetReportData.Results),RowCount:s.GetReportData.RowCount,ExecutionTime:s.GetReportData.ExecutionTime,ErrorMessage:s.GetReportData.ErrorMessage}}async InternalRunQuery(e,t){if(e.SQL)return this.RunAdhocQuery(e.SQL,e.MaxRows);if(e.QueryID)return this.RunQueryByID(e.QueryID,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);throw new Error("No SQL, QueryID, or QueryName provided to RunQuery")}async RunAdhocQuery(e,t,r){const s=
|
|
204
|
+
}`,s=await this.ExecuteGQL(r,{ReportID:e.ReportID});if(s&&s.GetReportData)return{ReportID:e.ReportID,Success:s.GetReportData.Success,Results:JSON.parse(s.GetReportData.Results),RowCount:s.GetReportData.RowCount,ExecutionTime:s.GetReportData.ExecutionTime,ErrorMessage:s.GetReportData.ErrorMessage}}async InternalRunQuery(e,t){if(e.SQL)return this.RunAdhocQuery(e.SQL,e.MaxRows);if(e.QueryID)return this.RunQueryByID(e.QueryID,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);throw new Error("No SQL, QueryID, or QueryName provided to RunQuery")}async RunAdhocQuery(e,t,r){const s=u.gql`
|
|
205
205
|
query ExecuteAdhocQuery($input: AdhocQueryInput!) {
|
|
206
206
|
ExecuteAdhocQuery(input: $input) {
|
|
207
207
|
${this.QueryReturnFieldList}
|
|
208
208
|
}
|
|
209
209
|
}
|
|
210
|
-
`,n={SQL:e};r!==void 0&&(n.TimeoutSeconds=r);const a=await this.ExecuteGQL(s,{input:n});return a?.ExecuteAdhocQuery?this.TransformQueryPayload(a.ExecuteAdhocQuery):{QueryID:"",QueryName:"Ad-Hoc Query",Success:!1,Results:[],RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Ad-hoc query execution failed \u2014 no response from server"}}async InternalRunQueries(e,t){const r=
|
|
210
|
+
`,n={SQL:e};r!==void 0&&(n.TimeoutSeconds=r);const a=await this.ExecuteGQL(s,{input:n});return a?.ExecuteAdhocQuery?this.TransformQueryPayload(a.ExecuteAdhocQuery):{QueryID:"",QueryName:"Ad-Hoc Query",Success:!1,Results:[],RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Ad-hoc query execution failed \u2014 no response from server"}}async InternalRunQueries(e,t){const r=u.gql`
|
|
211
211
|
query RunQueriesBatch($input: [RunQueryInput!]!) {
|
|
212
212
|
RunQueries(input: $input) {
|
|
213
213
|
${this.QueryReturnFieldList}
|
|
214
214
|
}
|
|
215
215
|
}
|
|
216
|
-
`,s=e.map(a=>({QueryID:a.QueryID,QueryName:a.QueryName,CategoryID:a.CategoryID,CategoryPath:a.CategoryPath,Parameters:a.Parameters,MaxRows:a.MaxRows,StartRow:a.StartRow,ForceAuditLog:a.ForceAuditLog,AuditLogDescription:a.AuditLogDescription})),n=await this.ExecuteGQL(r,{input:s});return n&&n.RunQueries?n.RunQueries.map(a=>this.TransformQueryPayload(a)):[]}async RunQueryByID(e,t,r,s,n,a,i){const o=
|
|
216
|
+
`,s=e.map(a=>({QueryID:a.QueryID,QueryName:a.QueryName,CategoryID:a.CategoryID,CategoryPath:a.CategoryPath,Parameters:a.Parameters,MaxRows:a.MaxRows,StartRow:a.StartRow,ForceAuditLog:a.ForceAuditLog,AuditLogDescription:a.AuditLogDescription})),n=await this.ExecuteGQL(r,{input:s});return n&&n.RunQueries?n.RunQueries.map(a=>this.TransformQueryPayload(a)):[]}async RunQueryByID(e,t,r,s,n,a,i){const o=u.gql`
|
|
217
217
|
query GetQueryDataQuery($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
|
|
218
218
|
GetQueryData(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
|
|
219
219
|
${this.QueryReturnFieldList}
|
|
220
220
|
}
|
|
221
221
|
}
|
|
222
|
-
`,
|
|
222
|
+
`,l={QueryID:e};t!==void 0&&(l.CategoryID=t),r!==void 0&&(l.CategoryPath=r),n!==void 0&&(l.Parameters=n),a!==void 0&&(l.MaxRows=a),i!==void 0&&(l.StartRow=i);const d=await this.ExecuteGQL(o,l);if(d&&d.GetQueryData)return this.TransformQueryPayload(d.GetQueryData)}async RunQueryByName(e,t,r,s,n,a,i){const o=u.gql`
|
|
223
223
|
query GetQueryDataByNameQuery($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
|
|
224
224
|
GetQueryDataByName(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
|
|
225
225
|
${this.QueryReturnFieldList}
|
|
226
226
|
}
|
|
227
227
|
}
|
|
228
|
-
`,
|
|
228
|
+
`,l={QueryName:e};t!==void 0&&(l.CategoryID=t),r!==void 0&&(l.CategoryPath=r),n!==void 0&&(l.Parameters=n),a!==void 0&&(l.MaxRows=a),i!==void 0&&(l.StartRow=i);const d=await this.ExecuteGQL(o,l);if(d&&d.GetQueryDataByName)return this.TransformQueryPayload(d.GetQueryDataByName)}get QueryReturnFieldList(){return`
|
|
229
229
|
Success
|
|
230
230
|
QueryID
|
|
231
231
|
QueryName
|
|
@@ -234,7 +234,7 @@
|
|
|
234
234
|
TotalRowCount
|
|
235
235
|
ExecutionTime
|
|
236
236
|
ErrorMessage
|
|
237
|
-
AppliedParameters`}TransformQueryPayload(e){try{return{QueryID:e.QueryID,QueryName:e.QueryName,Success:e.Success,Results:JSON.parse(e.Results),RowCount:e.RowCount,TotalRowCount:e.TotalRowCount,ExecutionTime:e.ExecutionTime,ErrorMessage:e.ErrorMessage,AppliedParameters:e.AppliedParameters?JSON.parse(e.AppliedParameters):void 0}}catch(t){return
|
|
237
|
+
AppliedParameters`}TransformQueryPayload(e){try{return{QueryID:e.QueryID,QueryName:e.QueryName,Success:e.Success,Results:JSON.parse(e.Results),RowCount:e.RowCount,TotalRowCount:e.TotalRowCount,ExecutionTime:e.ExecutionTime,ErrorMessage:e.ErrorMessage,AppliedParameters:e.AppliedParameters?JSON.parse(e.AppliedParameters):void 0}}catch(t){return c.LogError(`Error transforming query payload: ${t}`),null}}async RunQueriesWithCacheCheck(e,t){try{const r=e.map(o=>({params:{QueryID:o.params.QueryID||null,QueryName:o.params.QueryName||null,CategoryID:o.params.CategoryID||null,CategoryPath:o.params.CategoryPath||null,Parameters:o.params.Parameters||null,MaxRows:o.params.MaxRows??null,StartRow:o.params.StartRow??null,ForceAuditLog:o.params.ForceAuditLog||!1,AuditLogDescription:o.params.AuditLogDescription||null},cacheStatus:o.cacheStatus?{maxUpdatedAt:o.cacheStatus.maxUpdatedAt,rowCount:o.cacheStatus.rowCount}:null})),s=u.gql`
|
|
238
238
|
query RunQueriesWithCacheCheckQuery($input: [RunQueryWithCacheCheckInput!]!) {
|
|
239
239
|
RunQueriesWithCacheCheck(input: $input) {
|
|
240
240
|
success
|
|
@@ -250,18 +250,18 @@
|
|
|
250
250
|
}
|
|
251
251
|
}
|
|
252
252
|
}
|
|
253
|
-
`,a=(await this.ExecuteGQL(s,{input:r}))?.RunQueriesWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map(o=>{if((o.status==="stale"||o.status==="no_validation")&&o.Results){const
|
|
253
|
+
`,a=(await this.ExecuteGQL(s,{input:r}))?.RunQueriesWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map(o=>{if((o.status==="stale"||o.status==="no_validation")&&o.Results){const l=JSON.parse(o.Results);return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,results:l,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}});return{success:a.success,results:i,errorMessage:a.errorMessage}}catch(r){return c.LogError(`Error in RunQueriesWithCacheCheck: ${r}`),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async InternalRunView(e,t){try{let r="",s="";if(e){const n={};let a,i;if(e.ViewEntity)i=e.ViewEntity,a=i.Entity;else{const{entityName:p,v:f}=await this.getEntityNameAndUserView(e,t);i=f,a=p}const o=this.Entities.find(p=>p.Name===a);if(!o)throw new Error(`Entity ${a} not found in metadata`);let l=!1;const d=c.getGraphQLTypeNameBase(o);e.ViewID?(r=`Run${d}ViewByID`,s="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(r=`Run${d}ViewByName`,s="RunViewByNameInput",n.ViewName=e.ViewName):(l=!0,r=`Run${d}DynamicView`,s="RunDynamicViewInput",n.EntityName=e.EntityName),n.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",n.OrderBy=e.OrderBy?e.OrderBy:"",n.UserSearchString=e.UserSearchString?e.UserSearchString:"",n.Fields=e.Fields,n.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,e.MaxRows!==void 0&&(n.MaxRows=e.MaxRows),e.StartRow!==void 0&&(n.StartRow=e.StartRow),n.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,n.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(n.AuditLogDescription=e.AuditLogDescription),l||(n.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",n.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,n.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",n.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1),e.Aggregates&&e.Aggregates.length>0&&(n.Aggregates=e.Aggregates.map(p=>({expression:p.expression,alias:p.alias})));const I=this.getViewRunTimeFieldList(o,i,e,l),E=e.Aggregates&&e.Aggregates.length>0?`
|
|
254
254
|
AggregateResults {
|
|
255
255
|
alias
|
|
256
256
|
expression
|
|
257
257
|
value
|
|
258
258
|
error
|
|
259
259
|
}
|
|
260
|
-
AggregateExecutionTime`:"",y=
|
|
260
|
+
AggregateExecutionTime`:"",y=u.gql`
|
|
261
261
|
query RunViewQuery ($input: ${s}!) {
|
|
262
262
|
${r}(input: $input) {
|
|
263
263
|
Results {
|
|
264
|
-
${
|
|
264
|
+
${I.join(`
|
|
265
265
|
`)}
|
|
266
266
|
}
|
|
267
267
|
UserViewRunID
|
|
@@ -271,14 +271,14 @@
|
|
|
271
271
|
Success
|
|
272
272
|
ErrorMessage${E}
|
|
273
273
|
}
|
|
274
|
-
}`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:a,queryName:r,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const m=await this.ExecuteGQL(y,{input:n});if(m&&m[r]){const p=m[r].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:a,aggregateResultCount:p?.length||0,aggregateResults:p,aggregateExecutionTime:m[r].AggregateExecutionTime});const
|
|
274
|
+
}`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:a,queryName:r,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const m=await this.ExecuteGQL(y,{input:n});if(m&&m[r]){const p=m[r].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:a,aggregateResultCount:p?.length||0,aggregateResults:p,aggregateExecutionTime:m[r].AggregateExecutionTime});const f=m[r].Results;if(f&&f.length>0){const C=o.Fields.filter(w=>w.CodeName!==w.Name&&w.CodeName!==void 0);f.forEach(w=>{this.ConvertBackToMJFields(w),C.forEach(A=>{w[A.Name]=w[A.CodeName]})})}return m[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw c.LogError(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],n=[];for(const d of e){let I="",E="";const y={};let m=null,p=null;if(d.ViewEntity)p=d.ViewEntity,m=p.Get("Entity");else{const{entityName:w,v:A}=await this.getEntityNameAndUserView(d,t);p=A,m=w}const f=this.Entities.find(w=>w.Name===m);if(!f)throw new Error(`Entity ${m} not found in metadata`);s.push(f);let D=!1;const C=c.getGraphQLTypeNameBase(f);d.ViewID?(I=`Run${C}ViewByID`,E="RunViewByIDInput",y.ViewID=d.ViewID):d.ViewName?(I=`Run${C}ViewByName`,E="RunViewByNameInput",y.ViewName=d.ViewName):(D=!0,I=`Run${C}DynamicView`,E="RunDynamicViewInput",y.EntityName=d.EntityName),y.ExtraFilter=d.ExtraFilter||"",y.OrderBy=d.OrderBy||"",y.UserSearchString=d.UserSearchString||"",y.Fields=d.Fields,y.IgnoreMaxRows=d.IgnoreMaxRows||!1,d.MaxRows!==void 0&&(y.MaxRows=d.MaxRows),d.StartRow!==void 0&&(y.StartRow=d.StartRow),y.ForceAuditLog=d.ForceAuditLog||!1,y.ResultType=d.ResultType||"simple",d.AuditLogDescription&&d.AuditLogDescription.length>0&&(y.AuditLogDescription=d.AuditLogDescription),D||(y.ExcludeUserViewRunID=d.ExcludeUserViewRunID||"",y.ExcludeDataFromAllPriorViewRuns=d.ExcludeDataFromAllPriorViewRuns||!1,y.OverrideExcludeFilter=d.OverrideExcludeFilter||"",y.SaveViewResults=d.SaveViewResults||!1),d.Aggregates&&d.Aggregates.length>0&&(y.Aggregates=d.Aggregates.map(w=>({expression:w.expression,alias:w.alias}))),r.push(y),n.push(...this.getViewRunTimeFieldList(f,p,d,D))}const i=e.some(d=>d.Aggregates&&d.Aggregates.length>0)?`
|
|
275
275
|
AggregateResults {
|
|
276
276
|
alias
|
|
277
277
|
expression
|
|
278
278
|
value
|
|
279
279
|
error
|
|
280
280
|
}
|
|
281
|
-
AggregateExecutionTime`:"",o=
|
|
281
|
+
AggregateExecutionTime`:"",o=u.gql`
|
|
282
282
|
query RunViewsQuery ($input: [RunViewGenericInput!]!) {
|
|
283
283
|
RunViews(input: $input) {
|
|
284
284
|
Results {
|
|
@@ -296,7 +296,7 @@
|
|
|
296
296
|
Success
|
|
297
297
|
ErrorMessage${i}
|
|
298
298
|
}
|
|
299
|
-
}`,
|
|
299
|
+
}`,l=await this.ExecuteGQL(o,{input:r});if(l&&l.RunViews){const d=l.RunViews;for(const[I,E]of d.entries())E.Results=E.Results.map(y=>{let m=JSON.parse(y.Data);return this.ConvertBackToMJFields(m),m});return d}return null}catch(r){throw c.LogError(r),r}}async RunViewsWithCacheCheck(e,t){try{const r=e.map(o=>({params:{EntityName:o.params.EntityName||"",ExtraFilter:o.params.ExtraFilter||"",OrderBy:o.params.OrderBy||"",Fields:o.params.Fields,UserSearchString:o.params.UserSearchString||"",IgnoreMaxRows:o.params.IgnoreMaxRows||!1,MaxRows:o.params.MaxRows,StartRow:o.params.StartRow,ForceAuditLog:o.params.ForceAuditLog||!1,AuditLogDescription:o.params.AuditLogDescription||"",ResultType:o.params.ResultType||"simple"},cacheStatus:o.cacheStatus?{maxUpdatedAt:o.cacheStatus.maxUpdatedAt,rowCount:o.cacheStatus.rowCount}:null})),s=u.gql`
|
|
300
300
|
query RunViewsWithCacheCheckQuery($input: [RunViewWithCacheCheckInput!]!) {
|
|
301
301
|
RunViewsWithCacheCheck(input: $input) {
|
|
302
302
|
success
|
|
@@ -329,7 +329,7 @@
|
|
|
329
329
|
}
|
|
330
330
|
}
|
|
331
331
|
}
|
|
332
|
-
`,a=(await this.ExecuteGQL(s,{input:r}))?.RunViewsWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map((o,
|
|
332
|
+
`,a=(await this.ExecuteGQL(s,{input:r}))?.RunViewsWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map((o,l)=>{const d=e[l];if(o.status==="differential"&&o.differentialData){const I=o.differentialData.updatedRows.map(E=>{const y=JSON.parse(E.Data);return this.ConvertBackToMJFields(y),y});return{viewIndex:o.viewIndex,status:o.status,results:void 0,differentialData:{updatedRows:I,deletedRecordIDs:o.differentialData.deletedRecordIDs},maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}if(o.status==="stale"&&o.Results){const I=o.Results.map(E=>{const y=JSON.parse(E.Data);return this.ConvertBackToMJFields(y),y});return{viewIndex:o.viewIndex,status:o.status,results:I,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}return{viewIndex:o.viewIndex,status:o.status,results:void 0,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}});return{success:a.success,results:i,errorMessage:a.errorMessage}}catch(r){return c.LogError(r),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async getEntityNameAndUserView(e,t){let r,s;if(e.EntityName)r=e.EntityName;else if(e.ViewID)s=await N.ViewInfo.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await N.ViewInfo.GetViewEntityByName(e.ViewName,t),r=s.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:r,v:s}}getViewRunTimeFieldList(e,t,r,s){const n=[],a=new v;if(r.Fields){for(const i of e.PrimaryKeys)r.Fields.find(o=>o.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);r.Fields.forEach(i=>{n.push(a.MapFieldName(i))})}else if(s)e.Fields.forEach(i=>{i.IsBinaryFieldType||n.push(a.MapFieldName(i.CodeName))});else{for(const i of e.PrimaryKeys)n.find(o=>o.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);t.Columns.forEach(i=>{i.hidden===!1&&!n.find(o=>o.trim().toLowerCase()===i.EntityField?.Name.trim().toLowerCase())&&i.EntityField&&n.push(a.MapFieldName(i.EntityField.CodeName))})}return n}get ProviderType(){return c.ProviderType.Network}async GetRecordChanges(e,t){try{const r={EntityName:"MJ: Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},s=await this.RunView(r);return s?s.Results.sort((n,a)=>n.ChangedAt>a.ChangedAt?-1:1):null}catch(r){throw c.LogError(r),r}}async GetRecordDependencies(e,t){try{const r=u.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
|
|
333
333
|
GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
|
|
334
334
|
EntityName
|
|
335
335
|
RelatedEntityName
|
|
@@ -341,7 +341,7 @@
|
|
|
341
341
|
}
|
|
342
342
|
}
|
|
343
343
|
}
|
|
344
|
-
}`,s={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}};return(await this.ExecuteGQL(r,s))?.GetRecordDependencies}catch(r){throw
|
|
344
|
+
}`,s={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}};return(await this.ExecuteGQL(r,s))?.GetRecordDependencies}catch(r){throw c.LogError(r),r}}ensureKeyValuePairValueIsString(e){return e.map(t=>({FieldName:t.FieldName,Value:t.Value.toString()}))}async GetRecordDuplicates(e,t){if(!e)return null;const r=u.gql`query GetRecordDuplicatesQuery ($params: PotentialDuplicateRequestType!) {
|
|
345
345
|
GetRecordDuplicates(params: $params) {
|
|
346
346
|
Status
|
|
347
347
|
ErrorMessage
|
|
@@ -363,7 +363,7 @@
|
|
|
363
363
|
}
|
|
364
364
|
}
|
|
365
365
|
}
|
|
366
|
-
}`;let s={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(a=>a.Copy())};const n=await this.ExecuteGQL(r,{params:s});if(n&&n.GetRecordDuplicates)return n.GetRecordDuplicates}async MergeRecords(e,t,r){const s=this.Entities.find(n=>n.Name.trim().toLowerCase()===e.EntityName.trim().toLowerCase());if(!s||!s.AllowRecordMerge)throw new Error(`Entity ${e.EntityName} does not allow record merging, check the AllowRecordMerge property in the entity metadata`);try{const n=
|
|
366
|
+
}`;let s={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(a=>a.Copy())};const n=await this.ExecuteGQL(r,{params:s});if(n&&n.GetRecordDuplicates)return n.GetRecordDuplicates}async MergeRecords(e,t,r){const s=this.Entities.find(n=>n.Name.trim().toLowerCase()===e.EntityName.trim().toLowerCase());if(!s||!s.AllowRecordMerge)throw new Error(`Entity ${e.EntityName} does not allow record merging, check the AllowRecordMerge property in the entity metadata`);try{const n=u.gql`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
|
|
367
367
|
MergeRecords(request: $request) {
|
|
368
368
|
Success
|
|
369
369
|
OverallStatus
|
|
@@ -380,32 +380,32 @@
|
|
|
380
380
|
Message
|
|
381
381
|
}
|
|
382
382
|
}
|
|
383
|
-
}`,a={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(o=>({FieldName:o.FieldName,Value:o.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(o=>o.Copy())};return(await this.ExecuteGQL(n,{request:a}))?.MergeRecords}catch(n){return
|
|
384
|
-
${e.Fields.map(y=>
|
|
383
|
+
}`,a={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(o=>({FieldName:o.FieldName,Value:o.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(o=>o.Copy())};return(await this.ExecuteGQL(n,{request:a}))?.MergeRecords}catch(n){return c.LogError(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){if(r?.IsParentEntitySave){const n=new c.BaseEntityResult;return n.StartedAt=new Date,n.EndedAt=new Date,n.Type=e.IsSaved?"update":"create",n.Success=!0,n.NewValues=e.GetAll(),e.ResultHistory.push(n),n.NewValues}const s=new c.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const n={input:{}},a=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(y=>({FieldName:y.CodeName,Value:y.Value})),e.ResultHistory.push(s);const i=c.getGraphQLTypeNameBase(e.EntityInfo),o=`${a}${i}`,l=e.Fields.filter(y=>!y.ReadOnly||y.IsPrimaryKey&&e.IsSaved),d=new v,I=` ${o}(input: $input) {
|
|
384
|
+
${e.Fields.map(y=>d.MapFieldName(y.CodeName)).join(`
|
|
385
385
|
`)}
|
|
386
|
-
}`,E=
|
|
387
|
-
${
|
|
386
|
+
}`,E=u.gql`mutation ${a}${i} ($input: ${o}Input!) {
|
|
387
|
+
${I}
|
|
388
388
|
}
|
|
389
|
-
`;for(let y=0;y<
|
|
390
|
-
${
|
|
389
|
+
`;for(let y=0;y<l.length;y++){const m=l[y];let p=e.Get(m.Name);if(p)switch(m.EntityFieldInfo.TSType){case c.EntityFieldTSType.Date:p=p.getTime();break;case c.EntityFieldTSType.Boolean:typeof p!="boolean"&&(p=parseInt(p)!==0);break;case c.EntityFieldTSType.Number:if(typeof p!="number"){const f=Number(p);isNaN(f)||(p=f)}break}p===null&&m.EntityFieldInfo.AllowsNull===!1&&(m.EntityFieldInfo.DefaultValue!==null?p=m.EntityFieldInfo.DefaultValue:m.FieldType===c.EntityFieldTSType.Number||m.FieldType===c.EntityFieldTSType.Boolean?p=0:p=""),n.input[d.MapFieldName(m.CodeName)]=p}if(a.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const y=[];e.Fields.forEach(m=>{let p=null;m.OldValue!==null&&m.OldValue!==void 0&&(m.EntityFieldInfo.TSType===c.EntityFieldTSType.Date?p=m.OldValue.getTime().toString():m.EntityFieldInfo.TSType===c.EntityFieldTSType.Boolean?p=m.OldValue===!0?"1":"0":typeof m.OldValue!="string"?p=m.OldValue.toString():p=m.OldValue),y.push({Key:d.MapFieldName(m.CodeName),Value:p})}),n.input.OldValues___=y}if(e.TransactionGroup){const y=[{varName:"input",inputType:o+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,s.Type==="create"?"Create":"Update",I,n,{mutationName:o,mutationInputTypes:y},(m,p)=>{s.EndedAt=new Date,p&&m?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(m)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const y=await this.ExecuteGQL(E,n);if(y&&y[o])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(y[o]),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(n){return s.Success=!1,s.EndedAt=new Date,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,c.LogError(n),null}}async Load(e,t,r=null,s){try{const n={};let a="",i="";for(let y=0;y<t.KeyValuePairs.length;y++){const m=e.Fields.find(D=>D.Name.trim().toLowerCase()===t.KeyValuePairs[y].FieldName.trim().toLowerCase()).EntityFieldInfo,p=t.GetValueByIndex(y),f=m.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${m.CodeName}: ${f}!`,a.length>0&&(a+=", "),a+=`${m.CodeName}: $${m.CodeName}`,m.TSType===c.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(y)))throw new Error(`Primary Key value ${p} (${m.Name}) is not a valid number`);n[m.CodeName]=parseInt(p)}else n[m.CodeName]=p}const o=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",l=c.getGraphQLTypeNameBase(e.EntityInfo),d=new v,I=u.gql`query Single${l}${o.length>0?"Full":""} (${i}) {
|
|
390
|
+
${l}(${a}) {
|
|
391
391
|
${e.Fields.filter(y=>!y.EntityFieldInfo.IsBinaryFieldType).map(y=>y.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?y.CodeName.replace("__mj_","_mj__"):y.CodeName).join(`
|
|
392
392
|
`)}
|
|
393
393
|
${o}
|
|
394
394
|
}
|
|
395
395
|
}
|
|
396
|
-
`,E=await this.ExecuteGQL(
|
|
396
|
+
`,E=await this.ExecuteGQL(I,n);return E&&E[l]?this.ConvertBackToMJFields(E[l]):null}catch(n){return c.LogError(n),null}}ConvertBackToMJFields(e){return new v().ReverseMapFields(e),e}getRelatedEntityString(e,t){let r="";for(let s=0;s<e.RelatedEntities.length;s++)if(t.indexOf(e.RelatedEntities[s].RelatedEntity)>=0){const n=e.RelatedEntities[s],a=this.Entities.find(o=>R.UUIDsEqual(o.ID,n.RelatedEntityID));let i="";n.Type.toLowerCase().trim()==="many to many"?i=`${n.RelatedEntityCodeName}_${n.JoinEntityJoinField.replace(/\s/g,"")}`:i=`${n.RelatedEntityCodeName}_${n.RelatedEntityJoinField.replace(/\s/g,"")}`,r+=`
|
|
397
397
|
${i} {
|
|
398
398
|
${a.Fields.map(o=>o.CodeName).join(`
|
|
399
399
|
`)}
|
|
400
400
|
}
|
|
401
|
-
`}return r}async Delete(e,t,r){const s=new
|
|
402
|
-
`),
|
|
403
|
-
${
|
|
401
|
+
`}return r}async Delete(e,t,r){const s=new c.BaseEntityResult;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(m=>({FieldName:m.CodeName,Value:m.Value})),e.ResultHistory.push(s);const n={},a=[];let i="",o="",l="";for(let m of e.PrimaryKey.KeyValuePairs){const p=e.Fields.find(f=>f.Name.trim().toLowerCase()===m.FieldName.trim().toLowerCase());n[p.CodeName]=p.Value,a.push({varName:p.CodeName,inputType:p.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${p.CodeName}: $${p.CodeName}`,o.length>0&&(o+=", "),o+=`$${p.CodeName}: ${p.EntityFieldInfo.GraphQLType}!`,l.length>0&&(l+=`
|
|
402
|
+
`),l+=`${p.CodeName}`}a.push({varName:"options___",inputType:"DeleteOptionsInput!"}),n.options___={SkipEntityAIActions:t?.SkipEntityAIActions??!1,SkipEntityActions:t?.SkipEntityActions??!1,ReplayOnly:t?.ReplayOnly??!1,IsParentEntityDelete:t?.IsParentEntityDelete??!1};const I="Delete"+c.getGraphQLTypeNameBase(e.EntityInfo),E=u.gql`${I}(${i}, options___: $options___) {
|
|
403
|
+
${l}
|
|
404
404
|
}
|
|
405
|
-
`,y=
|
|
405
|
+
`,y=u.gql`mutation ${I} (${o}, $options___: DeleteOptionsInput!) {
|
|
406
406
|
${E}
|
|
407
407
|
}
|
|
408
|
-
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new
|
|
408
|
+
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,"Delete",E,n,{mutationName:I,mutationInputTypes:a},(m,p)=>{if(s.EndedAt=new Date,p&&m){let f=!0;for(const D of e.PrimaryKey.KeyValuePairs)D.Value!==m[D.FieldName]&&(f=!1);f?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const m=await this.ExecuteGQL(y,n);if(m&&m[I]){const p=m[I];for(let f of e.PrimaryKey.KeyValuePairs){let D=p[f.FieldName],C=f.Value;if(typeof C=="number"&&(C=C.toString()),typeof D=="number"&&(D=D.toString()),C!==D)throw new Error(`Primary key value mismatch in server Delete response. Field: ${f.FieldName}, Original: ${C}, Returned: ${D}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(n){return s.EndedAt=new Date,s.Success=!1,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,c.LogError(n),!1}}async GetDatasetByName(e,t){const r=u.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
|
|
409
409
|
GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
|
|
410
410
|
DatasetID
|
|
411
411
|
DatasetName
|
|
@@ -414,7 +414,7 @@
|
|
|
414
414
|
LatestUpdateDate
|
|
415
415
|
Results
|
|
416
416
|
}
|
|
417
|
-
}`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetByName&&s.GetDatasetByName.Success?{DatasetID:s.GetDatasetByName.DatasetID,DatasetName:s.GetDatasetByName.DatasetName,Success:s.GetDatasetByName.Success,Status:s.GetDatasetByName.Status,LatestUpdateDate:new Date(s.GetDatasetByName.LatestUpdateDate),Results:JSON.parse(s.GetDatasetByName.Results)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,Results:null}}static{this._datasetStatusQueue=[]}static{this._datasetStatusTimer=null}static{this._datasetStatusCoalesceMs=10}async GetDatasetStatusByName(e,t){return
|
|
417
|
+
}`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetByName&&s.GetDatasetByName.Success?{DatasetID:s.GetDatasetByName.DatasetID,DatasetName:s.GetDatasetByName.DatasetName,Success:s.GetDatasetByName.Success,Status:s.GetDatasetByName.Status,LatestUpdateDate:new Date(s.GetDatasetByName.LatestUpdateDate),Results:JSON.parse(s.GetDatasetByName.Results)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,Results:null}}static{this._datasetStatusQueue=[]}static{this._datasetStatusTimer=null}static{this._datasetStatusCoalesceMs=10}async GetDatasetStatusByName(e,t){return S._datasetStatusCoalesceMs>0&&!t?this.enqueueDatasetStatusCheck(e):this.executeDatasetStatusByName(e,t)}enqueueDatasetStatusCheck(e){return new Promise((t,r)=>{S._datasetStatusQueue.push({datasetName:e,resolve:t,reject:r}),S._datasetStatusTimer||(S._datasetStatusTimer=setTimeout(()=>this.flushDatasetStatusQueue(),S._datasetStatusCoalesceMs))})}async flushDatasetStatusQueue(){S._datasetStatusTimer=null;const e=S._datasetStatusQueue.splice(0);if(e.length===0)return;if(e.length===1){try{const r=await this.executeDatasetStatusByName(e[0].datasetName,e[0].itemFilters);e[0].resolve(r)}catch(r){e[0].reject(r)}return}const t=e.map(r=>r.datasetName);c.LogStatus(`\u26A1 [Coalesce] Batching ${t.length} dataset status checks into 1 request: [${t.join(", ")}]`);try{const r=u.gql`query GetMultipleDatasetStatusByName($DatasetNames: [String!]!) {
|
|
418
418
|
GetMultipleDatasetStatusByName(DatasetNames: $DatasetNames) {
|
|
419
419
|
DatasetID
|
|
420
420
|
DatasetName
|
|
@@ -423,7 +423,7 @@
|
|
|
423
423
|
LatestUpdateDate
|
|
424
424
|
EntityUpdateDates
|
|
425
425
|
}
|
|
426
|
-
}`,n=((await this.ExecuteGQL(r,{DatasetNames:t}))?.GetMultipleDatasetStatusByName||[]).map(a=>({DatasetID:a.DatasetID,DatasetName:a.DatasetName,Success:a.Success,Status:a.Status,LatestUpdateDate:a.LatestUpdateDate?new Date(a.LatestUpdateDate):null,EntityUpdateDates:a.EntityUpdateDates?JSON.parse(a.EntityUpdateDates):null}));for(const a of e){const i=n.find(o=>o.DatasetName===a.datasetName);i?a.resolve(i):a.resolve({DatasetID:"",DatasetName:a.datasetName,Success:!1,Status:"Not found in batch response",LatestUpdateDate:null,EntityUpdateDates:null})}}catch(r){
|
|
426
|
+
}`,n=((await this.ExecuteGQL(r,{DatasetNames:t}))?.GetMultipleDatasetStatusByName||[]).map(a=>({DatasetID:a.DatasetID,DatasetName:a.DatasetName,Success:a.Success,Status:a.Status,LatestUpdateDate:a.LatestUpdateDate?new Date(a.LatestUpdateDate):null,EntityUpdateDates:a.EntityUpdateDates?JSON.parse(a.EntityUpdateDates):null}));for(const a of e){const i=n.find(o=>o.DatasetName===a.datasetName);i?a.resolve(i):a.resolve({DatasetID:"",DatasetName:a.datasetName,Success:!1,Status:"Not found in batch response",LatestUpdateDate:null,EntityUpdateDates:null})}}catch(r){c.LogError(`Dataset status batch failed, falling back to individual calls: ${r}`);const s=e.map(async n=>{try{const a=await this.executeDatasetStatusByName(n.datasetName,n.itemFilters);n.resolve(a)}catch(a){n.reject(a)}});await Promise.all(s)}}async executeDatasetStatusByName(e,t){const r=u.gql`query GetDatasetStatusByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
|
|
427
427
|
GetDatasetStatusByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
|
|
428
428
|
DatasetID
|
|
429
429
|
DatasetName
|
|
@@ -432,22 +432,22 @@
|
|
|
432
432
|
LatestUpdateDate
|
|
433
433
|
EntityUpdateDates
|
|
434
434
|
}
|
|
435
|
-
}`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetStatusByName&&s.GetDatasetStatusByName.Success?{DatasetID:s.GetDatasetStatusByName.DatasetID,DatasetName:s.GetDatasetStatusByName.DatasetName,Success:s.GetDatasetStatusByName.Success,Status:s.GetDatasetStatusByName.Status,LatestUpdateDate:new Date(s.GetDatasetStatusByName.LatestUpdateDate),EntityUpdateDates:JSON.parse(s.GetDatasetStatusByName.EntityUpdateDates)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,EntityUpdateDates:null}}async CreateTransactionGroup(){return new
|
|
435
|
+
}`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetStatusByName&&s.GetDatasetStatusByName.Success?{DatasetID:s.GetDatasetStatusByName.DatasetID,DatasetName:s.GetDatasetStatusByName.DatasetName,Success:s.GetDatasetStatusByName.Success,Status:s.GetDatasetStatusByName.Status,LatestUpdateDate:new Date(s.GetDatasetStatusByName.LatestUpdateDate),EntityUpdateDates:JSON.parse(s.GetDatasetStatusByName.EntityUpdateDates)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,EntityUpdateDates:null}}async CreateTransactionGroup(){return new M(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const n=this.Entities.find(o=>o.Name===t);if(!n)throw new Error(`Entity ${t} not found in metadata`);const a=u.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
|
|
436
436
|
GetRecordFavoriteStatus(params: $params) {
|
|
437
437
|
Success
|
|
438
438
|
IsFavorite
|
|
439
439
|
}
|
|
440
|
-
}`,i=await this.ExecuteGQL(a,{params:{UserID:e,EntityID:n.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)}}});if(i&&i.GetRecordFavoriteStatus&&i.GetRecordFavoriteStatus.Success)return i.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,t,r,s,n){const a=this.Entities.find(
|
|
440
|
+
}`,i=await this.ExecuteGQL(a,{params:{UserID:e,EntityID:n.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)}}});if(i&&i.GetRecordFavoriteStatus&&i.GetRecordFavoriteStatus.Success)return i.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,t,r,s,n){const a=this.Entities.find(l=>l.Name===t);if(!a)throw new Error(`Entity ${t} not found in metadata`);const i=u.gql`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
|
|
441
441
|
SetRecordFavoriteStatus(params: $params){
|
|
442
442
|
Success
|
|
443
443
|
}
|
|
444
|
-
}`,o=await this.ExecuteGQL(i,{params:{UserID:e,EntityID:a.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)},IsFavorite:s}});if(o&&o.SetRecordFavoriteStatus!==null)return o.SetRecordFavoriteStatus.Success}async InternalGetEntityRecordName(e,t){if(!e||!t||t.KeyValuePairs?.length===0)return null;const r=
|
|
444
|
+
}`,o=await this.ExecuteGQL(i,{params:{UserID:e,EntityID:a.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)},IsFavorite:s}});if(o&&o.SetRecordFavoriteStatus!==null)return o.SetRecordFavoriteStatus.Success}async InternalGetEntityRecordName(e,t){if(!e||!t||t.KeyValuePairs?.length===0)return null;const r=u.gql`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
|
|
445
445
|
GetEntityRecordName(EntityName: $EntityName, CompositeKey: $CompositeKey) {
|
|
446
446
|
Success
|
|
447
447
|
Status
|
|
448
448
|
RecordName
|
|
449
449
|
}
|
|
450
|
-
}`,s=await this.ExecuteGQL(r,{EntityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}});if(s&&s.GetEntityRecordName&&s.GetEntityRecordName.Success)return s.GetEntityRecordName.RecordName}async InternalGetEntityRecordNames(e){if(!e)return null;const t=
|
|
450
|
+
}`,s=await this.ExecuteGQL(r,{EntityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}});if(s&&s.GetEntityRecordName&&s.GetEntityRecordName.Success)return s.GetEntityRecordName.RecordName}async InternalGetEntityRecordNames(e){if(!e)return null;const t=u.gql`query GetEntityRecordNamesQuery ($info: [EntityRecordNameInput!]!) {
|
|
451
451
|
GetEntityRecordNames(info: $info) {
|
|
452
452
|
Success
|
|
453
453
|
Status
|
|
@@ -460,28 +460,28 @@
|
|
|
460
460
|
EntityName
|
|
461
461
|
RecordName
|
|
462
462
|
}
|
|
463
|
-
}`,r=await this.ExecuteGQL(t,{info:e.map(s=>({EntityName:s.EntityName,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.CompositeKey.KeyValuePairs)}}))});if(r&&r.GetEntityRecordNames)return r.GetEntityRecordNames.map(s=>({...s,CompositeKey:new
|
|
463
|
+
}`,r=await this.ExecuteGQL(t,{info:e.map(s=>({EntityName:s.EntityName,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.CompositeKey.KeyValuePairs)}}))});if(r&&r.GetEntityRecordNames)return r.GetEntityRecordNames.map(s=>({...s,CompositeKey:new c.CompositeKey(s.CompositeKey.KeyValuePairs)}))}async GetDataContextData(e){try{const t=u.gql`query GetDataContextData ($DataContextID: String!) {
|
|
464
464
|
GetDataContextData(DataContextID: $DataContextID) {
|
|
465
465
|
Success
|
|
466
466
|
ErrorMessages
|
|
467
467
|
Results
|
|
468
468
|
}
|
|
469
|
-
}`,r=await this.ExecuteGQL(t,{DataContextID:e});if(r&&r.GetDataContextData){if(r.GetDataContextData.Success)return r.GetDataContextData.Results.map(s=>JSON.parse(s));throw new Error(r.GetDataContextData.ErrorMessages.join(", "))}else throw new Error("GraphQL query failed")}catch(t){throw
|
|
469
|
+
}`,r=await this.ExecuteGQL(t,{DataContextID:e});if(r&&r.GetDataContextData){if(r.GetDataContextData.Success)return r.GetDataContextData.Results.map(s=>JSON.parse(s));throw new Error(r.GetDataContextData.ErrorMessages.join(", "))}else throw new Error("GraphQL query failed")}catch(t){throw c.LogError(t),t}}async GetDataContextItemData(e){try{const t=u.gql`query GetDataContextItemData ($DataContextItemID: String!) {
|
|
470
470
|
GetDataContextItemData(DataContextItemID: $DataContextItemID) {
|
|
471
471
|
Success
|
|
472
472
|
ErrorMessage
|
|
473
473
|
Result
|
|
474
474
|
}
|
|
475
|
-
}`,r=await this.ExecuteGQL(t,{DataContextItemID:e});if(r&&r.GetDataContextItemData){if(r.GetDataContextItemData.Success)return JSON.parse(r.GetDataContextItemData.Result);throw new Error(r.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw
|
|
475
|
+
}`,r=await this.ExecuteGQL(t,{DataContextItemID:e});if(r&&r.GetDataContextItemData){if(r.GetDataContextItemData.Success)return JSON.parse(r.GetDataContextItemData.Result);throw new Error(r.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw c.LogError(t),t}}static async ExecuteGQL(e,t,r=!0){return S.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(console.error("[GraphQL] ExecuteGQL error caught:",{hasResponse:!!s?.response,hasErrors:!!s?.response?.errors,errorCount:s?.response?.errors?.length,firstError:s?.response?.errors?.[0],errorCode:s?.response?.errors?.[0]?.extensions?.code,errorMessage:s?.response?.errors?.[0]?.message,fullError:s}),s&&s.response&&s.response.errors?.length>0)if(s.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw c.LogError("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw c.LogError(s),s}}async RefreshToken(){const e=S.Instance&&S.Instance._configData===this._configData;if(e&&S.Instance._refreshPromise)return S.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(S.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&S.Instance&&(S.Instance._refreshPromise=null)}}async performTokenRefresh(){if(this._configData.Data.RefreshTokenFunction)try{const e=await this._configData.Data.RefreshTokenFunction();if(e){this._configData.Token=e;const t=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey,this._configData.UserAPIKey);this._client=t,S.Instance&&S.Instance._configData===this._configData&&(S.Instance._client=t)}else{const t=new Error("Refresh token function returned null or undefined token");throw this.notifyAuthenticationError(t),t}}catch(e){const t=e instanceof Error?e:new Error(String(e));throw this.notifyAuthenticationError(t),e}else{const e=new Error("No refresh token function provided");throw this.notifyAuthenticationError(e),e}}notifyAuthenticationError(e){try{const t=this._configData?.OnAuthenticationError;t&&t(e)}catch(t){console.error("[GraphQLDataProvider] Error in OnAuthenticationError callback:",t)}}static async RefreshToken(){return S.Instance.RefreshToken()}static async clearClientCache(e=new Set){const t=[];for(let r=0;r<localStorage.length;r++){const s=localStorage.key(r);s&&!e.has(s)&&t.push(s)}t.forEach(r=>localStorage.removeItem(r)),await new Promise(r=>{const s=indexedDB.deleteDatabase("MJ_Metadata");s.onsuccess=()=>r(),s.onerror=()=>r(),s.onblocked=()=>r()})}CreateNewGraphQLClient(e,t,r,s,n){const a={"x-session-id":r};t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),n&&(a["x-api-key"]=n);const i=new u.GraphQLClient(e,{headers:a});for(const[o,l]of this._dynamicHeaders)i.setHeader(o,l);return i}userInfoString(){return this.infoString(new c.UserInfo(null,null))}userRoleInfoString(){return this.infoString(new c.UserRoleInfo(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
|
|
476
476
|
`:s.startsWith("_")||(t+=s+`
|
|
477
|
-
`);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new F:this._localStorageProvider=new
|
|
477
|
+
`);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new F:this._localStorageProvider=new c.InMemoryLocalStorageProvider),this._localStorageProvider}get Metadata(){return this}getOrCreateWSClient(){const e=Date.now();return this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&this._activeSubscriptionCount===0&&this.disposeWSClient(),this._wsClient||(this._wsClient=q.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token},keepAlive:3e4,retryAttempts:3,shouldRetry:g(()=>!0,"shouldRetry")}),this._wsClientCreatedAt=e,this._subscriptionCleanupTimer||(this._subscriptionCleanupTimer=setInterval(()=>{this.cleanupStaleSubscriptions()},this.SUBSCRIPTION_CLEANUP_INTERVAL_MS))),this._wsClient}disposeWSClient(){if(this._wsClient){try{this._wsClient.dispose()}catch(e){console.error("[GraphQLDataProvider] Error disposing WebSocket client:",e)}this._wsClient=null,this._wsClientCreatedAt=null}}completeAllSubjects(){this._pushStatusSubjects.forEach((e,t)=>{try{e.subject.complete(),e.subscription.unsubscribe()}catch(r){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,r)}}),this._pushStatusSubjects.clear()}cleanupStaleSubscriptions(){if(!this._isCleaningUp){this._isCleaningUp=!0;try{const e=Date.now(),t=this._pushStatusSubjects.size,r=Array.from(this._pushStatusSubjects.entries()),s=[];r.forEach(([n,a])=>{const i=e-a.lastRequestedAt,o=e-a.lastEmissionAt;a.activeSubscribers===0&&i>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&o>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${n} for cleanup: activeSubscribers=${a.activeSubscribers}, timeSinceRequested=${Math.round(i/1e3)}s, timeSinceEmission=${Math.round(o/1e3)}s`),s.push(n))}),s.forEach(n=>{const a=this._pushStatusSubjects.get(n);if(a)try{a.subject.complete(),a.subscription.unsubscribe(),this._pushStatusSubjects.delete(n),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${n}`)}catch(i){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${n}:`,i)}}),s.length>0&&console.log(`[GraphQLDataProvider] Cleaned up ${s.length} stale subscription(s)`),this._pushStatusSubjects.size===0&&this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&(console.log("[GraphQLDataProvider] Disposing of idle WebSocket client"),this.disposeWSClient())}finally{this._isCleaningUp=!1}}}subscribe(e,t){return new b.Observable(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=s.subscribe({query:e,variables:t},{next:g(a=>{r.next(a.data)},"next"),error:g(async a=>{const i=a;if(i?.extensions?.code==="JWT_EXPIRED"||i?.message?.includes("token has expired")||i?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] WebSocket JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),r.complete()}catch(l){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",l),r.error(l)}}else r.error(a)},"error"),complete:g(()=>{r.complete()},"complete")});return()=>{this._activeSubscriptionCount--,n()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),r=this._pushStatusSubjects.get(e);if(r)return r.lastRequestedAt=t,new b.Observable(o=>{r.activeSubscribers++;const l=r.subject.subscribe(o);return()=>{const d=this._pushStatusSubjects.get(e);d&&d.activeSubscribers>0&&d.activeSubscribers--,l.unsubscribe()}});const s=u.gql`subscription StatusUpdates($sessionId: String!) {
|
|
478
478
|
statusUpdates(sessionId: $sessionId) {
|
|
479
479
|
date
|
|
480
480
|
message
|
|
481
481
|
sessionId
|
|
482
482
|
}
|
|
483
483
|
}
|
|
484
|
-
`,n=new b.Subject,a=this.getOrCreateWSClient(),i=new b.Subscription;return i.add(new b.Observable(o=>{const
|
|
484
|
+
`,n=new b.Subject,a=this.getOrCreateWSClient(),i=new b.Subscription;return i.add(new b.Observable(o=>{const l=a.subscribe({query:s,variables:{sessionId:e}},{next:g(d=>{const I=this._pushStatusSubjects.get(e);I&&(I.lastEmissionAt=Date.now()),o.next(d.data.statusUpdates.message)},"next"),error:g(async d=>{const I=d;if(I?.extensions?.code==="JWT_EXPIRED"||I?.message?.includes("token has expired")||I?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),o.complete()}catch(y){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",y),o.error(y)}}else o.error(d)},"error"),complete:g(()=>{o.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,l()}}).subscribe({next:g(o=>n.next(o),"next"),error:g(o=>{n.error(o),this._pushStatusSubjects.delete(e)},"error"),complete:g(()=>{n.complete(),this._pushStatusSubjects.delete(e)},"complete")})),this._pushStatusSubjects.set(e,{subject:n,subscription:i,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new b.Observable(o=>{const l=this._pushStatusSubjects.get(e);l&&l.activeSubscribers++;const d=n.subscribe(o);return()=>{const I=this._pushStatusSubjects.get(e);I&&I.activeSubscribers>0&&I.activeSubscribers--,d.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.UnsubscribeFromCacheInvalidation(),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}SubscribeToCacheInvalidation(){if(this._cacheInvalidationSubscription||!this.ConfigData?.WSURL)return;const e=u.gql`subscription CacheInvalidation {
|
|
485
485
|
cacheInvalidation {
|
|
486
486
|
EntityName
|
|
487
487
|
PrimaryKeyValues
|
|
@@ -491,26 +491,26 @@
|
|
|
491
491
|
OriginSessionID
|
|
492
492
|
RecordData
|
|
493
493
|
}
|
|
494
|
-
}`,t=this.subscribe(e);this._cacheInvalidationSubscription=t.subscribe({next:g(r=>{const s=r?.cacheInvalidation;if(!s)return;if(s.OriginSessionID&&s.OriginSessionID===this.sessionId){console.debug(`[GraphQLDataProvider] Skipping self-originated cache invalidation for "${s.EntityName}" (action: ${s.Action})`);return}console.debug(`[GraphQLDataProvider] Cache invalidation received: ${s.Action} for "${s.EntityName}" from server ${s.SourceServerID?.substring(0,8)||"unknown"}`);const n={type:"remote-invalidate",entityName:s.EntityName,baseEntity:null,payload:{primaryKeyValues:s.PrimaryKeyValues,action:s.Action,sourceServerId:s.SourceServerID,timestamp:s.Timestamp,recordData:s.RecordData}};R.MJGlobal.Instance.RaiseEvent({event:R.MJEventType.ComponentEvent,eventCode:
|
|
494
|
+
}`,t=this.subscribe(e);this._cacheInvalidationSubscription=t.subscribe({next:g(r=>{const s=r?.cacheInvalidation;if(!s)return;if(s.OriginSessionID&&s.OriginSessionID===this.sessionId){console.debug(`[GraphQLDataProvider] Skipping self-originated cache invalidation for "${s.EntityName}" (action: ${s.Action})`);return}console.debug(`[GraphQLDataProvider] Cache invalidation received: ${s.Action} for "${s.EntityName}" from server ${s.SourceServerID?.substring(0,8)||"unknown"}`);const n={type:"remote-invalidate",entityName:s.EntityName,baseEntity:null,payload:{primaryKeyValues:s.PrimaryKeyValues,action:s.Action,sourceServerId:s.SourceServerID,timestamp:s.Timestamp,recordData:s.RecordData}};R.MJGlobal.Instance.RaiseEvent({event:R.MJEventType.ComponentEvent,eventCode:c.BaseEntity.BaseEventCode,args:n,component:this})},"next"),error:g(r=>{console.error("[GraphQLDataProvider] Cache invalidation subscription error:",r),this._cacheInvalidationSubscription=null},"error"),complete:g(()=>{console.log("[GraphQLDataProvider] Cache invalidation subscription completed, will re-establish on next WebSocket creation"),this._cacheInvalidationSubscription=null},"complete")})}UnsubscribeFromCacheInvalidation(){this._cacheInvalidationSubscription&&(this._cacheInvalidationSubscription.unsubscribe(),this._cacheInvalidationSubscription=null)}async FindISAChildEntity(e,t,r){if(!e.IsParentType)return null;const s=`query FindISAChildEntity($EntityName: String!, $RecordID: String!) {
|
|
495
495
|
FindISAChildEntity(EntityName: $EntityName, RecordID: $RecordID) {
|
|
496
496
|
Success
|
|
497
497
|
ChildEntityName
|
|
498
498
|
ErrorMessage
|
|
499
499
|
}
|
|
500
|
-
}`;try{const n=await this.ExecuteGQL(s,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntity?.Success&&n.FindISAChildEntity.ChildEntityName?{ChildEntityName:n.FindISAChildEntity.ChildEntityName}:null}catch(n){return
|
|
500
|
+
}`;try{const n=await this.ExecuteGQL(s,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntity?.Success&&n.FindISAChildEntity.ChildEntityName?{ChildEntityName:n.FindISAChildEntity.ChildEntityName}:null}catch(n){return c.LogError(`FindISAChildEntity failed for ${e.Name}: ${n}`),null}}async FindISAChildEntities(e,t,r){if(!e.IsParentType)return[];const s=`query FindISAChildEntities($EntityName: String!, $RecordID: String!) {
|
|
501
501
|
FindISAChildEntities(EntityName: $EntityName, RecordID: $RecordID) {
|
|
502
502
|
Success
|
|
503
503
|
ChildEntityNames
|
|
504
504
|
ErrorMessage
|
|
505
505
|
}
|
|
506
|
-
}`;try{const n=await this.ExecuteGQL(s,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntities?.Success&&n.FindISAChildEntities.ChildEntityNames?n.FindISAChildEntities.ChildEntityNames.map(a=>({ChildEntityName:a})):[]}catch(n){return
|
|
506
|
+
}`;try{const n=await this.ExecuteGQL(s,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntities?.Success&&n.FindISAChildEntities.ChildEntityNames?n.FindISAChildEntities.ChildEntityNames.map(a=>({ChildEntityName:a})):[]}catch(n){return c.LogError(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function j(h){const e=new S;return c.SetProvider(e),await e.Config(h),R.MJGlobal.Instance.RaiseEvent({event:R.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),await c.StartupManager.Instance.Startup(),e}g(j,"setupGraphQLClient");class J{static{g(this,"SyncRolesAndUsersResult")}}class W{static{g(this,"RoleInput")}}class H{static{g(this,"UserInput")}}class z{static{g(this,"RolesAndUsersInput")}}var U=(h=>(h.Create="Create",h.Update="Update",h.CreateOrUpdate="CreateOrUpdate",h.Delete="Delete",h.DeleteWithFilter="DeleteWithFilter",h))(U||{});class X{static{g(this,"ActionItemInput")}}class Y{static{g(this,"SyncDataResult")}constructor(){this.Results=[]}}class Z{static{g(this,"ActionItemOutput")}}class ee{static{g(this,"GraphQLSystemUserClient")}get Client(){return this._client}constructor(e,t,r,s){const n={"x-session-id":r};this._sessionId=r,t&&(n.authorization="Bearer "+t),s&&(n["x-mj-api-key"]=s),this._client=new u.GraphQLClient(e,{headers:n})}resolvePlatformSQL(e){if(e!=null)return c.IsPlatformSQL(e)?e.default:e}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
|
|
507
507
|
GetData(input: $input) {
|
|
508
508
|
Success
|
|
509
509
|
ErrorMessages
|
|
510
510
|
Queries
|
|
511
511
|
Results
|
|
512
512
|
}
|
|
513
|
-
}`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(n=>n?R.SafeJSONParse(n):null),ErrorMessages:s.GetData.ErrorMessages,Queries:s.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:s.GetData?.ErrorMessages??["Unknown error"],Queries:s.GetData?.Queries??e}}catch(r){let s=r instanceof Error?r.message:String(r);const n=s.match(/Error: ([^:]+)\./);if(n&&(s=n[1]+"."),
|
|
513
|
+
}`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(n=>n?R.SafeJSONParse(n):null),ErrorMessages:s.GetData.ErrorMessages,Queries:s.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:s.GetData?.ErrorMessages??["Unknown error"],Queries:s.GetData?.Queries??e}}catch(r){let s=r instanceof Error?r.message:String(r);const n=s.match(/Error: ([^:]+)\./);if(n&&(s=n[1]+"."),c.IsVerboseLoggingEnabled()){const a=`GraphQLSystemUserClient::GetData - Error getting data - ${r}`;c.LogError(a)}return{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
|
|
514
514
|
GetAllEntities {
|
|
515
515
|
Success
|
|
516
516
|
ErrorMessage
|
|
@@ -533,7 +533,7 @@
|
|
|
533
533
|
}
|
|
534
534
|
}
|
|
535
535
|
}
|
|
536
|
-
}`);return t&&t.GetAllEntities?t.GetAllEntities:{Success:!1,Results:[],ErrorMessage:t.GetAllEntities?.ErrorMessage??"Unknown error"}}catch(e){return
|
|
536
|
+
}`);return t&&t.GetAllEntities?t.GetAllEntities:{Success:!1,Results:[],ErrorMessage:t.GetAllEntities?.ErrorMessage??"Unknown error"}}catch(e){return c.LogError(`GraphQLSystemUserClient::GetAllRemoteEntities - Error getting remote entities - ${e}`),{Success:!1,Results:[],ErrorMessage:e}}}async SyncData(e){try{const r=await this.Client.request(`mutation SyncData($items: [ActionItemInputType!]!) {
|
|
537
537
|
SyncData(items: $items) {
|
|
538
538
|
Success
|
|
539
539
|
Results {
|
|
@@ -557,11 +557,11 @@
|
|
|
557
557
|
RecordJSON
|
|
558
558
|
}
|
|
559
559
|
}
|
|
560
|
-
}`,{items:e});return r&&r.SyncData?r.SyncData:{Success:!1,Results:[]}}catch(t){return
|
|
560
|
+
}`,{items:e});return r&&r.SyncData?r.SyncData:{Success:!1,Results:[]}}catch(t){return c.LogError(`GraphQLSystemUserClient::SyncData - Error syncing data - ${t}`),{Success:!1,Results:[]}}}async SyncRolesAndUsers(e){try{const r=await this.Client.request(`mutation SyncRolesAndUsers($data: RolesAndUsersInputType!) {
|
|
561
561
|
SyncRolesAndUsers(data: $data) {
|
|
562
562
|
Success
|
|
563
563
|
}
|
|
564
|
-
}`,{data:e});return r&&r.SyncRolesAndUsers?r.SyncRolesAndUsers:{Success:!1}}catch(t){return
|
|
564
|
+
}`,{data:e});return r&&r.SyncRolesAndUsers?r.SyncRolesAndUsers:{Success:!1}}catch(t){return c.LogError(`GraphQLSystemUserClient::SyncRolesAndUsers - Error syncing roles and users - ${t}`),{Success:!1}}}async RunViewByName(e){try{const t=`query RunViewByNameSystemUser($input: RunViewByNameInput!) {
|
|
565
565
|
RunViewByNameSystemUser(input: $input) {
|
|
566
566
|
Results {
|
|
567
567
|
PrimaryKey {
|
|
@@ -578,7 +578,7 @@
|
|
|
578
578
|
ErrorMessage
|
|
579
579
|
Success
|
|
580
580
|
}
|
|
581
|
-
}`,r={...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)},s=await this.Client.request(t,{input:r});return s&&s.RunViewByNameSystemUser?s.RunViewByNameSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by name"}}catch(t){return
|
|
581
|
+
}`,r={...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)},s=await this.Client.request(t,{input:r});return s&&s.RunViewByNameSystemUser?s.RunViewByNameSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by name"}}catch(t){return c.LogError(`GraphQLSystemUserClient::RunViewByNameSystemUser - Error running view by name - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViewByID(e){try{const t=`query RunViewByIDSystemUser($input: RunViewByIDInput!) {
|
|
582
582
|
RunViewByIDSystemUser(input: $input) {
|
|
583
583
|
Results {
|
|
584
584
|
PrimaryKey {
|
|
@@ -595,7 +595,7 @@
|
|
|
595
595
|
ErrorMessage
|
|
596
596
|
Success
|
|
597
597
|
}
|
|
598
|
-
}`,r={...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)},s=await this.Client.request(t,{input:r});return s&&s.RunViewByIDSystemUser?s.RunViewByIDSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by ID"}}catch(t){return
|
|
598
|
+
}`,r={...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)},s=await this.Client.request(t,{input:r});return s&&s.RunViewByIDSystemUser?s.RunViewByIDSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by ID"}}catch(t){return c.LogError(`GraphQLSystemUserClient::RunViewByIDSystemUser - Error running view by ID - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunDynamicView(e){try{const t=`query RunDynamicViewSystemUser($input: RunDynamicViewInput!) {
|
|
599
599
|
RunDynamicViewSystemUser(input: $input) {
|
|
600
600
|
Results {
|
|
601
601
|
PrimaryKey {
|
|
@@ -612,7 +612,7 @@
|
|
|
612
612
|
ErrorMessage
|
|
613
613
|
Success
|
|
614
614
|
}
|
|
615
|
-
}`,r={...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)},s=await this.Client.request(t,{input:r});return s&&s.RunDynamicViewSystemUser?s.RunDynamicViewSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute dynamic view"}}catch(t){return
|
|
615
|
+
}`,r={...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)},s=await this.Client.request(t,{input:r});return s&&s.RunDynamicViewSystemUser?s.RunDynamicViewSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute dynamic view"}}catch(t){return c.LogError(`GraphQLSystemUserClient::RunDynamicViewSystemUser - Error running dynamic view - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViews(e){try{const t=`query RunViewsSystemUser($input: [RunViewGenericInput!]!) {
|
|
616
616
|
RunViewsSystemUser(input: $input) {
|
|
617
617
|
Results {
|
|
618
618
|
PrimaryKey {
|
|
@@ -629,7 +629,7 @@
|
|
|
629
629
|
ErrorMessage
|
|
630
630
|
Success
|
|
631
631
|
}
|
|
632
|
-
}`,r=e.map(n=>({...n,ExtraFilter:this.resolvePlatformSQL(n.ExtraFilter),OrderBy:this.resolvePlatformSQL(n.OrderBy)})),s=await this.Client.request(t,{input:r});return s&&s.RunViewsSystemUser?s.RunViewsSystemUser:[]}catch(t){return
|
|
632
|
+
}`,r=e.map(n=>({...n,ExtraFilter:this.resolvePlatformSQL(n.ExtraFilter),OrderBy:this.resolvePlatformSQL(n.OrderBy)})),s=await this.Client.request(t,{input:r});return s&&s.RunViewsSystemUser?s.RunViewsSystemUser:[]}catch(t){return c.LogError(`GraphQLSystemUserClient::RunViewsSystemUser - Error running views - ${t}`),[]}}async GetQueryData(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataSystemUser($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
|
|
633
633
|
GetQueryDataSystemUser(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
|
|
634
634
|
QueryID
|
|
635
635
|
QueryName
|
|
@@ -641,7 +641,7 @@
|
|
|
641
641
|
ErrorMessage
|
|
642
642
|
AppliedParameters
|
|
643
643
|
}
|
|
644
|
-
}`,r={QueryID:e.QueryID};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataSystemUser?{...s.GetQueryDataSystemUser,Results:s.GetQueryDataSystemUser.Results?R.SafeJSONParse(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
|
|
644
|
+
}`,r={QueryID:e.QueryID};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataSystemUser?{...s.GetQueryDataSystemUser,Results:s.GetQueryDataSystemUser.Results?R.SafeJSONParse(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 c.LogError(`GraphQLSystemUserClient::GetQueryDataSystemUser - Error executing query - ${t}`),{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async GetQueryDataByName(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataByNameSystemUser($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
|
|
645
645
|
GetQueryDataByNameSystemUser(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
|
|
646
646
|
QueryID
|
|
647
647
|
QueryName
|
|
@@ -653,7 +653,7 @@
|
|
|
653
653
|
ErrorMessage
|
|
654
654
|
AppliedParameters
|
|
655
655
|
}
|
|
656
|
-
}`,r={QueryName:e.QueryName};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataByNameSystemUser?{...s.GetQueryDataByNameSystemUser,Results:s.GetQueryDataByNameSystemUser.Results?R.SafeJSONParse(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
|
|
656
|
+
}`,r={QueryName:e.QueryName};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataByNameSystemUser?{...s.GetQueryDataByNameSystemUser,Results:s.GetQueryDataByNameSystemUser.Results?R.SafeJSONParse(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 c.LogError(`GraphQLSystemUserClient::GetQueryDataByNameSystemUser - Error executing query - ${t}`),{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async CreateQuery(e){try{const r=await this.Client.request(`mutation CreateQuerySystemUser($input: CreateQuerySystemUserInput!) {
|
|
657
657
|
CreateQuerySystemUser(input: $input) {
|
|
658
658
|
Success
|
|
659
659
|
ErrorMessage
|
|
@@ -712,7 +712,7 @@
|
|
|
712
712
|
}
|
|
713
713
|
}
|
|
714
714
|
}
|
|
715
|
-
}`,{input:e});return r&&r.CreateQuerySystemUser?r.CreateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to create query"}}catch(t){return
|
|
715
|
+
}`,{input:e});return r&&r.CreateQuerySystemUser?r.CreateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to create query"}}catch(t){return c.LogError(`GraphQLSystemUserClient::CreateQuery - Error creating query - ${t}`),{Success:!1,ErrorMessage:t.toString()}}}async UpdateQuery(e){try{const r=await this.Client.request(`mutation UpdateQuerySystemUser($input: UpdateQuerySystemUserInput!) {
|
|
716
716
|
UpdateQuerySystemUser(input: $input) {
|
|
717
717
|
Success
|
|
718
718
|
ErrorMessage
|
|
@@ -771,14 +771,14 @@
|
|
|
771
771
|
}
|
|
772
772
|
}
|
|
773
773
|
}
|
|
774
|
-
}`,{input:e});return r&&r.UpdateQuerySystemUser?r.UpdateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to update query"}}catch(t){return
|
|
774
|
+
}`,{input:e});return r&&r.UpdateQuerySystemUser?r.UpdateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to update query"}}catch(t){return c.LogError(`GraphQLSystemUserClient::UpdateQuery - Error updating query - ${t}`),{Success:!1,ErrorMessage:t.toString()}}}async DeleteQuery(e,t){try{if(!e||e.trim()==="")return c.LogError("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) {
|
|
775
775
|
DeleteQuerySystemResolver(ID: $ID, options: $options) {
|
|
776
776
|
Success
|
|
777
777
|
ErrorMessage
|
|
778
778
|
ID
|
|
779
779
|
Name
|
|
780
780
|
}
|
|
781
|
-
}`,s={ID:e};t!==void 0&&(s.options={SkipEntityAIActions:t.SkipEntityAIActions??!1,SkipEntityActions:t.SkipEntityActions??!1,ReplayOnly:t.ReplayOnly??!1,IsParentEntityDelete:t.IsParentEntityDelete??!1});const n=await this.Client.request(r,s);return n&&n.DeleteQuerySystemResolver?n.DeleteQuerySystemResolver:{Success:!1,ErrorMessage:"Failed to delete query"}}catch(r){let s="";if(r instanceof Error){if(s=r.message,"cause"in r&&r.cause){const n=r.cause;s+=` | Cause: ${n.message||n}`,"code"in n&&(s+=` | Code: ${n.code}`)}if("response"in r){const n=r.response;n?.status&&(s+=` | HTTP Status: ${n.status}`),n?.errors&&(s+=` | GraphQL Errors: ${JSON.stringify(n.errors)}`)}r.stack&&console.error("DeleteQuery stack trace:",r.stack)}else s=String(r);return
|
|
781
|
+
}`,s={ID:e};t!==void 0&&(s.options={SkipEntityAIActions:t.SkipEntityAIActions??!1,SkipEntityActions:t.SkipEntityActions??!1,ReplayOnly:t.ReplayOnly??!1,IsParentEntityDelete:t.IsParentEntityDelete??!1});const n=await this.Client.request(r,s);return n&&n.DeleteQuerySystemResolver?n.DeleteQuerySystemResolver:{Success:!1,ErrorMessage:"Failed to delete query"}}catch(r){let s="";if(r instanceof Error){if(s=r.message,"cause"in r&&r.cause){const n=r.cause;s+=` | Cause: ${n.message||n}`,"code"in n&&(s+=` | Code: ${n.code}`)}if("response"in r){const n=r.response;n?.status&&(s+=` | HTTP Status: ${n.status}`),n?.errors&&(s+=` | GraphQL Errors: ${JSON.stringify(n.errors)}`)}r.stack&&console.error("DeleteQuery stack trace:",r.stack)}else s=String(r);return c.LogError(`GraphQLSystemUserClient::DeleteQuery - Error deleting query - ${s}`),{Success:!1,ErrorMessage:s}}}async RunAIPrompt(e){try{const t=u.gql`
|
|
782
782
|
query RunAIPromptSystemUser(
|
|
783
783
|
$promptId: String!,
|
|
784
784
|
$data: String,
|
|
@@ -837,7 +837,7 @@
|
|
|
837
837
|
chatResult
|
|
838
838
|
}
|
|
839
839
|
}
|
|
840
|
-
`,r=this.preparePromptVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIPromptSystemUser?this.processPromptResult(s.RunAIPromptSystemUser):{success:!1,error:"Failed to execute AI prompt as system user"}}catch(t){return
|
|
840
|
+
`,r=this.preparePromptVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIPromptSystemUser?this.processPromptResult(s.RunAIPromptSystemUser):{success:!1,error:"Failed to execute AI prompt as system user"}}catch(t){return c.LogError(`GraphQLSystemUserClient::RunAIPrompt - Error running AI prompt - ${t}`),{success:!1,error:t.toString()}}}async RunAIAgent(e){try{const t=u.gql`
|
|
841
841
|
query RunAIAgentSystemUser(
|
|
842
842
|
$agentId: String!,
|
|
843
843
|
$messages: String!,
|
|
@@ -864,7 +864,7 @@
|
|
|
864
864
|
result
|
|
865
865
|
}
|
|
866
866
|
}
|
|
867
|
-
`,r=this.prepareAgentVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIAgentSystemUser?this.processAgentResult(s.RunAIAgentSystemUser.result):{success:!1,agentRun:void 0}}catch(t){return
|
|
867
|
+
`,r=this.prepareAgentVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIAgentSystemUser?this.processAgentResult(s.RunAIAgentSystemUser.result):{success:!1,agentRun:void 0}}catch(t){return c.LogError(`GraphQLSystemUserClient::RunAIAgent - Error running AI agent - ${t}`),{success:!1,agentRun:void 0}}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}prepareAgentVariables(e){const t={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._sessionId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),t}processPromptResult(e){let t,r,s;try{e.parsedResult&&(t=JSON.parse(e.parsedResult))}catch{t=e.parsedResult}try{e.validationResult&&(r=JSON.parse(e.validationResult))}catch{r=e.validationResult}try{e.chatResult&&(s=JSON.parse(e.chatResult))}catch{s=e.chatResult}return{success:e.success,output:e.output,parsedResult:t,error:e.error,executionTimeMs:e.executionTimeMs,tokensUsed:e.tokensUsed,promptRunId:e.promptRunId,rawResult:e.rawResult,validationResult:r,chatResult:s}}processAgentResult(e){return R.SafeJSONParse(e)}async TestQuerySQL(e){try{const r=await this.Client.request(`query TestQuerySQL($input: TestQuerySQLInput!) {
|
|
868
868
|
TestQuerySQL(input: $input) {
|
|
869
869
|
Success
|
|
870
870
|
Results
|
|
@@ -873,7 +873,7 @@
|
|
|
873
873
|
ErrorMessage
|
|
874
874
|
AppliedParameters
|
|
875
875
|
}
|
|
876
|
-
}`,{input:e});return r&&r.TestQuerySQL?{Success:r.TestQuerySQL.Success,Results:r.TestQuerySQL.Results?R.SafeJSONParse(r.TestQuerySQL.Results):null,RowCount:r.TestQuerySQL.RowCount,ExecutionTime:r.TestQuerySQL.ExecutionTime,ErrorMessage:r.TestQuerySQL.ErrorMessage,AppliedParameters:r.TestQuerySQL.AppliedParameters?R.SafeJSONParse(r.TestQuerySQL.AppliedParameters):void 0}:{Success:!1,Results:null,RowCount:0,ExecutionTime:0,ErrorMessage:"TestQuerySQL execution failed"}}catch(t){return
|
|
876
|
+
}`,{input:e});return r&&r.TestQuerySQL?{Success:r.TestQuerySQL.Success,Results:r.TestQuerySQL.Results?R.SafeJSONParse(r.TestQuerySQL.Results):null,RowCount:r.TestQuerySQL.RowCount,ExecutionTime:r.TestQuerySQL.ExecutionTime,ErrorMessage:r.TestQuerySQL.ErrorMessage,AppliedParameters:r.TestQuerySQL.AppliedParameters?R.SafeJSONParse(r.TestQuerySQL.AppliedParameters):void 0}:{Success:!1,Results:null,RowCount:0,ExecutionTime:0,ErrorMessage:"TestQuerySQL execution failed"}}catch(t){return c.LogError(`GraphQLSystemUserClient::TestQuerySQL - Error testing query SQL - ${t}`),{Success:!1,Results:null,RowCount:0,ExecutionTime:0,ErrorMessage:t instanceof Error?t.message:String(t)}}}async ExecuteSimplePrompt(e){try{const t=u.gql`
|
|
877
877
|
query ExecuteSimplePromptSystemUser(
|
|
878
878
|
$systemPrompt: String!,
|
|
879
879
|
$messages: String,
|
|
@@ -896,7 +896,7 @@
|
|
|
896
896
|
executionTimeMs
|
|
897
897
|
}
|
|
898
898
|
}
|
|
899
|
-
`,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this.Client.request(t,r);if(!s?.ExecuteSimplePromptSystemUser)return{success:!1,modelName:"Unknown",error:"Failed to execute simple prompt as system user"};const n=s.ExecuteSimplePromptSystemUser;let a;if(n.resultObject)try{a=JSON.parse(n.resultObject)}catch{a=n.resultObject}return{success:n.success,result:n.result,resultObject:a,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){return
|
|
899
|
+
`,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this.Client.request(t,r);if(!s?.ExecuteSimplePromptSystemUser)return{success:!1,modelName:"Unknown",error:"Failed to execute simple prompt as system user"};const n=s.ExecuteSimplePromptSystemUser;let a;if(n.resultObject)try{a=JSON.parse(n.resultObject)}catch{a=n.resultObject}return{success:n.success,result:n.result,resultObject:a,modelName:n.modelName,error:n.error,executionTimeMs:n.executionTimeMs}}catch(t){return c.LogError(`GraphQLSystemUserClient::ExecuteSimplePrompt - Error executing simple prompt - ${t}`),{success:!1,modelName:"Unknown",error:t.toString()}}}async EmbedText(e){try{const t=u.gql`
|
|
900
900
|
query EmbedTextSystemUser(
|
|
901
901
|
$textToEmbed: [String!]!,
|
|
902
902
|
$modelSize: String!
|
|
@@ -911,7 +911,7 @@
|
|
|
911
911
|
error
|
|
912
912
|
}
|
|
913
913
|
}
|
|
914
|
-
`,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this.Client.request(t,s);if(!n?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const a=n.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?a.embeddings:a.embeddings[0],modelName:a.modelName,vectorDimensions:a.vectorDimensions,error:a.error}}catch(t){return
|
|
914
|
+
`,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this.Client.request(t,s);if(!n?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const a=n.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?a.embeddings:a.embeddings[0],modelName:a.modelName,vectorDimensions:a.vectorDimensions,error:a.error}}catch(t){return c.LogError(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}}class te{static{g(this,"GetDataOutput")}}class re{static{g(this,"SimpleRemoteEntityOutput")}}class se{static{g(this,"SimpleRemoteEntity")}}class ne{static{g(this,"SimpleRemoteEntityField")}}class ae{static{g(this,"GraphQLActionClient")}constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),n=this.createActionVariables(e,s,r),a=await this.executeActionMutation(n);return this.processActionResult(a,t)}catch(s){return this.handleActionError(s,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{...t,Value:r}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=u.gql`
|
|
915
915
|
mutation RunAction($input: RunActionInput!) {
|
|
916
916
|
RunAction(input: $input) {
|
|
917
917
|
Success
|
|
@@ -920,7 +920,7 @@
|
|
|
920
920
|
ResultData
|
|
921
921
|
}
|
|
922
922
|
}
|
|
923
|
-
`;return await this._dataProvider.ExecuteGQL(t,e)}processActionResult(e,t){if(!e?.RunAction)throw new Error("Invalid response from server");let r;try{e.RunAction.ResultData&&(r=JSON.parse(e.RunAction.ResultData))}catch(s){
|
|
923
|
+
`;return await this._dataProvider.ExecuteGQL(t,e)}processActionResult(e,t){if(!e?.RunAction)throw new Error("Invalid response from server");let r;try{e.RunAction.ResultData&&(r=JSON.parse(e.RunAction.ResultData))}catch(s){c.LogError(`Failed to parse action result data: ${s}`)}return{Success:e.RunAction.Success,Message:e.RunAction.Message,Result:r,LogEntry:null,Params:t||[],RunParams:null}}handleActionError(e,t){const r=e;return c.LogError(`Error running action: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Result:null,LogEntry:null,Params:t||[],RunParams:null}}async RunEntityAction(e){try{const t=this.createEntityActionInput(e),r=await this.executeEntityActionMutation(t);return this.processEntityActionResult(r)}catch(t){return this.handleEntityActionError(t)}}createEntityActionInput(e){const t={EntityActionID:e.EntityAction.ID,InvocationType:e.InvocationType.Name,ListID:e.ListID,ViewID:e.ViewID};return e.Params&&(t.Params=this.convertActionParams(e.Params)),e.EntityObject&&this.addEntityInformation(t,e.EntityObject),t}convertActionParams(e){return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{Name:t.Name,Value:r,Type:t.Type}})}addEntityInformation(e,t){e.EntityName=t.EntityInfo?.Name,t.PrimaryKey&&(e.PrimaryKey=this.convertPrimaryKey(t.PrimaryKey))}convertPrimaryKey(e){return{KeyValuePairs:e.KeyValuePairs.map(t=>this.convertKeyValuePair(t))}}convertKeyValuePair(e){return{FieldName:e.FieldName,Value:e.Value!==null&&e.Value!==void 0?typeof e.Value=="object"?JSON.stringify(e.Value):e.Value.toString():null}}async executeEntityActionMutation(e){const t=u.gql`
|
|
924
924
|
mutation RunEntityAction($input: EntityActionInput!) {
|
|
925
925
|
RunEntityAction(input: $input) {
|
|
926
926
|
Success
|
|
@@ -928,7 +928,7 @@
|
|
|
928
928
|
ResultData
|
|
929
929
|
}
|
|
930
930
|
}
|
|
931
|
-
`;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(r){
|
|
931
|
+
`;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(r){c.LogError(`Failed to parse entity action result data: ${r}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return c.LogError(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}}class oe{static{g(this,"GraphQLEncryptionClient")}constructor(e){this._dataProvider=e}async CreateAPIKey(e){try{const t=this.createAPIKeyVariables(e),r=await this.executeCreateAPIKeyMutation(t);return this.processCreateAPIKeyResult(r)}catch(t){return this.handleCreateAPIKeyError(t)}}createAPIKeyVariables(e){return{input:{Label:e.Label,Description:e.Description,ExpiresAt:e.ExpiresAt?.toISOString(),ScopeIDs:e.ScopeIDs}}}async executeCreateAPIKeyMutation(e){const t=u.gql`
|
|
932
932
|
mutation CreateAPIKey($input: CreateAPIKeyInput!) {
|
|
933
933
|
CreateAPIKey(input: $input) {
|
|
934
934
|
Success
|
|
@@ -937,18 +937,18 @@
|
|
|
937
937
|
Error
|
|
938
938
|
}
|
|
939
939
|
}
|
|
940
|
-
`;return await this._dataProvider.ExecuteGQL(t,e)}processCreateAPIKeyResult(e){const t=e;return t?.CreateAPIKey?{Success:t.CreateAPIKey.Success,RawKey:t.CreateAPIKey.RawKey,APIKeyID:t.CreateAPIKey.APIKeyID,Error:t.CreateAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}handleCreateAPIKeyError(e){const t=e;return
|
|
940
|
+
`;return await this._dataProvider.ExecuteGQL(t,e)}processCreateAPIKeyResult(e){const t=e;return t?.CreateAPIKey?{Success:t.CreateAPIKey.Success,RawKey:t.CreateAPIKey.RawKey,APIKeyID:t.CreateAPIKey.APIKeyID,Error:t.CreateAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}handleCreateAPIKeyError(e){const t=e;return c.LogError(`Error creating API key: ${t.message}`),{Success:!1,Error:`Error: ${t.message}`}}async RevokeAPIKey(e){try{const t=u.gql`
|
|
941
941
|
mutation RevokeAPIKey($apiKeyId: String!) {
|
|
942
942
|
RevokeAPIKey(apiKeyId: $apiKeyId) {
|
|
943
943
|
Success
|
|
944
944
|
Error
|
|
945
945
|
}
|
|
946
946
|
}
|
|
947
|
-
`,s=await this._dataProvider.ExecuteGQL(t,{apiKeyId:e});return s?.RevokeAPIKey?{Success:s.RevokeAPIKey.Success,Error:s.RevokeAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}catch(t){const r=t;return
|
|
947
|
+
`,s=await this._dataProvider.ExecuteGQL(t,{apiKeyId:e});return s?.RevokeAPIKey?{Success:s.RevokeAPIKey.Success,Error:s.RevokeAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}catch(t){const r=t;return c.LogError(`Error revoking API key: ${r.message}`),{Success:!1,Error:`Error: ${r.message}`}}}}class ie{static{g(this,"GraphQLTestingClient")}constructor(e){this._dataProvider=e}async RunTest(e){try{const t=this.buildRunTestMutation(),r=this.buildRunTestVariables(e);return await P.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTest",operationLabel:"RunTest",validateAck:g(s=>s?.success===!0,"validateAck"),isCompletionEvent:g(s=>this.isTestCompletionEvent(s,e.testId),"isCompletionEvent"),extractResult:g(s=>this.extractTestResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardTestProgress(s,e.onProgress):void 0,createErrorResult:g(s=>({success:!1,errorMessage:s,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTest")}}async RunTestSuite(e){try{const t=this.buildRunTestSuiteMutation(),r=this.buildRunTestSuiteVariables(e);return await P.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTestSuite",operationLabel:"RunTestSuite",validateAck:g(s=>s?.success===!0,"validateAck"),isCompletionEvent:g(s=>this.isSuiteCompletionEvent(s,e.suiteId),"isCompletionEvent"),extractResult:g(s=>this.extractSuiteResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardTestProgress(s,e.onProgress):void 0,createErrorResult:g(s=>({success:!1,errorMessage:s,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTestSuite")}}async IsTestRunning(e){try{const t=u.gql`
|
|
948
948
|
query IsTestRunning($testId: String!) {
|
|
949
949
|
IsTestRunning(testId: $testId)
|
|
950
950
|
}
|
|
951
|
-
`;return(await this._dataProvider.ExecuteGQL(t,{testId:e})).IsTestRunning}catch(t){return
|
|
951
|
+
`;return(await this._dataProvider.ExecuteGQL(t,{testId:e})).IsTestRunning}catch(t){return c.LogError(`Error checking test running status: ${t.message}`),!1}}buildRunTestMutation(){return u.gql`
|
|
952
952
|
mutation RunTest(
|
|
953
953
|
$testId: String!,
|
|
954
954
|
$verbose: Boolean,
|
|
@@ -971,7 +971,7 @@
|
|
|
971
971
|
result
|
|
972
972
|
}
|
|
973
973
|
}
|
|
974
|
-
`}buildRunTestSuiteMutation(){return
|
|
974
|
+
`}buildRunTestSuiteMutation(){return u.gql`
|
|
975
975
|
mutation RunTestSuite(
|
|
976
976
|
$suiteId: String!,
|
|
977
977
|
$verbose: Boolean,
|
|
@@ -1002,7 +1002,7 @@
|
|
|
1002
1002
|
result
|
|
1003
1003
|
}
|
|
1004
1004
|
}
|
|
1005
|
-
`}buildRunTestVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0;return{testId:e.testId,verbose:e.verbose,environment:e.environment,tags:t,variables:r,fireAndForget:!0}}buildRunTestSuiteVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0,s=e.selectedTestIds&&e.selectedTestIds.length>0?JSON.stringify(e.selectedTestIds):void 0;return{suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel,tags:t,variables:r,selectedTestIds:s,sequenceStart:e.sequenceStart,sequenceEnd:e.sequenceEnd,fireAndForget:!0}}isTestCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetComplete"&&r?.type==="complete"&&r?.testId===t}isSuiteCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetSuiteComplete"&&r?.type==="complete"&&r?.suiteId===t}extractTestResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?R.SafeJSONParse(t.result):null}}extractSuiteResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?R.SafeJSONParse(t.result):null}}forwardTestProgress(e,t){if(e.resolver==="RunTestResolver"&&e.type==="TestExecutionProgress"&&e.status==="ok"){const s=e.data?.progress;s&&t(s)}}handleError(e,t){const r=e.message;return
|
|
1005
|
+
`}buildRunTestVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0;return{testId:e.testId,verbose:e.verbose,environment:e.environment,tags:t,variables:r,fireAndForget:!0}}buildRunTestSuiteVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0,s=e.selectedTestIds&&e.selectedTestIds.length>0?JSON.stringify(e.selectedTestIds):void 0;return{suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel,tags:t,variables:r,selectedTestIds:s,sequenceStart:e.sequenceStart,sequenceEnd:e.sequenceEnd,fireAndForget:!0}}isTestCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetComplete"&&r?.type==="complete"&&r?.testId===t}isSuiteCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetSuiteComplete"&&r?.type==="complete"&&r?.suiteId===t}extractTestResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?R.SafeJSONParse(t.result):null}}extractSuiteResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?R.SafeJSONParse(t.result):null}}forwardTestProgress(e,t){if(e.resolver==="RunTestResolver"&&e.type==="TestExecutionProgress"&&e.status==="ok"){const s=e.data?.progress;s&&t(s)}}handleError(e,t){const r=e.message;return c.LogError(`${t} failed: ${r}`),{success:!1,errorMessage:r.includes("Failed to fetch")||r.includes("NetworkError")?"Lost connection to the server. The test may still be running. Please refresh to check the latest status.":r,result:null}}}class ce{static{g(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=u.gql`
|
|
1006
1006
|
query GetRegistryComponent(
|
|
1007
1007
|
$registryName: String!,
|
|
1008
1008
|
$namespace: String!,
|
|
@@ -1023,7 +1023,7 @@
|
|
|
1023
1023
|
specification
|
|
1024
1024
|
}
|
|
1025
1025
|
}
|
|
1026
|
-
`,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const n=s.GetRegistryComponent;if(n.notModified&&!n.specification)return null;if(n.specification){if(typeof n.specification=="object")return n.specification;try{return JSON.parse(n.specification)}catch(a){return
|
|
1026
|
+
`,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const n=s.GetRegistryComponent;if(n.notModified&&!n.specification)return null;if(n.specification){if(typeof n.specification=="object")return n.specification;try{return JSON.parse(n.specification)}catch(a){return c.LogError(`Failed to parse component specification: ${a}`),null}}return null}return null}catch(t){throw c.LogError(t),new Error(`Failed to get registry component: ${t instanceof Error?t.message:"Unknown error"}`)}}async GetRegistryComponentWithHash(e){try{const t=u.gql`
|
|
1027
1027
|
query GetRegistryComponent(
|
|
1028
1028
|
$registryName: String!,
|
|
1029
1029
|
$namespace: String!,
|
|
@@ -1044,7 +1044,7 @@
|
|
|
1044
1044
|
specification
|
|
1045
1045
|
}
|
|
1046
1046
|
}
|
|
1047
|
-
`,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const n=s.GetRegistryComponent;let a;if(n.specification)try{a=JSON.parse(n.specification)}catch(i){
|
|
1047
|
+
`,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const n=s.GetRegistryComponent;let a;if(n.specification)try{a=JSON.parse(n.specification)}catch(i){c.LogError(`Failed to parse component specification in GetRegistryComponentWithHash: ${i}`),a=void 0}return{specification:a,hash:n.hash,notModified:n.notModified,message:n.message}}return{specification:void 0,hash:"",notModified:!1,message:"Component not found"}}catch(t){throw c.LogError(t),new Error(`Failed to get registry component with hash: ${t instanceof Error?t.message:"Unknown error"}`)}}async SearchRegistryComponents(e){try{const t=u.gql`
|
|
1048
1048
|
query SearchRegistryComponents($params: SearchRegistryComponentsInput!) {
|
|
1049
1049
|
SearchRegistryComponents(params: $params) {
|
|
1050
1050
|
components
|
|
@@ -1053,7 +1053,7 @@
|
|
|
1053
1053
|
limit
|
|
1054
1054
|
}
|
|
1055
1055
|
}
|
|
1056
|
-
`,r=await this._dataProvider.ExecuteGQL(t,{params:e});if(r&&r.SearchRegistryComponents){const s=r.SearchRegistryComponents;return{components:s.components.map(n=>JSON.parse(n)),total:s.total,offset:s.offset,limit:s.limit}}return{components:[],total:0,offset:0,limit:e.limit||10}}catch(t){throw
|
|
1056
|
+
`,r=await this._dataProvider.ExecuteGQL(t,{params:e});if(r&&r.SearchRegistryComponents){const s=r.SearchRegistryComponents;return{components:s.components.map(n=>JSON.parse(n)),total:s.total,offset:s.offset,limit:s.limit}}return{components:[],total:0,offset:0,limit:e.limit||10}}catch(t){throw c.LogError(t),new Error(`Failed to search registry components: ${t instanceof Error?t.message:"Unknown error"}`)}}async ResolveComponentDependencies(e,t){try{const r=u.gql`
|
|
1057
1057
|
query ResolveComponentDependencies(
|
|
1058
1058
|
$registryId: String!,
|
|
1059
1059
|
$componentId: String!
|
|
@@ -1078,7 +1078,7 @@
|
|
|
1078
1078
|
}
|
|
1079
1079
|
}
|
|
1080
1080
|
}
|
|
1081
|
-
`,s=await this._dataProvider.ExecuteGQL(r,{registryId:e,componentId:t});return s&&s.ResolveComponentDependencies?s.ResolveComponentDependencies:null}catch(r){throw
|
|
1081
|
+
`,s=await this._dataProvider.ExecuteGQL(r,{registryId:e,componentId:t});return s&&s.ResolveComponentDependencies?s.ResolveComponentDependencies:null}catch(r){throw c.LogError(r),new Error(`Failed to resolve component dependencies: ${r instanceof Error?r.message:"Unknown error"}`)}}async ComponentExists(e){try{return await this.GetRegistryComponent(e)!==null}catch{return!1}}async GetLatestVersion(e,t,r){try{return(await this.GetRegistryComponent({registryName:e,namespace:t,name:r,version:"latest"}))?.version||null}catch(s){return c.LogError(s),null}}async SendComponentFeedback(e){try{const t=u.gql`
|
|
1082
1082
|
mutation SendComponentFeedback($feedback: ComponentFeedbackInput!) {
|
|
1083
1083
|
SendComponentFeedback(feedback: $feedback) {
|
|
1084
1084
|
success
|
|
@@ -1086,7 +1086,7 @@
|
|
|
1086
1086
|
error
|
|
1087
1087
|
}
|
|
1088
1088
|
}
|
|
1089
|
-
`,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return
|
|
1089
|
+
`,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return c.LogError(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}}class ue{static{g(this,"GraphQLVersionHistoryClient")}constructor(e){this._dataProvider=e}async CreateLabel(e){let t;try{e.OnProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(a=>{try{const i=JSON.parse(a);i.resolver==="VersionHistoryResolver"&&i.type==="CreateLabelProgress"&&i.status==="ok"&&i.data&&e.OnProgress(i.data)}catch{}}));const r=u.gql`
|
|
1090
1090
|
mutation CreateVersionLabel($input: CreateVersionLabelInput!, $sessionId: String) {
|
|
1091
1091
|
CreateVersionLabel(input: $input, sessionId: $sessionId) {
|
|
1092
1092
|
Success
|
|
@@ -1102,7 +1102,7 @@
|
|
|
1102
1102
|
}
|
|
1103
1103
|
}
|
|
1104
1104
|
}
|
|
1105
|
-
`,s={input:this.buildInput(e),sessionId:this._dataProvider.sessionId},n=await this._dataProvider.ExecuteGQL(r,s);return this.processResult(n)}catch(r){const s=r instanceof Error?r.message:String(r);return
|
|
1105
|
+
`,s={input:this.buildInput(e),sessionId:this._dataProvider.sessionId},n=await this._dataProvider.ExecuteGQL(r,s);return this.processResult(n)}catch(r){const s=r instanceof Error?r.message:String(r);return c.LogError(`GraphQLVersionHistoryClient.CreateLabel error: ${s}`),{Success:!1,Error:s}}finally{t&&t.unsubscribe()}}buildInput(e){const t={Name:e.Name};return e.Description!=null&&(t.Description=e.Description),e.Scope!=null&&(t.Scope=e.Scope),e.EntityName!=null&&(t.EntityName=e.EntityName),e.ParentID!=null&&(t.ParentID=e.ParentID),e.ExternalSystemID!=null&&(t.ExternalSystemID=e.ExternalSystemID),e.IncludeDependencies!=null&&(t.IncludeDependencies=e.IncludeDependencies),e.MaxDepth!=null&&(t.MaxDepth=e.MaxDepth),e.ExcludeEntities!=null&&(t.ExcludeEntities=e.ExcludeEntities),e.RecordKeys&&e.RecordKeys.length>0&&(t.RecordKeys=e.RecordKeys.map(r=>({Key:r.Key,Value:r.Value}))),t}processResult(e){const t=e?.CreateVersionLabel;if(!t)return{Success:!1,Error:"Invalid response from server."};const r=Array.isArray(t.CaptureErrors)?t.CaptureErrors.map(s=>({EntityName:s.EntityName??"",RecordID:s.RecordID??"",ErrorMessage:s.ErrorMessage??""})):void 0;return{Success:t.Success,LabelID:t.LabelID,LabelName:t.LabelName,ItemsCaptured:t.ItemsCaptured,SyntheticSnapshotsCreated:t.SyntheticSnapshotsCreated,Error:t.Error,CaptureErrors:r}}}class le{static{g(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const s=u.gql`
|
|
1106
1106
|
query ListStorageObjects($input: ListStorageObjectsInput!) {
|
|
1107
1107
|
ListStorageObjects(input: $input) {
|
|
1108
1108
|
objects {
|
|
@@ -1119,34 +1119,34 @@
|
|
|
1119
1119
|
prefixes
|
|
1120
1120
|
}
|
|
1121
1121
|
}
|
|
1122
|
-
`,n={input:{AccountID:e,Prefix:t,Delimiter:r||"/"}},a=await this._dataProvider.ExecuteGQL(s,n);if(!a?.ListStorageObjects)throw new Error("Invalid response from server");return{objects:a.ListStorageObjects.objects.map(i=>({...i,lastModified:new Date(i.lastModified)})),prefixes:a.ListStorageObjects.prefixes}}catch(s){const n=s;throw
|
|
1122
|
+
`,n={input:{AccountID:e,Prefix:t,Delimiter:r||"/"}},a=await this._dataProvider.ExecuteGQL(s,n);if(!a?.ListStorageObjects)throw new Error("Invalid response from server");return{objects:a.ListStorageObjects.objects.map(i=>({...i,lastModified:new Date(i.lastModified)})),prefixes:a.ListStorageObjects.prefixes}}catch(s){const n=s;throw c.LogError(`Error listing storage objects: ${n}`),n}}async DirectoryExists(e,t){try{const r=await this.ListObjects(e,t.endsWith("/")?t:`${t}/`,"/");return r.objects.length>0||r.prefixes.length>0}catch(r){const s=r;return c.LogError(`Error checking directory existence: ${s}`),!1}}async CreateDirectory(e,t){try{const r=u.gql`
|
|
1123
1123
|
mutation CreateDirectory($input: CreateDirectoryInput!) {
|
|
1124
1124
|
CreateDirectory(input: $input)
|
|
1125
1125
|
}
|
|
1126
|
-
`,s={input:{AccountID:e,Path:t}};return(await this._dataProvider.ExecuteGQL(r,s))?.CreateDirectory??!1}catch(r){const s=r;return
|
|
1126
|
+
`,s={input:{AccountID:e,Path:t}};return(await this._dataProvider.ExecuteGQL(r,s))?.CreateDirectory??!1}catch(r){const s=r;return c.LogError(`Error creating directory: ${s}`),!1}}async ObjectExists(e,t){try{const r=t.substring(0,t.lastIndexOf("/")+1),s=t.substring(t.lastIndexOf("/")+1);return(await this.ListObjects(e,r,"/")).objects.some(a=>a.name===s||a.fullPath===t)}catch(r){const s=r;return c.LogError(`Error checking object existence: ${s}`),!1}}async CreatePreAuthUploadUrl(e,t,r){try{const s=u.gql`
|
|
1127
1127
|
mutation CreatePreAuthUploadUrl($input: CreatePreAuthUploadUrlInput!) {
|
|
1128
1128
|
CreatePreAuthUploadUrl(input: $input) {
|
|
1129
1129
|
UploadUrl
|
|
1130
1130
|
ProviderKey
|
|
1131
1131
|
}
|
|
1132
1132
|
}
|
|
1133
|
-
`,n={input:{AccountID:e,ObjectName:t,ContentType:r}},a=await this._dataProvider.ExecuteGQL(s,n);if(!a?.CreatePreAuthUploadUrl)throw new Error("Invalid response from server");return{uploadUrl:a.CreatePreAuthUploadUrl.UploadUrl,providerKey:a.CreatePreAuthUploadUrl.ProviderKey}}catch(s){const n=s;throw
|
|
1133
|
+
`,n={input:{AccountID:e,ObjectName:t,ContentType:r}},a=await this._dataProvider.ExecuteGQL(s,n);if(!a?.CreatePreAuthUploadUrl)throw new Error("Invalid response from server");return{uploadUrl:a.CreatePreAuthUploadUrl.UploadUrl,providerKey:a.CreatePreAuthUploadUrl.ProviderKey}}catch(s){const n=s;throw c.LogError(`Error creating pre-auth upload URL: ${n}`),n}}async CreatePreAuthDownloadUrl(e,t){try{const r=u.gql`
|
|
1134
1134
|
query CreatePreAuthDownloadUrl($input: CreatePreAuthDownloadUrlInput!) {
|
|
1135
1135
|
CreatePreAuthDownloadUrl(input: $input)
|
|
1136
1136
|
}
|
|
1137
|
-
`,s={input:{AccountID:e,ObjectName:t}},n=await this._dataProvider.ExecuteGQL(r,s);if(n?.CreatePreAuthDownloadUrl===void 0)throw new Error("Invalid response from server");return n.CreatePreAuthDownloadUrl}catch(r){const s=r;throw
|
|
1137
|
+
`,s={input:{AccountID:e,ObjectName:t}},n=await this._dataProvider.ExecuteGQL(r,s);if(n?.CreatePreAuthDownloadUrl===void 0)throw new Error("Invalid response from server");return n.CreatePreAuthDownloadUrl}catch(r){const s=r;throw c.LogError(`Error creating pre-auth download URL: ${s}`),s}}async DeleteObject(e,t){try{const r=u.gql`
|
|
1138
1138
|
mutation DeleteStorageObject($input: DeleteStorageObjectInput!) {
|
|
1139
1139
|
DeleteStorageObject(input: $input)
|
|
1140
1140
|
}
|
|
1141
|
-
`,s={input:{AccountID:e,ObjectName:t}};return(await this._dataProvider.ExecuteGQL(r,s))?.DeleteStorageObject??!1}catch(r){const s=r;return
|
|
1141
|
+
`,s={input:{AccountID:e,ObjectName:t}};return(await this._dataProvider.ExecuteGQL(r,s))?.DeleteStorageObject??!1}catch(r){const s=r;return c.LogError(`Error deleting storage object: ${s}`),!1}}async MoveObject(e,t,r){try{const s=u.gql`
|
|
1142
1142
|
mutation MoveStorageObject($input: MoveStorageObjectInput!) {
|
|
1143
1143
|
MoveStorageObject(input: $input)
|
|
1144
1144
|
}
|
|
1145
|
-
`,n={input:{AccountID:e,OldName:t,NewName:r}};return(await this._dataProvider.ExecuteGQL(s,n))?.MoveStorageObject??!1}catch(s){const n=s;return
|
|
1145
|
+
`,n={input:{AccountID:e,OldName:t,NewName:r}};return(await this._dataProvider.ExecuteGQL(s,n))?.MoveStorageObject??!1}catch(s){const n=s;return c.LogError(`Error moving storage object: ${n}`),!1}}async CopyObject(e,t,r){try{const s=u.gql`
|
|
1146
1146
|
mutation CopyStorageObject($input: CopyStorageObjectInput!) {
|
|
1147
1147
|
CopyStorageObject(input: $input)
|
|
1148
1148
|
}
|
|
1149
|
-
`,n={input:{AccountID:e,SourceName:t,DestinationName:r}};return(await this._dataProvider.ExecuteGQL(s,n))?.CopyStorageObject??!1}catch(s){const n=s;return
|
|
1149
|
+
`,n={input:{AccountID:e,SourceName:t,DestinationName:r}};return(await this._dataProvider.ExecuteGQL(s,n))?.CopyStorageObject??!1}catch(s){const n=s;return c.LogError(`Error copying storage object: ${n}`),!1}}async CopyObjectBetweenAccounts(e,t,r,s){try{const n=u.gql`
|
|
1150
1150
|
mutation CopyObjectBetweenAccounts($input: CopyObjectBetweenAccountsInput!) {
|
|
1151
1151
|
CopyObjectBetweenAccounts(input: $input) {
|
|
1152
1152
|
success
|
|
@@ -1158,7 +1158,7 @@
|
|
|
1158
1158
|
destinationPath
|
|
1159
1159
|
}
|
|
1160
1160
|
}
|
|
1161
|
-
`,a={input:{SourceAccountID:e,DestinationAccountID:t,SourcePath:r,DestinationPath:s}},i=await this._dataProvider.ExecuteGQL(n,a);if(!i?.CopyObjectBetweenAccounts)throw new Error("Invalid response from server");return{success:i.CopyObjectBetweenAccounts.success,message:i.CopyObjectBetweenAccounts.message,bytesTransferred:i.CopyObjectBetweenAccounts.bytesTransferred,sourceAccount:i.CopyObjectBetweenAccounts.sourceAccount,destinationAccount:i.CopyObjectBetweenAccounts.destinationAccount,sourcePath:i.CopyObjectBetweenAccounts.sourcePath,destinationPath:i.CopyObjectBetweenAccounts.destinationPath}}catch(n){const a=n;return
|
|
1161
|
+
`,a={input:{SourceAccountID:e,DestinationAccountID:t,SourcePath:r,DestinationPath:s}},i=await this._dataProvider.ExecuteGQL(n,a);if(!i?.CopyObjectBetweenAccounts)throw new Error("Invalid response from server");return{success:i.CopyObjectBetweenAccounts.success,message:i.CopyObjectBetweenAccounts.message,bytesTransferred:i.CopyObjectBetweenAccounts.bytesTransferred,sourceAccount:i.CopyObjectBetweenAccounts.sourceAccount,destinationAccount:i.CopyObjectBetweenAccounts.destinationAccount,sourcePath:i.CopyObjectBetweenAccounts.sourcePath,destinationPath:i.CopyObjectBetweenAccounts.destinationPath}}catch(n){const a=n;return c.LogError(`Error copying object between accounts: ${a}`),{success:!1,message:a.message,sourceAccount:"",destinationAccount:"",sourcePath:r,destinationPath:s}}}async SearchFiles(e,t,r){try{const s=u.gql`
|
|
1162
1162
|
query SearchAcrossAccounts($input: SearchAcrossAccountsInput!) {
|
|
1163
1163
|
SearchAcrossAccounts(input: $input) {
|
|
1164
1164
|
accountResults {
|
|
@@ -1186,7 +1186,7 @@
|
|
|
1186
1186
|
failedAccounts
|
|
1187
1187
|
}
|
|
1188
1188
|
}
|
|
1189
|
-
`,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:r?.maxResultsPerAccount,FileTypes:r?.fileTypes,SearchContent:r?.searchContent}},a=await this._dataProvider.ExecuteGQL(s,n);if(!a?.SearchAcrossAccounts)throw new Error("Invalid response from server");const i=a.SearchAcrossAccounts;return{accountResults:i.accountResults.map(o=>({accountId:o.accountID,accountName:o.accountName,success:o.success,errorMessage:o.errorMessage,results:o.results.map(
|
|
1189
|
+
`,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:r?.maxResultsPerAccount,FileTypes:r?.fileTypes,SearchContent:r?.searchContent}},a=await this._dataProvider.ExecuteGQL(s,n);if(!a?.SearchAcrossAccounts)throw new Error("Invalid response from server");const i=a.SearchAcrossAccounts;return{accountResults:i.accountResults.map(o=>({accountId:o.accountID,accountName:o.accountName,success:o.success,errorMessage:o.errorMessage,results:o.results.map(l=>({path:l.path,name:l.name,size:l.size,contentType:l.contentType,lastModified:new Date(l.lastModified),relevance:l.relevance,excerpt:l.excerpt,matchInFilename:l.matchInFilename,objectId:l.objectId})),totalMatches:o.totalMatches,hasMore:o.hasMore,nextPageToken:o.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(s){const n=s;return c.LogError(`Error searching across accounts: ${n}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}class de{static{g(this,"GraphQLIntegrationClient")}constructor(e){this._dataProvider=e}async DiscoverObjects(e){try{const t=u.gql`
|
|
1190
1190
|
query IntegrationDiscoverObjects($companyIntegrationID: String!) {
|
|
1191
1191
|
IntegrationDiscoverObjects(companyIntegrationID: $companyIntegrationID) {
|
|
1192
1192
|
Success
|
|
@@ -1199,7 +1199,7 @@
|
|
|
1199
1199
|
}
|
|
1200
1200
|
}
|
|
1201
1201
|
}
|
|
1202
|
-
`,s=(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationDiscoverObjects;if(!s)throw new Error("Invalid response from server");return{Success:s.Success,Message:s.Message,Data:s.Objects??[]}}catch(t){return this.handleError(t,[])}}async DiscoverFields(e,t){try{const r=
|
|
1202
|
+
`,s=(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationDiscoverObjects;if(!s)throw new Error("Invalid response from server");return{Success:s.Success,Message:s.Message,Data:s.Objects??[]}}catch(t){return this.handleError(t,[])}}async DiscoverFields(e,t){try{const r=u.gql`
|
|
1203
1203
|
query IntegrationDiscoverFields($companyIntegrationID: String!, $objectName: String!) {
|
|
1204
1204
|
IntegrationDiscoverFields(companyIntegrationID: $companyIntegrationID, objectName: $objectName) {
|
|
1205
1205
|
Success
|
|
@@ -1214,7 +1214,7 @@
|
|
|
1214
1214
|
}
|
|
1215
1215
|
}
|
|
1216
1216
|
}
|
|
1217
|
-
`,n=(await this._dataProvider.ExecuteGQL(r,{companyIntegrationID:e,objectName:t}))?.IntegrationDiscoverFields;if(!n)throw new Error("Invalid response from server");return{Success:n.Success,Message:n.Message,Data:n.Fields??[]}}catch(r){return this.handleError(r,[])}}async TestConnection(e){try{const t=
|
|
1217
|
+
`,n=(await this._dataProvider.ExecuteGQL(r,{companyIntegrationID:e,objectName:t}))?.IntegrationDiscoverFields;if(!n)throw new Error("Invalid response from server");return{Success:n.Success,Message:n.Message,Data:n.Fields??[]}}catch(r){return this.handleError(r,[])}}async TestConnection(e){try{const t=u.gql`
|
|
1218
1218
|
query IntegrationTestConnection($companyIntegrationID: String!) {
|
|
1219
1219
|
IntegrationTestConnection(companyIntegrationID: $companyIntegrationID) {
|
|
1220
1220
|
Success
|
|
@@ -1222,7 +1222,7 @@
|
|
|
1222
1222
|
ServerVersion
|
|
1223
1223
|
}
|
|
1224
1224
|
}
|
|
1225
|
-
`,s=(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationTestConnection;if(!s)throw new Error("Invalid response from server");return{Success:s.Success,Message:s.Message,ServerVersion:s.ServerVersion??null}}catch(t){const r=t;return
|
|
1225
|
+
`,s=(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationTestConnection;if(!s)throw new Error("Invalid response from server");return{Success:s.Success,Message:s.Message,ServerVersion:s.ServerVersion??null}}catch(t){const r=t;return c.LogError(`Error testing integration connection: ${r}`),{Success:!1,Message:`Error: ${r.message}`,ServerVersion:null}}}async SchemaPreview(e,t,r="sqlserver"){try{const s=u.gql`
|
|
1226
1226
|
query IntegrationSchemaPreview(
|
|
1227
1227
|
$companyIntegrationID: String!,
|
|
1228
1228
|
$objects: [SchemaPreviewObjectInput!]!,
|
|
@@ -1243,7 +1243,7 @@
|
|
|
1243
1243
|
Warnings
|
|
1244
1244
|
}
|
|
1245
1245
|
}
|
|
1246
|
-
`,a=(await this._dataProvider.ExecuteGQL(s,{companyIntegrationID:e,objects:t,platform:r}))?.IntegrationSchemaPreview;if(!a)throw new Error("Invalid response from server");return{Success:a.Success,Message:a.Message,Files:a.Files??[],Warnings:a.Warnings??[]}}catch(s){const n=s;return
|
|
1246
|
+
`,a=(await this._dataProvider.ExecuteGQL(s,{companyIntegrationID:e,objects:t,platform:r}))?.IntegrationSchemaPreview;if(!a)throw new Error("Invalid response from server");return{Success:a.Success,Message:a.Message,Files:a.Files??[],Warnings:a.Warnings??[]}}catch(s){const n=s;return c.LogError(`Error generating schema preview: ${n}`),{Success:!1,Message:`Error: ${n.message}`,Files:[],Warnings:[]}}}async PreviewData(e,t,r=5){try{const s=u.gql`
|
|
1247
1247
|
query IntegrationPreviewData(
|
|
1248
1248
|
$companyIntegrationID: String!,
|
|
1249
1249
|
$objectName: String!,
|
|
@@ -1261,7 +1261,7 @@
|
|
|
1261
1261
|
}
|
|
1262
1262
|
}
|
|
1263
1263
|
}
|
|
1264
|
-
`,a=(await this._dataProvider.ExecuteGQL(s,{companyIntegrationID:e,objectName:t,limit:r}))?.IntegrationPreviewData;if(!a)throw new Error("Invalid response from server");return{Success:a.Success,Message:a.Message,Records:a.Records??[]}}catch(s){const n=s;return
|
|
1264
|
+
`,a=(await this._dataProvider.ExecuteGQL(s,{companyIntegrationID:e,objectName:t,limit:r}))?.IntegrationPreviewData;if(!a)throw new Error("Invalid response from server");return{Success:a.Success,Message:a.Message,Records:a.Records??[]}}catch(s){const n=s;return c.LogError(`Error previewing integration data: ${n}`),{Success:!1,Message:`Error: ${n.message}`,Records:[]}}}async GetDefaultConfig(e){try{const t=u.gql`
|
|
1265
1265
|
query IntegrationGetDefaultConfig($companyIntegrationID: String!) {
|
|
1266
1266
|
IntegrationGetDefaultConfig(companyIntegrationID: $companyIntegrationID) {
|
|
1267
1267
|
Success
|
|
@@ -1280,5 +1280,70 @@
|
|
|
1280
1280
|
}
|
|
1281
1281
|
}
|
|
1282
1282
|
}
|
|
1283
|
-
`,s=(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationGetDefaultConfig;if(!s)throw new Error("Invalid response from server");return{Success:s.Success,Message:s.Message,DefaultSchemaName:s.DefaultSchemaName,DefaultObjects:s.DefaultObjects??[]}}catch(t){const r=t;return
|
|
1283
|
+
`,s=(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationGetDefaultConfig;if(!s)throw new Error("Invalid response from server");return{Success:s.Success,Message:s.Message,DefaultSchemaName:s.DefaultSchemaName,DefaultObjects:s.DefaultObjects??[]}}catch(t){const r=t;return c.LogError(`Error getting default config: ${r}`),{Success:!1,Message:`Error: ${r.message}`}}}async CreateConnection(e){try{const t=u.gql`mutation IntegrationCreateConnection($input: CreateConnectionInput!) {
|
|
1284
|
+
IntegrationCreateConnection(input: $input) { Success Message CompanyIntegrationID CredentialID }
|
|
1285
|
+
}`;return(await this._dataProvider.ExecuteGQL(t,{input:e}))?.IntegrationCreateConnection??{Success:!1,Message:"No response"}}catch(t){return{Success:!1,Message:t.message}}}async UpdateConnection(e,t,r,s){try{const n=u.gql`mutation IntegrationUpdateConnection(
|
|
1286
|
+
$companyIntegrationID: String!, $credentialValues: String, $configuration: String, $externalSystemID: String
|
|
1287
|
+
) {
|
|
1288
|
+
IntegrationUpdateConnection(companyIntegrationID: $companyIntegrationID, credentialValues: $credentialValues, configuration: $configuration, externalSystemID: $externalSystemID) { Success Message }
|
|
1289
|
+
}`;return(await this._dataProvider.ExecuteGQL(n,{companyIntegrationID:e,credentialValues:t,configuration:r,externalSystemID:s}))?.IntegrationUpdateConnection??{Success:!1,Message:"No response"}}catch(n){return{Success:!1,Message:n.message}}}async DeactivateConnection(e){try{const t=u.gql`mutation IntegrationDeactivateConnection($companyIntegrationID: String!) {
|
|
1290
|
+
IntegrationDeactivateConnection(companyIntegrationID: $companyIntegrationID) { Success Message }
|
|
1291
|
+
}`;return(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationDeactivateConnection??{Success:!1,Message:"No response"}}catch(t){return{Success:!1,Message:t.message}}}async CreateEntityMaps(e,t){try{const r=u.gql`mutation IntegrationCreateEntityMaps($companyIntegrationID: String!, $entityMaps: [EntityMapInput!]!) {
|
|
1292
|
+
IntegrationCreateEntityMaps(companyIntegrationID: $companyIntegrationID, entityMaps: $entityMaps) {
|
|
1293
|
+
Success Message Created { EntityMapID ExternalObjectName FieldMapCount }
|
|
1294
|
+
}
|
|
1295
|
+
}`;return(await this._dataProvider.ExecuteGQL(r,{companyIntegrationID:e,entityMaps:t}))?.IntegrationCreateEntityMaps??{Success:!1,Message:"No response"}}catch(r){return{Success:!1,Message:r.message}}}async ListEntityMaps(e){try{const t=u.gql`query IntegrationListEntityMaps($companyIntegrationID: String!) {
|
|
1296
|
+
IntegrationListEntityMaps(companyIntegrationID: $companyIntegrationID) { Success Message EntityMaps { ID Entity ExternalObjectName SyncDirection Priority Status } }
|
|
1297
|
+
}`;return(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationListEntityMaps??{Success:!1,Message:"No response"}}catch(t){return{Success:!1,Message:t.message}}}async UpdateEntityMaps(e){try{const t=u.gql`mutation IntegrationUpdateEntityMaps($updates: [EntityMapUpdateInput!]!) {
|
|
1298
|
+
IntegrationUpdateEntityMaps(updates: $updates) { Success Message }
|
|
1299
|
+
}`;return(await this._dataProvider.ExecuteGQL(t,{updates:e}))?.IntegrationUpdateEntityMaps??{Success:!1,Message:"No response"}}catch(t){return{Success:!1,Message:t.message}}}async DeleteEntityMaps(e){try{const t=u.gql`mutation IntegrationDeleteEntityMaps($entityMapIDs: [String!]!) {
|
|
1300
|
+
IntegrationDeleteEntityMaps(entityMapIDs: $entityMapIDs) { Success Message }
|
|
1301
|
+
}`;return(await this._dataProvider.ExecuteGQL(t,{entityMapIDs:e}))?.IntegrationDeleteEntityMaps??{Success:!1,Message:"No response"}}catch(t){return{Success:!1,Message:t.message}}}async ApplySchema(e,t,r="sqlserver",s=!1,n=!1){try{const a=u.gql`mutation IntegrationApplySchema(
|
|
1302
|
+
$companyIntegrationID: String!, $objects: [SchemaPreviewObjectInput!]!, $platform: String!, $skipGitCommit: Boolean!, $skipRestart: Boolean!
|
|
1303
|
+
) {
|
|
1304
|
+
IntegrationApplySchema(companyIntegrationID: $companyIntegrationID, objects: $objects, platform: $platform, skipGitCommit: $skipGitCommit, skipRestart: $skipRestart) {
|
|
1305
|
+
Success Message Steps { Name Status DurationMs Message } MigrationFilePath APIRestarted GitCommitSuccess
|
|
1306
|
+
}
|
|
1307
|
+
}`;return(await this._dataProvider.ExecuteGQL(a,{companyIntegrationID:e,objects:t,platform:r,skipGitCommit:s,skipRestart:n}))?.IntegrationApplySchema??{Success:!1,Message:"No response"}}catch(a){return{Success:!1,Message:a.message}}}async ApplySchemaBatch(e,t="sqlserver",r=!1,s=!1){try{const n=u.gql`mutation IntegrationApplySchemaBatch(
|
|
1308
|
+
$items: [ApplySchemaBatchItemInput!]!, $platform: String!, $skipGitCommit: Boolean!, $skipRestart: Boolean!
|
|
1309
|
+
) {
|
|
1310
|
+
IntegrationApplySchemaBatch(items: $items, platform: $platform, skipGitCommit: $skipGitCommit, skipRestart: $skipRestart) {
|
|
1311
|
+
Success Message
|
|
1312
|
+
Items { CompanyIntegrationID Success Message Warnings }
|
|
1313
|
+
Steps { Name Status DurationMs Message }
|
|
1314
|
+
GitCommitSuccess APIRestarted
|
|
1315
|
+
}
|
|
1316
|
+
}`;return(await this._dataProvider.ExecuteGQL(n,{items:e,platform:t,skipGitCommit:r,skipRestart:s}))?.IntegrationApplySchemaBatch??{Success:!1,Message:"No response"}}catch(n){return{Success:!1,Message:n.message}}}async ApplyAll(e,t,r="sqlserver",s=!1,n=!1){try{const a=u.gql`mutation IntegrationApplyAll(
|
|
1317
|
+
$input: ApplyAllInput!, $platform: String!, $skipGitCommit: Boolean!, $skipRestart: Boolean!
|
|
1318
|
+
) {
|
|
1319
|
+
IntegrationApplyAll(input: $input, platform: $platform, skipGitCommit: $skipGitCommit, skipRestart: $skipRestart) {
|
|
1320
|
+
Success Message
|
|
1321
|
+
Steps { Name Status DurationMs Message }
|
|
1322
|
+
EntityMapsCreated { SourceObjectName EntityName EntityMapID FieldMapCount }
|
|
1323
|
+
SyncRunID GitCommitSuccess APIRestarted Warnings
|
|
1324
|
+
}
|
|
1325
|
+
}`,i={CompanyIntegrationID:e,SourceObjectNames:t};return(await this._dataProvider.ExecuteGQL(a,{input:i,platform:r,skipGitCommit:s,skipRestart:n}))?.IntegrationApplyAll??{Success:!1,Message:"No response"}}catch(a){return{Success:!1,Message:a.message}}}async StartSync(e,t){try{const r=u.gql`mutation IntegrationStartSync($companyIntegrationID: String!, $webhookURL: String) {
|
|
1326
|
+
IntegrationStartSync(companyIntegrationID: $companyIntegrationID, webhookURL: $webhookURL) { Success Message RunID }
|
|
1327
|
+
}`;return(await this._dataProvider.ExecuteGQL(r,{companyIntegrationID:e,webhookURL:t}))?.IntegrationStartSync??{Success:!1,Message:"No response"}}catch(r){return{Success:!1,Message:r.message}}}async CancelSync(e){try{const t=u.gql`mutation IntegrationCancelSync($runID: String!) {
|
|
1328
|
+
IntegrationCancelSync(runID: $runID) { Success Message }
|
|
1329
|
+
}`;return(await this._dataProvider.ExecuteGQL(t,{runID:e}))?.IntegrationCancelSync??{Success:!1,Message:"No response"}}catch(t){return{Success:!1,Message:t.message}}}async CreateSchedule(e){try{const t=u.gql`mutation IntegrationCreateSchedule($input: CreateScheduleInput!) {
|
|
1330
|
+
IntegrationCreateSchedule(input: $input) { Success Message ScheduledJobID }
|
|
1331
|
+
}`;return(await this._dataProvider.ExecuteGQL(t,{input:e}))?.IntegrationCreateSchedule??{Success:!1,Message:"No response"}}catch(t){return{Success:!1,Message:t.message}}}async UpdateSchedule(e,t,r,s){try{const n=u.gql`mutation IntegrationUpdateSchedule($scheduledJobID: String!, $cronExpression: String, $timezone: String, $name: String) {
|
|
1332
|
+
IntegrationUpdateSchedule(scheduledJobID: $scheduledJobID, cronExpression: $cronExpression, timezone: $timezone, name: $name) { Success Message }
|
|
1333
|
+
}`;return(await this._dataProvider.ExecuteGQL(n,{scheduledJobID:e,cronExpression:t,timezone:r,name:s}))?.IntegrationUpdateSchedule??{Success:!1,Message:"No response"}}catch(n){return{Success:!1,Message:n.message}}}async ToggleSchedule(e,t){try{const r=u.gql`mutation IntegrationToggleSchedule($scheduledJobID: String!, $enabled: Boolean!) {
|
|
1334
|
+
IntegrationToggleSchedule(scheduledJobID: $scheduledJobID, enabled: $enabled) { Success Message }
|
|
1335
|
+
}`;return(await this._dataProvider.ExecuteGQL(r,{scheduledJobID:e,enabled:t}))?.IntegrationToggleSchedule??{Success:!1,Message:"No response"}}catch(r){return{Success:!1,Message:r.message}}}async DeleteSchedule(e,t){try{const r=u.gql`mutation IntegrationDeleteSchedule($scheduledJobID: String!, $companyIntegrationID: String) {
|
|
1336
|
+
IntegrationDeleteSchedule(scheduledJobID: $scheduledJobID, companyIntegrationID: $companyIntegrationID) { Success Message }
|
|
1337
|
+
}`;return(await this._dataProvider.ExecuteGQL(r,{scheduledJobID:e,companyIntegrationID:t}))?.IntegrationDeleteSchedule??{Success:!1,Message:"No response"}}catch(r){return{Success:!1,Message:r.message}}}async GetStatus(e){try{const t=u.gql`query IntegrationGetStatus($companyIntegrationID: String!) {
|
|
1338
|
+
IntegrationGetStatus(companyIntegrationID: $companyIntegrationID) {
|
|
1339
|
+
Success Message IsActive IntegrationName TotalEntityMaps ActiveEntityMaps
|
|
1340
|
+
LastRunStatus LastRunStartedAt LastRunEndedAt ScheduleEnabled
|
|
1341
|
+
}
|
|
1342
|
+
}`;return(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationGetStatus??{Success:!1,Message:"No response"}}catch(t){return{Success:!1,Message:t.message}}}async GetSyncHistory(e,t=20){try{const r=u.gql`query IntegrationGetSyncHistory($companyIntegrationID: String!, $limit: Float!) {
|
|
1343
|
+
IntegrationGetSyncHistory(companyIntegrationID: $companyIntegrationID, limit: $limit) { Success Message Runs { ID Status StartedAt EndedAt TotalRecords RunByUserID } }
|
|
1344
|
+
}`;return(await this._dataProvider.ExecuteGQL(r,{companyIntegrationID:e,limit:t}))?.IntegrationGetSyncHistory??{Success:!1,Message:"No response"}}catch(r){return{Success:!1,Message:r.message}}}async GetConnectorCapabilities(e){try{const t=u.gql`query IntegrationGetConnectorCapabilities($companyIntegrationID: String!) {
|
|
1345
|
+
IntegrationGetConnectorCapabilities(companyIntegrationID: $companyIntegrationID) {
|
|
1346
|
+
Success Message SupportsGet SupportsCreate SupportsUpdate SupportsDelete SupportsSearch
|
|
1347
|
+
}
|
|
1348
|
+
}`;return(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationGetConnectorCapabilities??{Success:!1,Message:"No response"}}catch(t){return{Success:!1,Message:t.message}}}handleError(e,t){const r=e;return c.LogError(`Error in integration discovery: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Data:t}}}Object.defineProperty(exports,"gql",{enumerable:!0,get:g(function(){return u.gql},"get")}),exports.ActionItemInput=X,exports.ActionItemOutput=Z,exports.BrowserIndexedDBStorageProvider=F,exports.BrowserStorageProviderBase=L,exports.FieldMapper=v,exports.FireAndForgetHelper=P,exports.GetDataOutput=te,exports.GraphQLAIClient=x,exports.GraphQLActionClient=ae,exports.GraphQLComponentRegistryClient=ce,exports.GraphQLDataProvider=S,exports.GraphQLEncryptionClient=oe,exports.GraphQLFileStorageClient=le,exports.GraphQLIntegrationClient=de,exports.GraphQLProviderConfigData=K,exports.GraphQLSystemUserClient=ee,exports.GraphQLTestingClient=ie,exports.GraphQLTransactionGroup=M,exports.GraphQLVersionHistoryClient=ue,exports.RoleInput=W,exports.RolesAndUsersInput=z,exports.SimpleRemoteEntity=se,exports.SimpleRemoteEntityField=ne,exports.SimpleRemoteEntityOutput=re,exports.SyncDataAction=U,exports.SyncDataResult=Y,exports.SyncRolesAndUsersResult=J,exports.UserInput=H,exports.setupGraphQLClient=j;
|
|
1284
1349
|
//# sourceMappingURL=index.cjs.map
|