@memberjunction/graphql-dataprovider 5.34.1 → 5.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var z=Object.defineProperty;var y=(I,e)=>z(I,"name",{value:e,configurable:!0});import{gql as c,GraphQLClient as Q}from"graphql-request";import{gql as tt}from"graphql-request";import{TransactionGroupBase as H,TransactionResult as X,LogError as d,LogStatus as A,LogErrorEx as b,ProviderBase as Y,UserInfo as U,getGraphQLTypeNameBase as M,ProviderType as Z,BaseEntityResult as L,EntityFieldTSType as N,TransactionItem as G,CompositeKey as ee,UserRoleInfo as te,InMemoryLocalStorageProvider as re,BaseEntity as se,ProviderConfigDataBase as ne,SetProvider as ae,StartupManager as oe,IsPlatformSQL as ie,IsVerboseLoggingEnabled as ce}from"@memberjunction/core";import{SafeJSONParse as C,CleanAndParseJSON as ue,GetGlobalObjectStore as V,UUIDsEqual as le,MJGlobal as _,MJEventType as q}from"@memberjunction/global";import{ViewInfo as O}from"@memberjunction/core-entities";import{BehaviorSubject as de,Observable as x,Subject as ye,Subscription as ge}from"rxjs";import{createClient as me}from"graphql-ws";import{v4 as Se}from"uuid";import{openDB as pe}from"@tempfix/idb";class v{static{y(this,"FieldMapper")}static{this.DB_PREFIX="__mj_"}static{this.GQL_PREFIX="_mj__"}constructor(){}MapFields(e){if(e)for(const t in e){const r=this.MapFieldName(t);r!==t&&(e[r]=e[t],delete e[t])}return e}MapFieldName(e){return e.startsWith(v.DB_PREFIX)?v.GQL_PREFIX+e.substring(v.DB_PREFIX.length):e}ReverseMapFieldName(e){return e.startsWith(v.GQL_PREFIX)?v.DB_PREFIX+e.substring(v.GQL_PREFIX.length):e}ReverseMapFields(e){for(const t in e){const r=this.ReverseMapFieldName(t);r!==t&&(e[r]=e[t],delete e[t])}return e}}class k extends H{static{y(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=c`
1
+ var re=Object.defineProperty;var y=(m,e)=>re(m,"name",{value:e,configurable:!0});import{gql as c,GraphQLClient as q}from"graphql-request";import{gql as yt}from"graphql-request";import{TransactionGroupBase as se,TransactionResult as ne,LogError as d,LogStatus as N,LogErrorEx as A,ProviderBase as ae,UserInfo as O,getGraphQLTypeNameBase as M,ProviderType as oe,BaseEntityResult as U,EntityFieldTSType as b,TransactionItem as k,CompositeKey as ie,UserRoleInfo as ce,InMemoryLocalStorageProvider as ue,BaseEntity as le,ProviderConfigDataBase as de,SetProvider as ye,StartupManager as me,IsPlatformSQL as ge,IsVerboseLoggingEnabled as pe}from"@memberjunction/core";import{SafeJSONParse as C,CleanAndParseJSON as Se,GetGlobalObjectStore as B,UUIDsEqual as he,MJGlobal as K,MJEventType as j}from"@memberjunction/global";import{ViewInfo as J}from"@memberjunction/core-entities";import{BehaviorSubject as Ie,Observable as T,Subject as fe,Subscription as De}from"rxjs";import{createClient as Re}from"graphql-ws";import{v4 as Ee}from"uuid";import{openDB as ve}from"@tempfix/idb";class v{static{y(this,"FieldMapper")}static{this.DB_PREFIX="__mj_"}static{this.GQL_PREFIX="_mj__"}constructor(){}MapFields(e){if(e)for(const t in e){const r=this.MapFieldName(t);r!==t&&(e[r]=e[t],delete e[t])}return e}MapFieldName(e){return e.startsWith(v.DB_PREFIX)?v.GQL_PREFIX+e.substring(v.DB_PREFIX.length):e}ReverseMapFieldName(e){return e.startsWith(v.GQL_PREFIX)?v.DB_PREFIX+e.substring(v.GQL_PREFIX.length):e}ReverseMapFields(e){for(const t in e){const r=this.ReverseMapFieldName(t);r!==t&&(e[r]=e[t],delete e[t])}return e}}class W extends se{static{y(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=c`
2
2
  mutation ExecuteTransactionGroup($group: TransactionInputType!) {
3
3
  ExecuteTransactionGroup(group: $group) {
4
4
  Success
@@ -6,7 +6,7 @@ var z=Object.defineProperty;var y=(I,e)=>z(I,"name",{value:e,configurable:!0});i
6
6
  ResultsJSON
7
7
  }
8
8
  }
9
- `,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const r={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const n=s.ExecuteTransactionGroup,a=[];for(let i=0;i<this.PendingTransactions.length;i++){const o=n.ResultsJSON[i],u=C(o),l=this.PendingTransactions[i];a.push(new X(l,u,u!==null))}return a}else throw new Error("Failed to execute transaction group")}}const he=900*1e3;class P{static{y(this,"FireAndForgetHelper")}static async Execute(e){const t=e.operationLabel??e.mutationFieldName;let r,s;try{const{promise:n,resolve:a,reject:i}=P.createCompletionPromise();s=P.setupTimeout(i,e.timeoutMs,e.timeoutErrorMessage),r=P.subscribeToPubSub(e,a,s);const o=await P.executeMutation(e);if(!e.validateAck(o)){s&&clearTimeout(s);const u=o?.errorMessage??"Server rejected the request";return d(`[FireAndForget:${t}] Server rejected: ${u}`),e.createErrorResult(u)}return A(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await n}catch(n){throw s&&clearTimeout(s),d(`[FireAndForget:${t}] Error: ${n.message}`),n}finally{s&&clearTimeout(s),r&&r.unsubscribe()}}static createCompletionPromise(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}static setupTimeout(e,t,r){const s=t??he,n=r??"The operation may still be running on the server but the client timed out after 15 minutes. Please refresh the page to check the latest status.";return setTimeout(()=>{e(new Error(n))},s)}static subscribeToPubSub(e,t,r){const s=e.dataProvider.sessionId,n=e.operationLabel??e.mutationFieldName;return e.dataProvider.PushStatusUpdates(s).subscribe(a=>{try{const i=JSON.parse(a);e.onMessage&&e.onMessage(i),e.isCompletionEvent(i)&&(clearTimeout(r),A(`[FireAndForget:${n}] Completion event received`),t(e.extractResult(i)))}catch(i){console.error(`[FireAndForget:${n}] Failed to parse PubSub message:`,i)}})}static async executeMutation(e){return(await e.dataProvider.ExecuteGQL(e.mutation,e.variables))[e.mutationFieldName]}}class B{static{y(this,"GraphQLAIClient")}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=c`
9
+ `,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const r={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const n=s.ExecuteTransactionGroup,a=[];for(let i=0;i<this.PendingTransactions.length;i++){const o=n.ResultsJSON[i],l=C(o),u=this.PendingTransactions[i];a.push(new ne(u,l,l!==null))}return a}else throw new Error("Failed to execute transaction group")}}const we=900*1e3;class P{static{y(this,"FireAndForgetHelper")}static async Execute(e){const t=e.operationLabel??e.mutationFieldName;let r,s;try{const{promise:n,resolve:a,reject:i}=P.createCompletionPromise();s=P.setupTimeout(i,e.timeoutMs,e.timeoutErrorMessage),r=P.subscribeToPubSub(e,a,s);const o=await P.executeMutation(e);if(!e.validateAck(o)){s&&clearTimeout(s);const l=o?.errorMessage??"Server rejected the request";return d(`[FireAndForget:${t}] Server rejected: ${l}`),e.createErrorResult(l)}return N(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await n}catch(n){throw s&&clearTimeout(s),d(`[FireAndForget:${t}] Error: ${n.message}`),n}finally{s&&clearTimeout(s),r&&r.unsubscribe()}}static createCompletionPromise(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}static setupTimeout(e,t,r){const s=t??we,n=r??"The operation may still be running on the server but the client timed out after 15 minutes. Please refresh the page to check the latest status.";return setTimeout(()=>{e(new Error(n))},s)}static subscribeToPubSub(e,t,r){const s=e.dataProvider.sessionId,n=e.operationLabel??e.mutationFieldName;return e.dataProvider.PushStatusUpdates(s).subscribe(a=>{try{const i=JSON.parse(a);e.onMessage&&e.onMessage(i),e.isCompletionEvent(i)&&(clearTimeout(r),N(`[FireAndForget:${n}] Completion event received`),t(e.extractResult(i)))}catch(i){console.error(`[FireAndForget:${n}] Failed to parse PubSub message:`,i)}})}static async executeMutation(e){return(await e.dataProvider.ExecuteGQL(e.mutation,e.variables))[e.mutationFieldName]}}class z{static{y(this,"GraphQLAIClient")}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=c`
10
10
  mutation RunAIPrompt(
11
11
  $promptId: String!,
12
12
  $data: String,
@@ -65,7 +65,7 @@ var z=Object.defineProperty;var y=(I,e)=>z(I,"name",{value:e,configurable:!0});i
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=ue(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 d(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){try{const s=this.buildRunAIAgentMutation(),n=this.prepareAgentVariables(e,t,r);return n.fireAndForget=!0,await P.Execute({dataProvider:this._dataProvider,mutation:s,variables:n,mutationFieldName:"RunAIAgent",operationLabel:"RunAIAgent",validateAck:y(a=>a?.success===!0,"validateAck"),isCompletionEvent:y(a=>this.isAgentCompletionEvent(a),"isCompletionEvent"),extractResult:y(a=>this.extractAgentResult(a),"extractResult"),onMessage:e.onProgress?a=>this.forwardAgentProgress(a,e.onProgress):void 0,createErrorResult:y(a=>this.createAgentErrorResult(a),"createErrorResult")})}catch(s){return this.handleAgentError(s)}}buildRunAIAgentMutation(){return c`
68
+ `,r=this.preparePromptVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(s)}catch(t){return this.handlePromptError(t)}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,n;try{t.parsedResult&&(r=Se(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 d(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){try{const s=this.buildRunAIAgentMutation(),n=this.prepareAgentVariables(e,t,r);return n.fireAndForget=!0,await P.Execute({dataProvider:this._dataProvider,mutation:s,variables:n,mutationFieldName:"RunAIAgent",operationLabel:"RunAIAgent",validateAck:y(a=>a?.success===!0,"validateAck"),isCompletionEvent:y(a=>this.isAgentCompletionEvent(a),"isCompletionEvent"),extractResult:y(a=>this.extractAgentResult(a),"extractResult"),onMessage:e.onProgress?a=>this.forwardAgentProgress(a,e.onProgress):void 0,createErrorResult:y(a=>this.createAgentErrorResult(a),"createErrorResult")})}catch(s){return this.handleAgentError(s)}}buildRunAIAgentMutation(){return c`
69
69
  mutation RunAIAgent(
70
70
  $agentId: String!,
71
71
  $messages: String!,
@@ -297,7 +297,7 @@ var z=Object.defineProperty;var y=(I,e)=>z(I,"name",{value:e,configurable:!0});i
297
297
  }
298
298
  }
299
299
  }
300
- `,r={entityDocumentID:e.entityDocumentID};e.maxRecords!==void 0&&(r.maxRecords=e.maxRecords),e.filter!==void 0&&(r.filter=e.filter);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.FetchEntityVectors)throw new Error("Invalid response from server");return s.FetchEntityVectors}catch(t){const r=t;return d("GraphQLAIClient.FetchEntityVectors failed",void 0,r),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,ErrorMessage:r.message||"Unknown error"}}}}const F="5.34.1",$="default";class K{static{y(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||$;let r=this._storage.get(t);return r||(r=new Map,this._storage.set(t,r)),r}async GetItem(e,t){const s=this.getCategoryMap(t||$).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||$);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||$).set(e,t)}async Remove(e,t){this.getCategoryMap(t||$).delete(e)}async ClearCategory(e){const t=e||$;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||$);return t?Array.from(t.keys()):[]}}const Ie="MJ_Metadata",fe=0;function Re(){try{const I=F.split("."),e=parseInt(I[0],10),t=parseInt(I[1],10);if(!Number.isFinite(e)||!Number.isFinite(t))throw new Error(`Could not parse major.minor from version "${F}"`);return e*1e3+t+fe}catch(I){return b({error:I,message:"Failed to derive IDB version from PACKAGE_VERSION; using fallback 99999"}),99999}}y(Re,"computeIdbVersion");const De=Re(),j=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"];class J extends K{static{y(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=pe(Ie,De,{upgrade:y((e,t,r)=>{try{A(`[IDBCache] Upgrading IndexedDB schema v${t} \u2192 v${r} (package ${F}). Dropping all stores; caches will repopulate on first use.`);for(const s of Array.from(e.objectStoreNames))e.deleteObjectStore(s);for(const s of j)e.objectStoreNames.contains(s)||e.createObjectStore(s)}catch(s){b({error:s,message:s?.message})}},"upgrade"),blocked:y((e,t)=>{A(`[IDBCache] Upgrade from v${e} to v${t} blocked by another tab. Close other tabs to allow the upgrade to proceed.`)},"blocked")}),this.dbPromise.then(e=>{this._dbReady=!0,e.onversionchange=()=>{A("[IDBCache] DB schema upgraded in another tab \u2014 closing local connection."),e.close(),this._dbReady=!1}}).catch(e=>{b({error:e,message:"IndexedDB initialization failed: "+e?.message})})}get IsReady(){return this._dbReady}isKnownCategory(e){const t=`mj:${e}`;return j.includes(t)}getStoreName(e){const t=e||$;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||$;return this.isKnownCategory(r)?e:`[${r}]:${e}`}async SetItem(e,t,r){try{const s=await this.dbPromise,n=this.getStoreName(r),a=this.getStoreKey(e,r),i=s.transaction(n,"readwrite");await i.objectStore(n).put(t,a),await i.done}catch(s){b({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 b({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(R=>this.getStoreKey(R,t)),o=s.transaction(n,"readonly"),u=o.objectStore(n),l=i.map(R=>u.get(R)),f=await Promise.all(l);await o.done;for(let R=0;R<a.length;R++){const S=f[R];r.set(a[R],S===void 0?null:S)}return r}catch(s){b({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){b({error:r,message:r?.message})}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||$,s=this.getStoreName(e);if(this.isKnownCategory(r)){const n=t.transaction(s,"readwrite");await n.objectStore(s).clear(),await n.done}else{const n=`[${r}]:`,a=t.transaction("mj:default","readwrite"),i=a.objectStore("mj:default"),o=await i.getAllKeys();for(const u of o)typeof u=="string"&&u.startsWith(n)&&await i.delete(u);await a.done}}catch(t){b({error:t,message:t?.message})}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||$,s=this.getStoreName(e),i=await t.transaction(s,"readonly").objectStore(s).getAllKeys();if(this.isKnownCategory(r))return i.map(u=>String(u));const o=`[${r}]:`;return i.map(u=>String(u)).filter(u=>u.startsWith(o)).map(u=>u.slice(o.length))}catch(t){return b({error:t,message:t?.message}),[]}}}class Ee extends ne{static{y(this,"GraphQLProviderConfigData")}get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get MJAPIKey(){return this.Data.MJAPIKey}set MJAPIKey(e){this.Data.MJAPIKey=e}get UserAPIKey(){return this.Data.UserAPIKey}set UserAPIKey(e){this.Data.UserAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}get OnAuthenticationError(){return this.Data.OnAuthenticationError}set OnAuthenticationError(e){this.Data.OnAuthenticationError=e}constructor(e,t,r,s,n,a,i,o,u,l){super({Token:e,URL:t,WSURL:r,MJAPIKey:o,UserAPIKey:u,RefreshTokenFunction:s,OnAuthenticationError:l},n,a,i)}}class p extends Y{static{y(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._dynamicHeaders=new Map,this._innerCurrentUserQueryString=`CurrentUser {
300
+ `,r={entityDocumentID:e.entityDocumentID};e.maxRecords!==void 0&&(r.maxRecords=e.maxRecords),e.filter!==void 0&&(r.filter=e.filter);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.FetchEntityVectors)throw new Error("Invalid response from server");return s.FetchEntityVectors}catch(t){const r=t;return d("GraphQLAIClient.FetchEntityVectors failed",void 0,r),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,ErrorMessage:r.message||"Unknown error"}}}}const L="5.36.0",$="default";class H{static{y(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||$;let r=this._storage.get(t);return r||(r=new Map,this._storage.set(t,r)),r}async GetItem(e,t){const s=this.getCategoryMap(t||$).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||$);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||$).set(e,t)}async Remove(e,t){this.getCategoryMap(t||$).delete(e)}async ClearCategory(e){const t=e||$;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||$);return t?Array.from(t.keys()):[]}}const Ce="MJ_Metadata",$e=0;function Pe(){try{const m=L.split("."),e=parseInt(m[0],10),t=parseInt(m[1],10);if(!Number.isFinite(e)||!Number.isFinite(t))throw new Error(`Could not parse major.minor from version "${L}"`);return e*1e3+t+$e}catch(m){return A({error:m,message:"Failed to derive IDB version from PACKAGE_VERSION; using fallback 99999"}),99999}}y(Pe,"computeIdbVersion");const Ae=Pe(),X=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"];class Y extends H{static{y(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=ve(Ce,Ae,{upgrade:y((e,t,r)=>{try{N(`[IDBCache] Upgrading IndexedDB schema v${t} \u2192 v${r} (package ${L}). Dropping all stores; caches will repopulate on first use.`);for(const s of Array.from(e.objectStoreNames))e.deleteObjectStore(s);for(const s of X)e.objectStoreNames.contains(s)||e.createObjectStore(s)}catch(s){A({error:s,message:s?.message})}},"upgrade"),blocked:y((e,t)=>{N(`[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=()=>{N("[IDBCache] DB schema upgraded in another tab \u2014 closing local connection."),e.close(),this._dbReady=!1}}).catch(e=>{A({error:e,message:"IndexedDB initialization failed: "+e?.message})})}get IsReady(){return this._dbReady}isKnownCategory(e){const t=`mj:${e}`;return X.includes(t)}getStoreName(e){const t=e||$;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||$;return this.isKnownCategory(r)?e:`[${r}]:${e}`}async SetItem(e,t,r){try{const s=await this.dbPromise,n=this.getStoreName(r),a=this.getStoreKey(e,r),i=s.transaction(n,"readwrite");await i.objectStore(n).put(t,a),await i.done}catch(s){A({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 A({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(D=>this.getStoreKey(D,t)),o=s.transaction(n,"readonly"),l=o.objectStore(n),u=i.map(D=>l.get(D)),f=await Promise.all(u);await o.done;for(let D=0;D<a.length;D++){const p=f[D];r.set(a[D],p===void 0?null:p)}return r}catch(s){A({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){A({error:r,message:r?.message})}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||$,s=this.getStoreName(e);if(this.isKnownCategory(r)){const n=t.transaction(s,"readwrite");await n.objectStore(s).clear(),await n.done}else{const n=`[${r}]:`,a=t.transaction("mj:default","readwrite"),i=a.objectStore("mj:default"),o=await i.getAllKeys();for(const l of o)typeof l=="string"&&l.startsWith(n)&&await i.delete(l);await a.done}}catch(t){A({error:t,message:t?.message})}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||$,s=this.getStoreName(e),i=await t.transaction(s,"readonly").objectStore(s).getAllKeys();if(this.isKnownCategory(r))return i.map(l=>String(l));const o=`[${r}]:`;return i.map(l=>String(l)).filter(l=>l.startsWith(o)).map(l=>l.slice(o.length))}catch(t){return A({error:t,message:t?.message}),[]}}}class be extends de{static{y(this,"GraphQLProviderConfigData")}get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get MJAPIKey(){return this.Data.MJAPIKey}set MJAPIKey(e){this.Data.MJAPIKey=e}get UserAPIKey(){return this.Data.UserAPIKey}set UserAPIKey(e){this.Data.UserAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}get OnAuthenticationError(){return this.Data.OnAuthenticationError}set OnAuthenticationError(e){this.Data.OnAuthenticationError=e}constructor(e,t,r,s,n,a,i,o,l,u){super({Token:e,URL:t,WSURL:r,MJAPIKey:o,UserAPIKey:l,RefreshTokenFunction:s,OnAuthenticationError:u},n,a,i)}}class h extends ae{static{y(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._dynamicHeaders=new Map,this._innerCurrentUserQueryString=`CurrentUser {
301
301
  ${this.userInfoString()}
302
302
  MJUserRoles_UserIDArray {
303
303
  ${this.userRoleInfoString()}
@@ -306,7 +306,7 @@ var z=Object.defineProperty;var y=(I,e)=>z(I,"name",{value:e,configurable:!0});i
306
306
  `,this._currentUserQuery=c`query CurrentUserAndRoles {
307
307
  ${this._innerCurrentUserQueryString}
308
308
  CurrentUserTenantContext
309
- }`,this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject=new de("unknown"),this._isDisposingSocketIntentionally=!1,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=1800*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=300*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=600*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,this._cacheInvalidationSubscription=null;const e=V();if(e&&e[p._globalStoreKey])return e[p._globalStoreKey];e&&(e[p._globalStoreKey]=this)}static{this._globalStoreKey="___SINGLETON__GraphQLDataProvider"}static get Instance(){const e=V();return e?e[p._globalStoreKey]:void 0}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new B(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 Se()}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)):(p.Instance._configData=e,p.Instance._sessionId===void 0&&(p.Instance._sessionId=await this.GetPreferredUUID(s)),p.Instance._client||(p.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,p.Instance._sessionId,e.MJAPIKey,e.UserAPIKey)),await p.Instance.SaveStoredSessionID(p.Instance._sessionId),this._sessionId=p.Instance._sessionId,this._client=p.Instance._client),super.Config(e)}catch(n){throw d(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),p.Instance&&p.Instance!==this&&p.Instance._configData===this._configData&&(p.Instance._dynamicHeaders.set(e,t),p.Instance._client&&p.Instance._client.setHeader(e,t))}RemoveDynamicHeader(e){this._dynamicHeaders.delete(e),this._client&&this._client.setHeader(e,""),p.Instance&&p.Instance!==this&&p.Instance._configData===this._configData&&(p.Instance._dynamicHeaders.delete(e),p.Instance._client&&p.Instance._client.setHeader(e,""))}GetDynamicHeaders(){return this._dynamicHeaders}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),r=t.MJUserRoles_UserIDArray.map(n=>this.ConvertBackToMJFields(n));t.MJUserRoles_UserIDArray=r;const s=new U(this,{...t,UserRoles:r});return e.CurrentUserTenantContext&&typeof e.CurrentUserTenantContext=="object"&&(s.TenantContext=e.CurrentUserTenantContext),s}}async RunReport(e,t){const r=c`
309
+ }`,this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject=new Ie("unknown"),this._isDisposingSocketIntentionally=!1,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=1800*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=300*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=600*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,this._cacheInvalidationSubscription=null;const e=B();if(e&&e[h._globalStoreKey])return e[h._globalStoreKey];e&&(e[h._globalStoreKey]=this)}static{this._globalStoreKey="___SINGLETON__GraphQLDataProvider"}static get Instance(){const e=B();return e?e[h._globalStoreKey]:void 0}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new z(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 Ee()}get LocalStoragePrefix(){if(this._configData===void 0||this._configData.URL===void 0)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const r=this.LocalStoragePrefix+"sessionId";await t.SetItem(r,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,r,s){try{return this._configData=e,r?(this._sessionId=await this.GetPreferredUUID(s),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey,e.UserAPIKey),await this.SaveStoredSessionID(this._sessionId)):(h.Instance._configData=e,h.Instance._sessionId===void 0&&(h.Instance._sessionId=await this.GetPreferredUUID(s)),h.Instance._client||(h.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,h.Instance._sessionId,e.MJAPIKey,e.UserAPIKey)),await h.Instance.SaveStoredSessionID(h.Instance._sessionId),this._sessionId=h.Instance._sessionId,this._client=h.Instance._client),super.Config(e)}catch(n){throw d(n),n}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}SetDynamicHeader(e,t){this._dynamicHeaders.set(e,t),this._client&&this._client.setHeader(e,t),h.Instance&&h.Instance!==this&&h.Instance._configData===this._configData&&(h.Instance._dynamicHeaders.set(e,t),h.Instance._client&&h.Instance._client.setHeader(e,t))}RemoveDynamicHeader(e){this._dynamicHeaders.delete(e),this._client&&this._client.setHeader(e,""),h.Instance&&h.Instance!==this&&h.Instance._configData===this._configData&&(h.Instance._dynamicHeaders.delete(e),h.Instance._client&&h.Instance._client.setHeader(e,""))}GetDynamicHeaders(){return this._dynamicHeaders}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),r=t.MJUserRoles_UserIDArray.map(n=>this.ConvertBackToMJFields(n));t.MJUserRoles_UserIDArray=r;const s=new O(this,{...t,UserRoles:r});return e.CurrentUserTenantContext&&typeof e.CurrentUserTenantContext=="object"&&(s.TenantContext=e.CurrentUserTenantContext),s}}async RunReport(e,t){const r=c`
310
310
  query GetReportDataQuery ($ReportID: String!) {
311
311
  GetReportData(ReportID: $ReportID) {
312
312
  Success
@@ -315,13 +315,13 @@ var z=Object.defineProperty;var y=(I,e)=>z(I,"name",{value:e,configurable:!0});i
315
315
  ExecutionTime
316
316
  ErrorMessage
317
317
  }
318
- }`,s=await this.ExecuteGQL(r,{ReportID:e.ReportID});if(s&&s.GetReportData)return{ReportID:e.ReportID,Success:s.GetReportData.Success,Results:JSON.parse(s.GetReportData.Results),RowCount:s.GetReportData.RowCount,ExecutionTime:s.GetReportData.ExecutionTime,ErrorMessage:s.GetReportData.ErrorMessage}}async InternalRunQuery(e,t){if(e.SQL)return this.RunAdhocQuery(e.SQL,e.MaxRows);if(e.QueryID)return this.RunQueryByID(e.QueryID,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);throw new Error("No SQL, QueryID, or QueryName provided to RunQuery")}async RunAdhocQuery(e,t,r){const s=c`
318
+ }`,s=await this.ExecuteGQL(r,{ReportID:e.ReportID});if(s&&s.GetReportData)return{ReportID:e.ReportID,Success:s.GetReportData.Success,Results:JSON.parse(s.GetReportData.Results),RowCount:s.GetReportData.RowCount,ExecutionTime:s.GetReportData.ExecutionTime,ErrorMessage:s.GetReportData.ErrorMessage}}async InternalRunQuery(e,t){if(e.SQL)return this.RunAdhocQuery(e.SQL,e.MaxRows,void 0,e.StartRow);if(e.QueryID)return this.RunQueryByID(e.QueryID,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);throw new Error("No SQL, QueryID, or QueryName provided to RunQuery")}async RunAdhocQuery(e,t,r,s){const n=c`
319
319
  query ExecuteAdhocQuery($input: AdhocQueryInput!) {
320
320
  ExecuteAdhocQuery(input: $input) {
321
321
  ${this.QueryReturnFieldList}
322
322
  }
323
323
  }
324
- `,n={SQL:e};r!==void 0&&(n.TimeoutSeconds=r);const a=await this.ExecuteGQL(s,{input:n});return a?.ExecuteAdhocQuery?this.TransformQueryPayload(a.ExecuteAdhocQuery):{QueryID:"",QueryName:"Ad-Hoc Query",Success:!1,Results:[],RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Ad-hoc query execution failed \u2014 no response from server"}}async InternalRunQueries(e,t){const r=c`
324
+ `,a={SQL:e};r!==void 0&&(a.TimeoutSeconds=r),t!==void 0&&(a.MaxRows=t),s!==void 0&&(a.StartRow=s);const i=await this.ExecuteGQL(n,{input:a});return i?.ExecuteAdhocQuery?this.TransformQueryPayload(i.ExecuteAdhocQuery):{QueryID:"",QueryName:"Ad-Hoc Query",Success:!1,Results:[],RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Ad-hoc query execution failed \u2014 no response from server"}}async InternalRunQueries(e,t){const r=c`
325
325
  query RunQueriesBatch($input: [RunQueryInput!]!) {
326
326
  RunQueries(input: $input) {
327
327
  ${this.QueryReturnFieldList}
@@ -333,13 +333,13 @@ var z=Object.defineProperty;var y=(I,e)=>z(I,"name",{value:e,configurable:!0});i
333
333
  ${this.QueryReturnFieldList}
334
334
  }
335
335
  }
336
- `,u={QueryID:e};t!==void 0&&(u.CategoryID=t),r!==void 0&&(u.CategoryPath=r),n!==void 0&&(u.Parameters=n),a!==void 0&&(u.MaxRows=a),i!==void 0&&(u.StartRow=i);const l=await this.ExecuteGQL(o,u);if(l&&l.GetQueryData)return this.TransformQueryPayload(l.GetQueryData)}async RunQueryByName(e,t,r,s,n,a,i){const o=c`
336
+ `,l={QueryID:e};t!==void 0&&(l.CategoryID=t),r!==void 0&&(l.CategoryPath=r),n!==void 0&&(l.Parameters=n),a!==void 0&&(l.MaxRows=a),i!==void 0&&(l.StartRow=i);const u=await this.ExecuteGQL(o,l);if(u&&u.GetQueryData)return this.TransformQueryPayload(u.GetQueryData)}async RunQueryByName(e,t,r,s,n,a,i){const o=c`
337
337
  query GetQueryDataByNameQuery($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
338
338
  GetQueryDataByName(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
339
339
  ${this.QueryReturnFieldList}
340
340
  }
341
341
  }
342
- `,u={QueryName:e};t!==void 0&&(u.CategoryID=t),r!==void 0&&(u.CategoryPath=r),n!==void 0&&(u.Parameters=n),a!==void 0&&(u.MaxRows=a),i!==void 0&&(u.StartRow=i);const l=await this.ExecuteGQL(o,u);if(l&&l.GetQueryDataByName)return this.TransformQueryPayload(l.GetQueryDataByName)}get QueryReturnFieldList(){return`
342
+ `,l={QueryName:e};t!==void 0&&(l.CategoryID=t),r!==void 0&&(l.CategoryPath=r),n!==void 0&&(l.Parameters=n),a!==void 0&&(l.MaxRows=a),i!==void 0&&(l.StartRow=i);const u=await this.ExecuteGQL(o,l);if(u&&u.GetQueryDataByName)return this.TransformQueryPayload(u.GetQueryDataByName)}get QueryReturnFieldList(){return`
343
343
  Success
344
344
  QueryID
345
345
  QueryName
@@ -364,14 +364,14 @@ var z=Object.defineProperty;var y=(I,e)=>z(I,"name",{value:e,configurable:!0});i
364
364
  }
365
365
  }
366
366
  }
367
- `,a=(await this.ExecuteGQL(s,{input:r}))?.RunQueriesWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map(o=>{if((o.status==="stale"||o.status==="no_validation")&&o.Results){const u=JSON.parse(o.Results);return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,results:u,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 d(`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:m,v:h}=await this.getEntityNameAndUserView(e,t);i=h,a=m}const o=this.Entities.find(m=>m.Name===a);if(!o)throw new Error(`Entity ${a} not found in metadata`);let u=!1;const l=M(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):(u=!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),u||(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(m=>({expression:m.expression,alias:m.alias})));const f=this.getViewRunTimeFieldList(o,i,e,u),R=e.Aggregates&&e.Aggregates.length>0?`
367
+ `,a=(await this.ExecuteGQL(s,{input:r}))?.RunQueriesWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map(o=>{if((o.status==="stale"||o.status==="no_validation")&&o.Results){const l=JSON.parse(o.Results);return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,results:l,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}});return{success:a.success,results:i,errorMessage:a.errorMessage}}catch(r){return d(`Error in RunQueriesWithCacheCheck: ${r}`),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async InternalRunView(e,t){try{let r="",s="";if(e){const n={};let a,i;if(e.ViewEntity)i=e.ViewEntity,a=i.Entity;else{const{entityName:S,v:I}=await this.getEntityNameAndUserView(e,t);i=I,a=S}const o=this.Entities.find(S=>S.Name===a);if(!o)throw new Error(`Entity ${a} not found in metadata`);let l=!1;const u=M(o);e.ViewID?(r=`Run${u}ViewByID`,s="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(r=`Run${u}ViewByName`,s="RunViewByNameInput",n.ViewName=e.ViewName):(l=!0,r=`Run${u}DynamicView`,s="RunDynamicViewInput",n.EntityName=e.EntityName),n.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",n.OrderBy=e.OrderBy?e.OrderBy:"",n.UserSearchString=e.UserSearchString?e.UserSearchString:"",n.Fields=e.Fields,n.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,e.MaxRows!==void 0&&(n.MaxRows=e.MaxRows),e.StartRow!==void 0&&(n.StartRow=e.StartRow),n.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,n.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(n.AuditLogDescription=e.AuditLogDescription),e.BypassCache!==void 0&&(n.BypassCache=e.BypassCache),l||(n.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",n.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,n.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",n.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1),e.Aggregates&&e.Aggregates.length>0&&(n.Aggregates=e.Aggregates.map(S=>({expression:S.expression,alias:S.alias})));const f=this.getViewRunTimeFieldList(o,i,e,l),D=e.Aggregates&&e.Aggregates.length>0?`
368
368
  AggregateResults {
369
369
  alias
370
370
  expression
371
371
  value
372
372
  error
373
373
  }
374
- AggregateExecutionTime`:"",S=c`
374
+ AggregateExecutionTime`:"",p=c`
375
375
  query RunViewQuery ($input: ${s}!) {
376
376
  ${r}(input: $input) {
377
377
  Results {
@@ -383,9 +383,9 @@ var z=Object.defineProperty;var y=(I,e)=>z(I,"name",{value:e,configurable:!0});i
383
383
  TotalRowCount
384
384
  ExecutionTime
385
385
  Success
386
- ErrorMessage${R}
386
+ ErrorMessage${D}
387
387
  }
388
- }`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:a,queryName:r,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const g=await this.ExecuteGQL(S,{input:n});if(g&&g[r]){const m=g[r].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:a,aggregateResultCount:m?.length||0,aggregateResults:m,aggregateExecutionTime:g[r].AggregateExecutionTime});const h=g[r].Results;if(h&&h.length>0){const w=o.Fields.filter(E=>E.CodeName!==E.Name&&E.CodeName!==void 0);h.forEach(E=>{this.ConvertBackToMJFields(E),w.forEach(T=>{E[T.Name]=E[T.CodeName]})})}return g[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw d(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],n=[];for(const l of e){let f="",R="";const S={};let g=null,m=null;if(l.ViewEntity)m=l.ViewEntity,g=m.Get("Entity");else{const{entityName:E,v:T}=await this.getEntityNameAndUserView(l,t);m=T,g=E}const h=this.Entities.find(E=>E.Name===g);if(!h)throw new Error(`Entity ${g} not found in metadata`);s.push(h);let D=!1;const w=M(h);l.ViewID?(f=`Run${w}ViewByID`,R="RunViewByIDInput",S.ViewID=l.ViewID):l.ViewName?(f=`Run${w}ViewByName`,R="RunViewByNameInput",S.ViewName=l.ViewName):(D=!0,f=`Run${w}DynamicView`,R="RunDynamicViewInput",S.EntityName=l.EntityName),S.ExtraFilter=l.ExtraFilter||"",S.OrderBy=l.OrderBy||"",S.UserSearchString=l.UserSearchString||"",S.Fields=l.Fields,S.IgnoreMaxRows=l.IgnoreMaxRows||!1,l.MaxRows!==void 0&&(S.MaxRows=l.MaxRows),l.StartRow!==void 0&&(S.StartRow=l.StartRow),l.AfterKey&&(S.AfterKey={KeyValuePairs:l.AfterKey.KeyValuePairs}),S.ForceAuditLog=l.ForceAuditLog||!1,S.ResultType=l.ResultType||"simple",l.AuditLogDescription&&l.AuditLogDescription.length>0&&(S.AuditLogDescription=l.AuditLogDescription),D||(S.ExcludeUserViewRunID=l.ExcludeUserViewRunID||"",S.ExcludeDataFromAllPriorViewRuns=l.ExcludeDataFromAllPriorViewRuns||!1,S.OverrideExcludeFilter=l.OverrideExcludeFilter||"",S.SaveViewResults=l.SaveViewResults||!1),l.Aggregates&&l.Aggregates.length>0&&(S.Aggregates=l.Aggregates.map(E=>({expression:E.expression,alias:E.alias}))),r.push(S),n.push(...this.getViewRunTimeFieldList(h,m,l,D))}const i=e.some(l=>l.Aggregates&&l.Aggregates.length>0)?`
388
+ }`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:a,queryName:r,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const g=await this.ExecuteGQL(p,{input:n});if(g&&g[r]){const S=g[r].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:a,aggregateResultCount:S?.length||0,aggregateResults:S,aggregateExecutionTime:g[r].AggregateExecutionTime});const I=g[r].Results;if(I&&I.length>0){const w=o.Fields.filter(E=>E.CodeName!==E.Name&&E.CodeName!==void 0);I.forEach(E=>{this.ConvertBackToMJFields(E),w.forEach(x=>{E[x.Name]=E[x.CodeName]})})}return g[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw d(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],n=[];for(const u of e){let f="",D="";const p={};let g=null,S=null;if(u.ViewEntity)S=u.ViewEntity,g=S.Get("Entity");else{const{entityName:E,v:x}=await this.getEntityNameAndUserView(u,t);S=x,g=E}const I=this.Entities.find(E=>E.Name===g);if(!I)throw new Error(`Entity ${g} not found in metadata`);s.push(I);let R=!1;const w=M(I);u.ViewID?(f=`Run${w}ViewByID`,D="RunViewByIDInput",p.ViewID=u.ViewID):u.ViewName?(f=`Run${w}ViewByName`,D="RunViewByNameInput",p.ViewName=u.ViewName):(R=!0,f=`Run${w}DynamicView`,D="RunDynamicViewInput",p.EntityName=u.EntityName),p.ExtraFilter=u.ExtraFilter||"",p.OrderBy=u.OrderBy||"",p.UserSearchString=u.UserSearchString||"",p.Fields=u.Fields,p.IgnoreMaxRows=u.IgnoreMaxRows||!1,u.MaxRows!==void 0&&(p.MaxRows=u.MaxRows),u.StartRow!==void 0&&(p.StartRow=u.StartRow),u.AfterKey&&(p.AfterKey={KeyValuePairs:u.AfterKey.KeyValuePairs}),p.ForceAuditLog=u.ForceAuditLog||!1,p.ResultType=u.ResultType||"simple",u.AuditLogDescription&&u.AuditLogDescription.length>0&&(p.AuditLogDescription=u.AuditLogDescription),u.BypassCache!==void 0&&(p.BypassCache=u.BypassCache),R||(p.ExcludeUserViewRunID=u.ExcludeUserViewRunID||"",p.ExcludeDataFromAllPriorViewRuns=u.ExcludeDataFromAllPriorViewRuns||!1,p.OverrideExcludeFilter=u.OverrideExcludeFilter||"",p.SaveViewResults=u.SaveViewResults||!1),u.Aggregates&&u.Aggregates.length>0&&(p.Aggregates=u.Aggregates.map(E=>({expression:E.expression,alias:E.alias}))),r.push(p),n.push(...this.getViewRunTimeFieldList(I,S,u,R))}const i=e.some(u=>u.Aggregates&&u.Aggregates.length>0)?`
389
389
  AggregateResults {
390
390
  alias
391
391
  expression
@@ -410,7 +410,7 @@ var z=Object.defineProperty;var y=(I,e)=>z(I,"name",{value:e,configurable:!0});i
410
410
  Success
411
411
  ErrorMessage${i}
412
412
  }
413
- }`,u=await this.ExecuteGQL(o,{input:r});if(u&&u.RunViews){const l=u.RunViews;for(const[f,R]of l.entries())R.Results=R.Results.map(S=>{let g=JSON.parse(S.Data);return this.ConvertBackToMJFields(g),g});return l}return null}catch(r){throw d(r),r}}async RunViewsWithCacheCheck(e,t){try{const r=e.map(o=>({params:{EntityName:o.params.EntityName||"",ExtraFilter:o.params.ExtraFilter||"",OrderBy:o.params.OrderBy||"",Fields:o.params.Fields,UserSearchString:o.params.UserSearchString||"",IgnoreMaxRows:o.params.IgnoreMaxRows||!1,MaxRows:o.params.MaxRows,StartRow:o.params.StartRow,AfterKey:o.params.AfterKey?{KeyValuePairs:o.params.AfterKey.KeyValuePairs}:null,ForceAuditLog:o.params.ForceAuditLog||!1,AuditLogDescription:o.params.AuditLogDescription||"",ResultType:o.params.ResultType||"simple"},cacheStatus:o.cacheStatus?{maxUpdatedAt:o.cacheStatus.maxUpdatedAt,rowCount:o.cacheStatus.rowCount}:null})),s=c`
413
+ }`,l=await this.ExecuteGQL(o,{input:r});if(l&&l.RunViews){const u=l.RunViews;for(const[f,D]of u.entries())D.Results=D.Results.map(p=>{let g=JSON.parse(p.Data);return this.ConvertBackToMJFields(g),g});return u}return null}catch(r){throw d(r),r}}async RunViewsWithCacheCheck(e,t){try{const r=e.map(o=>({params:{EntityName:o.params.EntityName||"",ExtraFilter:o.params.ExtraFilter||"",OrderBy:o.params.OrderBy||"",Fields:o.params.Fields,UserSearchString:o.params.UserSearchString||"",IgnoreMaxRows:o.params.IgnoreMaxRows||!1,MaxRows:o.params.MaxRows,StartRow:o.params.StartRow,AfterKey:o.params.AfterKey?{KeyValuePairs:o.params.AfterKey.KeyValuePairs}:null,ForceAuditLog:o.params.ForceAuditLog||!1,AuditLogDescription:o.params.AuditLogDescription||"",ResultType:o.params.ResultType||"simple"},cacheStatus:o.cacheStatus?{maxUpdatedAt:o.cacheStatus.maxUpdatedAt,rowCount:o.cacheStatus.rowCount}:null})),s=c`
414
414
  query RunViewsWithCacheCheckQuery($input: [RunViewWithCacheCheckInput!]!) {
415
415
  RunViewsWithCacheCheck(input: $input) {
416
416
  success
@@ -443,7 +443,7 @@ var z=Object.defineProperty;var y=(I,e)=>z(I,"name",{value:e,configurable:!0});i
443
443
  }
444
444
  }
445
445
  }
446
- `,a=(await this.ExecuteGQL(s,{input:r}))?.RunViewsWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map((o,u)=>{const l=e[u];if(o.status==="differential"&&o.differentialData){const f=o.differentialData.updatedRows.map(R=>{const S=JSON.parse(R.Data);return this.ConvertBackToMJFields(S),S});return{viewIndex:o.viewIndex,status:o.status,results:void 0,differentialData:{updatedRows:f,deletedRecordIDs:o.differentialData.deletedRecordIDs},maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}if(o.status==="stale"&&o.Results){const f=o.Results.map(R=>{const S=JSON.parse(R.Data);return this.ConvertBackToMJFields(S),S});return{viewIndex:o.viewIndex,status:o.status,results:f,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}return{viewIndex:o.viewIndex,status:o.status,results:void 0,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}});return{success:a.success,results:i,errorMessage:a.errorMessage}}catch(r){return d(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 O.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await O.GetViewEntityByName(e.ViewName,t),r=s.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:r,v:s}}getViewRunTimeFieldList(e,t,r,s){const n=[],a=new v;if(r.Fields){for(const i of e.PrimaryKeys)r.Fields.find(o=>o.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);r.Fields.forEach(i=>{n.push(a.MapFieldName(i))})}else if(s)e.Fields.forEach(i=>{i.IsBinaryFieldType||n.push(a.MapFieldName(i.CodeName))});else{for(const i of e.PrimaryKeys)n.find(o=>o.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);t.Columns.forEach(i=>{i.hidden===!1&&!n.find(o=>o.trim().toLowerCase()===i.EntityField?.Name.trim().toLowerCase())&&i.EntityField&&n.push(a.MapFieldName(i.EntityField.CodeName))})}return n}get ProviderType(){return Z.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 d(r),r}}async GetRecordDependencies(e,t){try{const r=c`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
446
+ `,a=(await this.ExecuteGQL(s,{input:r}))?.RunViewsWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map((o,l)=>{const u=e[l];if(o.status==="differential"&&o.differentialData){const f=o.differentialData.updatedRows.map(D=>{const p=JSON.parse(D.Data);return this.ConvertBackToMJFields(p),p});return{viewIndex:o.viewIndex,status:o.status,results:void 0,differentialData:{updatedRows:f,deletedRecordIDs:o.differentialData.deletedRecordIDs},maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}if(o.status==="stale"&&o.Results){const f=o.Results.map(D=>{const p=JSON.parse(D.Data);return this.ConvertBackToMJFields(p),p});return{viewIndex:o.viewIndex,status:o.status,results:f,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}return{viewIndex:o.viewIndex,status:o.status,results:void 0,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}});return{success:a.success,results:i,errorMessage:a.errorMessage}}catch(r){return d(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 J.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await J.GetViewEntityByName(e.ViewName,t),r=s.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:r,v:s}}getViewRunTimeFieldList(e,t,r,s){const n=[],a=new v;if(r.Fields){for(const i of e.PrimaryKeys)r.Fields.find(o=>o.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);r.Fields.forEach(i=>{n.push(a.MapFieldName(i))})}else if(s)e.Fields.forEach(i=>{i.IsBinaryFieldType||n.push(a.MapFieldName(i.CodeName))});else{for(const i of e.PrimaryKeys)n.find(o=>o.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);t.Columns.forEach(i=>{i.hidden===!1&&!n.find(o=>o.trim().toLowerCase()===i.EntityField?.Name.trim().toLowerCase())&&i.EntityField&&n.push(a.MapFieldName(i.EntityField.CodeName))})}return n}get ProviderType(){return oe.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 d(r),r}}async GetRecordDependencies(e,t){try{const r=c`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
447
447
  GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
448
448
  EntityName
449
449
  RelatedEntityName
@@ -494,32 +494,32 @@ var z=Object.defineProperty;var y=(I,e)=>z(I,"name",{value:e,configurable:!0});i
494
494
  Message
495
495
  }
496
496
  }
497
- }`,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 d(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 L;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 L;try{e.RegisterTransactionPreprocessing();const n={input:{}},a=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(g=>({FieldName:g.CodeName,Value:g.Value})),e.RegisterResultHistoryEntry(s);const i=M(e.EntityInfo),o=`${a}${i}`,u=e.Fields.filter(g=>!g.ReadOnly||g.IsPrimaryKey&&e.IsSaved),l=new v,f=` ${o}(input: $input) {
498
- ${e.Fields.map(g=>l.MapFieldName(g.CodeName)).join(`
497
+ }`,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 d(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){if(r?.IsParentEntitySave){const n=new U;return n.StartedAt=new Date,n.EndedAt=new Date,n.Type=e.IsSaved?"update":"create",n.Success=!0,n.NewValues=e.GetAll(),e.RegisterResultHistoryEntry(n),n.NewValues}const s=new U;try{e.RegisterTransactionPreprocessing();const n={input:{}},a=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(g=>({FieldName:g.CodeName,Value:g.Value})),e.RegisterResultHistoryEntry(s);const i=M(e.EntityInfo),o=`${a}${i}`,l=e.Fields.filter(g=>!g.ReadOnly||g.IsPrimaryKey&&e.IsSaved),u=new v,f=` ${o}(input: $input) {
498
+ ${e.Fields.map(g=>u.MapFieldName(g.CodeName)).join(`
499
499
  `)}
500
- }`,R=c`mutation ${a}${i} ($input: ${o}Input!) {
500
+ }`,D=c`mutation ${a}${i} ($input: ${o}Input!) {
501
501
  ${f}
502
502
  }
503
- `;for(let g=0;g<u.length;g++){const m=u[g];let h=e.Get(m.Name);if(h)switch(m.EntityFieldInfo.TSType){case N.Date:h=h.getTime();break;case N.Boolean:typeof h!="boolean"&&(h=parseInt(h)!==0);break;case N.Number:if(typeof h!="number"){const D=Number(h);isNaN(D)||(h=D)}break}h===null&&m.EntityFieldInfo.AllowsNull===!1&&(m.EntityFieldInfo.DefaultValue!==null?h=m.EntityFieldInfo.DefaultValue:m.FieldType===N.Number||m.FieldType===N.Boolean?h=0:h=""),n.input[l.MapFieldName(m.CodeName)]=h}const S=e.RestoreContext;if(S&&(n.input.RestoreContext___={SourceChangeID:S.SourceChangeID,Reason:S.Reason}),a.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const g=[];e.Fields.forEach(m=>{let h=null;m.OldValue!==null&&m.OldValue!==void 0&&(m.EntityFieldInfo.TSType===N.Date?h=m.OldValue.getTime().toString():m.EntityFieldInfo.TSType===N.Boolean?h=m.OldValue===!0?"1":"0":typeof m.OldValue!="string"?h=m.OldValue.toString():h=m.OldValue),g.push({Key:l.MapFieldName(m.CodeName),Value:h})}),n.input.OldValues___=g}if(e.TransactionGroup){const g=[{varName:"input",inputType:o+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new G(e,s.Type==="create"?"Create":"Update",f,n,{mutationName:o,mutationInputTypes:g},(m,h)=>{s.EndedAt=new Date,h&&m?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(m)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const g=await this.ExecuteGQL(R,n);if(g&&g[o])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(g[o]),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(n){return s.Success=!1,s.EndedAt=new Date,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,d(n),null}}async Load(e,t,r=null,s){try{const n={};let a="",i="";for(let S=0;S<t.KeyValuePairs.length;S++){const g=e.Fields.find(D=>D.Name.trim().toLowerCase()===t.KeyValuePairs[S].FieldName.trim().toLowerCase()).EntityFieldInfo,m=t.GetValueByIndex(S),h=g.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${g.CodeName}: ${h}!`,a.length>0&&(a+=", "),a+=`${g.CodeName}: $${g.CodeName}`,g.TSType===N.Number){if(isNaN(t.GetValueByIndex(S)))throw new Error(`Primary Key value ${m} (${g.Name}) is not a valid number`);n[g.CodeName]=parseInt(m)}else n[g.CodeName]=m}const o=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",u=M(e.EntityInfo),l=new v,f=c`query Single${u}${o.length>0?"Full":""} (${i}) {
504
- ${u}(${a}) {
505
- ${e.Fields.filter(S=>!S.EntityFieldInfo.IsBinaryFieldType).map(S=>S.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?S.CodeName.replace("__mj_","_mj__"):S.CodeName).join(`
503
+ `;for(let g=0;g<l.length;g++){const S=l[g];let I=e.Get(S.Name);if(I)switch(S.EntityFieldInfo.TSType){case b.Date:I=I.getTime();break;case b.Boolean:typeof I!="boolean"&&(I=parseInt(I)!==0);break;case b.Number:if(typeof I!="number"){const R=Number(I);isNaN(R)||(I=R)}break}I===null&&S.EntityFieldInfo.AllowsNull===!1&&(S.EntityFieldInfo.DefaultValue!==null?I=S.EntityFieldInfo.DefaultValue:S.FieldType===b.Number||S.FieldType===b.Boolean?I=0:I=""),n.input[u.MapFieldName(S.CodeName)]=I}const p=e.RestoreContext;if(p&&(n.input.RestoreContext___={SourceChangeID:p.SourceChangeID,Reason:p.Reason}),a.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const g=[];e.Fields.forEach(S=>{let I=null;S.OldValue!==null&&S.OldValue!==void 0&&(S.EntityFieldInfo.TSType===b.Date?I=S.OldValue.getTime().toString():S.EntityFieldInfo.TSType===b.Boolean?I=S.OldValue===!0?"1":"0":typeof S.OldValue!="string"?I=S.OldValue.toString():I=S.OldValue),g.push({Key:u.MapFieldName(S.CodeName),Value:I})}),n.input.OldValues___=g}if(e.TransactionGroup){const g=[{varName:"input",inputType:o+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new k(e,s.Type==="create"?"Create":"Update",f,n,{mutationName:o,mutationInputTypes:g},(S,I)=>{s.EndedAt=new Date,I&&S?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(S)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const g=await this.ExecuteGQL(D,n);if(g&&g[o])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(g[o]),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(n){return s.Success=!1,s.EndedAt=new Date,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,d(n),null}}async Load(e,t,r=null,s){try{const n={};let a="",i="";for(let p=0;p<t.KeyValuePairs.length;p++){const g=e.Fields.find(R=>R.Name.trim().toLowerCase()===t.KeyValuePairs[p].FieldName.trim().toLowerCase()).EntityFieldInfo,S=t.GetValueByIndex(p),I=g.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${g.CodeName}: ${I}!`,a.length>0&&(a+=", "),a+=`${g.CodeName}: $${g.CodeName}`,g.TSType===b.Number){if(isNaN(t.GetValueByIndex(p)))throw new Error(`Primary Key value ${S} (${g.Name}) is not a valid number`);n[g.CodeName]=parseInt(S)}else n[g.CodeName]=S}const o=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",l=M(e.EntityInfo),u=new v,f=c`query Single${l}${o.length>0?"Full":""} (${i}) {
504
+ ${l}(${a}) {
505
+ ${e.Fields.filter(p=>!p.EntityFieldInfo.IsBinaryFieldType).map(p=>p.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?p.CodeName.replace("__mj_","_mj__"):p.CodeName).join(`
506
506
  `)}
507
507
  ${o}
508
508
  }
509
509
  }
510
- `,R=await this.ExecuteGQL(f,n);return R&&R[u]?this.ConvertBackToMJFields(R[u]):null}catch(n){return d(n),null}}ConvertBackToMJFields(e){return new v().ReverseMapFields(e),e}getRelatedEntityString(e,t){let r="";for(let s=0;s<e.RelatedEntities.length;s++)if(t.indexOf(e.RelatedEntities[s].RelatedEntity)>=0){const n=e.RelatedEntities[s],a=this.Entities.find(o=>le(o.ID,n.RelatedEntityID));let i="";n.Type.toLowerCase().trim()==="many to many"?i=`${n.RelatedEntityCodeName}_${n.JoinEntityJoinField.replace(/\s/g,"")}`:i=`${n.RelatedEntityCodeName}_${n.RelatedEntityJoinField.replace(/\s/g,"")}`,r+=`
510
+ `,D=await this.ExecuteGQL(f,n);return D&&D[l]?this.ConvertBackToMJFields(D[l]):null}catch(n){return d(n),null}}ConvertBackToMJFields(e){return new v().ReverseMapFields(e),e}getRelatedEntityString(e,t){let r="";for(let s=0;s<e.RelatedEntities.length;s++)if(t.indexOf(e.RelatedEntities[s].RelatedEntity)>=0){const n=e.RelatedEntities[s],a=this.Entities.find(o=>he(o.ID,n.RelatedEntityID));let i="";n.Type.toLowerCase().trim()==="many to many"?i=`${n.RelatedEntityCodeName}_${n.JoinEntityJoinField.replace(/\s/g,"")}`:i=`${n.RelatedEntityCodeName}_${n.RelatedEntityJoinField.replace(/\s/g,"")}`,r+=`
511
511
  ${i} {
512
512
  ${a.Fields.map(o=>o.CodeName).join(`
513
513
  `)}
514
514
  }
515
- `}return r}async Delete(e,t,r){const s=new L;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(g=>({FieldName:g.CodeName,Value:g.Value})),e.RegisterResultHistoryEntry(s);const n={},a=[];let i="",o="",u="";for(let g of e.PrimaryKey.KeyValuePairs){const m=e.Fields.find(h=>h.Name.trim().toLowerCase()===g.FieldName.trim().toLowerCase());n[m.CodeName]=m.Value,a.push({varName:m.CodeName,inputType:m.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${m.CodeName}: $${m.CodeName}`,o.length>0&&(o+=", "),o+=`$${m.CodeName}: ${m.EntityFieldInfo.GraphQLType}!`,u.length>0&&(u+=`
516
- `),u+=`${m.CodeName}`}a.push({varName:"options___",inputType:"DeleteOptionsInput!"}),n.options___={SkipEntityAIActions:t?.SkipEntityAIActions??!1,SkipEntityActions:t?.SkipEntityActions??!1,ReplayOnly:t?.ReplayOnly??!1,IsParentEntityDelete:t?.IsParentEntityDelete??!1};const f="Delete"+M(e.EntityInfo),R=c`${f}(${i}, options___: $options___) {
517
- ${u}
515
+ `}return r}async Delete(e,t,r){const s=new U;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(g=>({FieldName:g.CodeName,Value:g.Value})),e.RegisterResultHistoryEntry(s);const n={},a=[];let i="",o="",l="";for(let g of e.PrimaryKey.KeyValuePairs){const S=e.Fields.find(I=>I.Name.trim().toLowerCase()===g.FieldName.trim().toLowerCase());n[S.CodeName]=S.Value,a.push({varName:S.CodeName,inputType:S.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${S.CodeName}: $${S.CodeName}`,o.length>0&&(o+=", "),o+=`$${S.CodeName}: ${S.EntityFieldInfo.GraphQLType}!`,l.length>0&&(l+=`
516
+ `),l+=`${S.CodeName}`}a.push({varName:"options___",inputType:"DeleteOptionsInput!"}),n.options___={SkipEntityAIActions:t?.SkipEntityAIActions??!1,SkipEntityActions:t?.SkipEntityActions??!1,ReplayOnly:t?.ReplayOnly??!1,IsParentEntityDelete:t?.IsParentEntityDelete??!1};const f="Delete"+M(e.EntityInfo),D=c`${f}(${i}, options___: $options___) {
517
+ ${l}
518
518
  }
519
- `,S=c`mutation ${f} (${o}, $options___: DeleteOptionsInput!) {
520
- ${R}
519
+ `,p=c`mutation ${f} (${o}, $options___: DeleteOptionsInput!) {
520
+ ${D}
521
521
  }
522
- `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new G(e,"Delete",R,n,{mutationName:f,mutationInputTypes:a},(g,m)=>{if(s.EndedAt=new Date,m&&g){let h=!0;for(const D of e.PrimaryKey.KeyValuePairs)D.Value!==g[D.FieldName]&&(h=!1);h?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const g=await this.ExecuteGQL(S,n);if(g&&g[f]){const m=g[f];for(let h of e.PrimaryKey.KeyValuePairs){let D=m[h.FieldName],w=h.Value;if(typeof w=="number"&&(w=w.toString()),typeof D=="number"&&(D=D.toString()),w!==D)throw new Error(`Primary key value mismatch in server Delete response. Field: ${h.FieldName}, Original: ${w}, Returned: ${D}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(n){return s.EndedAt=new Date,s.Success=!1,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,d(n),!1}}async GetDatasetByName(e,t){const r=c`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
522
+ `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new k(e,"Delete",D,n,{mutationName:f,mutationInputTypes:a},(g,S)=>{if(s.EndedAt=new Date,S&&g){let I=!0;for(const R of e.PrimaryKey.KeyValuePairs)R.Value!==g[R.FieldName]&&(I=!1);I?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const g=await this.ExecuteGQL(p,n);if(g&&g[f]){const S=g[f];for(let I of e.PrimaryKey.KeyValuePairs){let R=S[I.FieldName],w=I.Value;if(typeof w=="number"&&(w=w.toString()),typeof R=="number"&&(R=R.toString()),w!==R)throw new Error(`Primary key value mismatch in server Delete response. Field: ${I.FieldName}, Original: ${w}, Returned: ${R}`)}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,d(n),!1}}async GetDatasetByName(e,t){const r=c`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
523
523
  GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
524
524
  DatasetID
525
525
  DatasetName
@@ -528,7 +528,7 @@ var z=Object.defineProperty;var y=(I,e)=>z(I,"name",{value:e,configurable:!0});i
528
528
  LatestUpdateDate
529
529
  Results
530
530
  }
531
- }`,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 p._datasetStatusCoalesceMs>0&&!t?this.enqueueDatasetStatusCheck(e):this.executeDatasetStatusByName(e,t)}enqueueDatasetStatusCheck(e){return new Promise((t,r)=>{p._datasetStatusQueue.push({datasetName:e,resolve:t,reject:r}),p._datasetStatusTimer||(p._datasetStatusTimer=setTimeout(()=>this.flushDatasetStatusQueue(),p._datasetStatusCoalesceMs))})}async flushDatasetStatusQueue(){p._datasetStatusTimer=null;const e=p._datasetStatusQueue.splice(0);if(e.length===0)return;if(e.length===1){try{const r=await this.executeDatasetStatusByName(e[0].datasetName,e[0].itemFilters);e[0].resolve(r)}catch(r){e[0].reject(r)}return}const t=e.map(r=>r.datasetName);A(`\u26A1 [Coalesce] Batching ${t.length} dataset status checks into 1 request: [${t.join(", ")}]`);try{const r=c`query GetMultipleDatasetStatusByName($DatasetNames: [String!]!) {
531
+ }`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetByName&&s.GetDatasetByName.Success?{DatasetID:s.GetDatasetByName.DatasetID,DatasetName:s.GetDatasetByName.DatasetName,Success:s.GetDatasetByName.Success,Status:s.GetDatasetByName.Status,LatestUpdateDate:new Date(s.GetDatasetByName.LatestUpdateDate),Results:JSON.parse(s.GetDatasetByName.Results)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,Results:null}}static{this._datasetStatusQueue=[]}static{this._datasetStatusTimer=null}static{this._datasetStatusCoalesceMs=10}async GetDatasetStatusByName(e,t){return h._datasetStatusCoalesceMs>0&&!t?this.enqueueDatasetStatusCheck(e):this.executeDatasetStatusByName(e,t)}enqueueDatasetStatusCheck(e){return new Promise((t,r)=>{h._datasetStatusQueue.push({datasetName:e,resolve:t,reject:r}),h._datasetStatusTimer||(h._datasetStatusTimer=setTimeout(()=>this.flushDatasetStatusQueue(),h._datasetStatusCoalesceMs))})}async flushDatasetStatusQueue(){h._datasetStatusTimer=null;const e=h._datasetStatusQueue.splice(0);if(e.length===0)return;if(e.length===1){try{const r=await this.executeDatasetStatusByName(e[0].datasetName,e[0].itemFilters);e[0].resolve(r)}catch(r){e[0].reject(r)}return}const t=e.map(r=>r.datasetName);N(`\u26A1 [Coalesce] Batching ${t.length} dataset status checks into 1 request: [${t.join(", ")}]`);try{const r=c`query GetMultipleDatasetStatusByName($DatasetNames: [String!]!) {
532
532
  GetMultipleDatasetStatusByName(DatasetNames: $DatasetNames) {
533
533
  DatasetID
534
534
  DatasetName
@@ -546,12 +546,12 @@ var z=Object.defineProperty;var y=(I,e)=>z(I,"name",{value:e,configurable:!0});i
546
546
  LatestUpdateDate
547
547
  EntityUpdateDates
548
548
  }
549
- }`,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 k(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const n=this.Entities.find(o=>o.Name===t);if(!n)throw new Error(`Entity ${t} not found in metadata`);const a=c`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
549
+ }`,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 W(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const n=this.Entities.find(o=>o.Name===t);if(!n)throw new Error(`Entity ${t} not found in metadata`);const a=c`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
550
550
  GetRecordFavoriteStatus(params: $params) {
551
551
  Success
552
552
  IsFavorite
553
553
  }
554
- }`,i=await this.ExecuteGQL(a,{params:{UserID:e,EntityID:n.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)}}});if(i&&i.GetRecordFavoriteStatus&&i.GetRecordFavoriteStatus.Success)return i.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,t,r,s,n){const a=this.Entities.find(u=>u.Name===t);if(!a)throw new Error(`Entity ${t} not found in metadata`);const i=c`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
554
+ }`,i=await this.ExecuteGQL(a,{params:{UserID:e,EntityID:n.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)}}});if(i&&i.GetRecordFavoriteStatus&&i.GetRecordFavoriteStatus.Success)return i.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,t,r,s,n){const a=this.Entities.find(l=>l.Name===t);if(!a)throw new Error(`Entity ${t} not found in metadata`);const i=c`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
555
555
  SetRecordFavoriteStatus(params: $params){
556
556
  Success
557
557
  }
@@ -574,7 +574,7 @@ var z=Object.defineProperty;var y=(I,e)=>z(I,"name",{value:e,configurable:!0});i
574
574
  EntityName
575
575
  RecordName
576
576
  }
577
- }`,r=await this.ExecuteGQL(t,{info:e.map(s=>({EntityName:s.EntityName,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.CompositeKey.KeyValuePairs)}}))});if(r&&r.GetEntityRecordNames)return r.GetEntityRecordNames.map(s=>({...s,CompositeKey:new ee(s.CompositeKey.KeyValuePairs)}))}async GetDataContextData(e){try{const t=c`query GetDataContextData ($DataContextID: String!) {
577
+ }`,r=await this.ExecuteGQL(t,{info:e.map(s=>({EntityName:s.EntityName,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.CompositeKey.KeyValuePairs)}}))});if(r&&r.GetEntityRecordNames)return r.GetEntityRecordNames.map(s=>({...s,CompositeKey:new ie(s.CompositeKey.KeyValuePairs)}))}async GetDataContextData(e){try{const t=c`query GetDataContextData ($DataContextID: String!) {
578
578
  GetDataContextData(DataContextID: $DataContextID) {
579
579
  Success
580
580
  ErrorMessages
@@ -586,16 +586,16 @@ var z=Object.defineProperty;var y=(I,e)=>z(I,"name",{value:e,configurable:!0});i
586
586
  ErrorMessage
587
587
  Result
588
588
  }
589
- }`,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 d(t),t}}static async ExecuteGQL(e,t,r=!0){return p.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(console.error("[GraphQL] ExecuteGQL error caught:",{hasResponse:!!s?.response,hasErrors:!!s?.response?.errors,errorCount:s?.response?.errors?.length,firstError:s?.response?.errors?.[0],errorCode:s?.response?.errors?.[0]?.extensions?.code,errorMessage:s?.response?.errors?.[0]?.message,fullError:s}),s&&s.response&&s.response.errors?.length>0)if(s.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw d("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw d(s),s}}async RefreshToken(){const e=p.Instance&&p.Instance._configData===this._configData;if(e&&p.Instance._refreshPromise)return p.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(p.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&p.Instance&&(p.Instance._refreshPromise=null)}}async performTokenRefresh(){if(this._configData.Data.RefreshTokenFunction)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,p.Instance&&p.Instance._configData===this._configData&&(p.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 p.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 Q(e,{headers:a});for(const[o,u]of this._dynamicHeaders)i.setHeader(o,u);return i}userInfoString(){return this.infoString(new U(null,null))}userRoleInfoString(){return this.infoString(new te(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
589
+ }`,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 d(t),t}}static async ExecuteGQL(e,t,r=!0){return h.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(console.error("[GraphQL] ExecuteGQL error caught:",{hasResponse:!!s?.response,hasErrors:!!s?.response?.errors,errorCount:s?.response?.errors?.length,firstError:s?.response?.errors?.[0],errorCode:s?.response?.errors?.[0]?.extensions?.code,errorMessage:s?.response?.errors?.[0]?.message,fullError:s}),s&&s.response&&s.response.errors?.length>0)if(s.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw d("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw d(s),s}}async RefreshToken(){const e=h.Instance&&h.Instance._configData===this._configData;if(e&&h.Instance._refreshPromise)return h.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(h.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&h.Instance&&(h.Instance._refreshPromise=null)}}async performTokenRefresh(){if(this._configData.Data.RefreshTokenFunction)try{const e=await this._configData.Data.RefreshTokenFunction();if(e){this._configData.Token=e;const t=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey,this._configData.UserAPIKey);this._client=t,h.Instance&&h.Instance._configData===this._configData&&(h.Instance._client=t)}else{const t=new Error("Refresh token function returned null or undefined token");throw this.notifyAuthenticationError(t),t}}catch(e){const t=e instanceof Error?e:new Error(String(e));throw this.notifyAuthenticationError(t),e}else{const e=new Error("No refresh token function provided");throw this.notifyAuthenticationError(e),e}}notifyAuthenticationError(e){try{const t=this._configData?.OnAuthenticationError;t&&t(e)}catch(t){console.error("[GraphQLDataProvider] Error in OnAuthenticationError callback:",t)}}static async RefreshToken(){return h.Instance.RefreshToken()}static async clearClientCache(e=new Set){const t=[];for(let r=0;r<localStorage.length;r++){const s=localStorage.key(r);s&&!e.has(s)&&t.push(s)}t.forEach(r=>localStorage.removeItem(r)),await new Promise(r=>{const s=indexedDB.deleteDatabase("MJ_Metadata");s.onsuccess=()=>r(),s.onerror=()=>r(),s.onblocked=()=>r()})}CreateNewGraphQLClient(e,t,r,s,n){const a={"x-session-id":r};t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),n&&(a["x-api-key"]=n);const i=new q(e,{headers:a});for(const[o,l]of this._dynamicHeaders)i.setHeader(o,l);return i}userInfoString(){return this.infoString(new O(null,null))}userRoleInfoString(){return this.infoString(new ce(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
590
590
  `:s.startsWith("_")||(t+=s+`
591
- `);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new J:this._localStorageProvider=new re),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=me({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token},keepAlive:3e4,retryAttempts:3,shouldRetry:y(()=>!0,"shouldRetry")}),this._wsClientCreatedAt=e,this._wsClient.on("connected",()=>{this._socketStateSubject.next("connected")}),this._wsClient.on("closed",()=>{this._isDisposingSocketIntentionally||this._socketStateSubject.next("disconnected")}),this._subscriptionCleanupTimer||(this._subscriptionCleanupTimer=setInterval(()=>{this.cleanupStaleSubscriptions()},this.SUBSCRIPTION_CLEANUP_INTERVAL_MS))),this._wsClient}disposeWSClient(){if(this._wsClient){this._isDisposingSocketIntentionally=!0;try{this._wsClient.dispose()}catch(e){console.error("[GraphQLDataProvider] Error disposing WebSocket client:",e)}this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject.next("unknown")}}completeAllSubjects(){this._pushStatusSubjects.forEach((e,t)=>{try{e.subject.complete(),e.subscription.unsubscribe()}catch(r){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,r)}}),this._pushStatusSubjects.clear()}cleanupStaleSubscriptions(){if(!this._isCleaningUp){this._isCleaningUp=!0;try{const e=Date.now(),t=this._pushStatusSubjects.size,r=Array.from(this._pushStatusSubjects.entries()),s=[];r.forEach(([n,a])=>{const i=e-a.lastRequestedAt,o=e-a.lastEmissionAt;a.activeSubscribers===0&&i>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&o>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${n} for cleanup: activeSubscribers=${a.activeSubscribers}, timeSinceRequested=${Math.round(i/1e3)}s, timeSinceEmission=${Math.round(o/1e3)}s`),s.push(n))}),s.forEach(n=>{const a=this._pushStatusSubjects.get(n);if(a)try{a.subject.complete(),a.subscription.unsubscribe(),this._pushStatusSubjects.delete(n),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${n}`)}catch(i){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${n}:`,i)}}),s.length>0&&console.log(`[GraphQLDataProvider] Cleaned up ${s.length} stale subscription(s)`),this._pushStatusSubjects.size===0&&this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&(console.log("[GraphQLDataProvider] Disposing of idle WebSocket client"),this.disposeWSClient())}finally{this._isCleaningUp=!1}}}subscribe(e,t){return new x(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=s.subscribe({query:e,variables:t},{next:y(a=>{r.next(a.data)},"next"),error:y(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(u){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",u),r.error(u)}}else r.error(a)},"error"),complete:y(()=>{r.complete()},"complete")});return()=>{this._activeSubscriptionCount--,n()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),r=this._pushStatusSubjects.get(e);if(r)return r.lastRequestedAt=t,new x(o=>{r.activeSubscribers++;const u=r.subject.subscribe(o);return()=>{const l=this._pushStatusSubjects.get(e);l&&l.activeSubscribers>0&&l.activeSubscribers--,u.unsubscribe()}});const s=c`subscription StatusUpdates($sessionId: String!) {
591
+ `);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new Y:this._localStorageProvider=new ue),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=Re({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token},keepAlive:3e4,retryAttempts:3,shouldRetry:y(()=>!0,"shouldRetry")}),this._wsClientCreatedAt=e,this._wsClient.on("connected",()=>{this._socketStateSubject.next("connected")}),this._wsClient.on("closed",()=>{this._isDisposingSocketIntentionally||this._socketStateSubject.next("disconnected")}),this._subscriptionCleanupTimer||(this._subscriptionCleanupTimer=setInterval(()=>{this.cleanupStaleSubscriptions()},this.SUBSCRIPTION_CLEANUP_INTERVAL_MS))),this._wsClient}disposeWSClient(){if(this._wsClient){this._isDisposingSocketIntentionally=!0;try{this._wsClient.dispose()}catch(e){console.error("[GraphQLDataProvider] Error disposing WebSocket client:",e)}this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject.next("unknown")}}completeAllSubjects(){this._pushStatusSubjects.forEach((e,t)=>{try{e.subject.complete(),e.subscription.unsubscribe()}catch(r){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,r)}}),this._pushStatusSubjects.clear()}cleanupStaleSubscriptions(){if(!this._isCleaningUp){this._isCleaningUp=!0;try{const e=Date.now(),t=this._pushStatusSubjects.size,r=Array.from(this._pushStatusSubjects.entries()),s=[];r.forEach(([n,a])=>{const i=e-a.lastRequestedAt,o=e-a.lastEmissionAt;a.activeSubscribers===0&&i>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&o>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${n} for cleanup: activeSubscribers=${a.activeSubscribers}, timeSinceRequested=${Math.round(i/1e3)}s, timeSinceEmission=${Math.round(o/1e3)}s`),s.push(n))}),s.forEach(n=>{const a=this._pushStatusSubjects.get(n);if(a)try{a.subject.complete(),a.subscription.unsubscribe(),this._pushStatusSubjects.delete(n),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${n}`)}catch(i){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${n}:`,i)}}),s.length>0&&console.log(`[GraphQLDataProvider] Cleaned up ${s.length} stale subscription(s)`),this._pushStatusSubjects.size===0&&this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&(console.log("[GraphQLDataProvider] Disposing of idle WebSocket client"),this.disposeWSClient())}finally{this._isCleaningUp=!1}}}subscribe(e,t){return new T(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=s.subscribe({query:e,variables:t},{next:y(a=>{r.next(a.data)},"next"),error:y(async a=>{const i=a;if(i?.extensions?.code==="JWT_EXPIRED"||i?.message?.includes("token has expired")||i?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] WebSocket JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),r.complete()}catch(l){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",l),r.error(l)}}else r.error(a)},"error"),complete:y(()=>{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 T(o=>{r.activeSubscribers++;const l=r.subject.subscribe(o);return()=>{const u=this._pushStatusSubjects.get(e);u&&u.activeSubscribers>0&&u.activeSubscribers--,l.unsubscribe()}});const s=c`subscription StatusUpdates($sessionId: String!) {
592
592
  statusUpdates(sessionId: $sessionId) {
593
593
  date
594
594
  message
595
595
  sessionId
596
596
  }
597
597
  }
598
- `,n=new ye,a=this.getOrCreateWSClient(),i=new ge;return i.add(new x(o=>{const u=a.subscribe({query:s,variables:{sessionId:e}},{next:y(l=>{const f=this._pushStatusSubjects.get(e);f&&(f.lastEmissionAt=Date.now()),o.next(l.data.statusUpdates.message)},"next"),error:y(async l=>{const f=l;if(f?.extensions?.code==="JWT_EXPIRED"||f?.message?.includes("token has expired")||f?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),o.complete()}catch(S){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",S),o.error(S)}}else o.error(l)},"error"),complete:y(()=>{o.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,u()}}).subscribe({next:y(o=>n.next(o),"next"),error:y(o=>{n.error(o),this._pushStatusSubjects.delete(e)},"error"),complete:y(()=>{n.complete(),this._pushStatusSubjects.delete(e)},"complete")})),this._pushStatusSubjects.set(e,{subject:n,subscription:i,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new x(o=>{const u=this._pushStatusSubjects.get(e);u&&u.activeSubscribers++;const l=n.subscribe(o);return()=>{const f=this._pushStatusSubjects.get(e);f&&f.activeSubscribers>0&&f.activeSubscribers--,l.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.UnsubscribeFromCacheInvalidation(),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}ClientToolRequests(e){return this.subscribe(`
598
+ `,n=new fe,a=this.getOrCreateWSClient(),i=new De;return i.add(new T(o=>{const l=a.subscribe({query:s,variables:{sessionId:e}},{next:y(u=>{const f=this._pushStatusSubjects.get(e);f&&(f.lastEmissionAt=Date.now()),o.next(u.data.statusUpdates.message)},"next"),error:y(async u=>{const f=u;if(f?.extensions?.code==="JWT_EXPIRED"||f?.message?.includes("token has expired")||f?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),o.complete()}catch(p){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",p),o.error(p)}}else o.error(u)},"error"),complete:y(()=>{o.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,l()}}).subscribe({next:y(o=>n.next(o),"next"),error:y(o=>{n.error(o),this._pushStatusSubjects.delete(e)},"error"),complete:y(()=>{n.complete(),this._pushStatusSubjects.delete(e)},"complete")})),this._pushStatusSubjects.set(e,{subject:n,subscription:i,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new T(o=>{const l=this._pushStatusSubjects.get(e);l&&l.activeSubscribers++;const u=n.subscribe(o);return()=>{const f=this._pushStatusSubjects.get(e);f&&f.activeSubscribers>0&&f.activeSubscribers--,u.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.UnsubscribeFromCacheInvalidation(),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}ClientToolRequests(e){return this.subscribe(`
599
599
  subscription ClientToolRequest($sessionID: String!) {
600
600
  ClientToolRequest(sessionID: $sessionID) {
601
601
  AgentRunID
@@ -617,7 +617,7 @@ var z=Object.defineProperty;var y=(I,e)=>z(I,"name",{value:e,configurable:!0});i
617
617
  OriginSessionID
618
618
  RecordData
619
619
  }
620
- }`,t=this.subscribe(e);this._cacheInvalidationSubscription=t.subscribe({next:y(r=>{const s=r?.cacheInvalidation;if(!s)return;if(s.OriginSessionID&&s.OriginSessionID===this.sessionId){console.debug(`[GraphQLDataProvider] Skipping self-originated cache invalidation for "${s.EntityName}" (action: ${s.Action})`);return}console.debug(`[GraphQLDataProvider] Cache invalidation received: ${s.Action} for "${s.EntityName}" from server ${s.SourceServerID?.substring(0,8)||"unknown"}`);const n={type:"remote-invalidate",entityName:s.EntityName,baseEntity:null,provider:this,payload:{primaryKeyValues:s.PrimaryKeyValues,action:s.Action,sourceServerId:s.SourceServerID,timestamp:s.Timestamp,recordData:s.RecordData}};_.Instance.RaiseEvent({event:q.ComponentEvent,eventCode:se.BaseEventCode,args:n,component:this})},"next"),error:y(r=>{console.error("[GraphQLDataProvider] Cache invalidation subscription error:",r),this._cacheInvalidationSubscription=null},"error"),complete:y(()=>{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!) {
620
+ }`,t=this.subscribe(e);this._cacheInvalidationSubscription=t.subscribe({next:y(r=>{const s=r?.cacheInvalidation;if(!s)return;if(s.OriginSessionID&&s.OriginSessionID===this.sessionId){console.debug(`[GraphQLDataProvider] Skipping self-originated cache invalidation for "${s.EntityName}" (action: ${s.Action})`);return}console.debug(`[GraphQLDataProvider] Cache invalidation received: ${s.Action} for "${s.EntityName}" from server ${s.SourceServerID?.substring(0,8)||"unknown"}`);const n={type:"remote-invalidate",entityName:s.EntityName,baseEntity:null,provider:this,payload:{primaryKeyValues:s.PrimaryKeyValues,action:s.Action,sourceServerId:s.SourceServerID,timestamp:s.Timestamp,recordData:s.RecordData}};K.Instance.RaiseEvent({event:j.ComponentEvent,eventCode:le.BaseEventCode,args:n,component:this})},"next"),error:y(r=>{console.error("[GraphQLDataProvider] Cache invalidation subscription error:",r),this._cacheInvalidationSubscription=null},"error"),complete:y(()=>{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!) {
621
621
  FindISAChildEntity(EntityName: $EntityName, RecordID: $RecordID) {
622
622
  Success
623
623
  ChildEntityName
@@ -629,14 +629,14 @@ var z=Object.defineProperty;var y=(I,e)=>z(I,"name",{value:e,configurable:!0});i
629
629
  ChildEntityNames
630
630
  ErrorMessage
631
631
  }
632
- }`;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 d(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function ve(I){const e=new p;return ae(e),await e.Config(I),await e.preValidateAndRefresh(),_.Instance.RaiseEvent({event:q.LoggedIn,eventCode:null,component:this,args:null}),await oe.Instance.Startup(),e}y(ve,"setupGraphQLClient");class we{static{y(this,"SyncRolesAndUsersResult")}}class Ce{static{y(this,"RoleInput")}}class $e{static{y(this,"UserInput")}}class Pe{static{y(this,"RolesAndUsersInput")}}var W=(I=>(I.Create="Create",I.Update="Update",I.CreateOrUpdate="CreateOrUpdate",I.Delete="Delete",I.DeleteWithFilter="DeleteWithFilter",I))(W||{});class be{static{y(this,"ActionItemInput")}}class Ne{static{y(this,"SyncDataResult")}constructor(){this.Results=[]}}class Ae{static{y(this,"ActionItemOutput")}}class Me{static{y(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 Q(e,{headers:n})}resolvePlatformSQL(e){if(e!=null)return ie(e)?e.default:e}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
632
+ }`;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 d(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function Ne(m){const e=new h;return ye(e),await e.Config(m),await e.preValidateAndRefresh(),K.Instance.RaiseEvent({event:j.LoggedIn,eventCode:null,component:this,args:null}),await me.Instance.Startup(),e}y(Ne,"setupGraphQLClient");class Me{static{y(this,"SyncRolesAndUsersResult")}}class Te{static{y(this,"RoleInput")}}class xe{static{y(this,"UserInput")}}class Le{static{y(this,"RolesAndUsersInput")}}var Z=(m=>(m.Create="Create",m.Update="Update",m.CreateOrUpdate="CreateOrUpdate",m.Delete="Delete",m.DeleteWithFilter="DeleteWithFilter",m))(Z||{});class Fe{static{y(this,"ActionItemInput")}}class Qe{static{y(this,"SyncDataResult")}constructor(){this.Results=[]}}class Ue{static{y(this,"ActionItemOutput")}}class Ge{static{y(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 q(e,{headers:n})}resolvePlatformSQL(e){if(e!=null)return ge(e)?e.default:e}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
633
633
  GetData(input: $input) {
634
634
  Success
635
635
  ErrorMessages
636
636
  Queries
637
637
  Results
638
638
  }
639
- }`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(n=>n?C(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]+"."),ce()){const a=`GraphQLSystemUserClient::GetData - Error getting data - ${r}`;d(a)}return{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
639
+ }`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(n=>n?C(n):null),ErrorMessages:s.GetData.ErrorMessages,Queries:s.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:s.GetData?.ErrorMessages??["Unknown error"],Queries:s.GetData?.Queries??e}}catch(r){let s=r instanceof Error?r.message:String(r);const n=s.match(/Error: ([^:]+)\./);if(n&&(s=n[1]+"."),pe()){const a=`GraphQLSystemUserClient::GetData - Error getting data - ${r}`;d(a)}return{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
640
640
  GetAllEntities {
641
641
  Success
642
642
  ErrorMessage
@@ -1131,7 +1131,7 @@ var z=Object.defineProperty;var y=(I,e)=>z(I,"name",{value:e,configurable:!0});i
1131
1131
  ErrorMessage
1132
1132
  }
1133
1133
  }
1134
- `,r={query:e.Query};e.MaxResults!==void 0&&(r.maxResults=e.MaxResults);const s=await this.Client.request(t,r);return s?.PreviewSearchAsSystemUser?this.mapSearchResponse(s.PreviewSearchAsSystemUser):this.searchErrorResponse("Invalid response from server")}catch(t){return d(`GraphQLSystemUserClient::PreviewSearch - Error executing preview search - ${t}`),this.searchErrorResponse(t instanceof Error?t.message:String(t))}}mapSearchResponse(e){return{Success:e.Success,Results:(e.Results||[]).map(t=>({ID:t.ID,EntityName:t.EntityName,RecordID:t.RecordID,SourceType:t.SourceType,ResultType:t.ResultType,Title:t.Title,Snippet:t.Snippet,Score:t.Score,ScoreBreakdown:this.mapScoreBreakdown(t.ScoreBreakdown),Tags:t.Tags||[],EntityIcon:t.EntityIcon,RecordName:t.RecordName,MatchedAt:t.MatchedAt,RawMetadata:t.RawMetadata,ProviderId:t.ProviderId,ProviderLabel:t.ProviderLabel,ProviderIcon:t.ProviderIcon})),TotalCount:e.TotalCount,ElapsedMs:e.ElapsedMs,SourceCounts:this.mapSourceCounts(e.SourceCounts),Providers:(e.Providers||[]).map(t=>({ID:t.ID,Name:t.Name,DisplayName:t.DisplayName,Icon:t.Icon,SourceType:t.SourceType,Priority:t.Priority})),ErrorMessage:e.ErrorMessage}}mapScoreBreakdown(e){if(!e)return{};const t={};return e.Vector!==void 0&&(t.Vector=e.Vector),e.FullText!==void 0&&(t.FullText=e.FullText),e.Entity!==void 0&&(t.Entity=e.Entity),e.Storage!==void 0&&(t.Storage=e.Storage),t}mapSourceCounts(e){return e?{Vector:e.Vector??0,FullText:e.FullText??0,Entity:e.Entity??0,Storage:e.Storage??0}:{Vector:0,FullText:0,Entity:0,Storage:0}}searchErrorResponse(e){return{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,SourceCounts:{Vector:0,FullText:0,Entity:0,Storage:0},Providers:[],ErrorMessage:`Error: ${e}`}}}class xe{static{y(this,"GetDataOutput")}}class Te{static{y(this,"SimpleRemoteEntityOutput")}}class Fe{static{y(this,"SimpleRemoteEntity")}}class Le{static{y(this,"SimpleRemoteEntityField")}}class Qe{static{y(this,"GraphQLActionClient")}constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),n=this.createActionVariables(e,s,r),a=await this.executeActionMutation(n);return this.processActionResult(a,t)}catch(s){return this.handleActionError(s,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{...t,Value:r}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=c`
1134
+ `,r={query:e.Query};e.MaxResults!==void 0&&(r.maxResults=e.MaxResults);const s=await this.Client.request(t,r);return s?.PreviewSearchAsSystemUser?this.mapSearchResponse(s.PreviewSearchAsSystemUser):this.searchErrorResponse("Invalid response from server")}catch(t){return d(`GraphQLSystemUserClient::PreviewSearch - Error executing preview search - ${t}`),this.searchErrorResponse(t instanceof Error?t.message:String(t))}}mapSearchResponse(e){return{Success:e.Success,Results:(e.Results||[]).map(t=>({ID:t.ID,EntityName:t.EntityName,RecordID:t.RecordID,SourceType:t.SourceType,ResultType:t.ResultType,Title:t.Title,Snippet:t.Snippet,Score:t.Score,ScoreBreakdown:this.mapScoreBreakdown(t.ScoreBreakdown),Tags:t.Tags||[],EntityIcon:t.EntityIcon,RecordName:t.RecordName,MatchedAt:t.MatchedAt,RawMetadata:t.RawMetadata,ProviderId:t.ProviderId,ProviderLabel:t.ProviderLabel,ProviderIcon:t.ProviderIcon})),TotalCount:e.TotalCount,ElapsedMs:e.ElapsedMs,SourceCounts:this.mapSourceCounts(e.SourceCounts),Providers:(e.Providers||[]).map(t=>({ID:t.ID,Name:t.Name,DisplayName:t.DisplayName,Icon:t.Icon,SourceType:t.SourceType,Priority:t.Priority})),ErrorMessage:e.ErrorMessage}}mapScoreBreakdown(e){if(!e)return{};const t={};return e.Vector!==void 0&&(t.Vector=e.Vector),e.FullText!==void 0&&(t.FullText=e.FullText),e.Entity!==void 0&&(t.Entity=e.Entity),e.Storage!==void 0&&(t.Storage=e.Storage),t}mapSourceCounts(e){return e?{Vector:e.Vector??0,FullText:e.FullText??0,Entity:e.Entity??0,Storage:e.Storage??0}:{Vector:0,FullText:0,Entity:0,Storage:0}}searchErrorResponse(e){return{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,SourceCounts:{Vector:0,FullText:0,Entity:0,Storage:0},Providers:[],ErrorMessage:`Error: ${e}`}}}class Ve{static{y(this,"GetDataOutput")}}class _e{static{y(this,"SimpleRemoteEntityOutput")}}class qe{static{y(this,"SimpleRemoteEntity")}}class Oe{static{y(this,"SimpleRemoteEntityField")}}class ke{static{y(this,"GraphQLActionClient")}constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),n=this.createActionVariables(e,s,r),a=await this.executeActionMutation(n);return this.processActionResult(a,t)}catch(s){return this.handleActionError(s,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{...t,Value:r}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=c`
1135
1135
  mutation RunAction($input: RunActionInput!) {
1136
1136
  RunAction(input: $input) {
1137
1137
  Success
@@ -1148,7 +1148,157 @@ var z=Object.defineProperty;var y=(I,e)=>z(I,"name",{value:e,configurable:!0});i
1148
1148
  ResultData
1149
1149
  }
1150
1150
  }
1151
- `;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){d(`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 d(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}}class Ue{static{y(this,"GraphQLEncryptionClient")}constructor(e){this._dataProvider=e}async CreateAPIKey(e){try{const t=this.createAPIKeyVariables(e),r=await this.executeCreateAPIKeyMutation(t);return this.processCreateAPIKeyResult(r)}catch(t){return this.handleCreateAPIKeyError(t)}}createAPIKeyVariables(e){return{input:{Label:e.Label,Description:e.Description,ExpiresAt:e.ExpiresAt?.toISOString(),ScopeIDs:e.ScopeIDs}}}async executeCreateAPIKeyMutation(e){const t=c`
1151
+ `;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){d(`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 d(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}}class Be{static{y(this,"GraphQLListsClient")}constructor(e){this.dataProvider=e}async PreviewListDelta(e){const t=c`
1152
+ query PreviewListDelta($input: ComputeDeltaInput!) {
1153
+ PreviewListDelta(input: $input) {
1154
+ ...ListDeltaFields
1155
+ }
1156
+ }
1157
+ ${ee}
1158
+ `,r=await this.dataProvider.ExecuteGQL(t,{input:{Target:e.Target,Source:_(e.Source),Mode:e.Mode}});return te(r?.PreviewListDelta)}async ApplyListDelta(e){const t=c`
1159
+ mutation ApplyListDelta($input: ApplyDeltaInput!) {
1160
+ ApplyListDelta(input: $input) {
1161
+ ...ApplyResultFields
1162
+ }
1163
+ }
1164
+ ${F}
1165
+ `,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 Q(r?.ApplyListDelta)}async MaterializeFromView(e,t){const r=c`
1166
+ mutation MaterializeListFromView($viewId: String!, $options: MaterializeOptionsInput!) {
1167
+ MaterializeListFromView(viewId: $viewId, options: $options) {
1168
+ ...ApplyResultFields
1169
+ }
1170
+ }
1171
+ ${F}
1172
+ `,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 Q(s?.MaterializeListFromView)}async AddViewResultsToList(e,t){const r=c`
1173
+ mutation AddViewResultsToList($viewId: String!, $listId: String!) {
1174
+ AddViewResultsToList(viewId: $viewId, listId: $listId) {
1175
+ ...ApplyResultFields
1176
+ }
1177
+ }
1178
+ ${F}
1179
+ `,s=await this.dataProvider.ExecuteGQL(r,{viewId:e,listId:t});return Q(s?.AddViewResultsToList)}async RefreshFromSource(e){const t=c`
1180
+ mutation RefreshListFromSource($listId: String!, $mode: String!, $confirmDrops: Boolean!) {
1181
+ RefreshListFromSource(listId: $listId, mode: $mode, confirmDrops: $confirmDrops) {
1182
+ ...ApplyResultFields
1183
+ }
1184
+ }
1185
+ ${F}
1186
+ `,r=await this.dataProvider.ExecuteGQL(t,{listId:e.ListId,mode:e.Mode,confirmDrops:e.ConfirmDrops});return Q(r?.RefreshListFromSource)}async ComposeLists(e){const t=c`
1187
+ mutation ComposeLists($input: ComposeListsInput!) {
1188
+ ComposeLists(input: $input) {
1189
+ ...ListDeltaFields
1190
+ }
1191
+ }
1192
+ ${ee}
1193
+ `,r=await this.dataProvider.ExecuteGQL(t,{input:{Op:e.Op,Inputs:e.Inputs.map(_),Target:e.Target?_(e.Target):null}});return te(r?.ComposeLists)}async Share(e){const t=c`
1194
+ mutation ShareList($input: ShareListInput!) {
1195
+ ShareList(input: $input) {
1196
+ ...ShareResultFields
1197
+ }
1198
+ }
1199
+ ${G}
1200
+ `,r=await this.dataProvider.ExecuteGQL(t,{input:{ListID:e.ListID,Target:Ke(e.Target),PermissionLevel:e.PermissionLevel}});return V(r?.ShareList)}async Unshare(e){const t=c`
1201
+ mutation UnshareList($permissionId: String!) {
1202
+ UnshareList(permissionId: $permissionId) {
1203
+ ...ShareResultFields
1204
+ }
1205
+ }
1206
+ ${G}
1207
+ `,r=await this.dataProvider.ExecuteGQL(t,{permissionId:e});return V(r?.UnshareList)}async Invite(e){const t=c`
1208
+ mutation InviteToList($input: InviteToListInput!) {
1209
+ InviteToList(input: $input) {
1210
+ Success
1211
+ ResultCode
1212
+ Message
1213
+ InvitationID
1214
+ Token
1215
+ ExpiresAt
1216
+ }
1217
+ }
1218
+ `,s=(await this.dataProvider.ExecuteGQL(t,{input:{ListID:e.ListID,Email:e.Email,Role:e.Role,TtlHours:e.TtlHours}}))?.InviteToList;if(!s)throw new Error("GraphQLListsClient: empty InviteResult response");return{Success:s.Success,ResultCode:s.ResultCode,Message:s.Message,InvitationID:s.InvitationID??void 0,Token:s.Token??void 0,ExpiresAt:s.ExpiresAt?new Date(s.ExpiresAt):void 0}}async AcceptInvitation(e){const t=c`
1219
+ mutation AcceptListInvitation($token: String!) {
1220
+ AcceptListInvitation(token: $token) {
1221
+ Success
1222
+ ResultCode
1223
+ Message
1224
+ PermissionID
1225
+ ListID
1226
+ }
1227
+ }
1228
+ `,s=(await this.dataProvider.ExecuteGQL(t,{token:e}))?.AcceptListInvitation;if(!s)throw new Error("GraphQLListsClient: empty AcceptInvitation response");return{Success:s.Success,ResultCode:s.ResultCode,Message:s.Message,PermissionID:s.PermissionID??void 0,ListID:s.ListID??void 0}}async RevokeInvitation(e){const t=c`
1229
+ mutation RevokeListInvitation($invitationId: String!) {
1230
+ RevokeListInvitation(invitationId: $invitationId) {
1231
+ ...ShareResultFields
1232
+ }
1233
+ }
1234
+ ${G}
1235
+ `,r=await this.dataProvider.ExecuteGQL(t,{invitationId:e});return V(r?.RevokeListInvitation)}async GetSharesForList(e){const t=c`
1236
+ query ListSharesForList($listId: String!) {
1237
+ ListSharesForList(listId: $listId) {
1238
+ PermissionID
1239
+ ListID
1240
+ Target {
1241
+ Kind
1242
+ UserID
1243
+ RoleID
1244
+ }
1245
+ PermissionLevel
1246
+ Status
1247
+ SharedByUserID
1248
+ CreatedAt
1249
+ }
1250
+ }
1251
+ `;return((await this.dataProvider.ExecuteGQL(t,{listId:e}))?.ListSharesForList??[]).map(je)}async ListsSharedWithMe(){const e=c`
1252
+ query ListsSharedWithMe {
1253
+ ListsSharedWithMe {
1254
+ ListID
1255
+ ListName
1256
+ PermissionLevel
1257
+ SharedByUserID
1258
+ SharedAt
1259
+ }
1260
+ }
1261
+ `;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 ee=c`
1262
+ fragment ListDeltaFields on ListDeltaType {
1263
+ TargetListId
1264
+ EntityName
1265
+ ToAdd
1266
+ ToRemove
1267
+ Unchanged
1268
+ Counts {
1269
+ Add
1270
+ Remove
1271
+ Unchanged
1272
+ SourceTotal
1273
+ TargetTotal
1274
+ }
1275
+ Warnings {
1276
+ Code
1277
+ Message
1278
+ DetailsJSON
1279
+ }
1280
+ DeltaToken
1281
+ }
1282
+ `,F=c`
1283
+ fragment ApplyResultFields on ApplyListResultType {
1284
+ Success
1285
+ ResultCode
1286
+ Message
1287
+ CreatedListId
1288
+ TargetListId
1289
+ AddedCount
1290
+ RemovedCount
1291
+ FailedCount
1292
+ Errors
1293
+ }
1294
+ `,G=c`
1295
+ fragment ShareResultFields on ShareResultType {
1296
+ Success
1297
+ ResultCode
1298
+ Message
1299
+ PermissionID
1300
+ }
1301
+ `;function Ke(m){return m.kind==="user"?{Kind:"user",UserID:m.userId}:{Kind:"role",RoleID:m.roleId}}y(Ke,"serializeShareTarget");function V(m){if(!m||typeof m!="object")throw new Error("GraphQLListsClient: empty/invalid ShareResult response");const e=m;return{Success:e.Success,ResultCode:e.ResultCode,Message:e.Message,PermissionID:e.PermissionID??void 0}}y(V,"parseShareResult");function je(m){const e=m,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)}}y(je,"parseShareSummary");function _(m){switch(m.kind){case"list":return{Kind:"list",ListID:m.listId};case"view":return{Kind:"view",ViewID:m.viewId};case"adhoc":return{Kind:"adhoc",EntityName:m.entityName,ExtraFilter:m.extraFilter}}}y(_,"serializeListSource");function te(m){if(!m||typeof m!="object")throw new Error("GraphQLListsClient: empty/invalid ListDelta response from server");const e=m;return{TargetListId:e.TargetListId,EntityName:e.EntityName,ToAdd:e.ToAdd,ToRemove:e.ToRemove,Unchanged:e.Unchanged,Counts:e.Counts,Warnings:e.Warnings.map(Je),DeltaToken:e.DeltaToken}}y(te,"parseListDelta");function Je(m){let e;if(m.DetailsJSON)try{e=JSON.parse(m.DetailsJSON)}catch(t){d(`GraphQLListsClient: failed to parse warning details JSON: ${t}`)}return{Code:m.Code,Message:m.Message,Details:e}}y(Je,"parseWarning");function Q(m){if(!m||typeof m!="object")throw new Error("GraphQLListsClient: empty/invalid ApplyResult response from server");const e=m;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}}y(Q,"parseApplyResult");class We{static{y(this,"GraphQLEncryptionClient")}constructor(e){this._dataProvider=e}async CreateAPIKey(e){try{const t=this.createAPIKeyVariables(e),r=await this.executeCreateAPIKeyMutation(t);return this.processCreateAPIKeyResult(r)}catch(t){return this.handleCreateAPIKeyError(t)}}createAPIKeyVariables(e){return{input:{Label:e.Label,Description:e.Description,ExpiresAt:e.ExpiresAt?.toISOString(),ScopeIDs:e.ScopeIDs}}}async executeCreateAPIKeyMutation(e){const t=c`
1152
1302
  mutation CreateAPIKey($input: CreateAPIKeyInput!) {
1153
1303
  CreateAPIKey(input: $input) {
1154
1304
  Success
@@ -1164,7 +1314,7 @@ var z=Object.defineProperty;var y=(I,e)=>z(I,"name",{value:e,configurable:!0});i
1164
1314
  Error
1165
1315
  }
1166
1316
  }
1167
- `,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 d(`Error revoking API key: ${r.message}`),{Success:!1,Error:`Error: ${r.message}`}}}}class Ge{static{y(this,"GraphQLTestingClient")}constructor(e){this._dataProvider=e}async RunTest(e){try{const t=this.buildRunTestMutation(),r=this.buildRunTestVariables(e);return await P.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTest",operationLabel:"RunTest",validateAck:y(s=>s?.success===!0,"validateAck"),isCompletionEvent:y(s=>this.isTestCompletionEvent(s,e.testId),"isCompletionEvent"),extractResult:y(s=>this.extractTestResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardTestProgress(s,e.onProgress):void 0,createErrorResult:y(s=>({success:!1,errorMessage:s,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTest")}}async RunTestSuite(e){try{const t=this.buildRunTestSuiteMutation(),r=this.buildRunTestSuiteVariables(e);return await P.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTestSuite",operationLabel:"RunTestSuite",validateAck:y(s=>s?.success===!0,"validateAck"),isCompletionEvent:y(s=>this.isSuiteCompletionEvent(s,e.suiteId),"isCompletionEvent"),extractResult:y(s=>this.extractSuiteResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardTestProgress(s,e.onProgress):void 0,createErrorResult:y(s=>({success:!1,errorMessage:s,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTestSuite")}}async IsTestRunning(e){try{const t=c`
1317
+ `,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 d(`Error revoking API key: ${r.message}`),{Success:!1,Error:`Error: ${r.message}`}}}}class ze{static{y(this,"GraphQLTestingClient")}constructor(e){this._dataProvider=e}async RunTest(e){try{const t=this.buildRunTestMutation(),r=this.buildRunTestVariables(e);return await P.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTest",operationLabel:"RunTest",validateAck:y(s=>s?.success===!0,"validateAck"),isCompletionEvent:y(s=>this.isTestCompletionEvent(s,e.testId),"isCompletionEvent"),extractResult:y(s=>this.extractTestResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardTestProgress(s,e.onProgress):void 0,createErrorResult:y(s=>({success:!1,errorMessage:s,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTest")}}async RunTestSuite(e){try{const t=this.buildRunTestSuiteMutation(),r=this.buildRunTestSuiteVariables(e);return await P.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTestSuite",operationLabel:"RunTestSuite",validateAck:y(s=>s?.success===!0,"validateAck"),isCompletionEvent:y(s=>this.isSuiteCompletionEvent(s,e.suiteId),"isCompletionEvent"),extractResult:y(s=>this.extractSuiteResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardTestProgress(s,e.onProgress):void 0,createErrorResult:y(s=>({success:!1,errorMessage:s,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTestSuite")}}async IsTestRunning(e){try{const t=c`
1168
1318
  query IsTestRunning($testId: String!) {
1169
1319
  IsTestRunning(testId: $testId)
1170
1320
  }
@@ -1222,7 +1372,7 @@ var z=Object.defineProperty;var y=(I,e)=>z(I,"name",{value:e,configurable:!0});i
1222
1372
  result
1223
1373
  }
1224
1374
  }
1225
- `}buildRunTestVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0;return{testId:e.testId,verbose:e.verbose,environment:e.environment,tags:t,variables:r,fireAndForget:!0}}buildRunTestSuiteVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0,s=e.selectedTestIds&&e.selectedTestIds.length>0?JSON.stringify(e.selectedTestIds):void 0;return{suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel,tags:t,variables:r,selectedTestIds:s,sequenceStart:e.sequenceStart,sequenceEnd:e.sequenceEnd,fireAndForget:!0}}isTestCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetComplete"&&r?.type==="complete"&&r?.testId===t}isSuiteCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetSuiteComplete"&&r?.type==="complete"&&r?.suiteId===t}extractTestResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?C(t.result):null}}extractSuiteResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?C(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 d(`${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 Ve{static{y(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=c`
1375
+ `}buildRunTestVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0;return{testId:e.testId,verbose:e.verbose,environment:e.environment,tags:t,variables:r,fireAndForget:!0}}buildRunTestSuiteVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0,s=e.selectedTestIds&&e.selectedTestIds.length>0?JSON.stringify(e.selectedTestIds):void 0;return{suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel,tags:t,variables:r,selectedTestIds:s,sequenceStart:e.sequenceStart,sequenceEnd:e.sequenceEnd,fireAndForget:!0}}isTestCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetComplete"&&r?.type==="complete"&&r?.testId===t}isSuiteCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetSuiteComplete"&&r?.type==="complete"&&r?.suiteId===t}extractTestResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?C(t.result):null}}extractSuiteResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?C(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 d(`${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 He{static{y(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=c`
1226
1376
  query GetRegistryComponent(
1227
1377
  $registryName: String!,
1228
1378
  $namespace: String!,
@@ -1306,7 +1456,7 @@ var z=Object.defineProperty;var y=(I,e)=>z(I,"name",{value:e,configurable:!0});i
1306
1456
  error
1307
1457
  }
1308
1458
  }
1309
- `,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return d(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}}class _e{static{y(this,"GraphQLVersionHistoryClient")}constructor(e){this._dataProvider=e}async CreateLabel(e){let t;try{e.OnProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(a=>{try{const i=JSON.parse(a);i.resolver==="VersionHistoryResolver"&&i.type==="CreateLabelProgress"&&i.status==="ok"&&i.data&&e.OnProgress(i.data)}catch{}}));const r=c`
1459
+ `,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return d(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}}class Xe{static{y(this,"GraphQLVersionHistoryClient")}constructor(e){this._dataProvider=e}async CreateLabel(e){let t;try{e.OnProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(a=>{try{const i=JSON.parse(a);i.resolver==="VersionHistoryResolver"&&i.type==="CreateLabelProgress"&&i.status==="ok"&&i.data&&e.OnProgress(i.data)}catch{}}));const r=c`
1310
1460
  mutation CreateVersionLabel($input: CreateVersionLabelInput!, $sessionId: String) {
1311
1461
  CreateVersionLabel(input: $input, sessionId: $sessionId) {
1312
1462
  Success
@@ -1322,7 +1472,7 @@ var z=Object.defineProperty;var y=(I,e)=>z(I,"name",{value:e,configurable:!0});i
1322
1472
  }
1323
1473
  }
1324
1474
  }
1325
- `,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 d(`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 qe{static{y(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const s=c`
1475
+ `,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 d(`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 Ye{static{y(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const s=c`
1326
1476
  query ListStorageObjects($input: ListStorageObjectsInput!) {
1327
1477
  ListStorageObjects(input: $input) {
1328
1478
  objects {
@@ -1406,7 +1556,7 @@ var z=Object.defineProperty;var y=(I,e)=>z(I,"name",{value:e,configurable:!0});i
1406
1556
  failedAccounts
1407
1557
  }
1408
1558
  }
1409
- `,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(u=>({path:u.path,name:u.name,size:u.size,contentType:u.contentType,lastModified:new Date(u.lastModified),relevance:u.relevance,excerpt:u.excerpt,matchInFilename:u.matchInFilename,objectId:u.objectId})),totalMatches:o.totalMatches,hasMore:o.hasMore,nextPageToken:o.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(s){return d(`Error searching across accounts: ${s}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}class Oe{static{y(this,"GraphQLSearchClient")}constructor(e){this._dataProvider=e}async ExecuteSearch(e){try{const t=this.buildSearchKnowledgeMutation(),r=this.prepareSearchVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processSearchKnowledgeResult(s)}catch(t){return this.handleSearchError(t)}}async PreviewSearch(e,t){try{const r=this.buildPreviewSearchMutation(),s=this.preparePreviewVariables(e,t),n=await this._dataProvider.ExecuteGQL(r,s);return this.processPreviewSearchResult(n)}catch(r){return this.handleSearchError(r)}}buildSearchKnowledgeMutation(){return c`
1559
+ `,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:r?.maxResultsPerAccount,FileTypes:r?.fileTypes,SearchContent:r?.searchContent}},a=await this._dataProvider.ExecuteGQL(s,n);if(!a?.SearchAcrossAccounts)throw new Error("Invalid response from server");const i=a.SearchAcrossAccounts;return{accountResults:i.accountResults.map(o=>({accountId:o.accountID,accountName:o.accountName,success:o.success,errorMessage:o.errorMessage,results:o.results.map(l=>({path:l.path,name:l.name,size:l.size,contentType:l.contentType,lastModified:new Date(l.lastModified),relevance:l.relevance,excerpt:l.excerpt,matchInFilename:l.matchInFilename,objectId:l.objectId})),totalMatches:o.totalMatches,hasMore:o.hasMore,nextPageToken:o.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(s){return d(`Error searching across accounts: ${s}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}class Ze{static{y(this,"GraphQLSearchClient")}constructor(e){this._dataProvider=e}async ExecuteSearch(e){try{const t=this.buildSearchKnowledgeMutation(),r=this.prepareSearchVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processSearchKnowledgeResult(s)}catch(t){return this.handleSearchError(t)}}async PreviewSearch(e,t){try{const r=this.buildPreviewSearchMutation(),s=this.preparePreviewVariables(e,t),n=await this._dataProvider.ExecuteGQL(r,s);return this.processPreviewSearchResult(n)}catch(r){return this.handleSearchError(r)}}buildSearchKnowledgeMutation(){return c`
1410
1560
  mutation SearchKnowledge($query: String!, $maxResults: Float, $filters: SearchFiltersInput, $minScore: Float, $scopeIDs: [ID!], $searchContext: SearchContextInput) {
1411
1561
  SearchKnowledge(query: $query, maxResults: $maxResults, filters: $filters, minScore: $minScore, scopeIDs: $scopeIDs, searchContext: $searchContext) {
1412
1562
  Success
@@ -1512,7 +1662,7 @@ var z=Object.defineProperty;var y=(I,e)=>z(I,"name",{value:e,configurable:!0});i
1512
1662
  IsPersonal
1513
1663
  }
1514
1664
  }
1515
- `;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 d(`GraphQLSearchClient.GetSearchScopes failed: ${e instanceof Error?e.message:String(e)}`),[]}}StreamSearch(e){return new x(t=>{const r=c`
1665
+ `;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 d(`GraphQLSearchClient.GetSearchScopes failed: ${e instanceof Error?e.message:String(e)}`),[]}}StreamSearch(e){return new T(t=>{const r=c`
1516
1666
  mutation StreamScopedSearch(
1517
1667
  $query: String!,
1518
1668
  $maxResults: Float,
@@ -1545,7 +1695,7 @@ var z=Object.defineProperty;var y=(I,e)=>z(I,"name",{value:e,configurable:!0});i
1545
1695
  ElapsedMs
1546
1696
  ErrorMessage
1547
1697
  }
1548
- }`;n=this._dataProvider.subscribe(o,{streamID:i.StreamID}).subscribe({next:y(u=>{const l=u?.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:y(u=>t.error(u),"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 d(`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 ke{static{y(this,"GraphQLIntegrationClient")}constructor(e){this._dataProvider=e}async DiscoverObjects(e){try{const t=c`
1698
+ }`;n=this._dataProvider.subscribe(o,{streamID:i.StreamID}).subscribe({next:y(l=>{const u=l?.SearchStreamEvents;u&&(t.next(u),u.Phase==="final"?(t.complete(),n?.unsubscribe()):u.Phase==="error"&&(t.error(new Error(u.ErrorMessage??"Stream error")),n?.unsubscribe()))},"next"),error:y(l=>t.error(l),"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 d(`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 et{static{y(this,"GraphQLIntegrationClient")}constructor(e){this._dataProvider=e}async DiscoverObjects(e){try{const t=c`
1549
1699
  query IntegrationDiscoverObjects($companyIntegrationID: String!) {
1550
1700
  IntegrationDiscoverObjects(companyIntegrationID: $companyIntegrationID) {
1551
1701
  Success
@@ -1696,7 +1846,7 @@ var z=Object.defineProperty;var y=(I,e)=>z(I,"name",{value:e,configurable:!0});i
1696
1846
  PipelineSteps { Name Status DurationMs Message }
1697
1847
  GitCommitSuccess APIRestarted
1698
1848
  }
1699
- }`,u={Connectors:e.map(f=>({CompanyIntegrationID:f.CompanyIntegrationID,SourceObjects:f.SourceObjects.map(R=>({SourceObjectID:R.SourceObjectID??null,SourceObjectName:R.SourceObjectName??null,Fields:R.Fields??null}))})),StartSync:t,FullSync:r,SyncScope:s},l=(await this._dataProvider.ExecuteGQL(o,{input:u,platform:n,skipGitCommit:a,skipRestart:i}))?.IntegrationApplyAllBatch;return l?{Success:l.Success,Message:l.Message,Steps:l.PipelineSteps,GitCommitSuccess:l.GitCommitSuccess,APIRestarted:l.APIRestarted,EntityMapsCreated:l.ConnectorResults?.[0]?.EntityMapsCreated,SyncRunID:l.ConnectorResults?.[0]?.SyncRunID,Warnings:l.ConnectorResults?.flatMap(f=>f.Warnings??[])}:{Success:!1,Message:"No response"}}catch(o){return{Success:!1,Message:o.message}}}async ApplyAll(e,t,r="sqlserver",s=!1,n=!1){try{const a=c`mutation IntegrationApplyAll(
1849
+ }`,l={Connectors:e.map(f=>({CompanyIntegrationID:f.CompanyIntegrationID,SourceObjects:f.SourceObjects.map(D=>({SourceObjectID:D.SourceObjectID??null,SourceObjectName:D.SourceObjectName??null,Fields:D.Fields??null}))})),StartSync:t,FullSync:r,SyncScope:s},u=(await this._dataProvider.ExecuteGQL(o,{input:l,platform:n,skipGitCommit:a,skipRestart:i}))?.IntegrationApplyAllBatch;return u?{Success:u.Success,Message:u.Message,Steps:u.PipelineSteps,GitCommitSuccess:u.GitCommitSuccess,APIRestarted:u.APIRestarted,EntityMapsCreated:u.ConnectorResults?.[0]?.EntityMapsCreated,SyncRunID:u.ConnectorResults?.[0]?.SyncRunID,Warnings:u.ConnectorResults?.flatMap(f=>f.Warnings??[])}:{Success:!1,Message:"No response"}}catch(o){return{Success:!1,Message:o.message}}}async ApplyAll(e,t,r="sqlserver",s=!1,n=!1){try{const a=c`mutation IntegrationApplyAll(
1700
1850
  $input: ApplyAllInput!, $platform: String!, $skipGitCommit: Boolean!, $skipRestart: Boolean!
1701
1851
  ) {
1702
1852
  IntegrationApplyAll(input: $input, platform: $platform, skipGitCommit: $skipGitCommit, skipRestart: $skipRestart) {
@@ -1738,5 +1888,5 @@ var z=Object.defineProperty;var y=(I,e)=>z(I,"name",{value:e,configurable:!0});i
1738
1888
  IntegrationGetConnectorCapabilities(companyIntegrationID: $companyIntegrationID) {
1739
1889
  Success Message SupportsGet SupportsCreate SupportsUpdate SupportsDelete SupportsSearch
1740
1890
  }
1741
- }`;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 d(`Error in integration discovery: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Data:t}}}export{be as ActionItemInput,Ae as ActionItemOutput,J as BrowserIndexedDBStorageProvider,K as BrowserStorageProviderBase,v as FieldMapper,P as FireAndForgetHelper,xe as GetDataOutput,B as GraphQLAIClient,Qe as GraphQLActionClient,Ve as GraphQLComponentRegistryClient,p as GraphQLDataProvider,Ue as GraphQLEncryptionClient,qe as GraphQLFileStorageClient,ke as GraphQLIntegrationClient,Ee as GraphQLProviderConfigData,Oe as GraphQLSearchClient,Me as GraphQLSystemUserClient,Ge as GraphQLTestingClient,k as GraphQLTransactionGroup,_e as GraphQLVersionHistoryClient,F as PACKAGE_VERSION,Ce as RoleInput,Pe as RolesAndUsersInput,Fe as SimpleRemoteEntity,Le as SimpleRemoteEntityField,Te as SimpleRemoteEntityOutput,W as SyncDataAction,Ne as SyncDataResult,we as SyncRolesAndUsersResult,$e as UserInput,tt as gql,ve as setupGraphQLClient};
1891
+ }`;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 d(`Error in integration discovery: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Data:t}}}export{Fe as ActionItemInput,Ue as ActionItemOutput,Y as BrowserIndexedDBStorageProvider,H as BrowserStorageProviderBase,v as FieldMapper,P as FireAndForgetHelper,Ve as GetDataOutput,z as GraphQLAIClient,ke as GraphQLActionClient,He as GraphQLComponentRegistryClient,h as GraphQLDataProvider,We as GraphQLEncryptionClient,Ye as GraphQLFileStorageClient,et as GraphQLIntegrationClient,Be as GraphQLListsClient,be as GraphQLProviderConfigData,Ze as GraphQLSearchClient,Ge as GraphQLSystemUserClient,ze as GraphQLTestingClient,W as GraphQLTransactionGroup,Xe as GraphQLVersionHistoryClient,L as PACKAGE_VERSION,Te as RoleInput,Le as RolesAndUsersInput,qe as SimpleRemoteEntity,Oe as SimpleRemoteEntityField,_e as SimpleRemoteEntityOutput,Z as SyncDataAction,Qe as SyncDataResult,Me as SyncRolesAndUsersResult,xe as UserInput,yt as gql,Ne as setupGraphQLClient};
1742
1892
  //# sourceMappingURL=index.mjs.map