@memberjunction/graphql-dataprovider 6.1.0-edge.1 → 6.1.0-edge.3
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/LICENSE +180 -4
- package/README.md +1 -1
- package/dist/index.cjs +214 -220
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +357 -34
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +357 -34
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +248 -254
- package/dist/index.mjs.map +1 -1
- package/package.json +9 -9
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var X=Object.defineProperty;var d=(g,e)=>X(g,"name",{value:e,configurable:!0});var u=require("graphql-request"),c=require("@memberjunction/core"),D=require("@memberjunction/global"),_=require("@memberjunction/core-entities"),$=require("rxjs"),Y=require("graphql-ws"),Z=require("uuid"),ee=require("@tempfix/idb");class b{static{d(this,"FieldMapper")}static{this.DB_PREFIX="__mj_"}static{this.GQL_PREFIX="_mj__"}constructor(){}MapFields(e){if(e)for(const t in e){const r=this.MapFieldName(t);r!==t&&(e[r]=e[t],delete e[t])}return e}MapFieldName(e){return e.startsWith(b.DB_PREFIX)?b.GQL_PREFIX+e.substring(b.DB_PREFIX.length):e}ReverseMapFieldName(e){return e.startsWith(b.GQL_PREFIX)?b.DB_PREFIX+e.substring(b.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 V extends c.TransactionGroupBase{static{d(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=u.gql`
|
|
2
2
|
mutation ExecuteTransactionGroup($group: TransactionInputType!) {
|
|
3
3
|
ExecuteTransactionGroup(group: $group) {
|
|
4
4
|
Success
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
ResultsJSON
|
|
7
7
|
}
|
|
8
8
|
}
|
|
9
|
-
`,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const r={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const n=s.ExecuteTransactionGroup,
|
|
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=n.Success===!0,i=[];for(let o=0;o<this.PendingTransactions.length;o++){const y=n.ResultsJSON[o],l=D.SafeJSONParse(y),S=this.PendingTransactions[o];i.push(new c.TransactionResult(S,l,a&&l!==null))}return i}else throw new Error("Failed to execute transaction group")}}const te=720*1e3,re=6;class w{static{d(this,"FireAndForgetHelper")}static async Execute(e){const t=e.operationLabel??e.mutationFieldName;if(!(typeof e.dataProvider.PushStatusUpdates=="function"))return w.executeSynchronously(e);const s=e.timeoutMs??te,n=e.maxStallReconciles??re;let a,i=!1,o=0;const{promise:y,resolve:l,reject:S}=w.createCompletionPromise(),h=d(E=>{i||(i=!0,R.clear(),E())},"finish"),m=d(E=>h(()=>l(E)),"settleResolve"),p=d(E=>h(()=>S(E)),"settleReject"),I=d(async()=>{if(i)return;if(!e.onStall){p(new Error(w.timeoutMessage(e.timeoutErrorMessage,s)));return}let E;try{c.LogStatus(`[FireAndForget:${t}] Idle window elapsed, reconciling against server run record`),E=await e.onStall()}catch(v){p(v);return}i||(E==="continue"?++o>n?p(new Error(`The operation is still reported as running but no signal has arrived after ${o} checks. Please refresh the page to check the latest status.`)):R.reset():"resolve"in E?(c.LogStatus(`[FireAndForget:${t}] Reconciliation recovered a completed run`),m(E.resolve)):p(E.reject))},"onStall"),R=w.createIdleTimer(s,()=>{I()});try{R.reset(),a=w.subscribeToPubSub(e,{onActivity:d(()=>{o=0,R.reset()},"onActivity"),onCompletion:d(v=>m(v),"onCompletion"),onStreamEnd:d(()=>{I()},"onStreamEnd")});const E=await w.executeMutation(e);if(!e.validateAck(E)){R.clear();const v=E?.errorMessage??"Server rejected the request";return c.LogError(`[FireAndForget:${t}] Server rejected: ${v}`),e.createErrorResult(v)}return c.LogStatus(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await y}catch(E){const v=E;throw c.LogError(`[FireAndForget:${t}] Error: ${v.message}`),E}finally{R.clear(),a&&a.unsubscribe()}}static createCompletionPromise(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}static createIdleTimer(e,t){let r;return{reset:d(()=>{r&&clearTimeout(r),r=setTimeout(t,e)},"reset"),clear:d(()=>{r&&clearTimeout(r),r=void 0},"clear")}}static timeoutMessage(e,t){const r=Math.round(t/6e4);return e??`The operation may still be running on the server but the client received no updates for ${r} minutes. Please refresh the page to check the latest status.`}static subscribeToPubSub(e,t){const r=e.dataProvider.sessionId,s=e.operationLabel??e.mutationFieldName;return e.dataProvider.PushStatusUpdates(r).subscribe({next:d(n=>{t.onActivity();try{const a=JSON.parse(n);e.onMessage&&e.onMessage(a),e.isCompletionEvent(a)&&(c.LogStatus(`[FireAndForget:${s}] Completion event received`),t.onCompletion(e.extractResult(a)))}catch(a){console.error(`[FireAndForget:${s}] Failed to parse PubSub message:`,a)}},"next"),error:d(()=>t.onStreamEnd(),"error"),complete:d(()=>t.onStreamEnd(),"complete")})}static async executeMutation(e){return(await e.dataProvider.ExecuteGQL(e.mutation,e.variables))[e.mutationFieldName]}static async executeSynchronously(e){const t=e.operationLabel??e.mutationFieldName;c.LogStatus(`[FireAndForget:${t}] Provider has no PushStatusUpdates channel \u2014 running synchronously (fireAndForget disabled)`);const r={...e.variables,fireAndForget:!1},n=(await e.dataProvider.ExecuteGQL(e.mutation,r))?.[e.mutationFieldName];return n?e.extractSyncResult?(c.LogStatus(`[FireAndForget:${t}] Synchronous execution completed`),e.extractSyncResult(n)):e.createErrorResult(`${t} cannot run on this data provider: it has no PushStatusUpdates channel and no synchronous result extractor is configured for this operation.`):(c.LogError(`[FireAndForget:${t}] Synchronous execution returned no '${e.mutationFieldName}' payload`),e.createErrorResult(`Server returned no '${e.mutationFieldName}' result for ${t}`))}}class O{static{d(this,"GraphQLAIClient")}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=u.gql`
|
|
10
10
|
mutation RunAIPrompt(
|
|
11
11
|
$promptId: String!,
|
|
12
12
|
$data: String,
|
|
@@ -65,7 +65,7 @@
|
|
|
65
65
|
chatResult
|
|
66
66
|
}
|
|
67
67
|
}
|
|
68
|
-
`,r=this.preparePromptVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(s)}catch(t){return this.handlePromptError(t)}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,n;try{t.parsedResult&&(r=D.CleanAndParseJSON(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(n=JSON.parse(t.chatResult))}catch{n=t.chatResult}return{success:t.success,output:t.output,parsedResult:r,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:s,chatResult:n}}handlePromptError(e){const t=e;return c.LogError(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){try{const s=this.buildRunAIAgentMutation(),n=this.prepareAgentVariables(e,t,r);n.fireAndForget=!0;const
|
|
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=D.CleanAndParseJSON(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(n=JSON.parse(t.chatResult))}catch{n=t.chatResult}return{success:t.success,output:t.output,parsedResult:r,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:s,chatResult:n}}handlePromptError(e){const t=e;return c.LogError(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){try{const s=this.buildRunAIAgentMutation(),n=this.prepareAgentVariables(e,t,r);n.fireAndForget=!0;const a={};return await w.Execute({dataProvider:this._dataProvider,mutation:s,variables:n,mutationFieldName:"RunAIAgent",operationLabel:"RunAIAgent",validateAck:d(i=>i?.success===!0,"validateAck"),isCompletionEvent:d(i=>this.isAgentCompletionEvent(i),"isCompletionEvent"),extractResult:d(i=>this.extractAgentResult(i),"extractResult"),extractSyncResult:d(i=>this.extractAgentResultFromAck(i),"extractSyncResult"),onMessage:d(i=>{this.captureAgentRunId(i,a),e.onProgress&&this.forwardAgentProgress(i,e.onProgress)},"onMessage"),onStall:d(()=>this.reconcileAgentRun(a.id?`ID='${a.id}'`:void 0),"onStall"),createErrorResult:d(i=>this.createAgentErrorResult(i),"createErrorResult")})}catch(s){return this.handleAgentError(s)}}buildRunAIAgentMutation(){return u.gql`
|
|
69
69
|
mutation RunAIAgent(
|
|
70
70
|
$agentId: String!,
|
|
71
71
|
$messages: String!,
|
|
@@ -83,7 +83,8 @@
|
|
|
83
83
|
$sourceArtifactVersionId: String,
|
|
84
84
|
$fireAndForget: Boolean,
|
|
85
85
|
$planMode: Boolean,
|
|
86
|
-
$requestedSkillIDs: [String!]
|
|
86
|
+
$requestedSkillIDs: [String!],
|
|
87
|
+
$taskGraphDebug: String
|
|
87
88
|
) {
|
|
88
89
|
RunAIAgent(
|
|
89
90
|
agentId: $agentId,
|
|
@@ -102,7 +103,8 @@
|
|
|
102
103
|
sourceArtifactVersionId: $sourceArtifactVersionId,
|
|
103
104
|
fireAndForget: $fireAndForget,
|
|
104
105
|
planMode: $planMode,
|
|
105
|
-
requestedSkillIDs: $requestedSkillIDs
|
|
106
|
+
requestedSkillIDs: $requestedSkillIDs,
|
|
107
|
+
taskGraphDebug: $taskGraphDebug
|
|
106
108
|
) {
|
|
107
109
|
success
|
|
108
110
|
errorMessage
|
|
@@ -110,7 +112,7 @@
|
|
|
110
112
|
result
|
|
111
113
|
}
|
|
112
114
|
}
|
|
113
|
-
`}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),t!==void 0&&(s.sourceArtifactId=t),r!==void 0&&(s.sourceArtifactVersionId=r),e.planMode!==void 0&&(s.planMode=e.planMode),e.requestedSkillIDs!==void 0&&(s.requestedSkillIDs=e.requestedSkillIDs),s}processAgentResult(e){return D.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
|
|
115
|
+
`}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),t!==void 0&&(s.sourceArtifactId=t),r!==void 0&&(s.sourceArtifactVersionId=r),e.planMode!==void 0&&(s.planMode=e.planMode),e.requestedSkillIDs!==void 0&&(s.requestedSkillIDs=e.requestedSkillIDs),e.taskGraphDebug!==void 0&&(s.taskGraphDebug=JSON.stringify(e.taskGraphDebug)),s}processAgentResult(e){return D.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 w.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunAIAgentFromConversationDetail",operationLabel:"RunAIAgentFromConversationDetail",validateAck:d(s=>s?.success===!0,"validateAck"),isCompletionEvent:d(s=>this.isConversationDetailCompletionEvent(s,e.conversationDetailId),"isCompletionEvent"),extractResult:d(s=>this.extractAgentResult(s),"extractResult"),extractSyncResult:d(s=>this.extractAgentResultFromAck(s),"extractSyncResult"),onMessage:e.onProgress?s=>this.forwardConversationDetailProgress(s,e.onProgress):void 0,onStall:d(()=>this.reconcileAgentRun(`ConversationDetailID='${e.conversationDetailId}'`),"onStall"),createErrorResult:d(s=>this.createAgentErrorResult(s),"createErrorResult")})}catch(t){return this.handleAgentError(t)}}buildConversationDetailMutation(){return u.gql`
|
|
114
116
|
mutation RunAIAgentFromConversationDetail(
|
|
115
117
|
$conversationDetailId: String!,
|
|
116
118
|
$agentId: String!,
|
|
@@ -176,7 +178,7 @@
|
|
|
176
178
|
executionTimeMs
|
|
177
179
|
}
|
|
178
180
|
}
|
|
179
|
-
`,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.ExecuteSimplePrompt)throw new Error("Invalid response from server");const n=s.ExecuteSimplePrompt;let
|
|
181
|
+
`,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`
|
|
180
182
|
mutation EmbedText(
|
|
181
183
|
$textToEmbed: [String!]!,
|
|
182
184
|
$modelSize: String!
|
|
@@ -191,7 +193,7 @@
|
|
|
191
193
|
error
|
|
192
194
|
}
|
|
193
195
|
}
|
|
194
|
-
`,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this._dataProvider.ExecuteGQL(t,s);if(!n?.EmbedText)throw new Error("Invalid response from server");const
|
|
196
|
+
`,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this._dataProvider.ExecuteGQL(t,s);if(!n?.EmbedText)throw new Error("Invalid response from server");const a=n.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?a.embeddings:a.embeddings[0],modelName:a.modelName,vectorDimensions:a.vectorDimensions,error:a.error}}catch(t){const r=t;return c.LogError(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}async RunAutotagPipeline(e){try{const t=u.gql`
|
|
195
197
|
mutation RunAutotagPipeline($contentSourceIDs: [String!], $forceReprocess: Boolean) {
|
|
196
198
|
RunAutotagPipeline(contentSourceIDs: $contentSourceIDs, forceReprocess: $forceReprocess) {
|
|
197
199
|
Success
|
|
@@ -305,45 +307,47 @@
|
|
|
305
307
|
}
|
|
306
308
|
}
|
|
307
309
|
}
|
|
308
|
-
`,r={entityDocumentID:e.entityDocumentID};e.maxRecords!==void 0&&(r.maxRecords=e.maxRecords),e.filter!==void 0&&(r.filter=e.filter);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.FetchEntityVectors)throw new Error("Invalid response from server");return s.FetchEntityVectors}catch(t){const r=t;return c.LogError("GraphQLAIClient.FetchEntityVectors failed",void 0,r),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,ErrorMessage:r.message||"Unknown error"}}}}const
|
|
310
|
+
`,r={entityDocumentID:e.entityDocumentID};e.maxRecords!==void 0&&(r.maxRecords=e.maxRecords),e.filter!==void 0&&(r.filter=e.filter);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.FetchEntityVectors)throw new Error("Invalid response from server");return s.FetchEntityVectors}catch(t){const r=t;return c.LogError("GraphQLAIClient.FetchEntityVectors failed",void 0,r),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,ErrorMessage:r.message||"Unknown error"}}}}const A="6.1.0-edge.3",P="default";class k{static{d(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}get SharesReferences(){return!0}getCategoryMap(e){const t=e||P;let r=this._storage.get(t);return r||(r=new Map,this._storage.set(t,r)),r}async GetItem(e,t){const s=this.getCategoryMap(t||P).get(e);return s===void 0?null:s}async GetItems(e,t){const r=new Map;if(e.length===0)return r;const s=this.getCategoryMap(t||P);for(const n of new Set(e)){const a=s.get(n);r.set(n,a===void 0?null:a)}return r}async SetItem(e,t,r){this.getCategoryMap(r||P).set(e,t)}async Remove(e,t){this.getCategoryMap(t||P).delete(e)}async ClearCategory(e){const t=e||P;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||P);return t?Array.from(t.keys()):[]}}const se="MJ_Metadata",ne=0;function ae(){try{const g=A.split("."),e=parseInt(g[0],10),t=parseInt(g[1],10);if(!Number.isFinite(e)||!Number.isFinite(t))throw new Error(`Could not parse major.minor from version "${A}"`);return e*1e3+t+ne}catch(g){return c.LogErrorEx({error:g,message:"Failed to derive IDB version from PACKAGE_VERSION; using fallback 99999"}),99999}}d(ae,"computeIdbVersion");const oe=ae(),K=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"];class B extends k{static{d(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=ee.openDB(se,oe,{upgrade:d((e,t,r)=>{try{c.LogStatus(`[IDBCache] Upgrading IndexedDB schema v${t} \u2192 v${r} (package ${A}). Dropping all stores; caches will repopulate on first use.`);for(const s of Array.from(e.objectStoreNames))e.deleteObjectStore(s);for(const s of K)e.objectStoreNames.contains(s)||e.createObjectStore(s)}catch(s){c.LogErrorEx({error:s,message:s?.message})}},"upgrade"),blocked:d((e,t)=>{c.LogStatus(`[IDBCache] Upgrade from v${e} to v${t} blocked by another tab. Close other tabs to allow the upgrade to proceed.`)},"blocked")}),this.dbPromise.then(e=>{this._dbReady=!0,e.onversionchange=()=>{c.LogStatus("[IDBCache] DB schema upgraded in another tab \u2014 closing local connection."),e.close(),this._dbReady=!1}}).catch(e=>{c.LogErrorEx({error:e,message:"IndexedDB initialization failed: "+e?.message})})}get SharesReferences(){return!1}get IsReady(){return this._dbReady}isKnownCategory(e){const t=`mj:${e}`;return K.includes(t)}getStoreName(e){const t=e||P;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||P;return this.isKnownCategory(r)?e:`[${r}]:${e}`}async SetItem(e,t,r){try{const s=await this.dbPromise,n=this.getStoreName(r),a=this.getStoreKey(e,r),i=s.transaction(n,"readwrite");await i.objectStore(n).put(t,a),await i.done}catch(s){c.LogErrorEx({error:s,message:s?.message})}}async GetItem(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t),a=await r.transaction(s).objectStore(s).get(n);return a===void 0?null:a}catch(r){return c.LogErrorEx({error:r,message:r?.message}),null}}async GetItems(e,t){const r=new Map;if(e.length===0)return r;try{const s=await this.dbPromise,n=this.getStoreName(t),a=Array.from(new Set(e)),i=a.map(h=>this.getStoreKey(h,t)),o=s.transaction(n,"readonly"),y=o.objectStore(n),l=i.map(h=>y.get(h)),S=await Promise.all(l);await o.done;for(let h=0;h<a.length;h++){const m=S[h];r.set(a[h],m===void 0?null:m)}return r}catch(s){c.LogErrorEx({error:s,message:s?.message});for(const n of new Set(e))r.set(n,null);return r}}async Remove(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t),a=r.transaction(s,"readwrite");await a.objectStore(s).delete(n),await a.done}catch(r){c.LogErrorEx({error:r,message:r?.message})}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||P,s=this.getStoreName(e);if(this.isKnownCategory(r)){const n=t.transaction(s,"readwrite");await n.objectStore(s).clear(),await n.done}else{const n=`[${r}]:`,a=t.transaction("mj:default","readwrite"),i=a.objectStore("mj:default"),o=await i.getAllKeys();for(const y of o)typeof y=="string"&&y.startsWith(n)&&await i.delete(y);await a.done}}catch(t){c.LogErrorEx({error:t,message:t?.message})}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||P,s=this.getStoreName(e),i=await t.transaction(s,"readonly").objectStore(s).getAllKeys();if(this.isKnownCategory(r))return i.map(y=>String(y));const o=`[${r}]:`;return i.map(y=>String(y)).filter(y=>y.startsWith(o)).map(y=>y.slice(o.length))}catch(t){return c.LogErrorEx({error:t,message:t?.message}),[]}}}class x extends Error{static{d(this,"SafeGraphQLError")}constructor(e){super(e.message),this.name=e.name,this.response={status:e.status,errors:e.errors},this.request={query:e.query},this.Code=e.code,this.VariableShape=e.variableShape,this.stack=e.stackFrames?`${e.name}: ${e.message}
|
|
311
|
+
${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}d(j,"ToSafeGraphQLError");const ie=3,ce=25;function F(g,e=0){if(g===null)return"null";if(g===void 0)return"undefined";if(Array.isArray(g))return g.length===0?"array(empty)":`array(${g.length} \xD7 ${ue(F(g[0],e+1))})`;if(typeof g=="object"){if(e>=ie)return"object(\u2026)";const t=Object.keys(g);if(t.length>ce)return`object(${t.length} keys)`;const r={};for(const s of t)r[s]=F(g[s],e+1);return r}return typeof g=="string"?g.length===0?"string(empty)":"string":typeof g}d(F,"describeShape");function ue(g){return typeof g=="string"?g:"object"}d(ue,"typeOf");function le(g){const e=g.indexOf(`
|
|
312
|
+
at `);return e===-1?"":g.slice(e+1)}d(le,"stripStackHeader");function de(g,e){const t=g?.[0]?.message;return typeof t=="string"&&t.length>0?t:`GraphQL Error (Code: ${String(e??"unknown")})`}d(de,"deriveMessage");function ge(g){if(Array.isArray(g))return g.map(e=>{const t=e??{};return{message:typeof t.message=="string"?t.message:void 0,path:Array.isArray(t.path)?t.path:void 0,extensions:t.extensions&&typeof t.extensions=="object"?t.extensions:void 0}})}d(ge,"extractErrors");function G(g,e=!1){if(!g||typeof g!="object")return{name:typeof g,message:"Non-object value thrown; contents withheld",variables:"[REDACTED]"};const t=g,r=typeof t.response?.status=="number"?t.response.status:void 0,s=ge(t.response?.errors),n=s?.[0]?.extensions?.code;return{name:typeof t.name=="string"?t.name:"Error",message:de(s,r),status:r,errors:s,code:typeof n=="string"?n:void 0,query:typeof t.request?.query=="string"?t.request.query:void 0,stackFrames:typeof t.stack=="string"?le(t.stack):void 0,variables:e?t.request?.variables:"[REDACTED]",variableShape:t.request?.variables===void 0?void 0:F(t.request.variables)}}d(G,"SanitizeGraphQLError");const L=new b,ye=u.gql`subscription RemoteOperationProgress($channelId: ID!) {
|
|
309
313
|
RemoteOperationProgress(channelId: $channelId) {
|
|
310
314
|
ChannelId
|
|
311
315
|
ProgressJSON
|
|
312
316
|
}
|
|
313
|
-
}`;class
|
|
317
|
+
}`;class me extends c.ProviderConfigDataBase{static{d(this,"GraphQLProviderConfigData")}get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get MJAPIKey(){return this.Data.MJAPIKey}set MJAPIKey(e){this.Data.MJAPIKey=e}get UserAPIKey(){return this.Data.UserAPIKey}set UserAPIKey(e){this.Data.UserAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get LogVariableValues(){return this.Data.LogVariableValues===!0}set LogVariableValues(e){this.Data.LogVariableValues=e}get RefreshTokenFunction(){return this.Data.RefreshFunction}get OnAuthenticationError(){return this.Data.OnAuthenticationError}set OnAuthenticationError(e){this.Data.OnAuthenticationError=e}constructor(e,t,r,s,n,a,i,o,y,l){super({Token:e,URL:t,WSURL:r,MJAPIKey:o,UserAPIKey:y,RefreshTokenFunction:s,OnAuthenticationError:l},n,a,i)}}class f extends c.ProviderBase{static{d(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._dynamicHeaders=new Map,this._innerCurrentUserQueryString=`CurrentUser {
|
|
314
318
|
${this.userInfoString()}
|
|
315
|
-
|
|
319
|
+
Roles {
|
|
316
320
|
${this.userRoleInfoString()}
|
|
317
321
|
}
|
|
318
322
|
}
|
|
319
323
|
`,this._currentUserQuery=u.gql`query CurrentUserAndRoles {
|
|
320
324
|
${this._innerCurrentUserQueryString}
|
|
321
325
|
CurrentUserTenantContext
|
|
322
|
-
}`,this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject=new
|
|
326
|
+
}`,this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject=new $.BehaviorSubject("unknown"),this._isDisposingSocketIntentionally=!1,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=1800*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=300*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=600*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,this._taskGraphFrameStreams=new Map,this._cacheInvalidationSubscription=null;const e=D.GetGlobalObjectStore();if(e&&e[f._globalStoreKey])return e[f._globalStoreKey];e&&(e[f._globalStoreKey]=this)}static{this.VerboseCacheInvalidationLogging=!1}static{this._globalStoreKey="___SINGLETON__GraphQLDataProvider"}static get Instance(){const e=D.GetGlobalObjectStore();return e?e[f._globalStoreKey]:void 0}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new O(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 Z.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)):(f.Instance._configData=e,f.Instance._sessionId===void 0&&(f.Instance._sessionId=await this.GetPreferredUUID(s)),f.Instance._client||(f.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,f.Instance._sessionId,e.MJAPIKey,e.UserAPIKey)),await f.Instance.SaveStoredSessionID(f.Instance._sessionId),this._sessionId=f.Instance._sessionId,this._client=f.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),f.Instance&&f.Instance!==this&&f.Instance._configData===this._configData&&(f.Instance._dynamicHeaders.set(e,t),f.Instance._client&&f.Instance._client.setHeader(e,t))}RemoveDynamicHeader(e){this._dynamicHeaders.delete(e),this._client&&this._client.setHeader(e,""),f.Instance&&f.Instance!==this&&f.Instance._configData===this._configData&&(f.Instance._dynamicHeaders.delete(e),f.Instance._client&&f.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),{Roles:r,...s}=t,n=(r??[]).map(i=>this.ConvertBackToMJFields(i)),a=new c.UserInfo(this,{...s,UserRoles:n});return e.CurrentUserTenantContext&&typeof e.CurrentUserTenantContext=="object"&&(a.TenantContext=e.CurrentUserTenantContext),a}}async InternalRunQuery(e,t){if(e.SQL)return this.RunAdhocQuery(e.SQL,e.MaxRows,void 0,e.StartRow);if(e.QueryID)return this.RunQueryByID(e.QueryID,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow,e.Enrichment,e.DataSource);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow,e.Enrichment,e.DataSource);throw new Error("No SQL, QueryID, or QueryName provided to RunQuery")}async RunAdhocQuery(e,t,r,s){const n=u.gql`
|
|
323
327
|
query ExecuteAdhocQuery($input: AdhocQueryInput!) {
|
|
324
328
|
ExecuteAdhocQuery(input: $input) {
|
|
325
329
|
${this.QueryReturnFieldList}
|
|
326
330
|
}
|
|
327
331
|
}
|
|
328
|
-
`,
|
|
332
|
+
`,a={SQL:e};r!==void 0&&(a.TimeoutSeconds=r),t!==void 0&&(a.MaxRows=t),s!==void 0&&(a.StartRow=s);const i=await this.ExecuteGQL(n,{input:a});return i?.ExecuteAdhocQuery?this.TransformQueryPayload(i.ExecuteAdhocQuery):{QueryID:"",QueryName:"Ad-Hoc Query",Success:!1,Results:[],RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Ad-hoc query execution failed \u2014 no response from server"}}async InternalRunQueries(e,t){const r=u.gql`
|
|
329
333
|
query RunQueriesBatch($input: [RunQueryInput!]!) {
|
|
330
334
|
RunQueries(input: $input) {
|
|
331
335
|
${this.QueryReturnFieldList}
|
|
332
336
|
}
|
|
333
337
|
}
|
|
334
|
-
`,s=e.map(
|
|
335
|
-
query GetQueryDataQuery($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int, $Enrichment: JSONObject) {
|
|
336
|
-
GetQueryData(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow, Enrichment: $Enrichment) {
|
|
338
|
+
`,s=e.map(a=>({QueryID:a.QueryID,QueryName:a.QueryName,CategoryID:a.CategoryID,CategoryPath:a.CategoryPath,Parameters:a.Parameters,MaxRows:a.MaxRows,StartRow:a.StartRow,ForceAuditLog:a.ForceAuditLog,AuditLogDescription:a.AuditLogDescription,Enrichment:a.Enrichment,DataSource:a.DataSource})),n=await this.ExecuteGQL(r,{input:s});return n&&n.RunQueries?n.RunQueries.map(a=>this.TransformQueryPayload(a)):[]}async RunQueryByID(e,t,r,s,n,a,i,o,y){const l=u.gql`
|
|
339
|
+
query GetQueryDataQuery($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int, $Enrichment: JSONObject, $DataSource: String) {
|
|
340
|
+
GetQueryData(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow, Enrichment: $Enrichment, DataSource: $DataSource) {
|
|
337
341
|
${this.QueryReturnFieldList}
|
|
338
342
|
}
|
|
339
343
|
}
|
|
340
|
-
`,
|
|
341
|
-
query GetQueryDataByNameQuery($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int, $Enrichment: JSONObject) {
|
|
342
|
-
GetQueryDataByName(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow, Enrichment: $Enrichment) {
|
|
344
|
+
`,S={QueryID:e};t!==void 0&&(S.CategoryID=t),r!==void 0&&(S.CategoryPath=r),n!==void 0&&(S.Parameters=n),a!==void 0&&(S.MaxRows=a),i!==void 0&&(S.StartRow=i),o!==void 0&&(S.Enrichment=o),y!==void 0&&(S.DataSource=y);const h=await this.ExecuteGQL(l,S);if(h&&h.GetQueryData)return this.TransformQueryPayload(h.GetQueryData)}async RunQueryByName(e,t,r,s,n,a,i,o,y){const l=u.gql`
|
|
345
|
+
query GetQueryDataByNameQuery($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int, $Enrichment: JSONObject, $DataSource: String) {
|
|
346
|
+
GetQueryDataByName(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow, Enrichment: $Enrichment, DataSource: $DataSource) {
|
|
343
347
|
${this.QueryReturnFieldList}
|
|
344
348
|
}
|
|
345
349
|
}
|
|
346
|
-
`,
|
|
350
|
+
`,S={QueryName:e};t!==void 0&&(S.CategoryID=t),r!==void 0&&(S.CategoryPath=r),n!==void 0&&(S.Parameters=n),a!==void 0&&(S.MaxRows=a),i!==void 0&&(S.StartRow=i),o!==void 0&&(S.Enrichment=o),y!==void 0&&(S.DataSource=y);const h=await this.ExecuteGQL(l,S);if(h&&h.GetQueryDataByName)return this.TransformQueryPayload(h.GetQueryDataByName)}get QueryReturnFieldList(){return`
|
|
347
351
|
Success
|
|
348
352
|
QueryID
|
|
349
353
|
QueryName
|
|
@@ -352,7 +356,7 @@
|
|
|
352
356
|
TotalRowCount
|
|
353
357
|
ExecutionTime
|
|
354
358
|
ErrorMessage
|
|
355
|
-
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(
|
|
359
|
+
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,Enrichment:o.params.Enrichment||null,DataSource:o.params.DataSource||null},cacheStatus:o.cacheStatus?{maxUpdatedAt:o.cacheStatus.maxUpdatedAt,rowCount:o.cacheStatus.rowCount}:null})),s=u.gql`
|
|
356
360
|
query RunQueriesWithCacheCheckQuery($input: [RunQueryWithCacheCheckInput!]!) {
|
|
357
361
|
RunQueriesWithCacheCheck(input: $input) {
|
|
358
362
|
success
|
|
@@ -368,18 +372,18 @@
|
|
|
368
372
|
}
|
|
369
373
|
}
|
|
370
374
|
}
|
|
371
|
-
`,
|
|
375
|
+
`,a=(await this.ExecuteGQL(s,{input:r}))?.RunQueriesWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map(o=>{if((o.status==="stale"||o.status==="no_validation")&&o.Results){const y=JSON.parse(o.Results);return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,results:y,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}});return{success:a.success,results:i,errorMessage:a.errorMessage}}catch(r){return c.LogError(`Error in RunQueriesWithCacheCheck: ${r}`),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async InternalRunView(e,t){try{let r="",s="";if(e){const n={};let a,i;if(e.ViewEntity)i=e.ViewEntity,a=i.Entity;else{const{entityName:I,v:R}=await this.getEntityNameAndUserView(e,t);i=R,a=I}const o=this.EntityByName(a);if(!o)throw new Error(`Entity ${a} not found in metadata`);let y=!1;const l=c.getGraphQLTypeNameBase(o);e.ViewID?(r=`Run${l}ViewByID`,s="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(r=`Run${l}ViewByName`,s="RunViewByNameInput",n.ViewName=e.ViewName):(y=!0,r=`Run${l}DynamicView`,s="RunDynamicViewInput",n.EntityName=e.EntityName),n.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",n.OrderBy=e.OrderBy?e.OrderBy:"",n.UserSearchString=e.UserSearchString?e.UserSearchString:"",n.Fields=e.Fields,n.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,e.MaxRows!==void 0&&(n.MaxRows=e.MaxRows),e.StartRow!==void 0&&(n.StartRow=e.StartRow),n.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,n.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(n.AuditLogDescription=e.AuditLogDescription),e.BypassCache!==void 0&&(n.BypassCache=e.BypassCache),e.DataSource!==void 0&&(n.DataSource=e.DataSource),y||(n.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",n.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,n.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",n.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1),e.Aggregates&&e.Aggregates.length>0&&(n.Aggregates=e.Aggregates.map(I=>({expression:I.expression,alias:I.alias})));const S=this.getViewRunTimeFieldList(o,i,e,y),h=e.Aggregates&&e.Aggregates.length>0?`
|
|
372
376
|
AggregateResults {
|
|
373
377
|
alias
|
|
374
378
|
expression
|
|
375
379
|
value
|
|
376
380
|
error
|
|
377
381
|
}
|
|
378
|
-
AggregateExecutionTime`:"",
|
|
382
|
+
AggregateExecutionTime`:"",m=u.gql`
|
|
379
383
|
query RunViewQuery ($input: ${s}!) {
|
|
380
384
|
${r}(input: $input) {
|
|
381
385
|
Results {
|
|
382
|
-
${
|
|
386
|
+
${S.join(`
|
|
383
387
|
`)}
|
|
384
388
|
}
|
|
385
389
|
UserViewRunID
|
|
@@ -387,16 +391,16 @@
|
|
|
387
391
|
TotalRowCount
|
|
388
392
|
ExecutionTime
|
|
389
393
|
Success
|
|
390
|
-
ErrorMessage${
|
|
394
|
+
ErrorMessage${h}
|
|
391
395
|
}
|
|
392
|
-
}`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:
|
|
396
|
+
}`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:a,queryName:r,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const p=await this.ExecuteGQL(m,{input:n});if(p&&p[r]){const I=p[r].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:a,aggregateResultCount:I?.length||0,aggregateResults:I,aggregateExecutionTime:p[r].AggregateExecutionTime});const R=p[r].Results;if(R&&R.length>0){const v=o.Fields.filter(C=>C.CodeName!==C.Name&&C.CodeName!==void 0);R.forEach(C=>{this.ConvertBackToMJFields(C),v.forEach(N=>{C[N.Name]=C[N.CodeName]})})}return p[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw c.LogError(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],n=[];for(const l of e){let S="",h="";const m={};let p=null,I=null;if(l.ViewEntity)I=l.ViewEntity,p=I.Get("Entity");else{const{entityName:C,v:N}=await this.getEntityNameAndUserView(l,t);I=N,p=C}const R=this.EntityByName(p);if(!R)throw new Error(`Entity ${p} not found in metadata`);s.push(R);let E=!1;const v=c.getGraphQLTypeNameBase(R);l.ViewID?(S=`Run${v}ViewByID`,h="RunViewByIDInput",m.ViewID=l.ViewID):l.ViewName?(S=`Run${v}ViewByName`,h="RunViewByNameInput",m.ViewName=l.ViewName):(E=!0,S=`Run${v}DynamicView`,h="RunDynamicViewInput",m.EntityName=l.EntityName),m.ExtraFilter=l.ExtraFilter||"",m.OrderBy=l.OrderBy||"",m.UserSearchString=l.UserSearchString||"",m.Fields=l.Fields,m.IgnoreMaxRows=l.IgnoreMaxRows||!1,l.MaxRows!==void 0&&(m.MaxRows=l.MaxRows),l.StartRow!==void 0&&(m.StartRow=l.StartRow),l.AfterKey&&(m.AfterKey={KeyValuePairs:l.AfterKey.KeyValuePairs}),m.ForceAuditLog=l.ForceAuditLog||!1,m.ResultType=l.ResultType||"simple",l.AuditLogDescription&&l.AuditLogDescription.length>0&&(m.AuditLogDescription=l.AuditLogDescription),l.BypassCache!==void 0&&(m.BypassCache=l.BypassCache),l.DataSource!==void 0&&(m.DataSource=l.DataSource),E||(m.ExcludeUserViewRunID=l.ExcludeUserViewRunID||"",m.ExcludeDataFromAllPriorViewRuns=l.ExcludeDataFromAllPriorViewRuns||!1,m.OverrideExcludeFilter=l.OverrideExcludeFilter||"",m.SaveViewResults=l.SaveViewResults||!1),l.Aggregates&&l.Aggregates.length>0&&(m.Aggregates=l.Aggregates.map(C=>({expression:C.expression,alias:C.alias}))),r.push(m),n.push(...this.getViewRunTimeFieldList(R,I,l,E))}const i=e.some(l=>l.Aggregates&&l.Aggregates.length>0)?`
|
|
393
397
|
AggregateResults {
|
|
394
398
|
alias
|
|
395
399
|
expression
|
|
396
400
|
value
|
|
397
401
|
error
|
|
398
402
|
}
|
|
399
|
-
AggregateExecutionTime`:"",
|
|
403
|
+
AggregateExecutionTime`:"",o=u.gql`
|
|
400
404
|
query RunViewsQuery ($input: [RunViewGenericInput!]!) {
|
|
401
405
|
RunViews(input: $input) {
|
|
402
406
|
Results {
|
|
@@ -414,7 +418,7 @@
|
|
|
414
418
|
Success
|
|
415
419
|
ErrorMessage${i}
|
|
416
420
|
}
|
|
417
|
-
}`,y=await this.ExecuteGQL(
|
|
421
|
+
}`,y=await this.ExecuteGQL(o,{input:r});if(y&&y.RunViews){const l=y.RunViews;for(const[S,h]of l.entries())h.Results=h.Results.map(m=>{let p=JSON.parse(m.Data);return this.ConvertBackToMJFields(p),p});return l}return null}catch(r){throw c.LogError(r),r}}async RunViewsWithCacheCheck(e,t){try{const r=e.map(o=>({params:{EntityName:o.params.EntityName||"",ExtraFilter:o.params.ExtraFilter||"",OrderBy:o.params.OrderBy||"",Fields:o.params.Fields,UserSearchString:o.params.UserSearchString||"",IgnoreMaxRows:o.params.IgnoreMaxRows||!1,MaxRows:o.params.MaxRows,StartRow:o.params.StartRow,AfterKey:o.params.AfterKey?{KeyValuePairs:o.params.AfterKey.KeyValuePairs}:null,ForceAuditLog:o.params.ForceAuditLog||!1,AuditLogDescription:o.params.AuditLogDescription||"",ResultType:o.params.ResultType||"simple",Aggregates:o.params.Aggregates??null,DataSource:o.params.DataSource},cacheStatus:o.cacheStatus?{maxUpdatedAt:o.cacheStatus.maxUpdatedAt,rowCount:o.cacheStatus.rowCount}:null})),s=u.gql`
|
|
418
422
|
query RunViewsWithCacheCheckQuery($input: [RunViewWithCacheCheckInput!]!) {
|
|
419
423
|
RunViewsWithCacheCheck(input: $input) {
|
|
420
424
|
success
|
|
@@ -453,7 +457,7 @@
|
|
|
453
457
|
}
|
|
454
458
|
}
|
|
455
459
|
}
|
|
456
|
-
`,
|
|
460
|
+
`,a=(await this.ExecuteGQL(s,{input:r}))?.RunViewsWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map((o,y)=>{const l=e[y];if(o.status==="differential"&&o.differentialData){const S=o.differentialData.updatedRows.map(h=>{const m=JSON.parse(h.Data);return this.ConvertBackToMJFields(m),m});return{viewIndex:o.viewIndex,status:o.status,results:void 0,differentialData:{updatedRows:S,deletedRecordIDs:o.differentialData.deletedRecordIDs},maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}if(o.status==="stale"&&o.Results){const S=o.Results.map(m=>{const p=JSON.parse(m.Data);return this.ConvertBackToMJFields(p),p}),h=o.aggregateResults?.map(m=>({expression:m.expression,alias:m.alias,value:m.value!==void 0&&m.value!==null?JSON.parse(m.value):null,error:m.error}));return{viewIndex:o.viewIndex,status:o.status,results:S,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage,aggregateResults:h}}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 _.ViewInfo.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await _.ViewInfo.GetViewEntityByName(e.ViewName,t),r=s.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:r,v:s}}getViewRunTimeFieldList(e,t,r,s){const n=[];if(r.Fields){for(const a of e.PrimaryKeys)r.Fields.find(i=>i.trim().toLowerCase()===a.Name.toLowerCase())===void 0&&n.push(L.MapFieldName(a.Name));r.Fields.forEach(a=>{n.push(L.MapFieldName(a))})}else if(s)e.Fields.forEach(a=>{a.IsBinaryFieldType||n.push(L.MapFieldName(a.CodeName))});else{for(const a of e.PrimaryKeys)n.find(i=>i.trim().toLowerCase()===a.Name.toLowerCase())===void 0&&n.push(L.MapFieldName(a.Name));t.Columns.forEach(a=>{a.hidden===!1&&!n.find(i=>i.trim().toLowerCase()===a.EntityField?.Name.trim().toLowerCase())&&a.EntityField&&n.push(L.MapFieldName(a.EntityField.CodeName))})}return n}get ProviderType(){return c.ProviderType.Network}async GetRecordChanges(e,t){try{const r={EntityName:"MJ: Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},s=await this.RunView(r);return s?s.Results.sort((n,a)=>n.ChangedAt>a.ChangedAt?-1:1):null}catch(r){throw c.LogError(r),r}}async GetRecordDependencies(e,t){try{const r=u.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
|
|
457
461
|
GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
|
|
458
462
|
EntityName
|
|
459
463
|
RelatedEntityName
|
|
@@ -487,7 +491,7 @@
|
|
|
487
491
|
}
|
|
488
492
|
}
|
|
489
493
|
}
|
|
490
|
-
}`;let s={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(
|
|
494
|
+
}`;let s={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(a=>a.Copy())};const n=await this.ExecuteGQL(r,{params:s});if(n&&n.GetRecordDuplicates)return n.GetRecordDuplicates}async SearchEntities(e){if(!e||e.length===0)return[];if(e.filter(i=>i?.entityName&&i?.searchText&&i.searchText.trim()).length===0)return e.map(()=>[]);const r=u.gql`query SearchEntitiesQuery($params: [SearchEntityInput!]!) {
|
|
491
495
|
SearchEntities(params: $params) {
|
|
492
496
|
Success
|
|
493
497
|
ErrorMessage
|
|
@@ -503,7 +507,7 @@
|
|
|
503
507
|
}
|
|
504
508
|
}
|
|
505
509
|
}
|
|
506
|
-
}`,s=e.map(i=>({EntityName:i.entityName,SearchText:i.searchText,Mode:i.options?.mode??"hybrid",RrfK:i.options?.rrfK,LexicalWeight:i.options?.weights?.lexical,SemanticWeight:i.options?.weights?.semantic,TopK:i.options?.topK,MinScore:i.options?.minScore,EntityDocumentID:i.options?.entityDocumentId})),n=await this.ExecuteGQL(r,{params:s});return n?.SearchEntities?.Success?n.SearchEntities.Groups.map(i=>i.Results.map(
|
|
510
|
+
}`,s=e.map(i=>({EntityName:i.entityName,SearchText:i.searchText,Mode:i.options?.mode??"hybrid",RrfK:i.options?.rrfK,LexicalWeight:i.options?.weights?.lexical,SemanticWeight:i.options?.weights?.semantic,TopK:i.options?.topK,MinScore:i.options?.minScore,EntityDocumentID:i.options?.entityDocumentId})),n=await this.ExecuteGQL(r,{params:s});return n?.SearchEntities?.Success?n.SearchEntities.Groups.map(i=>i.Results.map(o=>({entityRecordDocumentId:o.EntityRecordDocumentID,recordId:o.RecordID,score:o.Score,matchType:o.MatchType,components:{lexical:o.LexicalScore??void 0,semantic:o.SemanticScore??void 0}}))):(n?.SearchEntities?.ErrorMessage&&c.LogError(`SearchEntities GraphQL error: ${n.SearchEntities.ErrorMessage}`),e.map(()=>[]))}async SearchEntity(e){return(await this.SearchEntities([e]))[0]??[]}async searchEntitiesSemanticPass(){return[]}async InternalRouteOperation(e,t,r){const s=u.gql`mutation ExecuteRemoteOperation($operationKey: String!, $inputJSON: String!, $invokeMode: String!, $progressChannelId: String) {
|
|
507
511
|
ExecuteRemoteOperation(input: { operationKey: $operationKey, inputJSON: $inputJSON, invokeMode: $invokeMode, progressChannelId: $progressChannelId }) {
|
|
508
512
|
success
|
|
509
513
|
resultCode
|
|
@@ -511,7 +515,7 @@
|
|
|
511
515
|
handle
|
|
512
516
|
errorMessage
|
|
513
517
|
}
|
|
514
|
-
}`;let n,
|
|
518
|
+
}`;let n,a;r.onProgress&&(n=this.GenerateUUID(),a=this.subscribe(ye,{channelId:n}).subscribe({next:d(i=>{const o=i?.RemoteOperationProgress?.ProgressJSON;if(o)try{r.onProgress(JSON.parse(o))}catch{}},"next"),error:d(()=>{},"error")}),await new Promise(i=>setTimeout(i,400)));try{const o=(await this.ExecuteGQL(s,{operationKey:e,inputJSON:JSON.stringify(t??null),invokeMode:r.mode??"attached",progressChannelId:n??null}))?.ExecuteRemoteOperation;return o?{Success:!!o.success,ResultCode:o.resultCode??void 0,Output:o.outputJSON!=null?JSON.parse(o.outputJSON):void 0,Handle:o.handle??void 0,ErrorMessage:o.errorMessage??void 0}:{Success:!1,ResultCode:"NO_RESPONSE",ErrorMessage:"No response from ExecuteRemoteOperation"}}catch(i){return{Success:!1,ResultCode:"TRANSPORT_ERROR",ErrorMessage:i instanceof Error?i.message:String(i)}}finally{a?.unsubscribe()}}async MergeRecords(e,t,r){const s=this.Entities.find(n=>n.Name.trim().toLowerCase()===e.EntityName.trim().toLowerCase());if(!s||!s.AllowRecordMerge)throw new Error(`Entity ${e.EntityName} does not allow record merging, check the AllowRecordMerge property in the entity metadata`);try{const n=u.gql`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
|
|
515
519
|
MergeRecords(request: $request) {
|
|
516
520
|
Success
|
|
517
521
|
OverallStatus
|
|
@@ -528,32 +532,32 @@
|
|
|
528
532
|
Message
|
|
529
533
|
}
|
|
530
534
|
}
|
|
531
|
-
}`,
|
|
532
|
-
${e.Fields.map(
|
|
535
|
+
}`,a={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(o=>({FieldName:o.FieldName,Value:o.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(o=>o.Copy())};return(await this.ExecuteGQL(n,{request:a}))?.MergeRecords}catch(n){return c.LogError(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){if(r?.IsParentEntitySave){const n=new c.BaseEntityResult;return n.StartedAt=new Date,n.EndedAt=new Date,n.Type=e.IsSaved?"update":"create",n.Success=!0,n.NewValues=e.GetAll(),e.RegisterResultHistoryEntry(n),n.NewValues}const s=new c.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const n={input:{}},a=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(m=>({FieldName:m.CodeName,Value:m.Value})),e.RegisterResultHistoryEntry(s);const i=c.getGraphQLTypeNameBase(e.EntityInfo),o=`${a}${i}`,y=e.Fields.filter(m=>!m.ReadOnly||m.IsPrimaryKey&&e.IsSaved),l=` ${o}(input: $input) {
|
|
536
|
+
${e.Fields.map(m=>L.MapFieldName(m.CodeName)).join(`
|
|
533
537
|
`)}
|
|
534
|
-
}`,
|
|
538
|
+
}`,S=u.gql`mutation ${a}${i} ($input: ${o}Input!) {
|
|
535
539
|
${l}
|
|
536
540
|
}
|
|
537
|
-
`;for(let
|
|
538
|
-
${y}(${
|
|
539
|
-
${e.Fields.filter(
|
|
541
|
+
`;for(let m=0;m<y.length;m++){const p=y[m];let I=e.Get(p.Name);if(I)switch(p.EntityFieldInfo.TSType){case c.EntityFieldTSType.Date:I=I.getTime();break;case c.EntityFieldTSType.Boolean:typeof I!="boolean"&&(I=parseInt(I)!==0);break;case c.EntityFieldTSType.Number:if(typeof I!="number"){const R=Number(I);isNaN(R)||(I=R)}break}I===null&&p.EntityFieldInfo.AllowsNull===!1&&(p.EntityFieldInfo.DefaultValue!==null?I=p.EntityFieldInfo.DefaultValue:p.FieldType===c.EntityFieldTSType.Number||p.FieldType===c.EntityFieldTSType.Boolean?I=0:I=""),n.input[L.MapFieldName(p.CodeName)]=I}const h=e.RestoreContext;if(h&&(n.input.RestoreContext___={SourceChangeID:h.SourceChangeID,Reason:h.Reason}),a.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const m=[];e.Fields.forEach(p=>{let I=null;p.OldValue!==null&&p.OldValue!==void 0&&(p.EntityFieldInfo.TSType===c.EntityFieldTSType.Date?I=p.OldValue.getTime().toString():p.EntityFieldInfo.TSType===c.EntityFieldTSType.Boolean?I=p.OldValue===!0?"1":"0":typeof p.OldValue!="string"?I=p.OldValue.toString():I=p.OldValue),m.push({Key:L.MapFieldName(p.CodeName),Value:I})}),n.input.OldValues___=m}if(e.TransactionGroup){const m=[{varName:"input",inputType:o+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,s.Type==="create"?"Create":"Update",l,n,{mutationName:o,mutationInputTypes:m},(p,I)=>{s.EndedAt=new Date,I&&p?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(p)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const m=await this.ExecuteGQL(S,n);if(m&&m[o])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(m[o]),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(n){return s.Success=!1,s.EndedAt=new Date,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,c.LogError(n),null}}async Load(e,t,r=null,s){try{const n={};let a="",i="";for(let h=0;h<t.KeyValuePairs.length;h++){const m=e.Fields.find(E=>E.Name.trim().toLowerCase()===t.KeyValuePairs[h].FieldName.trim().toLowerCase()).EntityFieldInfo,p=t.GetValueByIndex(h),I=m.GraphQLType;i.length>0&&(i+=", "),i+=`$${m.CodeName}: ${I}!`,a.length>0&&(a+=", ");const R=m.CodeName.startsWith("__mj_")?m.CodeName.replace("__mj_","_mj__"):m.CodeName;if(a+=`${R}: $${m.CodeName}`,m.TSType===c.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(h)))throw new Error(`Primary Key value ${p} (${m.Name}) is not a valid number`);n[m.CodeName]=parseInt(p)}else n[m.CodeName]=p}const o=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",y=c.getGraphQLTypeNameBase(e.EntityInfo),l=u.gql`query Single${y}${o.length>0?"Full":""} (${i}) {
|
|
542
|
+
${y}(${a}) {
|
|
543
|
+
${e.Fields.filter(h=>!h.EntityFieldInfo.IsBinaryFieldType).map(h=>h.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?h.CodeName.replace("__mj_","_mj__"):h.CodeName).join(`
|
|
540
544
|
`)}
|
|
541
|
-
${
|
|
545
|
+
${o}
|
|
542
546
|
}
|
|
543
547
|
}
|
|
544
|
-
`,
|
|
548
|
+
`,S=await this.ExecuteGQL(l,n);return S&&S[y]?this.ConvertBackToMJFields(S[y]):null}catch(n){return c.LogError(n),null}}ConvertBackToMJFields(e){return L.ReverseMapFields(e),e}getRelatedEntityString(e,t){let r="";for(let s=0;s<e.RelatedEntities.length;s++)if(t.indexOf(e.RelatedEntities[s].RelatedEntity)>=0){const n=e.RelatedEntities[s],a=this.EntityByID(n.RelatedEntityID);let i="";n.Type.toLowerCase().trim()==="many to many"?i=`${n.RelatedEntityCodeName}_${n.JoinEntityJoinField.replace(/\s/g,"")}`:i=`${n.RelatedEntityCodeName}_${n.RelatedEntityJoinField.replace(/\s/g,"")}`,r+=`
|
|
545
549
|
${i} {
|
|
546
|
-
${
|
|
550
|
+
${a.Fields.map(o=>o.CodeName).join(`
|
|
547
551
|
`)}
|
|
548
552
|
}
|
|
549
|
-
`}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(
|
|
550
|
-
`),y+=`${
|
|
553
|
+
`}return r}async Delete(e,t,r){const s=new c.BaseEntityResult;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(p=>({FieldName:p.CodeName,Value:p.Value})),e.RegisterResultHistoryEntry(s);const n={},a=[];let i="",o="",y="";for(let p of e.PrimaryKey.KeyValuePairs){const I=e.Fields.find(E=>E.Name.trim().toLowerCase()===p.FieldName.trim().toLowerCase());n[I.CodeName]=I.Value,a.push({varName:I.CodeName,inputType:I.EntityFieldInfo.GraphQLType+"!"});const R=I.CodeName.startsWith("__mj_")?I.CodeName.replace("__mj_","_mj__"):I.CodeName;i.length>0&&(i+=", "),i+=`${R}: $${I.CodeName}`,o.length>0&&(o+=", "),o+=`$${I.CodeName}: ${I.EntityFieldInfo.GraphQLType}!`,y.length>0&&(y+=`
|
|
554
|
+
`),y+=`${R}`}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 S="Delete"+c.getGraphQLTypeNameBase(e.EntityInfo),h=u.gql`${S}(${i}, options___: $options___) {
|
|
551
555
|
${y}
|
|
552
556
|
}
|
|
553
|
-
`,
|
|
554
|
-
${
|
|
557
|
+
`,m=u.gql`mutation ${S} (${o}, $options___: DeleteOptionsInput!) {
|
|
558
|
+
${h}
|
|
555
559
|
}
|
|
556
|
-
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,"Delete",
|
|
560
|
+
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,"Delete",h,n,{mutationName:S,mutationInputTypes:a},(p,I)=>{if(s.EndedAt=new Date,I&&p){let R=!0;for(const E of e.PrimaryKey.KeyValuePairs)E.Value!==p[E.FieldName]&&(R=!1);R?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const p=await this.ExecuteGQL(m,n);if(p&&p[S]){const I=p[S];for(let R of e.PrimaryKey.KeyValuePairs){let E=I[R.FieldName],v=R.Value;if(typeof v=="number"&&(v=v.toString()),typeof E=="number"&&(E=E.toString()),v!==E)throw new Error(`Primary key value mismatch in server Delete response. Field: ${R.FieldName}, Original: ${v}, Returned: ${E}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(n){return s.EndedAt=new Date,s.Success=!1,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,c.LogError(n),!1}}async GetDatasetByName(e,t){const r=u.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
|
|
557
561
|
GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
|
|
558
562
|
DatasetID
|
|
559
563
|
DatasetName
|
|
@@ -562,7 +566,7 @@
|
|
|
562
566
|
LatestUpdateDate
|
|
563
567
|
Results
|
|
564
568
|
}
|
|
565
|
-
}`,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
|
|
569
|
+
}`,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 f._datasetStatusCoalesceMs>0&&!t?this.enqueueDatasetStatusCheck(e):this.executeDatasetStatusByName(e,t)}enqueueDatasetStatusCheck(e){return new Promise((t,r)=>{f._datasetStatusQueue.push({datasetName:e,resolve:t,reject:r}),f._datasetStatusTimer||(f._datasetStatusTimer=setTimeout(()=>this.flushDatasetStatusQueue(),f._datasetStatusCoalesceMs))})}async flushDatasetStatusQueue(){f._datasetStatusTimer=null;const e=f._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!]!) {
|
|
566
570
|
GetMultipleDatasetStatusByName(DatasetNames: $DatasetNames) {
|
|
567
571
|
DatasetID
|
|
568
572
|
DatasetName
|
|
@@ -571,7 +575,7 @@
|
|
|
571
575
|
LatestUpdateDate
|
|
572
576
|
EntityUpdateDates
|
|
573
577
|
}
|
|
574
|
-
}`,n=((await this.ExecuteGQL(r,{DatasetNames:t}))?.GetMultipleDatasetStatusByName||[]).map(
|
|
578
|
+
}`,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!]) {
|
|
575
579
|
GetDatasetStatusByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
|
|
576
580
|
DatasetID
|
|
577
581
|
DatasetName
|
|
@@ -580,16 +584,16 @@
|
|
|
580
584
|
LatestUpdateDate
|
|
581
585
|
EntityUpdateDates
|
|
582
586
|
}
|
|
583
|
-
}`,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
|
|
587
|
+
}`,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 V(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const n=this.EntityByName(t);if(!n)throw new Error(`Entity ${t} not found in metadata`);const a=u.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
|
|
584
588
|
GetRecordFavoriteStatus(params: $params) {
|
|
585
589
|
Success
|
|
586
590
|
IsFavorite
|
|
587
591
|
}
|
|
588
|
-
}`,i=await this.ExecuteGQL(
|
|
592
|
+
}`,i=await this.ExecuteGQL(a,{params:{UserID:e,EntityID:n.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)}}});if(i&&i.GetRecordFavoriteStatus&&i.GetRecordFavoriteStatus.Success)return i.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,t,r,s,n){const a=this.EntityByName(t);if(!a)throw new Error(`Entity ${t} not found in metadata`);const i=u.gql`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
|
|
589
593
|
SetRecordFavoriteStatus(params: $params){
|
|
590
594
|
Success
|
|
591
595
|
}
|
|
592
|
-
}`,
|
|
596
|
+
}`,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!) {
|
|
593
597
|
GetEntityRecordName(EntityName: $EntityName, CompositeKey: $CompositeKey) {
|
|
594
598
|
Success
|
|
595
599
|
Status
|
|
@@ -620,16 +624,44 @@
|
|
|
620
624
|
ErrorMessage
|
|
621
625
|
Result
|
|
622
626
|
}
|
|
623
|
-
}`,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
|
|
627
|
+
}`,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 f.Instance.ExecuteGQL(e,t,r)}static async ExecuteGQLWithProgress(e,t,r,s=!0){return f.Instance.ExecuteGQLWithProgress(e,t,r,s)}async ExecuteGQLWithProgress(e,t,r,s=!0){if(!this._configData?.URL)throw new Error("GraphQLDataProvider is not configured with a URL.");const n=this._configData.URL,a=JSON.stringify({query:e,variables:t});return new Promise((i,o)=>{const y=new XMLHttpRequest;y.open("POST",n),y.setRequestHeader("Content-Type","application/json"),this._sessionId&&y.setRequestHeader("x-session-id",this._sessionId),this._configData?.Token&&y.setRequestHeader("authorization","Bearer "+this._configData.Token),this._configData?.MJAPIKey&&y.setRequestHeader("x-mj-api-key",this._configData.MJAPIKey),this._configData?.UserAPIKey&&y.setRequestHeader("x-api-key",this._configData.UserAPIKey);for(const[l,S]of this._dynamicHeaders)y.setRequestHeader(l,S);y.upload&&r&&(y.upload.onprogress=l=>{if(l.lengthComputable&&l.total>0){const S=Math.min(100,Math.round(l.loaded/l.total*100));r({loaded:l.loaded,total:l.total,percent:S})}}),y.onload=async()=>{if(y.status>=200&&y.status<300)try{const l=JSON.parse(y.responseText);if(l.errors&&l.errors.length>0){const S=l.errors[0];if(S?.extensions?.code?.toUpperCase()?.trim()==="JWT_EXPIRED"&&s){await this.RefreshToken(),i(await this.ExecuteGQLWithProgress(e,t,r,!1));return}o(new Error(S.message||"GraphQL Error"))}else i(l.data)}catch(l){o(l)}else o(new Error(`HTTP error ${y.status}: ${y.statusText}`))},y.onerror=()=>o(new Error("Network error during request")),y.onabort=()=>o(new Error("Request aborted")),y.send(a)})}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){const n=G(s,this._configData?.LogVariableValues===!0);console.error("[GraphQL] ExecuteGQL error caught:",n);const a=j(s);if(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"),a}else throw a;else throw c.LogError(JSON.stringify(n)),a}}async RefreshToken(){const e=f.Instance&&f.Instance._configData===this._configData;if(e&&f.Instance._refreshPromise)return f.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(f.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&f.Instance&&(f.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,f.Instance&&f.Instance._configData===this._configData&&(f.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 f.Instance.RefreshToken()}static async clearClientCache(e=new Set){const t=[];for(let r=0;r<localStorage.length;r++){const s=localStorage.key(r);s&&!e.has(s)&&t.push(s)}t.forEach(r=>localStorage.removeItem(r)),await new Promise(r=>{const s=indexedDB.deleteDatabase("MJ_Metadata");s.onsuccess=()=>r(),s.onerror=()=>r(),s.onblocked=()=>r()})}CreateNewGraphQLClient(e,t,r,s,n){const a={"x-session-id":r};t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),n&&(a["x-api-key"]=n);const i=new u.GraphQLClient(e,{headers:a});for(const[o,y]of this._dynamicHeaders)i.setHeader(o,y);return i}userInfoString(){return this.infoString(new c.UserInfo(null,null))}userRoleInfoString(){return this.infoString(new c.UserRoleInfo(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
|
|
624
628
|
`:s.startsWith("_")||(t+=s+`
|
|
625
|
-
`);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new
|
|
629
|
+
`);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new B:this._localStorageProvider=new c.InMemoryLocalStorageProvider),this._localStorageProvider}get Metadata(){return this}get SocketConnectivity$(){return this._socketStateSubject.asObservable()}get SocketConnectionState(){return this._socketStateSubject.value}ForceSocketReconnect(){this.disposeWSClient()}getOrCreateWSClient(){const e=Date.now();return this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&this._activeSubscriptionCount===0&&this.disposeWSClient(),this._wsClient||(this._isDisposingSocketIntentionally=!1,this._wsClient=Y.createClient({url:this.ConfigData.WSURL,connectionParams:d(()=>({Authorization:"Bearer "+this.ConfigData.Token,...this.ConfigData.MJAPIKey?{"x-mj-api-key":this.ConfigData.MJAPIKey}:{},...this.ConfigData.UserAPIKey?{"x-mj-user-api-key":this.ConfigData.UserAPIKey}:{}}),"connectionParams"),keepAlive:3e4,retryAttempts:3,shouldRetry:d(()=>!0,"shouldRetry")}),this._wsClientCreatedAt=e,this._wsClient.on("connected",()=>{this._socketStateSubject.next("connected")}),this._wsClient.on("closed",t=>{if(this._isDisposingSocketIntentionally)return;this._socketStateSubject.next("disconnected"),t?.code===4403&&this._configData.Data.RefreshTokenFunction&&this.RefreshToken().catch(()=>{})}),this._subscriptionCleanupTimer||(this._subscriptionCleanupTimer=setInterval(()=>{this.cleanupStaleSubscriptions()},this.SUBSCRIPTION_CLEANUP_INTERVAL_MS))),this._wsClient}disposeWSClient(){if(this._wsClient){this._isDisposingSocketIntentionally=!0;try{this._wsClient.dispose()}catch(e){console.error("[GraphQLDataProvider] Error disposing WebSocket client:",e)}this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject.next("unknown")}}completeAllSubjects(){this._pushStatusSubjects.forEach((e,t)=>{try{e.subject.complete(),e.subscription.unsubscribe()}catch(r){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,r)}}),this._pushStatusSubjects.clear(),this._taskGraphFrameStreams.forEach((e,t)=>{try{e.subject.complete(),e.subscription.unsubscribe()}catch(r){console.error(`[GraphQLDataProvider] Error cleaning up frame stream for ${t}:`,r)}}),this._taskGraphFrameStreams.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 $.Observable(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=s.subscribe({query:e,variables:t},{next:d(a=>{r.next(a.data)},"next"),error:d(async a=>{const i=a;if(i?.extensions?.code==="JWT_EXPIRED"||i?.message?.includes("token has expired")||i?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] WebSocket JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),r.complete()}catch(y){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",y),r.error(y)}}else r.error(a)},"error"),complete:d(()=>{r.complete()},"complete")});return()=>{this._activeSubscriptionCount--,n()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),r=this._pushStatusSubjects.get(e);if(r)return r.lastRequestedAt=t,new $.Observable(o=>{r.activeSubscribers++;const y=r.subject.subscribe(o);return()=>{const l=this._pushStatusSubjects.get(e);l&&l.activeSubscribers>0&&l.activeSubscribers--,y.unsubscribe()}});const s=u.gql`subscription StatusUpdates($sessionId: String!) {
|
|
626
630
|
statusUpdates(sessionId: $sessionId) {
|
|
627
631
|
date
|
|
628
632
|
message
|
|
629
633
|
sessionId
|
|
630
634
|
}
|
|
631
635
|
}
|
|
632
|
-
`,n=new
|
|
636
|
+
`,n=new $.Subject,a=this.getOrCreateWSClient(),i=new $.Subscription;return i.add(new $.Observable(o=>{const y=a.subscribe({query:s,variables:{sessionId:e}},{next:d(l=>{const S=this._pushStatusSubjects.get(e);S&&(S.lastEmissionAt=Date.now()),o.next(l.data.statusUpdates.message)},"next"),error:d(async l=>{const S=l;if(S?.extensions?.code==="JWT_EXPIRED"||S?.message?.includes("token has expired")||S?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),o.complete()}catch(m){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",m),o.error(m)}}else o.error(l)},"error"),complete:d(()=>{o.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,y()}}).subscribe({next:d(o=>n.next(o),"next"),error:d(o=>{n.error(o),this._pushStatusSubjects.delete(e)},"error"),complete:d(()=>{n.complete(),this._pushStatusSubjects.delete(e)},"complete")})),this._pushStatusSubjects.set(e,{subject:n,subscription:i,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new $.Observable(o=>{const y=this._pushStatusSubjects.get(e);y&&y.activeSubscribers++;const l=n.subscribe(o);return()=>{const S=this._pushStatusSubjects.get(e);S&&S.activeSubscribers>0&&S.activeSubscribers--,l.unsubscribe()}})}TaskGraphFrames(e){const t=d(o=>new $.Observable(y=>{o.activeSubscribers++;const l=o.subject.subscribe(y);return()=>{l.unsubscribe();const S=this._taskGraphFrameStreams.get(e);S&&(S.activeSubscribers--,S.activeSubscribers<=0&&(S.subscription.unsubscribe(),S.subject.complete(),this._taskGraphFrameStreams.delete(e)))}}),"attachTo"),r=this._taskGraphFrameStreams.get(e);if(r)return t(r);const s=u.gql`subscription TaskGraphFrames($parentTaskId: ID!) {
|
|
637
|
+
taskGraphFrames(parentTaskId: $parentTaskId) {
|
|
638
|
+
kind
|
|
639
|
+
parentTaskId
|
|
640
|
+
taskId
|
|
641
|
+
taskName
|
|
642
|
+
status
|
|
643
|
+
errorMessage
|
|
644
|
+
assignedUserId
|
|
645
|
+
completedCount
|
|
646
|
+
totalCount
|
|
647
|
+
edgeId
|
|
648
|
+
dependsOnTaskId
|
|
649
|
+
verdict
|
|
650
|
+
conditionText
|
|
651
|
+
reason
|
|
652
|
+
claimEvent
|
|
653
|
+
claimedBy
|
|
654
|
+
claimExpiresAt
|
|
655
|
+
passNumber
|
|
656
|
+
eligibleCount
|
|
657
|
+
heldCount
|
|
658
|
+
claimedCount
|
|
659
|
+
instanceInFlightCount
|
|
660
|
+
progressMessage
|
|
661
|
+
progressPercent
|
|
662
|
+
date
|
|
663
|
+
}
|
|
664
|
+
}`,n=new $.Subject,a=new $.Subscription;a.add(this.subscribe(s,{parentTaskId:e}).subscribe({next:d(o=>{o?.taskGraphFrames&&n.next(o.taskGraphFrames)},"next"),error:d(o=>{n.error(o),this._taskGraphFrameStreams.delete(e)},"error"),complete:d(()=>{n.complete(),this._taskGraphFrameStreams.delete(e)},"complete")}));const i={subject:n,subscription:a,activeSubscribers:0};return this._taskGraphFrameStreams.set(e,i),t(i)}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.UnsubscribeFromCacheInvalidation(),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}ClientToolRequests(e){return this.subscribe(`
|
|
633
665
|
subscription ClientToolRequest($sessionID: String!) {
|
|
634
666
|
ClientToolRequest(sessionID: $sessionID) {
|
|
635
667
|
AgentRunID
|
|
@@ -651,7 +683,7 @@
|
|
|
651
683
|
OriginSessionID
|
|
652
684
|
RecordData
|
|
653
685
|
}
|
|
654
|
-
}`,t=this.subscribe(e);this._cacheInvalidationSubscription=t.subscribe({next:d(r=>{const s=r?.cacheInvalidation;if(!s)return;if(s.OriginSessionID&&s.OriginSessionID===this.sessionId){
|
|
686
|
+
}`,t=this.subscribe(e);this._cacheInvalidationSubscription=t.subscribe({next:d(r=>{const s=r?.cacheInvalidation;if(!s)return;if(s.OriginSessionID&&s.OriginSessionID===this.sessionId){f.VerboseCacheInvalidationLogging&&console.debug(`[GraphQLDataProvider] Skipping self-originated cache invalidation for "${s.EntityName}" (action: ${s.Action})`);return}f.VerboseCacheInvalidationLogging&&console.debug(`[GraphQLDataProvider] Cache invalidation received: ${s.Action} for "${s.EntityName}" from server ${s.SourceServerID?.substring(0,8)||"unknown"}`);const n={type:"remote-invalidate",entityName:s.EntityName,baseEntity:null,provider:this,payload:{primaryKeyValues:s.PrimaryKeyValues,action:s.Action,sourceServerId:s.SourceServerID,timestamp:s.Timestamp,recordData:s.RecordData}};D.MJGlobal.Instance.RaiseEvent({event:D.MJEventType.ComponentEvent,eventCode:c.BaseEntity.BaseEventCode,args:n,component:this})},"next"),error:d(r=>{console.error("[GraphQLDataProvider] Cache invalidation subscription error:",r),this._cacheInvalidationSubscription=null},"error"),complete:d(()=>{console.log("[GraphQLDataProvider] Cache invalidation subscription completed, will re-establish on next WebSocket creation"),this._cacheInvalidationSubscription=null},"complete")})}UnsubscribeFromCacheInvalidation(){this._cacheInvalidationSubscription&&(this._cacheInvalidationSubscription.unsubscribe(),this._cacheInvalidationSubscription=null)}async FindISAChildEntity(e,t,r){if(!e.IsParentType)return null;const s=`query FindISAChildEntity($EntityName: String!, $RecordID: String!) {
|
|
655
687
|
FindISAChildEntity(EntityName: $EntityName, RecordID: $RecordID) {
|
|
656
688
|
Success
|
|
657
689
|
ChildEntityName
|
|
@@ -663,14 +695,69 @@
|
|
|
663
695
|
ChildEntityNames
|
|
664
696
|
ErrorMessage
|
|
665
697
|
}
|
|
666
|
-
}`;try{const n=await this.ExecuteGQL(s,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntities?.Success&&n.FindISAChildEntities.ChildEntityNames?n.FindISAChildEntities.ChildEntityNames.map(
|
|
698
|
+
}`;try{const n=await this.ExecuteGQL(s,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntities?.Success&&n.FindISAChildEntities.ChildEntityNames?n.FindISAChildEntities.ChildEntityNames.map(a=>({ChildEntityName:a})):[]}catch(n){return c.LogError(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function Se(g){const e=new f;return c.SetProvider(e),await e.Config(g),await e.preValidateAndRefresh(),D.MJGlobal.Instance.RaiseEvent({event:D.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),await c.StartupManager.Instance.Startup(),e}d(Se,"setupGraphQLClient");class pe{static{d(this,"SyncRolesAndUsersResult")}}class he{static{d(this,"RoleInput")}}class Ie{static{d(this,"UserInput")}}class fe{static{d(this,"RolesAndUsersInput")}}var J=(g=>(g.Create="Create",g.Update="Update",g.CreateOrUpdate="CreateOrUpdate",g.Delete="Delete",g.DeleteWithFilter="DeleteWithFilter",g))(J||{});class Ee{static{d(this,"ActionItemInput")}}class Re{static{d(this,"SyncDataResult")}constructor(){this.Results=[]}}class De{static{d(this,"ActionItemOutput")}}const W=`Success
|
|
699
|
+
ErrorMessage
|
|
700
|
+
Query {
|
|
701
|
+
ID
|
|
702
|
+
Name
|
|
703
|
+
Description
|
|
704
|
+
CategoryID
|
|
705
|
+
Category
|
|
706
|
+
SQL
|
|
707
|
+
Status
|
|
708
|
+
QualityRank
|
|
709
|
+
EmbeddingVector
|
|
710
|
+
EmbeddingModelID
|
|
711
|
+
EmbeddingModel
|
|
712
|
+
TechnicalDescription
|
|
713
|
+
Reusable
|
|
714
|
+
}
|
|
715
|
+
Fields {
|
|
716
|
+
ID
|
|
717
|
+
QueryID
|
|
718
|
+
Name
|
|
719
|
+
Description
|
|
720
|
+
Sequence
|
|
721
|
+
SQLBaseType
|
|
722
|
+
SQLFullType
|
|
723
|
+
SourceEntityID
|
|
724
|
+
SourceEntity
|
|
725
|
+
SourceFieldName
|
|
726
|
+
IsComputed
|
|
727
|
+
ComputationDescription
|
|
728
|
+
IsSummary
|
|
729
|
+
SummaryDescription
|
|
730
|
+
}
|
|
731
|
+
Parameters {
|
|
732
|
+
ID
|
|
733
|
+
QueryID
|
|
734
|
+
Name
|
|
735
|
+
Description
|
|
736
|
+
Type
|
|
737
|
+
IsRequired
|
|
738
|
+
DefaultValue
|
|
739
|
+
SampleValue
|
|
740
|
+
ValidationFilters
|
|
741
|
+
}
|
|
742
|
+
Entities {
|
|
743
|
+
ID
|
|
744
|
+
QueryID
|
|
745
|
+
EntityID
|
|
746
|
+
Entity
|
|
747
|
+
}
|
|
748
|
+
Permissions {
|
|
749
|
+
ID
|
|
750
|
+
QueryID
|
|
751
|
+
RoleID
|
|
752
|
+
Role
|
|
753
|
+
}`;class ve{static{d(this,"GraphQLSystemUserClient")}get Client(){return this._client}constructor(e,t,r,s){const n={"x-session-id":r};this._sessionId=r,t&&(n.authorization="Bearer "+t),s&&(n["x-mj-api-key"]=s),this._client=new 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!) {
|
|
667
754
|
GetData(input: $input) {
|
|
668
755
|
Success
|
|
669
756
|
ErrorMessages
|
|
670
757
|
Queries
|
|
671
758
|
Results
|
|
672
759
|
}
|
|
673
|
-
}`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(n=>n?D.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
|
|
760
|
+
}`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(n=>n?D.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 {
|
|
674
761
|
GetAllEntities {
|
|
675
762
|
Success
|
|
676
763
|
ErrorMessage
|
|
@@ -813,125 +900,15 @@
|
|
|
813
900
|
ErrorMessage
|
|
814
901
|
AppliedParameters
|
|
815
902
|
}
|
|
816
|
-
}`,r={QueryName:e.QueryName};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow),e.Enrichment!==void 0&&(r.Enrichment=e.Enrichment);const s=await this.Client.request(t,r);return s&&s.GetQueryDataByNameSystemUser?{...s.GetQueryDataByNameSystemUser,Results:s.GetQueryDataByNameSystemUser.Results?D.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
|
|
903
|
+
}`,r={QueryName:e.QueryName};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow),e.Enrichment!==void 0&&(r.Enrichment=e.Enrichment);const s=await this.Client.request(t,r);return s&&s.GetQueryDataByNameSystemUser?{...s.GetQueryDataByNameSystemUser,Results:s.GetQueryDataByNameSystemUser.Results?D.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 t=`mutation CreateQueryExtended($input: CreateQuerySystemUserInput!) {
|
|
817
904
|
CreateQueryExtended(input: $input) {
|
|
818
|
-
|
|
819
|
-
ErrorMessage
|
|
820
|
-
Query {
|
|
821
|
-
ID
|
|
822
|
-
Name
|
|
823
|
-
Description
|
|
824
|
-
CategoryID
|
|
825
|
-
Category
|
|
826
|
-
SQL
|
|
827
|
-
Status
|
|
828
|
-
QualityRank
|
|
829
|
-
EmbeddingVector
|
|
830
|
-
EmbeddingModelID
|
|
831
|
-
EmbeddingModel
|
|
832
|
-
TechnicalDescription
|
|
833
|
-
Reusable
|
|
834
|
-
MJQueryFields_QueryIDArray {
|
|
835
|
-
ID
|
|
836
|
-
QueryID
|
|
837
|
-
Name
|
|
838
|
-
Description
|
|
839
|
-
Sequence
|
|
840
|
-
SQLBaseType
|
|
841
|
-
SQLFullType
|
|
842
|
-
SourceEntityID
|
|
843
|
-
SourceEntity
|
|
844
|
-
SourceFieldName
|
|
845
|
-
IsComputed
|
|
846
|
-
ComputationDescription
|
|
847
|
-
IsSummary
|
|
848
|
-
SummaryDescription
|
|
849
|
-
}
|
|
850
|
-
MJQueryParameters_QueryIDArray {
|
|
851
|
-
ID
|
|
852
|
-
QueryID
|
|
853
|
-
Name
|
|
854
|
-
Description
|
|
855
|
-
Type
|
|
856
|
-
IsRequired
|
|
857
|
-
DefaultValue
|
|
858
|
-
SampleValue
|
|
859
|
-
ValidationFilters
|
|
860
|
-
}
|
|
861
|
-
MJQueryEntities_QueryIDArray {
|
|
862
|
-
ID
|
|
863
|
-
QueryID
|
|
864
|
-
EntityID
|
|
865
|
-
Entity
|
|
866
|
-
}
|
|
867
|
-
MJQueryPermissions_QueryIDArray {
|
|
868
|
-
ID
|
|
869
|
-
QueryID
|
|
870
|
-
RoleID
|
|
871
|
-
Role
|
|
872
|
-
}
|
|
873
|
-
}
|
|
905
|
+
${W}
|
|
874
906
|
}
|
|
875
|
-
}`,{input:e});return r&&r.CreateQueryExtended?r.CreateQueryExtended:{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
|
|
907
|
+
}`,r=await this.Client.request(t,{input:e});return r&&r.CreateQueryExtended?r.CreateQueryExtended:{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 t=`mutation UpdateQueryExtended($input: UpdateQuerySystemUserInput!) {
|
|
876
908
|
UpdateQueryExtended(input: $input) {
|
|
877
|
-
|
|
878
|
-
ErrorMessage
|
|
879
|
-
Query {
|
|
880
|
-
ID
|
|
881
|
-
Name
|
|
882
|
-
Description
|
|
883
|
-
CategoryID
|
|
884
|
-
Category
|
|
885
|
-
SQL
|
|
886
|
-
Status
|
|
887
|
-
QualityRank
|
|
888
|
-
EmbeddingVector
|
|
889
|
-
EmbeddingModelID
|
|
890
|
-
EmbeddingModel
|
|
891
|
-
TechnicalDescription
|
|
892
|
-
Reusable
|
|
893
|
-
MJQueryFields_QueryIDArray {
|
|
894
|
-
ID
|
|
895
|
-
QueryID
|
|
896
|
-
Name
|
|
897
|
-
Description
|
|
898
|
-
Sequence
|
|
899
|
-
SQLBaseType
|
|
900
|
-
SQLFullType
|
|
901
|
-
SourceEntityID
|
|
902
|
-
SourceEntity
|
|
903
|
-
SourceFieldName
|
|
904
|
-
IsComputed
|
|
905
|
-
ComputationDescription
|
|
906
|
-
IsSummary
|
|
907
|
-
SummaryDescription
|
|
908
|
-
}
|
|
909
|
-
MJQueryParameters_QueryIDArray {
|
|
910
|
-
ID
|
|
911
|
-
QueryID
|
|
912
|
-
Name
|
|
913
|
-
Description
|
|
914
|
-
Type
|
|
915
|
-
IsRequired
|
|
916
|
-
DefaultValue
|
|
917
|
-
SampleValue
|
|
918
|
-
ValidationFilters
|
|
919
|
-
}
|
|
920
|
-
MJQueryEntities_QueryIDArray {
|
|
921
|
-
ID
|
|
922
|
-
QueryID
|
|
923
|
-
EntityID
|
|
924
|
-
Entity
|
|
925
|
-
}
|
|
926
|
-
MJQueryPermissions_QueryIDArray {
|
|
927
|
-
ID
|
|
928
|
-
QueryID
|
|
929
|
-
RoleID
|
|
930
|
-
Role
|
|
931
|
-
}
|
|
932
|
-
}
|
|
909
|
+
${W}
|
|
933
910
|
}
|
|
934
|
-
}`,{input:e});return r&&r.UpdateQueryExtended?r.UpdateQueryExtended:{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 DeleteQueryExtended($ID: String!, $options: DeleteOptionsInput) {
|
|
911
|
+
}`,r=await this.Client.request(t,{input:e});return r&&r.UpdateQueryExtended?r.UpdateQueryExtended:{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 DeleteQueryExtended($ID: String!, $options: DeleteOptionsInput) {
|
|
935
912
|
DeleteQueryExtended(ID: $ID, options: $options) {
|
|
936
913
|
Success
|
|
937
914
|
ErrorMessage
|
|
@@ -1056,7 +1033,7 @@
|
|
|
1056
1033
|
executionTimeMs
|
|
1057
1034
|
}
|
|
1058
1035
|
}
|
|
1059
|
-
`,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
|
|
1036
|
+
`,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`
|
|
1060
1037
|
query EmbedTextSystemUser(
|
|
1061
1038
|
$textToEmbed: [String!]!,
|
|
1062
1039
|
$modelSize: String!
|
|
@@ -1071,7 +1048,7 @@
|
|
|
1071
1048
|
error
|
|
1072
1049
|
}
|
|
1073
1050
|
}
|
|
1074
|
-
`,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
|
|
1051
|
+
`,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this.Client.request(t,s);if(!n?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const a=n.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?a.embeddings:a.embeddings[0],modelName:a.modelName,vectorDimensions:a.vectorDimensions,error:a.error}}catch(t){return c.LogError(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}async SearchKnowledge(e){try{const t=u.gql`
|
|
1075
1052
|
mutation SearchKnowledgeAsSystemUser($query: String!, $maxResults: Float, $filters: SearchFiltersInput, $minScore: Float) {
|
|
1076
1053
|
SearchKnowledgeAsSystemUser(query: $query, maxResults: $maxResults, filters: $filters, minScore: $minScore) {
|
|
1077
1054
|
Success
|
|
@@ -1176,7 +1153,7 @@
|
|
|
1176
1153
|
ErrorMessage
|
|
1177
1154
|
}
|
|
1178
1155
|
}
|
|
1179
|
-
`,s={EntityNames:e,UserEmail:t},n=await this.Client.request(r,s);if(n?.CheckEntityPermissionsSystemUser){const
|
|
1156
|
+
`,s={EntityNames:e,UserEmail:t},n=await this.Client.request(r,s);if(n?.CheckEntityPermissionsSystemUser){const a=n.CheckEntityPermissionsSystemUser;return{Success:a.Success,Results:(a.Results||[]).map(i=>({EntityName:i.EntityName,CanRead:i.CanRead})),ErrorMessage:a.ErrorMessage}}return{Success:!1,Results:[],ErrorMessage:"Invalid response from server"}}catch(r){return c.LogError(`GraphQLSystemUserClient::CheckEntityPermissionsSystemUser - Error checking entity permissions - ${r}`),{Success:!1,Results:[],ErrorMessage:r instanceof Error?r.message:String(r)}}}}class Ce{static{d(this,"GetDataOutput")}}class we{static{d(this,"SimpleRemoteEntityOutput")}}class $e{static{d(this,"SimpleRemoteEntity")}}class Pe{static{d(this,"SimpleRemoteEntityField")}}class Le{static{d(this,"GraphQLActionClient")}constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),n=this.createActionVariables(e,s,r),a=await this.executeActionMutation(n);return this.processActionResult(a,t)}catch(s){return this.handleActionError(s,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{...t,Value:r}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=u.gql`
|
|
1180
1157
|
mutation RunAction($input: RunActionInput!) {
|
|
1181
1158
|
RunAction(input: $input) {
|
|
1182
1159
|
Success
|
|
@@ -1193,63 +1170,63 @@
|
|
|
1193
1170
|
ResultData
|
|
1194
1171
|
}
|
|
1195
1172
|
}
|
|
1196
|
-
`;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
|
|
1173
|
+
`;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 be{static{d(this,"GraphQLListsClient")}constructor(e){this.dataProvider=e}async PreviewListDelta(e){const t=u.gql`
|
|
1197
1174
|
query PreviewListDelta($input: ComputeDeltaInput!) {
|
|
1198
1175
|
PreviewListDelta(input: $input) {
|
|
1199
1176
|
...ListDeltaFields
|
|
1200
1177
|
}
|
|
1201
1178
|
}
|
|
1202
|
-
${
|
|
1203
|
-
`,r=await this.dataProvider.ExecuteGQL(t,{input:{Target:e.Target,Source:
|
|
1179
|
+
${H}
|
|
1180
|
+
`,r=await this.dataProvider.ExecuteGQL(t,{input:{Target:e.Target,Source:U(e.Source),Mode:e.Mode}});return z(r?.PreviewListDelta)}async ApplyListDelta(e){const t=u.gql`
|
|
1204
1181
|
mutation ApplyListDelta($input: ApplyDeltaInput!) {
|
|
1205
1182
|
ApplyListDelta(input: $input) {
|
|
1206
1183
|
...ApplyResultFields
|
|
1207
1184
|
}
|
|
1208
1185
|
}
|
|
1209
|
-
${
|
|
1186
|
+
${M}
|
|
1210
1187
|
`,r=await this.dataProvider.ExecuteGQL(t,{input:{TargetListId:e.Delta.TargetListId,EntityName:e.Delta.EntityName,ToAdd:e.Delta.ToAdd,ToRemove:e.Delta.ToRemove,Unchanged:e.Delta.Unchanged,AddCount:e.Delta.Counts.Add,RemoveCount:e.Delta.Counts.Remove,UnchangedCount:e.Delta.Counts.Unchanged,SourceTotal:e.Delta.Counts.SourceTotal,TargetTotal:e.Delta.Counts.TargetTotal,DeltaToken:e.Delta.DeltaToken,ConfirmDrops:e.ConfirmDrops}});return T(r?.ApplyListDelta)}async MaterializeFromView(e,t){const r=u.gql`
|
|
1211
1188
|
mutation MaterializeListFromView($viewId: String!, $options: MaterializeOptionsInput!) {
|
|
1212
1189
|
MaterializeListFromView(viewId: $viewId, options: $options) {
|
|
1213
1190
|
...ApplyResultFields
|
|
1214
1191
|
}
|
|
1215
1192
|
}
|
|
1216
|
-
${
|
|
1193
|
+
${M}
|
|
1217
1194
|
`,s=await this.dataProvider.ExecuteGQL(r,{viewId:e,options:{ListName:t.ListName,CategoryId:t.CategoryId,Description:t.Description,RememberLineage:t.RememberLineage,UseSnapshot:t.UseSnapshot,RefreshMode:t.RefreshMode}});return T(s?.MaterializeListFromView)}async AddViewResultsToList(e,t){const r=u.gql`
|
|
1218
1195
|
mutation AddViewResultsToList($viewId: String!, $listId: String!) {
|
|
1219
1196
|
AddViewResultsToList(viewId: $viewId, listId: $listId) {
|
|
1220
1197
|
...ApplyResultFields
|
|
1221
1198
|
}
|
|
1222
1199
|
}
|
|
1223
|
-
${
|
|
1200
|
+
${M}
|
|
1224
1201
|
`,s=await this.dataProvider.ExecuteGQL(r,{viewId:e,listId:t});return T(s?.AddViewResultsToList)}async RefreshFromSource(e){const t=u.gql`
|
|
1225
1202
|
mutation RefreshListFromSource($listId: String!, $mode: String!, $confirmDrops: Boolean!) {
|
|
1226
1203
|
RefreshListFromSource(listId: $listId, mode: $mode, confirmDrops: $confirmDrops) {
|
|
1227
1204
|
...ApplyResultFields
|
|
1228
1205
|
}
|
|
1229
1206
|
}
|
|
1230
|
-
${
|
|
1207
|
+
${M}
|
|
1231
1208
|
`,r=await this.dataProvider.ExecuteGQL(t,{listId:e.ListId,mode:e.Mode,confirmDrops:e.ConfirmDrops});return T(r?.RefreshListFromSource)}async ComposeLists(e){const t=u.gql`
|
|
1232
1209
|
mutation ComposeLists($input: ComposeListsInput!) {
|
|
1233
1210
|
ComposeLists(input: $input) {
|
|
1234
1211
|
...ListDeltaFields
|
|
1235
1212
|
}
|
|
1236
1213
|
}
|
|
1237
|
-
${
|
|
1238
|
-
`,r=await this.dataProvider.ExecuteGQL(t,{input:{Op:e.Op,Inputs:e.Inputs.map(
|
|
1214
|
+
${H}
|
|
1215
|
+
`,r=await this.dataProvider.ExecuteGQL(t,{input:{Op:e.Op,Inputs:e.Inputs.map(U),Target:e.Target?U(e.Target):null}});return z(r?.ComposeLists)}async Share(e){const t=u.gql`
|
|
1239
1216
|
mutation ShareList($input: ShareListInput!) {
|
|
1240
1217
|
ShareList(input: $input) {
|
|
1241
1218
|
...ShareResultFields
|
|
1242
1219
|
}
|
|
1243
1220
|
}
|
|
1244
|
-
${
|
|
1245
|
-
`,r=await this.dataProvider.ExecuteGQL(t,{input:{ListID:e.ListID,Target:
|
|
1221
|
+
${q}
|
|
1222
|
+
`,r=await this.dataProvider.ExecuteGQL(t,{input:{ListID:e.ListID,Target:Ne(e.Target),PermissionLevel:e.PermissionLevel}});return Q(r?.ShareList)}async Unshare(e){const t=u.gql`
|
|
1246
1223
|
mutation UnshareList($permissionId: String!) {
|
|
1247
1224
|
UnshareList(permissionId: $permissionId) {
|
|
1248
1225
|
...ShareResultFields
|
|
1249
1226
|
}
|
|
1250
1227
|
}
|
|
1251
|
-
${
|
|
1252
|
-
`,r=await this.dataProvider.ExecuteGQL(t,{permissionId:e});return
|
|
1228
|
+
${q}
|
|
1229
|
+
`,r=await this.dataProvider.ExecuteGQL(t,{permissionId:e});return Q(r?.UnshareList)}async Invite(e){const t=u.gql`
|
|
1253
1230
|
mutation InviteToList($input: InviteToListInput!) {
|
|
1254
1231
|
InviteToList(input: $input) {
|
|
1255
1232
|
Success
|
|
@@ -1276,8 +1253,8 @@
|
|
|
1276
1253
|
...ShareResultFields
|
|
1277
1254
|
}
|
|
1278
1255
|
}
|
|
1279
|
-
${
|
|
1280
|
-
`,r=await this.dataProvider.ExecuteGQL(t,{invitationId:e});return
|
|
1256
|
+
${q}
|
|
1257
|
+
`,r=await this.dataProvider.ExecuteGQL(t,{invitationId:e});return Q(r?.RevokeListInvitation)}async GetSharesForList(e){const t=u.gql`
|
|
1281
1258
|
query ListSharesForList($listId: String!) {
|
|
1282
1259
|
ListSharesForList(listId: $listId) {
|
|
1283
1260
|
PermissionID
|
|
@@ -1293,7 +1270,7 @@
|
|
|
1293
1270
|
CreatedAt
|
|
1294
1271
|
}
|
|
1295
1272
|
}
|
|
1296
|
-
`;return((await this.dataProvider.ExecuteGQL(t,{listId:e}))?.ListSharesForList??[]).map(
|
|
1273
|
+
`;return((await this.dataProvider.ExecuteGQL(t,{listId:e}))?.ListSharesForList??[]).map(Ae)}async ListsSharedWithMe(){const e=u.gql`
|
|
1297
1274
|
query ListsSharedWithMe {
|
|
1298
1275
|
ListsSharedWithMe {
|
|
1299
1276
|
ListID
|
|
@@ -1303,7 +1280,7 @@
|
|
|
1303
1280
|
SharedAt
|
|
1304
1281
|
}
|
|
1305
1282
|
}
|
|
1306
|
-
`;return((await this.dataProvider.ExecuteGQL(e,{}))?.ListsSharedWithMe??[]).map(s=>({ListID:s.ListID,ListName:s.ListName,PermissionLevel:s.PermissionLevel,SharedByUserID:s.SharedByUserID??null,SharedAt:new Date(s.SharedAt)}))}}const
|
|
1283
|
+
`;return((await this.dataProvider.ExecuteGQL(e,{}))?.ListsSharedWithMe??[]).map(s=>({ListID:s.ListID,ListName:s.ListName,PermissionLevel:s.PermissionLevel,SharedByUserID:s.SharedByUserID??null,SharedAt:new Date(s.SharedAt)}))}}const H=u.gql`
|
|
1307
1284
|
fragment ListDeltaFields on ListDeltaType {
|
|
1308
1285
|
TargetListId
|
|
1309
1286
|
EntityName
|
|
@@ -1324,7 +1301,7 @@
|
|
|
1324
1301
|
}
|
|
1325
1302
|
DeltaToken
|
|
1326
1303
|
}
|
|
1327
|
-
`,
|
|
1304
|
+
`,M=u.gql`
|
|
1328
1305
|
fragment ApplyResultFields on ApplyListResultType {
|
|
1329
1306
|
Success
|
|
1330
1307
|
ResultCode
|
|
@@ -1336,14 +1313,14 @@
|
|
|
1336
1313
|
FailedCount
|
|
1337
1314
|
Errors
|
|
1338
1315
|
}
|
|
1339
|
-
`,
|
|
1316
|
+
`,q=u.gql`
|
|
1340
1317
|
fragment ShareResultFields on ShareResultType {
|
|
1341
1318
|
Success
|
|
1342
1319
|
ResultCode
|
|
1343
1320
|
Message
|
|
1344
1321
|
PermissionID
|
|
1345
1322
|
}
|
|
1346
|
-
`;function
|
|
1323
|
+
`;function Ne(g){return g.kind==="user"?{Kind:"user",UserID:g.userId}:{Kind:"role",RoleID:g.roleId}}d(Ne,"serializeShareTarget");function Q(g){if(!g||typeof g!="object")throw new Error("GraphQLListsClient: empty/invalid ShareResult response");const e=g;return{Success:e.Success,ResultCode:e.ResultCode,Message:e.Message,PermissionID:e.PermissionID??void 0}}d(Q,"parseShareResult");function Ae(g){const e=g,t=e.Target.Kind==="user"?{kind:"user",userId:e.Target.UserID}:{kind:"role",roleId:e.Target.RoleID};return{PermissionID:e.PermissionID,ListID:e.ListID,Target:t,PermissionLevel:e.PermissionLevel,Status:e.Status,SharedByUserID:e.SharedByUserID??null,CreatedAt:new Date(e.CreatedAt)}}d(Ae,"parseShareSummary");function U(g){switch(g.kind){case"list":return{Kind:"list",ListID:g.listId};case"view":return{Kind:"view",ViewID:g.viewId};case"adhoc":return{Kind:"adhoc",EntityName:g.entityName,ExtraFilter:g.extraFilter}}}d(U,"serializeListSource");function z(g){if(!g||typeof g!="object")throw new Error("GraphQLListsClient: empty/invalid ListDelta response from server");const e=g;return{TargetListId:e.TargetListId,EntityName:e.EntityName,ToAdd:e.ToAdd,ToRemove:e.ToRemove,Unchanged:e.Unchanged,Counts:e.Counts,Warnings:e.Warnings.map(Me),DeltaToken:e.DeltaToken}}d(z,"parseListDelta");function Me(g){let e;if(g.DetailsJSON)try{e=JSON.parse(g.DetailsJSON)}catch(t){c.LogError(`GraphQLListsClient: failed to parse warning details JSON: ${t}`)}return{Code:g.Code,Message:g.Message,Details:e}}d(Me,"parseWarning");function T(g){if(!g||typeof g!="object")throw new Error("GraphQLListsClient: empty/invalid ApplyResult response from server");const e=g;return{Success:e.Success,ResultCode:e.ResultCode,Message:e.Message,CreatedListId:e.CreatedListId??void 0,TargetListId:e.TargetListId??void 0,Counts:e.AddedCount!=null||e.RemovedCount!=null||e.FailedCount!=null?{Added:e.AddedCount??0,Removed:e.RemovedCount??0,Failed:e.FailedCount??0}:void 0,Errors:e.Errors??void 0}}d(T,"parseApplyResult");class Te{static{d(this,"GraphQLEncryptionClient")}constructor(e){this._dataProvider=e}async CreateAPIKey(e){try{const t=this.createAPIKeyVariables(e),r=await this.executeCreateAPIKeyMutation(t);return this.processCreateAPIKeyResult(r)}catch(t){return this.handleCreateAPIKeyError(t)}}createAPIKeyVariables(e){return{input:{Label:e.Label,Description:e.Description,ExpiresAt:e.ExpiresAt?.toISOString(),ScopeIDs:e.ScopeIDs}}}async executeCreateAPIKeyMutation(e){const t=u.gql`
|
|
1347
1324
|
mutation CreateAPIKey($input: CreateAPIKeyInput!) {
|
|
1348
1325
|
CreateAPIKey(input: $input) {
|
|
1349
1326
|
Success
|
|
@@ -1359,7 +1336,7 @@
|
|
|
1359
1336
|
Error
|
|
1360
1337
|
}
|
|
1361
1338
|
}
|
|
1362
|
-
`,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
|
|
1339
|
+
`,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 xe{static{d(this,"GraphQLClusterClient")}constructor(e){this._dataProvider=e}async RunClusterAnalysis(e){try{const t=u.gql`
|
|
1363
1340
|
mutation RunClusterAnalysis($input: RunClusterAnalysisInput!) {
|
|
1364
1341
|
RunClusterAnalysis(input: $input) {
|
|
1365
1342
|
Success
|
|
@@ -1375,7 +1352,7 @@
|
|
|
1375
1352
|
AnalysisID
|
|
1376
1353
|
}
|
|
1377
1354
|
}
|
|
1378
|
-
`,s=(await this._dataProvider.ExecuteGQL(t,{input:e}))?.RunClusterAnalysis;if(!s)throw new Error("Invalid response from server");return this.parseResult(s)}catch(t){const r=t;return c.LogError("GraphQLClusterClient.RunClusterAnalysis failed",void 0,r),this.errorResult(r.message||"Unknown error occurred")}}parseResult(e){const t=this.parseMetrics(e),r=D.SafeJSONParse(e.ClustersJSON)??[],s=D.SafeJSONParse(e.PointsJSON)??[];return{Success:e.Success,ErrorMessage:e.ErrorMessage,Metrics:t,Clusters:r,Points:s,AnalysisID:e.AnalysisID}}parseMetrics(e){const t=D.SafeJSONParse(e.MetricsJSON);return t||{SilhouetteScore:e.SilhouetteScore,ClusterCount:e.ClusterCount,ComputationTimeMs:e.ComputationTimeMs,RecordCount:e.RecordCount,OutlierCount:e.OutlierCount}}errorResult(e){return{Success:!1,ErrorMessage:e,Metrics:{SilhouetteScore:0,ClusterCount:0,ComputationTimeMs:0,RecordCount:0,OutlierCount:0},Clusters:[],Points:[]}}}class
|
|
1355
|
+
`,s=(await this._dataProvider.ExecuteGQL(t,{input:e}))?.RunClusterAnalysis;if(!s)throw new Error("Invalid response from server");return this.parseResult(s)}catch(t){const r=t;return c.LogError("GraphQLClusterClient.RunClusterAnalysis failed",void 0,r),this.errorResult(r.message||"Unknown error occurred")}}parseResult(e){const t=this.parseMetrics(e),r=D.SafeJSONParse(e.ClustersJSON)??[],s=D.SafeJSONParse(e.PointsJSON)??[];return{Success:e.Success,ErrorMessage:e.ErrorMessage,Metrics:t,Clusters:r,Points:s,AnalysisID:e.AnalysisID}}parseMetrics(e){const t=D.SafeJSONParse(e.MetricsJSON);return t||{SilhouetteScore:e.SilhouetteScore,ClusterCount:e.ClusterCount,ComputationTimeMs:e.ComputationTimeMs,RecordCount:e.RecordCount,OutlierCount:e.OutlierCount}}errorResult(e){return{Success:!1,ErrorMessage:e,Metrics:{SilhouetteScore:0,ClusterCount:0,ComputationTimeMs:0,RecordCount:0,OutlierCount:0},Clusters:[],Points:[]}}}class Fe{static{d(this,"GraphQLLiveKitClient")}constructor(e){this._dataProvider=e}async MintClientToken(e){try{const t=u.gql`
|
|
1379
1356
|
mutation MintLiveKitClientToken($input: MintLiveKitClientTokenInput!) {
|
|
1380
1357
|
MintLiveKitClientToken(input: $input) {
|
|
1381
1358
|
Success
|
|
@@ -1440,7 +1417,7 @@
|
|
|
1440
1417
|
RecordingFileID
|
|
1441
1418
|
}
|
|
1442
1419
|
}
|
|
1443
|
-
`,{egressID:e},"StopLiveKitRecording",e)}async runRecordingMutation(e,t,r,s){try{const
|
|
1420
|
+
`,{egressID:e},"StopLiveKitRecording",e)}async runRecordingMutation(e,t,r,s){try{const a=(await this._dataProvider.ExecuteGQL(e,t))?.[r];if(!a)throw new Error("Invalid response from server");return a}catch(n){const a=n;return c.LogError(`GraphQLLiveKitClient.${r} failed`,void 0,a),{Success:!1,ErrorMessage:a.message||"Unknown error",EgressID:s,Status:""}}}}class Ge{static{d(this,"GraphQLClassifyClient")}constructor(e){this._dataProvider=e}async GenerateSeedTaxonomy(e){try{const t=u.gql`
|
|
1444
1421
|
mutation GenerateSeedTaxonomy($sourceID: String!, $sampleSize: Int!) {
|
|
1445
1422
|
GenerateSeedTaxonomy(sourceID: $sourceID, sampleSize: $sampleSize) {
|
|
1446
1423
|
Success
|
|
@@ -1450,7 +1427,7 @@
|
|
|
1450
1427
|
NodesJSON
|
|
1451
1428
|
}
|
|
1452
1429
|
}
|
|
1453
|
-
`,s=(await this._dataProvider.ExecuteGQL(t,{sourceID:e.SourceID,sampleSize:e.SampleSize}))?.GenerateSeedTaxonomy;if(!s)throw new Error("Invalid response from server");return this.parseResult(s)}catch(t){const r=t;return c.LogError("GraphQLClassifyClient.GenerateSeedTaxonomy failed",void 0,r),this.errorResult(r.message||"Unknown error occurred")}}parseResult(e){const t=D.SafeJSONParse(e.NodesJSON)??[];return{Success:e.Success,ErrorMessage:e.ErrorMessage,Method:e.Method,SampleSize:e.SampleSize,Nodes:t}}errorResult(e){return{Success:!1,ErrorMessage:e,SampleSize:0,Nodes:[]}}}class
|
|
1430
|
+
`,s=(await this._dataProvider.ExecuteGQL(t,{sourceID:e.SourceID,sampleSize:e.SampleSize}))?.GenerateSeedTaxonomy;if(!s)throw new Error("Invalid response from server");return this.parseResult(s)}catch(t){const r=t;return c.LogError("GraphQLClassifyClient.GenerateSeedTaxonomy failed",void 0,r),this.errorResult(r.message||"Unknown error occurred")}}parseResult(e){const t=D.SafeJSONParse(e.NodesJSON)??[];return{Success:e.Success,ErrorMessage:e.ErrorMessage,Method:e.Method,SampleSize:e.SampleSize,Nodes:t}}errorResult(e){return{Success:!1,ErrorMessage:e,SampleSize:0,Nodes:[]}}}class qe{static{d(this,"GraphQLTestingClient")}constructor(e){this._dataProvider=e}async RunTest(e){try{const t=this.buildRunTestMutation(),r=this.buildRunTestVariables(e),s={};return await w.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTest",operationLabel:"RunTest",validateAck:d(n=>n?.success===!0,"validateAck"),isCompletionEvent:d(n=>this.isTestCompletionEvent(n,e.testId),"isCompletionEvent"),extractResult:d(n=>this.extractTestResult(n),"extractResult"),onMessage:d(n=>{this.captureTestRunId(n,s),e.onProgress&&this.forwardTestProgress(n,e.onProgress)},"onMessage"),onStall:d(()=>this.reconcileTestRun(s),"onStall"),createErrorResult:d(n=>({success:!1,errorMessage:n,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTest")}}async RunTestSuite(e){try{const t=this.buildRunTestSuiteMutation(),r=this.buildRunTestSuiteVariables(e);return await w.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTestSuite",operationLabel:"RunTestSuite",validateAck:d(s=>s?.success===!0,"validateAck"),isCompletionEvent:d(s=>this.isSuiteCompletionEvent(s,e.suiteId),"isCompletionEvent"),extractResult:d(s=>this.extractSuiteResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardTestProgress(s,e.onProgress):void 0,createErrorResult:d(s=>({success:!1,errorMessage:s,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTestSuite")}}async IsTestRunning(e){try{const t=u.gql`
|
|
1454
1431
|
query IsTestRunning($testId: String!) {
|
|
1455
1432
|
IsTestRunning(testId: $testId)
|
|
1456
1433
|
}
|
|
@@ -1508,7 +1485,7 @@
|
|
|
1508
1485
|
result
|
|
1509
1486
|
}
|
|
1510
1487
|
}
|
|
1511
|
-
`}buildRunTestVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0;return{testId:e.testId,verbose:e.verbose,environment:e.environment,tags:t,variables:r,fireAndForget:!0}}buildRunTestSuiteVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0,s=e.selectedTestIds&&e.selectedTestIds.length>0?JSON.stringify(e.selectedTestIds):void 0;return{suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel,tags:t,variables:r,selectedTestIds:s,sequenceStart:e.sequenceStart,sequenceEnd:e.sequenceEnd,fireAndForget:!0}}isTestCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetComplete"&&r?.type==="complete"&&r?.testId===t}isSuiteCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetSuiteComplete"&&r?.type==="complete"&&r?.suiteId===t}captureTestRunId(e,t){if(e.resolver!=="RunTestResolver")return;const s=e.data?.testRunId;s&&(t.id=s)}async reconcileTestRun(e){if(!e.id)return"continue";const t=await this._dataProvider.RunView({EntityName:"MJ: Test Runs",ExtraFilter:`ID='${e.id}'`,ResultType:"entity_object",BypassCache:!0}),r=t.Success?t.Results?.[0]:void 0;if(!r||r.Status==="Pending"||r.Status==="Running")return"continue";const s=r.Status==="Passed";return{resolve:{success:s,errorMessage:s?void 0:`Test run ${r.Status}`,result:null}}}extractTestResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?D.SafeJSONParse(t.result):null}}extractSuiteResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?D.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
|
|
1488
|
+
`}buildRunTestVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0;return{testId:e.testId,verbose:e.verbose,environment:e.environment,tags:t,variables:r,fireAndForget:!0}}buildRunTestSuiteVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0,s=e.selectedTestIds&&e.selectedTestIds.length>0?JSON.stringify(e.selectedTestIds):void 0;return{suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel,tags:t,variables:r,selectedTestIds:s,sequenceStart:e.sequenceStart,sequenceEnd:e.sequenceEnd,fireAndForget:!0}}isTestCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetComplete"&&r?.type==="complete"&&r?.testId===t}isSuiteCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetSuiteComplete"&&r?.type==="complete"&&r?.suiteId===t}captureTestRunId(e,t){if(e.resolver!=="RunTestResolver")return;const s=e.data?.testRunId;s&&(t.id=s)}async reconcileTestRun(e){if(!e.id)return"continue";const t=await this._dataProvider.RunView({EntityName:"MJ: Test Runs",ExtraFilter:`ID='${e.id}'`,ResultType:"entity_object",BypassCache:!0}),r=t.Success?t.Results?.[0]:void 0;if(!r||r.Status==="Pending"||r.Status==="Running")return"continue";const s=r.Status==="Passed";return{resolve:{success:s,errorMessage:s?void 0:`Test run ${r.Status}`,result:null}}}extractTestResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?D.SafeJSONParse(t.result):null}}extractSuiteResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?D.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 Qe{static{d(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=u.gql`
|
|
1512
1489
|
query GetRegistryComponent(
|
|
1513
1490
|
$registryName: String!,
|
|
1514
1491
|
$namespace: String!,
|
|
@@ -1529,7 +1506,7 @@
|
|
|
1529
1506
|
specification
|
|
1530
1507
|
}
|
|
1531
1508
|
}
|
|
1532
|
-
`,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(
|
|
1509
|
+
`,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`
|
|
1533
1510
|
query GetRegistryComponent(
|
|
1534
1511
|
$registryName: String!,
|
|
1535
1512
|
$namespace: String!,
|
|
@@ -1550,7 +1527,7 @@
|
|
|
1550
1527
|
specification
|
|
1551
1528
|
}
|
|
1552
1529
|
}
|
|
1553
|
-
`,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
|
|
1530
|
+
`,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`
|
|
1554
1531
|
query SearchRegistryComponents($params: SearchRegistryComponentsInput!) {
|
|
1555
1532
|
SearchRegistryComponents(params: $params) {
|
|
1556
1533
|
components
|
|
@@ -1592,7 +1569,7 @@
|
|
|
1592
1569
|
error
|
|
1593
1570
|
}
|
|
1594
1571
|
}
|
|
1595
|
-
`,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
|
|
1572
|
+
`,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{d(this,"GraphQLVersionHistoryClient")}constructor(e){this._dataProvider=e}async CreateLabel(e){let t;try{e.OnProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(a=>{try{const i=JSON.parse(a);i.resolver==="VersionHistoryResolver"&&i.type==="CreateLabelProgress"&&i.status==="ok"&&i.data&&e.OnProgress(i.data)}catch{}}));const r=u.gql`
|
|
1596
1573
|
mutation CreateVersionLabel($input: CreateVersionLabelInput!, $sessionId: String) {
|
|
1597
1574
|
CreateVersionLabel(input: $input, sessionId: $sessionId) {
|
|
1598
1575
|
Success
|
|
@@ -1608,7 +1585,7 @@
|
|
|
1608
1585
|
}
|
|
1609
1586
|
}
|
|
1610
1587
|
}
|
|
1611
|
-
`,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
|
|
1588
|
+
`,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 _e{static{d(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const s=u.gql`
|
|
1612
1589
|
query ListStorageObjects($input: ListStorageObjectsInput!) {
|
|
1613
1590
|
ListStorageObjects(input: $input) {
|
|
1614
1591
|
objects {
|
|
@@ -1625,18 +1602,35 @@
|
|
|
1625
1602
|
prefixes
|
|
1626
1603
|
}
|
|
1627
1604
|
}
|
|
1628
|
-
`,n={input:{AccountID:e,Prefix:t,Delimiter:r||"/"}},
|
|
1605
|
+
`,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`
|
|
1629
1606
|
mutation CreateDirectory($input: CreateDirectoryInput!) {
|
|
1630
1607
|
CreateDirectory(input: $input)
|
|
1631
1608
|
}
|
|
1632
|
-
`,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(
|
|
1609
|
+
`,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`
|
|
1633
1610
|
mutation CreatePreAuthUploadUrl($input: CreatePreAuthUploadUrlInput!) {
|
|
1634
1611
|
CreatePreAuthUploadUrl(input: $input) {
|
|
1635
1612
|
UploadUrl
|
|
1636
1613
|
ProviderKey
|
|
1637
1614
|
}
|
|
1638
1615
|
}
|
|
1639
|
-
`,n={input:{AccountID:e,ObjectName:t,ContentType:r}},
|
|
1616
|
+
`,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");const i=a.CreatePreAuthUploadUrl;return{success:!!i.UploadUrl,uploadUrl:i.UploadUrl||"",providerKey:i.ProviderKey}}catch(s){const n=s;throw c.LogError(`Error creating pre-auth upload URL: ${n}`),n}}async UploadFile(e){try{const t=u.gql`
|
|
1617
|
+
mutation UploadStorageFile($input: UploadStorageFileInput!) {
|
|
1618
|
+
UploadStorageFile(input: $input) {
|
|
1619
|
+
Success
|
|
1620
|
+
FileID
|
|
1621
|
+
ErrorMessage
|
|
1622
|
+
File {
|
|
1623
|
+
ID
|
|
1624
|
+
Name
|
|
1625
|
+
Description
|
|
1626
|
+
ContentType
|
|
1627
|
+
Status
|
|
1628
|
+
ProviderID
|
|
1629
|
+
CategoryID
|
|
1630
|
+
}
|
|
1631
|
+
}
|
|
1632
|
+
}
|
|
1633
|
+
`,r=await this._dataProvider.ExecuteGQL(t,{input:e});if(!r?.UploadStorageFile)throw new Error("Invalid response from UploadStorageFile mutation");return r.UploadStorageFile}catch(t){const r=t;throw c.LogError(`Error uploading file via MJ Storage: ${r}`),r}}async CreatePreAuthDownloadUrl(e,t){try{const r=u.gql`
|
|
1640
1634
|
query CreatePreAuthDownloadUrl($input: CreatePreAuthDownloadUrlInput!) {
|
|
1641
1635
|
CreatePreAuthDownloadUrl(input: $input)
|
|
1642
1636
|
}
|
|
@@ -1664,7 +1658,7 @@
|
|
|
1664
1658
|
destinationPath
|
|
1665
1659
|
}
|
|
1666
1660
|
}
|
|
1667
|
-
`,
|
|
1661
|
+
`,a={input:{SourceAccountID:e,DestinationAccountID:t,SourcePath:r,DestinationPath:s}},i=await this._dataProvider.ExecuteGQL(n,a);if(!i?.CopyObjectBetweenAccounts)throw new Error("Invalid response from server");return{success:i.CopyObjectBetweenAccounts.success,message:i.CopyObjectBetweenAccounts.message,bytesTransferred:i.CopyObjectBetweenAccounts.bytesTransferred,sourceAccount:i.CopyObjectBetweenAccounts.sourceAccount,destinationAccount:i.CopyObjectBetweenAccounts.destinationAccount,sourcePath:i.CopyObjectBetweenAccounts.sourcePath,destinationPath:i.CopyObjectBetweenAccounts.destinationPath}}catch(n){const a=n;return 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`
|
|
1668
1662
|
query SearchAcrossAccounts($input: SearchAcrossAccountsInput!) {
|
|
1669
1663
|
SearchAcrossAccounts(input: $input) {
|
|
1670
1664
|
accountResults {
|
|
@@ -1692,7 +1686,7 @@
|
|
|
1692
1686
|
failedAccounts
|
|
1693
1687
|
}
|
|
1694
1688
|
}
|
|
1695
|
-
`,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:r?.maxResultsPerAccount,FileTypes:r?.fileTypes,SearchContent:r?.searchContent}},
|
|
1689
|
+
`,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:r?.maxResultsPerAccount,FileTypes:r?.fileTypes,SearchContent:r?.searchContent}},a=await this._dataProvider.ExecuteGQL(s,n);if(!a?.SearchAcrossAccounts)throw new Error("Invalid response from server");const i=a.SearchAcrossAccounts;return{accountResults:i.accountResults.map(o=>({accountId:o.accountID,accountName:o.accountName,success:o.success,errorMessage:o.errorMessage,results:o.results.map(y=>({path:y.path,name:y.name,size:y.size,contentType:y.contentType,lastModified:new Date(y.lastModified),relevance:y.relevance,excerpt:y.excerpt,matchInFilename:y.matchInFilename,objectId:y.objectId})),totalMatches:o.totalMatches,hasMore:o.hasMore,nextPageToken:o.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(s){const n=s;return c.LogError(`Error searching across accounts: ${n}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}class Ve{static{d(this,"GraphQLSearchClient")}constructor(e){this._dataProvider=e}async ExecuteSearch(e){try{const t=this.buildSearchKnowledgeMutation(),r=this.prepareSearchVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processSearchKnowledgeResult(s)}catch(t){return this.handleSearchError(t)}}async PreviewSearch(e,t){try{const r=this.buildPreviewSearchMutation(),s=this.preparePreviewVariables(e,t),n=await this._dataProvider.ExecuteGQL(r,s);return this.processPreviewSearchResult(n)}catch(r){return this.handleSearchError(r)}}buildSearchKnowledgeMutation(){return u.gql`
|
|
1696
1690
|
mutation SearchKnowledge($query: String!, $maxResults: Float, $filters: SearchFiltersInput, $minScore: Float, $scopeIDs: [ID!], $searchContext: SearchContextInput) {
|
|
1697
1691
|
SearchKnowledge(query: $query, maxResults: $maxResults, filters: $filters, minScore: $minScore, scopeIDs: $scopeIDs, searchContext: $searchContext) {
|
|
1698
1692
|
Success
|
|
@@ -1798,7 +1792,7 @@
|
|
|
1798
1792
|
IsPersonal
|
|
1799
1793
|
}
|
|
1800
1794
|
}
|
|
1801
|
-
`;return((await this._dataProvider.ExecuteGQL(e,{}))?.SearchScopes??[]).map(s=>({ID:s.ID,Name:s.Name,Description:s.Description??void 0,Icon:s.Icon??void 0,IsGlobal:!!s.IsGlobal,IsDefault:!!s.IsDefault,IsPersonal:!!s.IsPersonal}))}catch(e){return c.LogError(`GraphQLSearchClient.GetSearchScopes failed: ${e instanceof Error?e.message:String(e)}`),[]}}StreamSearch(e){return new
|
|
1795
|
+
`;return((await this._dataProvider.ExecuteGQL(e,{}))?.SearchScopes??[]).map(s=>({ID:s.ID,Name:s.Name,Description:s.Description??void 0,Icon:s.Icon??void 0,IsGlobal:!!s.IsGlobal,IsDefault:!!s.IsDefault,IsPersonal:!!s.IsPersonal}))}catch(e){return c.LogError(`GraphQLSearchClient.GetSearchScopes failed: ${e instanceof Error?e.message:String(e)}`),[]}}StreamSearch(e){return new $.Observable(t=>{const r=u.gql`
|
|
1802
1796
|
mutation StreamScopedSearch(
|
|
1803
1797
|
$query: String!,
|
|
1804
1798
|
$maxResults: Float,
|
|
@@ -1819,7 +1813,7 @@
|
|
|
1819
1813
|
StreamID
|
|
1820
1814
|
ErrorMessage
|
|
1821
1815
|
}
|
|
1822
|
-
}`,s=this.prepareSearchVariables(e);let n=null;return(async()=>{try{const i=(await this._dataProvider.ExecuteGQL(r,s))?.StreamScopedSearch;if(!i?.Success){t.error(new Error(i?.ErrorMessage??"StreamScopedSearch failed to start"));return}const
|
|
1816
|
+
}`,s=this.prepareSearchVariables(e);let n=null;return(async()=>{try{const i=(await this._dataProvider.ExecuteGQL(r,s))?.StreamScopedSearch;if(!i?.Success){t.error(new Error(i?.ErrorMessage??"StreamScopedSearch failed to start"));return}const o=u.gql`
|
|
1823
1817
|
subscription SearchStream($streamID: ID!) {
|
|
1824
1818
|
SearchStreamEvents(streamID: $streamID) {
|
|
1825
1819
|
StreamID
|
|
@@ -1831,7 +1825,7 @@
|
|
|
1831
1825
|
ElapsedMs
|
|
1832
1826
|
ErrorMessage
|
|
1833
1827
|
}
|
|
1834
|
-
}`;n=this._dataProvider.subscribe(
|
|
1828
|
+
}`;n=this._dataProvider.subscribe(o,{streamID:i.StreamID}).subscribe({next:d(y=>{const l=y?.SearchStreamEvents;l&&(t.next(l),l.Phase==="final"?(t.complete(),n?.unsubscribe()):l.Phase==="error"&&(t.error(new Error(l.ErrorMessage??"Stream error")),n?.unsubscribe()))},"next"),error:d(y=>t.error(y),"error")})}catch(a){t.error(a)}})(),()=>{n?.unsubscribe()}})}prepareFilters(e){const t={};return e.EntityNames!==void 0&&e.EntityNames.length>0&&(t.EntityNames=e.EntityNames),e.SourceTypes!==void 0&&e.SourceTypes.length>0&&(t.SourceTypes=e.SourceTypes),e.Tags!==void 0&&e.Tags.length>0&&(t.Tags=e.Tags),t}preparePreviewVariables(e,t){const r={query:e};return t!==void 0&&(r.maxResults=t),r}processSearchKnowledgeResult(e){if(!e?.SearchKnowledge)throw new Error("Invalid response from server");const t=e.SearchKnowledge;return this.mapSearchResponse(t)}processPreviewSearchResult(e){if(!e?.PreviewSearch)throw new Error("Invalid response from server");const t=e.PreviewSearch;return this.mapSearchResponse(t)}mapSearchResponse(e){return{Success:e.Success,Results:(e.Results||[]).map(t=>this.mapResultItem(t)),TotalCount:e.TotalCount,ElapsedMs:e.ElapsedMs,SourceCounts:this.mapSourceCounts(e.SourceCounts),Providers:(e.Providers||[]).map(t=>({ID:t.ID,Name:t.Name,DisplayName:t.DisplayName,Icon:t.Icon,SourceType:t.SourceType,Priority:t.Priority})),ErrorMessage:e.ErrorMessage}}mapResultItem(e){return{ID:e.ID,EntityName:e.EntityName,RecordID:e.RecordID,SourceType:e.SourceType,ResultType:e.ResultType,Title:e.Title,Snippet:e.Snippet,Score:e.Score,ScoreBreakdown:this.mapScoreBreakdown(e.ScoreBreakdown),Tags:e.Tags||[],EntityIcon:e.EntityIcon,RecordName:e.RecordName,MatchedAt:e.MatchedAt,RawMetadata:e.RawMetadata,ProviderId:e.ProviderId,ProviderLabel:e.ProviderLabel,ProviderIcon:e.ProviderIcon}}mapScoreBreakdown(e){if(!e)return{};const t={};return e.Vector!==void 0&&(t.Vector=e.Vector),e.FullText!==void 0&&(t.FullText=e.FullText),e.Entity!==void 0&&(t.Entity=e.Entity),e.Storage!==void 0&&(t.Storage=e.Storage),t}mapSourceCounts(e){return e?{Vector:e.Vector??0,FullText:e.FullText??0,Entity:e.Entity??0,Storage:e.Storage??0}:{Vector:0,FullText:0,Entity:0,Storage:0}}handleSearchError(e){const t=e;return c.LogError(`Error executing search: ${t}`),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,SourceCounts:{Vector:0,FullText:0,Entity:0,Storage:0},Providers:[],ErrorMessage:`Error: ${t.message}`}}}class Oe{static{d(this,"GraphQLIntegrationClient")}constructor(e){this._dataProvider=e}async DiscoverObjects(e){try{const t=u.gql`
|
|
1835
1829
|
query IntegrationDiscoverObjects($companyIntegrationID: String!) {
|
|
1836
1830
|
IntegrationDiscoverObjects(companyIntegrationID: $companyIntegrationID) {
|
|
1837
1831
|
Success
|
|
@@ -1888,7 +1882,7 @@
|
|
|
1888
1882
|
Warnings
|
|
1889
1883
|
}
|
|
1890
1884
|
}
|
|
1891
|
-
`,
|
|
1885
|
+
`,a=(await this._dataProvider.ExecuteGQL(s,{companyIntegrationID:e,objects:t,platform:r}))?.IntegrationSchemaPreview;if(!a)throw new Error("Invalid response from server");return{Success:a.Success,Message:a.Message,Files:a.Files??[],Warnings:a.Warnings??[]}}catch(s){const n=s;return 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`
|
|
1892
1886
|
query IntegrationPreviewData(
|
|
1893
1887
|
$companyIntegrationID: String!,
|
|
1894
1888
|
$objectName: String!,
|
|
@@ -1906,7 +1900,7 @@
|
|
|
1906
1900
|
}
|
|
1907
1901
|
}
|
|
1908
1902
|
}
|
|
1909
|
-
`,
|
|
1903
|
+
`,a=(await this._dataProvider.ExecuteGQL(s,{companyIntegrationID:e,objectName:t,limit:r}))?.IntegrationPreviewData;if(!a)throw new Error("Invalid response from server");return{Success:a.Success,Message:a.Message,Records:a.Records??[]}}catch(s){const n=s;return c.LogError(`Error previewing integration data: ${n}`),{Success:!1,Message:`Error: ${n.message}`,Records:[]}}}async GetDefaultConfig(e){try{const t=u.gql`
|
|
1910
1904
|
query IntegrationGetDefaultConfig($companyIntegrationID: String!) {
|
|
1911
1905
|
IntegrationGetDefaultConfig(companyIntegrationID: $companyIntegrationID) {
|
|
1912
1906
|
Success
|
|
@@ -1943,13 +1937,13 @@
|
|
|
1943
1937
|
IntegrationUpdateEntityMaps(updates: $updates) { Success Message }
|
|
1944
1938
|
}`;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!]!) {
|
|
1945
1939
|
IntegrationDeleteEntityMaps(entityMapIDs: $entityMapIDs) { Success Message }
|
|
1946
|
-
}`;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
|
|
1940
|
+
}`;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(
|
|
1947
1941
|
$companyIntegrationID: String!, $objects: [SchemaPreviewObjectInput!]!, $platform: String!, $skipGitCommit: Boolean!, $skipRestart: Boolean!
|
|
1948
1942
|
) {
|
|
1949
1943
|
IntegrationApplySchema(companyIntegrationID: $companyIntegrationID, objects: $objects, platform: $platform, skipGitCommit: $skipGitCommit, skipRestart: $skipRestart) {
|
|
1950
1944
|
Success Message Steps { Name Status DurationMs Message } MigrationFilePath APIRestarted GitCommitSuccess
|
|
1951
1945
|
}
|
|
1952
|
-
}`;return(await this._dataProvider.ExecuteGQL(
|
|
1946
|
+
}`;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(
|
|
1953
1947
|
$items: [ApplySchemaBatchItemInput!]!, $platform: String!, $skipGitCommit: Boolean!, $skipRestart: Boolean!
|
|
1954
1948
|
) {
|
|
1955
1949
|
IntegrationApplySchemaBatch(items: $items, platform: $platform, skipGitCommit: $skipGitCommit, skipRestart: $skipRestart) {
|
|
@@ -1975,14 +1969,14 @@
|
|
|
1975
1969
|
}
|
|
1976
1970
|
}
|
|
1977
1971
|
}
|
|
1978
|
-
`,s=(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationListSourceObjects;if(!s)throw new Error("Invalid response from server");return{Success:s.Success,Message:s.Message,Data:s.Objects??[]}}catch(t){return this.handleError(t,[])}}async ApplyAllBatch(e,t=!0,r=!1,s="created",n="sqlserver",
|
|
1972
|
+
`,s=(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationListSourceObjects;if(!s)throw new Error("Invalid response from server");return{Success:s.Success,Message:s.Message,Data:s.Objects??[]}}catch(t){return this.handleError(t,[])}}async ApplyAllBatch(e,t=!0,r=!1,s="created",n="sqlserver",a=!1,i=!1){try{const o=u.gql`mutation($input: ApplyAllBatchInput!, $platform: String!, $skipGitCommit: Boolean!, $skipRestart: Boolean!) {
|
|
1979
1973
|
IntegrationApplyAllBatch(input: $input, platform: $platform, skipGitCommit: $skipGitCommit, skipRestart: $skipRestart) {
|
|
1980
1974
|
Success Message SuccessCount FailureCount
|
|
1981
1975
|
ConnectorResults { CompanyIntegrationID IntegrationName Success Message EntityMapsCreated { SourceObjectName EntityName EntityMapID FieldMapCount } SyncRunID Warnings }
|
|
1982
1976
|
PipelineSteps { Name Status DurationMs Message }
|
|
1983
1977
|
GitCommitSuccess APIRestarted
|
|
1984
1978
|
}
|
|
1985
|
-
}`,y={Connectors:e.map(
|
|
1979
|
+
}`,y={Connectors:e.map(S=>({CompanyIntegrationID:S.CompanyIntegrationID,SourceObjects:S.SourceObjects.map(h=>({SourceObjectID:h.SourceObjectID??null,SourceObjectName:h.SourceObjectName??null,Fields:h.Fields??null}))})),StartSync:t,FullSync:r,SyncScope:s},l=(await this._dataProvider.ExecuteGQL(o,{input:y,platform:n,skipGitCommit:a,skipRestart:i}))?.IntegrationApplyAllBatch;return l?{Success:l.Success,Message:l.Message,Steps:l.PipelineSteps,GitCommitSuccess:l.GitCommitSuccess,APIRestarted:l.APIRestarted,EntityMapsCreated:l.ConnectorResults?.[0]?.EntityMapsCreated,SyncRunID:l.ConnectorResults?.[0]?.SyncRunID,Warnings:l.ConnectorResults?.flatMap(S=>S.Warnings??[])}:{Success:!1,Message:"No response"}}catch(o){return{Success:!1,Message:o.message}}}async ApplyAll(e,t,r="sqlserver",s=!1,n=!1){try{const a=u.gql`mutation IntegrationApplyAll(
|
|
1986
1980
|
$input: ApplyAllInput!, $platform: String!, $skipGitCommit: Boolean!, $skipRestart: Boolean!
|
|
1987
1981
|
) {
|
|
1988
1982
|
IntegrationApplyAll(input: $input, platform: $platform, skipGitCommit: $skipGitCommit, skipRestart: $skipRestart) {
|
|
@@ -1991,7 +1985,7 @@
|
|
|
1991
1985
|
EntityMapsCreated { SourceObjectName EntityName EntityMapID FieldMapCount }
|
|
1992
1986
|
SyncRunID GitCommitSuccess APIRestarted Warnings
|
|
1993
1987
|
}
|
|
1994
|
-
}`,i={CompanyIntegrationID:e,SourceObjectNames:t};return(await this._dataProvider.ExecuteGQL(
|
|
1988
|
+
}`,i={CompanyIntegrationID:e,SourceObjectNames:t};return(await this._dataProvider.ExecuteGQL(a,{input:i,platform:r,skipGitCommit:s,skipRestart:n}))?.IntegrationApplyAll??{Success:!1,Message:"No response"}}catch(a){return{Success:!1,Message:a.message}}}async StartSync(e,t,r,s){try{const n=u.gql`mutation IntegrationStartSync(
|
|
1995
1989
|
$companyIntegrationID: String!,
|
|
1996
1990
|
$webhookURL: String,
|
|
1997
1991
|
$fullSync: Boolean,
|
|
@@ -2024,5 +2018,5 @@
|
|
|
2024
2018
|
IntegrationGetConnectorCapabilities(companyIntegrationID: $companyIntegrationID) {
|
|
2025
2019
|
Success Message SupportsGet SupportsCreate SupportsUpdate SupportsDelete SupportsSearch
|
|
2026
2020
|
}
|
|
2027
|
-
}`;return(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationGetConnectorCapabilities??{Success:!1,Message:"No response"}}catch(t){return{Success:!1,Message:t.message}}}handleError(e,t){const r=e;return c.LogError(`Error in integration discovery: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Data:t}}}Object.defineProperty(exports,"gql",{enumerable:!0,get:d(function(){return u.gql},"get")}),exports.ActionItemInput=
|
|
2021
|
+
}`;return(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationGetConnectorCapabilities??{Success:!1,Message:"No response"}}catch(t){return{Success:!1,Message:t.message}}}handleError(e,t){const r=e;return c.LogError(`Error in integration discovery: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Data:t}}}Object.defineProperty(exports,"gql",{enumerable:!0,get:d(function(){return u.gql},"get")}),exports.ActionItemInput=Ee,exports.ActionItemOutput=De,exports.BrowserIndexedDBStorageProvider=B,exports.BrowserStorageProviderBase=k,exports.FieldMapper=b,exports.FireAndForgetHelper=w,exports.GetDataOutput=Ce,exports.GraphQLAIClient=O,exports.GraphQLActionClient=Le,exports.GraphQLClassifyClient=Ge,exports.GraphQLClusterClient=xe,exports.GraphQLComponentRegistryClient=Qe,exports.GraphQLDataProvider=f,exports.GraphQLEncryptionClient=Te,exports.GraphQLFileStorageClient=_e,exports.GraphQLIntegrationClient=Oe,exports.GraphQLListsClient=be,exports.GraphQLLiveKitClient=Fe,exports.GraphQLProviderConfigData=me,exports.GraphQLSearchClient=Ve,exports.GraphQLSystemUserClient=ve,exports.GraphQLTestingClient=qe,exports.GraphQLTransactionGroup=V,exports.GraphQLVersionHistoryClient=Ue,exports.PACKAGE_VERSION=A,exports.RoleInput=he,exports.RolesAndUsersInput=fe,exports.SafeGraphQLError=x,exports.SanitizeGraphQLError=G,exports.SimpleRemoteEntity=$e,exports.SimpleRemoteEntityField=Pe,exports.SimpleRemoteEntityOutput=we,exports.SyncDataAction=J,exports.SyncDataResult=Re,exports.SyncRolesAndUsersResult=pe,exports.ToSafeGraphQLError=j,exports.UserInput=Ie,exports.setupGraphQLClient=Se;
|
|
2028
2022
|
//# sourceMappingURL=index.cjs.map
|