@memberjunction/graphql-dataprovider 6.1.0-edge.1 → 6.1.0-edge.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var j=Object.defineProperty;var d=(m,e)=>j(m,"name",{value:e,configurable:!0});var u=require("graphql-request"),c=require("@memberjunction/core"),D=require("@memberjunction/global"),q=require("@memberjunction/core-entities"),L=require("rxjs"),J=require("graphql-ws"),W=require("uuid"),z=require("@tempfix/idb");class P{static{d(this,"FieldMapper")}static{this.DB_PREFIX="__mj_"}static{this.GQL_PREFIX="_mj__"}constructor(){}MapFields(e){if(e)for(const t in e){const r=this.MapFieldName(t);r!==t&&(e[r]=e[t],delete e[t])}return e}MapFieldName(e){return e.startsWith(P.DB_PREFIX)?P.GQL_PREFIX+e.substring(P.DB_PREFIX.length):e}ReverseMapFieldName(e){return e.startsWith(P.GQL_PREFIX)?P.DB_PREFIX+e.substring(P.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 G extends c.TransactionGroupBase{static{d(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=u.gql`
1
+ "use strict";var H=Object.defineProperty;var d=(l,e)=>H(l,"name",{value:e,configurable:!0});var u=require("graphql-request"),c=require("@memberjunction/core"),D=require("@memberjunction/global"),V=require("@memberjunction/core-entities"),L=require("rxjs"),X=require("graphql-ws"),Y=require("uuid"),Z=require("@tempfix/idb");class P{static{d(this,"FieldMapper")}static{this.DB_PREFIX="__mj_"}static{this.GQL_PREFIX="_mj__"}constructor(){}MapFields(e){if(e)for(const t in e){const r=this.MapFieldName(t);r!==t&&(e[r]=e[t],delete e[t])}return e}MapFieldName(e){return e.startsWith(P.DB_PREFIX)?P.GQL_PREFIX+e.substring(P.DB_PREFIX.length):e}ReverseMapFieldName(e){return e.startsWith(P.GQL_PREFIX)?P.DB_PREFIX+e.substring(P.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 _ extends c.TransactionGroupBase{static{d(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=u.gql`
2
2
  mutation ExecuteTransactionGroup($group: TransactionInputType!) {
3
3
  ExecuteTransactionGroup(group: $group) {
4
4
  Success
@@ -6,7 +6,7 @@
6
6
  ResultsJSON
7
7
  }
8
8
  }
9
- `,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const r={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const n=s.ExecuteTransactionGroup,o=n.Success===!0,i=[];for(let a=0;a<this.PendingTransactions.length;a++){const y=n.ResultsJSON[a],l=D.SafeJSONParse(y),h=this.PendingTransactions[a];i.push(new c.TransactionResult(h,l,o&&l!==null))}return i}else throw new Error("Failed to execute transaction group")}}const H=720*1e3,X=6;class w{static{d(this,"FireAndForgetHelper")}static async Execute(e){const t=e.operationLabel??e.mutationFieldName;if(!(typeof e.dataProvider.PushStatusUpdates=="function"))return w.executeSynchronously(e);const s=e.timeoutMs??H,n=e.maxStallReconciles??X;let o,i=!1,a=0;const{promise:y,resolve:l,reject:h}=w.createCompletionPromise(),f=d(R=>{i||(i=!0,E.clear(),R())},"finish"),g=d(R=>f(()=>l(R)),"settleResolve"),S=d(R=>f(()=>h(R)),"settleReject"),p=d(async()=>{if(i)return;if(!e.onStall){S(new Error(w.timeoutMessage(e.timeoutErrorMessage,s)));return}let R;try{c.LogStatus(`[FireAndForget:${t}] Idle window elapsed, reconciling against server run record`),R=await e.onStall()}catch(v){S(v);return}i||(R==="continue"?++a>n?S(new Error(`The operation is still reported as running but no signal has arrived after ${a} checks. Please refresh the page to check the latest status.`)):E.reset():"resolve"in R?(c.LogStatus(`[FireAndForget:${t}] Reconciliation recovered a completed run`),g(R.resolve)):S(R.reject))},"onStall"),E=w.createIdleTimer(s,()=>{p()});try{E.reset(),o=w.subscribeToPubSub(e,{onActivity:d(()=>{a=0,E.reset()},"onActivity"),onCompletion:d(v=>g(v),"onCompletion"),onStreamEnd:d(()=>{p()},"onStreamEnd")});const R=await w.executeMutation(e);if(!e.validateAck(R)){E.clear();const v=R?.errorMessage??"Server rejected the request";return c.LogError(`[FireAndForget:${t}] Server rejected: ${v}`),e.createErrorResult(v)}return c.LogStatus(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await y}catch(R){const v=R;throw c.LogError(`[FireAndForget:${t}] Error: ${v.message}`),R}finally{E.clear(),o&&o.unsubscribe()}}static createCompletionPromise(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}static createIdleTimer(e,t){let r;return{reset:d(()=>{r&&clearTimeout(r),r=setTimeout(t,e)},"reset"),clear:d(()=>{r&&clearTimeout(r),r=void 0},"clear")}}static timeoutMessage(e,t){const r=Math.round(t/6e4);return e??`The operation may still be running on the server but the client received no updates for ${r} minutes. Please refresh the page to check the latest status.`}static subscribeToPubSub(e,t){const r=e.dataProvider.sessionId,s=e.operationLabel??e.mutationFieldName;return e.dataProvider.PushStatusUpdates(r).subscribe({next:d(n=>{t.onActivity();try{const o=JSON.parse(n);e.onMessage&&e.onMessage(o),e.isCompletionEvent(o)&&(c.LogStatus(`[FireAndForget:${s}] Completion event received`),t.onCompletion(e.extractResult(o)))}catch(o){console.error(`[FireAndForget:${s}] Failed to parse PubSub message:`,o)}},"next"),error:d(()=>t.onStreamEnd(),"error"),complete:d(()=>t.onStreamEnd(),"complete")})}static async executeMutation(e){return(await e.dataProvider.ExecuteGQL(e.mutation,e.variables))[e.mutationFieldName]}static async executeSynchronously(e){const t=e.operationLabel??e.mutationFieldName;c.LogStatus(`[FireAndForget:${t}] Provider has no PushStatusUpdates channel \u2014 running synchronously (fireAndForget disabled)`);const r={...e.variables,fireAndForget:!1},n=(await e.dataProvider.ExecuteGQL(e.mutation,r))?.[e.mutationFieldName];return n?e.extractSyncResult?(c.LogStatus(`[FireAndForget:${t}] Synchronous execution completed`),e.extractSyncResult(n)):e.createErrorResult(`${t} cannot run on this data provider: it has no PushStatusUpdates channel and no synchronous result extractor is configured for this operation.`):(c.LogError(`[FireAndForget:${t}] Synchronous execution returned no '${e.mutationFieldName}' payload`),e.createErrorResult(`Server returned no '${e.mutationFieldName}' result for ${t}`))}}class U{static{d(this,"GraphQLAIClient")}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=u.gql`
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,o=n.Success===!0,i=[];for(let a=0;a<this.PendingTransactions.length;a++){const m=n.ResultsJSON[a],g=D.SafeJSONParse(m),h=this.PendingTransactions[a];i.push(new c.TransactionResult(h,g,o&&g!==null))}return i}else throw new Error("Failed to execute transaction group")}}const ee=720*1e3,te=6;class w{static{d(this,"FireAndForgetHelper")}static async Execute(e){const t=e.operationLabel??e.mutationFieldName;if(!(typeof e.dataProvider.PushStatusUpdates=="function"))return w.executeSynchronously(e);const s=e.timeoutMs??ee,n=e.maxStallReconciles??te;let o,i=!1,a=0;const{promise:m,resolve:g,reject:h}=w.createCompletionPromise(),f=d(R=>{i||(i=!0,E.clear(),R())},"finish"),y=d(R=>f(()=>g(R)),"settleResolve"),S=d(R=>f(()=>h(R)),"settleReject"),p=d(async()=>{if(i)return;if(!e.onStall){S(new Error(w.timeoutMessage(e.timeoutErrorMessage,s)));return}let R;try{c.LogStatus(`[FireAndForget:${t}] Idle window elapsed, reconciling against server run record`),R=await e.onStall()}catch(v){S(v);return}i||(R==="continue"?++a>n?S(new Error(`The operation is still reported as running but no signal has arrived after ${a} checks. Please refresh the page to check the latest status.`)):E.reset():"resolve"in R?(c.LogStatus(`[FireAndForget:${t}] Reconciliation recovered a completed run`),y(R.resolve)):S(R.reject))},"onStall"),E=w.createIdleTimer(s,()=>{p()});try{E.reset(),o=w.subscribeToPubSub(e,{onActivity:d(()=>{a=0,E.reset()},"onActivity"),onCompletion:d(v=>y(v),"onCompletion"),onStreamEnd:d(()=>{p()},"onStreamEnd")});const R=await w.executeMutation(e);if(!e.validateAck(R)){E.clear();const v=R?.errorMessage??"Server rejected the request";return c.LogError(`[FireAndForget:${t}] Server rejected: ${v}`),e.createErrorResult(v)}return c.LogStatus(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await m}catch(R){const v=R;throw c.LogError(`[FireAndForget:${t}] Error: ${v.message}`),R}finally{E.clear(),o&&o.unsubscribe()}}static createCompletionPromise(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}static createIdleTimer(e,t){let r;return{reset:d(()=>{r&&clearTimeout(r),r=setTimeout(t,e)},"reset"),clear:d(()=>{r&&clearTimeout(r),r=void 0},"clear")}}static timeoutMessage(e,t){const r=Math.round(t/6e4);return e??`The operation may still be running on the server but the client received no updates for ${r} minutes. Please refresh the page to check the latest status.`}static subscribeToPubSub(e,t){const r=e.dataProvider.sessionId,s=e.operationLabel??e.mutationFieldName;return e.dataProvider.PushStatusUpdates(r).subscribe({next:d(n=>{t.onActivity();try{const o=JSON.parse(n);e.onMessage&&e.onMessage(o),e.isCompletionEvent(o)&&(c.LogStatus(`[FireAndForget:${s}] Completion event received`),t.onCompletion(e.extractResult(o)))}catch(o){console.error(`[FireAndForget:${s}] Failed to parse PubSub message:`,o)}},"next"),error:d(()=>t.onStreamEnd(),"error"),complete:d(()=>t.onStreamEnd(),"complete")})}static async executeMutation(e){return(await e.dataProvider.ExecuteGQL(e.mutation,e.variables))[e.mutationFieldName]}static async executeSynchronously(e){const t=e.operationLabel??e.mutationFieldName;c.LogStatus(`[FireAndForget:${t}] Provider has no PushStatusUpdates channel \u2014 running synchronously (fireAndForget disabled)`);const r={...e.variables,fireAndForget:!1},n=(await e.dataProvider.ExecuteGQL(e.mutation,r))?.[e.mutationFieldName];return n?e.extractSyncResult?(c.LogStatus(`[FireAndForget:${t}] Synchronous execution completed`),e.extractSyncResult(n)):e.createErrorResult(`${t} cannot run on this data provider: it has no PushStatusUpdates channel and no synchronous result extractor is configured for this operation.`):(c.LogError(`[FireAndForget:${t}] Synchronous execution returned no '${e.mutationFieldName}' payload`),e.createErrorResult(`Server returned no '${e.mutationFieldName}' result for ${t}`))}}class O{static{d(this,"GraphQLAIClient")}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=u.gql`
10
10
  mutation RunAIPrompt(
11
11
  $promptId: String!,
12
12
  $data: String,
@@ -305,12 +305,14 @@
305
305
  }
306
306
  }
307
307
  }
308
- `,r={entityDocumentID:e.entityDocumentID};e.maxRecords!==void 0&&(r.maxRecords=e.maxRecords),e.filter!==void 0&&(r.filter=e.filter);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.FetchEntityVectors)throw new Error("Invalid response from server");return s.FetchEntityVectors}catch(t){const r=t;return c.LogError("GraphQLAIClient.FetchEntityVectors failed",void 0,r),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,ErrorMessage:r.message||"Unknown error"}}}}const M="6.1.0-edge.1",$="default";class V{static{d(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 o=s.get(n);r.set(n,o===void 0?null:o)}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 Y="MJ_Metadata",Z=0;function ee(){try{const m=M.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 "${M}"`);return e*1e3+t+Z}catch(m){return c.LogErrorEx({error:m,message:"Failed to derive IDB version from PACKAGE_VERSION; using fallback 99999"}),99999}}d(ee,"computeIdbVersion");const te=ee(),_=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"];class O extends V{static{d(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=z.openDB(Y,te,{upgrade:d((e,t,r)=>{try{c.LogStatus(`[IDBCache] Upgrading IndexedDB schema v${t} \u2192 v${r} (package ${M}). Dropping all stores; caches will repopulate on first use.`);for(const s of Array.from(e.objectStoreNames))e.deleteObjectStore(s);for(const s of _)e.objectStoreNames.contains(s)||e.createObjectStore(s)}catch(s){c.LogErrorEx({error:s,message:s?.message})}},"upgrade"),blocked:d((e,t)=>{c.LogStatus(`[IDBCache] Upgrade from v${e} to v${t} blocked by another tab. Close other tabs to allow the upgrade to proceed.`)},"blocked")}),this.dbPromise.then(e=>{this._dbReady=!0,e.onversionchange=()=>{c.LogStatus("[IDBCache] DB schema upgraded in another tab \u2014 closing local connection."),e.close(),this._dbReady=!1}}).catch(e=>{c.LogErrorEx({error:e,message:"IndexedDB initialization failed: "+e?.message})})}get IsReady(){return this._dbReady}isKnownCategory(e){const t=`mj:${e}`;return _.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),o=this.getStoreKey(e,r),i=s.transaction(n,"readwrite");await i.objectStore(n).put(t,o),await i.done}catch(s){c.LogErrorEx({error:s,message:s?.message})}}async GetItem(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t),o=await r.transaction(s).objectStore(s).get(n);return o===void 0?null:o}catch(r){return c.LogErrorEx({error:r,message:r?.message}),null}}async GetItems(e,t){const r=new Map;if(e.length===0)return r;try{const s=await this.dbPromise,n=this.getStoreName(t),o=Array.from(new Set(e)),i=o.map(f=>this.getStoreKey(f,t)),a=s.transaction(n,"readonly"),y=a.objectStore(n),l=i.map(f=>y.get(f)),h=await Promise.all(l);await a.done;for(let f=0;f<o.length;f++){const g=h[f];r.set(o[f],g===void 0?null:g)}return r}catch(s){c.LogErrorEx({error:s,message:s?.message});for(const n of new Set(e))r.set(n,null);return r}}async Remove(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t),o=r.transaction(s,"readwrite");await o.objectStore(s).delete(n),await o.done}catch(r){c.LogErrorEx({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}]:`,o=t.transaction("mj:default","readwrite"),i=o.objectStore("mj:default"),a=await i.getAllKeys();for(const y of a)typeof y=="string"&&y.startsWith(n)&&await i.delete(y);await o.done}}catch(t){c.LogErrorEx({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(y=>String(y));const a=`[${r}]:`;return i.map(y=>String(y)).filter(y=>y.startsWith(a)).map(y=>y.slice(a.length))}catch(t){return c.LogErrorEx({error:t,message:t?.message}),[]}}}const A=new P,re=u.gql`subscription RemoteOperationProgress($channelId: ID!) {
308
+ `,r={entityDocumentID:e.entityDocumentID};e.maxRecords!==void 0&&(r.maxRecords=e.maxRecords),e.filter!==void 0&&(r.filter=e.filter);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.FetchEntityVectors)throw new Error("Invalid response from server");return s.FetchEntityVectors}catch(t){const r=t;return c.LogError("GraphQLAIClient.FetchEntityVectors failed",void 0,r),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,ErrorMessage:r.message||"Unknown error"}}}}const M="6.1.0-edge.2",$="default";class k{static{d(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}get SharesReferences(){return!0}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 o=s.get(n);r.set(n,o===void 0?null:o)}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 re="MJ_Metadata",se=0;function ne(){try{const l=M.split("."),e=parseInt(l[0],10),t=parseInt(l[1],10);if(!Number.isFinite(e)||!Number.isFinite(t))throw new Error(`Could not parse major.minor from version "${M}"`);return e*1e3+t+se}catch(l){return c.LogErrorEx({error:l,message:"Failed to derive IDB version from PACKAGE_VERSION; using fallback 99999"}),99999}}d(ne,"computeIdbVersion");const oe=ne(),K=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"];class B extends k{static{d(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=Z.openDB(re,oe,{upgrade:d((e,t,r)=>{try{c.LogStatus(`[IDBCache] Upgrading IndexedDB schema v${t} \u2192 v${r} (package ${M}). Dropping all stores; caches will repopulate on first use.`);for(const s of Array.from(e.objectStoreNames))e.deleteObjectStore(s);for(const s of K)e.objectStoreNames.contains(s)||e.createObjectStore(s)}catch(s){c.LogErrorEx({error:s,message:s?.message})}},"upgrade"),blocked:d((e,t)=>{c.LogStatus(`[IDBCache] Upgrade from v${e} to v${t} blocked by another tab. Close other tabs to allow the upgrade to proceed.`)},"blocked")}),this.dbPromise.then(e=>{this._dbReady=!0,e.onversionchange=()=>{c.LogStatus("[IDBCache] DB schema upgraded in another tab \u2014 closing local connection."),e.close(),this._dbReady=!1}}).catch(e=>{c.LogErrorEx({error:e,message:"IndexedDB initialization failed: "+e?.message})})}get SharesReferences(){return!1}get IsReady(){return this._dbReady}isKnownCategory(e){const t=`mj:${e}`;return K.includes(t)}getStoreName(e){const t=e||$;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),o=this.getStoreKey(e,r),i=s.transaction(n,"readwrite");await i.objectStore(n).put(t,o),await i.done}catch(s){c.LogErrorEx({error:s,message:s?.message})}}async GetItem(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t),o=await r.transaction(s).objectStore(s).get(n);return o===void 0?null:o}catch(r){return c.LogErrorEx({error:r,message:r?.message}),null}}async GetItems(e,t){const r=new Map;if(e.length===0)return r;try{const s=await this.dbPromise,n=this.getStoreName(t),o=Array.from(new Set(e)),i=o.map(f=>this.getStoreKey(f,t)),a=s.transaction(n,"readonly"),m=a.objectStore(n),g=i.map(f=>m.get(f)),h=await Promise.all(g);await a.done;for(let f=0;f<o.length;f++){const y=h[f];r.set(o[f],y===void 0?null:y)}return r}catch(s){c.LogErrorEx({error:s,message:s?.message});for(const n of new Set(e))r.set(n,null);return r}}async Remove(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t),o=r.transaction(s,"readwrite");await o.objectStore(s).delete(n),await o.done}catch(r){c.LogErrorEx({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}]:`,o=t.transaction("mj:default","readwrite"),i=o.objectStore("mj:default"),a=await i.getAllKeys();for(const m of a)typeof m=="string"&&m.startsWith(n)&&await i.delete(m);await o.done}}catch(t){c.LogErrorEx({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(m=>String(m));const a=`[${r}]:`;return i.map(m=>String(m)).filter(m=>m.startsWith(a)).map(m=>m.slice(a.length))}catch(t){return c.LogErrorEx({error:t,message:t?.message}),[]}}}class x extends Error{static{d(this,"SafeGraphQLError")}constructor(e){super(e.message),this.name=e.name,this.response={status:e.status,errors:e.errors},this.request={query:e.query},this.Code=e.code,this.VariableShape=e.variableShape,this.stack=e.stackFrames?`${e.name}: ${e.message}
309
+ ${e.stackFrames}`:this.stack}}function j(l){return l instanceof x?l:new x(Q(l))}d(j,"ToSafeGraphQLError");const ae=3,ie=25;function F(l,e=0){if(l===null)return"null";if(l===void 0)return"undefined";if(Array.isArray(l))return l.length===0?"array(empty)":`array(${l.length} \xD7 ${ce(F(l[0],e+1))})`;if(typeof l=="object"){if(e>=ae)return"object(\u2026)";const t=Object.keys(l);if(t.length>ie)return`object(${t.length} keys)`;const r={};for(const s of t)r[s]=F(l[s],e+1);return r}return typeof l=="string"?l.length===0?"string(empty)":"string":typeof l}d(F,"describeShape");function ce(l){return typeof l=="string"?l:"object"}d(ce,"typeOf");function ue(l){const e=l.indexOf(`
310
+ at `);return e===-1?"":l.slice(e+1)}d(ue,"stripStackHeader");function le(l,e){const t=l?.[0]?.message;return typeof t=="string"&&t.length>0?t:`GraphQL Error (Code: ${String(e??"unknown")})`}d(le,"deriveMessage");function de(l){if(Array.isArray(l))return l.map(e=>{const t=e??{};return{message:typeof t.message=="string"?t.message:void 0,path:Array.isArray(t.path)?t.path:void 0,extensions:t.extensions&&typeof t.extensions=="object"?t.extensions:void 0}})}d(de,"extractErrors");function Q(l,e=!1){if(!l||typeof l!="object")return{name:typeof l,message:"Non-object value thrown; contents withheld",variables:"[REDACTED]"};const t=l,r=typeof t.response?.status=="number"?t.response.status:void 0,s=de(t.response?.errors),n=s?.[0]?.extensions?.code;return{name:typeof t.name=="string"?t.name:"Error",message:le(s,r),status:r,errors:s,code:typeof n=="string"?n:void 0,query:typeof t.request?.query=="string"?t.request.query:void 0,stackFrames:typeof t.stack=="string"?ue(t.stack):void 0,variables:e?t.request?.variables:"[REDACTED]",variableShape:t.request?.variables===void 0?void 0:F(t.request.variables)}}d(Q,"SanitizeGraphQLError");const A=new P,ge=u.gql`subscription RemoteOperationProgress($channelId: ID!) {
309
311
  RemoteOperationProgress(channelId: $channelId) {
310
312
  ChannelId
311
313
  ProgressJSON
312
314
  }
313
- }`;class se extends c.ProviderConfigDataBase{static{d(this,"GraphQLProviderConfigData")}get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get MJAPIKey(){return this.Data.MJAPIKey}set MJAPIKey(e){this.Data.MJAPIKey=e}get UserAPIKey(){return this.Data.UserAPIKey}set UserAPIKey(e){this.Data.UserAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}get OnAuthenticationError(){return this.Data.OnAuthenticationError}set OnAuthenticationError(e){this.Data.OnAuthenticationError=e}constructor(e,t,r,s,n,o,i,a,y,l){super({Token:e,URL:t,WSURL:r,MJAPIKey:a,UserAPIKey:y,RefreshTokenFunction:s,OnAuthenticationError:l},n,o,i)}}class I extends c.ProviderBase{static{d(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._dynamicHeaders=new Map,this._innerCurrentUserQueryString=`CurrentUser {
315
+ }`;class ye extends c.ProviderConfigDataBase{static{d(this,"GraphQLProviderConfigData")}get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get MJAPIKey(){return this.Data.MJAPIKey}set MJAPIKey(e){this.Data.MJAPIKey=e}get UserAPIKey(){return this.Data.UserAPIKey}set UserAPIKey(e){this.Data.UserAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get LogVariableValues(){return this.Data.LogVariableValues===!0}set LogVariableValues(e){this.Data.LogVariableValues=e}get RefreshTokenFunction(){return this.Data.RefreshFunction}get OnAuthenticationError(){return this.Data.OnAuthenticationError}set OnAuthenticationError(e){this.Data.OnAuthenticationError=e}constructor(e,t,r,s,n,o,i,a,m,g){super({Token:e,URL:t,WSURL:r,MJAPIKey:a,UserAPIKey:m,RefreshTokenFunction:s,OnAuthenticationError:g},n,o,i)}}class I extends c.ProviderBase{static{d(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._dynamicHeaders=new Map,this._innerCurrentUserQueryString=`CurrentUser {
314
316
  ${this.userInfoString()}
315
317
  MJUserRoles_UserIDArray {
316
318
  ${this.userRoleInfoString()}
@@ -319,7 +321,7 @@
319
321
  `,this._currentUserQuery=u.gql`query CurrentUserAndRoles {
320
322
  ${this._innerCurrentUserQueryString}
321
323
  CurrentUserTenantContext
322
- }`,this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject=new L.BehaviorSubject("unknown"),this._isDisposingSocketIntentionally=!1,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=1800*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=300*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=600*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,this._cacheInvalidationSubscription=null;const e=D.GetGlobalObjectStore();if(e&&e[I._globalStoreKey])return e[I._globalStoreKey];e&&(e[I._globalStoreKey]=this)}static{this.VerboseCacheInvalidationLogging=!1}static{this._globalStoreKey="___SINGLETON__GraphQLDataProvider"}static get Instance(){const e=D.GetGlobalObjectStore();return e?e[I._globalStoreKey]:void 0}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new U(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 W.v4()}get LocalStoragePrefix(){if(this._configData===void 0||this._configData.URL===void 0)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const r=this.LocalStoragePrefix+"sessionId";await t.SetItem(r,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,r,s){try{return this._configData=e,r?(this._sessionId=await this.GetPreferredUUID(s),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey,e.UserAPIKey),await this.SaveStoredSessionID(this._sessionId)):(I.Instance._configData=e,I.Instance._sessionId===void 0&&(I.Instance._sessionId=await this.GetPreferredUUID(s)),I.Instance._client||(I.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,I.Instance._sessionId,e.MJAPIKey,e.UserAPIKey)),await I.Instance.SaveStoredSessionID(I.Instance._sessionId),this._sessionId=I.Instance._sessionId,this._client=I.Instance._client),super.Config(e)}catch(n){throw c.LogError(n),n}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}SetDynamicHeader(e,t){this._dynamicHeaders.set(e,t),this._client&&this._client.setHeader(e,t),I.Instance&&I.Instance!==this&&I.Instance._configData===this._configData&&(I.Instance._dynamicHeaders.set(e,t),I.Instance._client&&I.Instance._client.setHeader(e,t))}RemoveDynamicHeader(e){this._dynamicHeaders.delete(e),this._client&&this._client.setHeader(e,""),I.Instance&&I.Instance!==this&&I.Instance._configData===this._configData&&(I.Instance._dynamicHeaders.delete(e),I.Instance._client&&I.Instance._client.setHeader(e,""))}GetDynamicHeaders(){return this._dynamicHeaders}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),r=t.MJUserRoles_UserIDArray.map(n=>this.ConvertBackToMJFields(n));t.MJUserRoles_UserIDArray=r;const s=new c.UserInfo(this,{...t,UserRoles:r});return e.CurrentUserTenantContext&&typeof e.CurrentUserTenantContext=="object"&&(s.TenantContext=e.CurrentUserTenantContext),s}}async InternalRunQuery(e,t){if(e.SQL)return this.RunAdhocQuery(e.SQL,e.MaxRows,void 0,e.StartRow);if(e.QueryID)return this.RunQueryByID(e.QueryID,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow,e.Enrichment);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow,e.Enrichment);throw new Error("No SQL, QueryID, or QueryName provided to RunQuery")}async RunAdhocQuery(e,t,r,s){const n=u.gql`
324
+ }`,this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject=new L.BehaviorSubject("unknown"),this._isDisposingSocketIntentionally=!1,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=1800*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=300*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=600*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,this._cacheInvalidationSubscription=null;const e=D.GetGlobalObjectStore();if(e&&e[I._globalStoreKey])return e[I._globalStoreKey];e&&(e[I._globalStoreKey]=this)}static{this.VerboseCacheInvalidationLogging=!1}static{this._globalStoreKey="___SINGLETON__GraphQLDataProvider"}static get Instance(){const e=D.GetGlobalObjectStore();return e?e[I._globalStoreKey]:void 0}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new O(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}async InternalExecuteQueryFromSpec(e,t){throw new Error("ExecuteQueryFromSpec is not supported by this provider.")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return Y.v4()}get LocalStoragePrefix(){if(this._configData===void 0||this._configData.URL===void 0)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const r=this.LocalStoragePrefix+"sessionId";await t.SetItem(r,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,r,s){try{return this._configData=e,r?(this._sessionId=await this.GetPreferredUUID(s),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey,e.UserAPIKey),await this.SaveStoredSessionID(this._sessionId)):(I.Instance._configData=e,I.Instance._sessionId===void 0&&(I.Instance._sessionId=await this.GetPreferredUUID(s)),I.Instance._client||(I.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,I.Instance._sessionId,e.MJAPIKey,e.UserAPIKey)),await I.Instance.SaveStoredSessionID(I.Instance._sessionId),this._sessionId=I.Instance._sessionId,this._client=I.Instance._client),super.Config(e)}catch(n){throw c.LogError(n),n}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}SetDynamicHeader(e,t){this._dynamicHeaders.set(e,t),this._client&&this._client.setHeader(e,t),I.Instance&&I.Instance!==this&&I.Instance._configData===this._configData&&(I.Instance._dynamicHeaders.set(e,t),I.Instance._client&&I.Instance._client.setHeader(e,t))}RemoveDynamicHeader(e){this._dynamicHeaders.delete(e),this._client&&this._client.setHeader(e,""),I.Instance&&I.Instance!==this&&I.Instance._configData===this._configData&&(I.Instance._dynamicHeaders.delete(e),I.Instance._client&&I.Instance._client.setHeader(e,""))}GetDynamicHeaders(){return this._dynamicHeaders}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),r=t.MJUserRoles_UserIDArray.map(n=>this.ConvertBackToMJFields(n));t.MJUserRoles_UserIDArray=r;const s=new c.UserInfo(this,{...t,UserRoles:r});return e.CurrentUserTenantContext&&typeof e.CurrentUserTenantContext=="object"&&(s.TenantContext=e.CurrentUserTenantContext),s}}async InternalRunQuery(e,t){if(e.SQL)return this.RunAdhocQuery(e.SQL,e.MaxRows,void 0,e.StartRow);if(e.QueryID)return this.RunQueryByID(e.QueryID,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow,e.Enrichment);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow,e.Enrichment);throw new Error("No SQL, QueryID, or QueryName provided to RunQuery")}async RunAdhocQuery(e,t,r,s){const n=u.gql`
323
325
  query ExecuteAdhocQuery($input: AdhocQueryInput!) {
324
326
  ExecuteAdhocQuery(input: $input) {
325
327
  ${this.QueryReturnFieldList}
@@ -331,19 +333,19 @@
331
333
  ${this.QueryReturnFieldList}
332
334
  }
333
335
  }
334
- `,s=e.map(o=>({QueryID:o.QueryID,QueryName:o.QueryName,CategoryID:o.CategoryID,CategoryPath:o.CategoryPath,Parameters:o.Parameters,MaxRows:o.MaxRows,StartRow:o.StartRow,ForceAuditLog:o.ForceAuditLog,AuditLogDescription:o.AuditLogDescription,Enrichment:o.Enrichment})),n=await this.ExecuteGQL(r,{input:s});return n&&n.RunQueries?n.RunQueries.map(o=>this.TransformQueryPayload(o)):[]}async RunQueryByID(e,t,r,s,n,o,i,a){const y=u.gql`
336
+ `,s=e.map(o=>({QueryID:o.QueryID,QueryName:o.QueryName,CategoryID:o.CategoryID,CategoryPath:o.CategoryPath,Parameters:o.Parameters,MaxRows:o.MaxRows,StartRow:o.StartRow,ForceAuditLog:o.ForceAuditLog,AuditLogDescription:o.AuditLogDescription,Enrichment:o.Enrichment})),n=await this.ExecuteGQL(r,{input:s});return n&&n.RunQueries?n.RunQueries.map(o=>this.TransformQueryPayload(o)):[]}async RunQueryByID(e,t,r,s,n,o,i,a){const m=u.gql`
335
337
  query GetQueryDataQuery($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int, $Enrichment: JSONObject) {
336
338
  GetQueryData(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow, Enrichment: $Enrichment) {
337
339
  ${this.QueryReturnFieldList}
338
340
  }
339
341
  }
340
- `,l={QueryID:e};t!==void 0&&(l.CategoryID=t),r!==void 0&&(l.CategoryPath=r),n!==void 0&&(l.Parameters=n),o!==void 0&&(l.MaxRows=o),i!==void 0&&(l.StartRow=i),a!==void 0&&(l.Enrichment=a);const h=await this.ExecuteGQL(y,l);if(h&&h.GetQueryData)return this.TransformQueryPayload(h.GetQueryData)}async RunQueryByName(e,t,r,s,n,o,i,a){const y=u.gql`
342
+ `,g={QueryID:e};t!==void 0&&(g.CategoryID=t),r!==void 0&&(g.CategoryPath=r),n!==void 0&&(g.Parameters=n),o!==void 0&&(g.MaxRows=o),i!==void 0&&(g.StartRow=i),a!==void 0&&(g.Enrichment=a);const h=await this.ExecuteGQL(m,g);if(h&&h.GetQueryData)return this.TransformQueryPayload(h.GetQueryData)}async RunQueryByName(e,t,r,s,n,o,i,a){const m=u.gql`
341
343
  query GetQueryDataByNameQuery($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int, $Enrichment: JSONObject) {
342
344
  GetQueryDataByName(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow, Enrichment: $Enrichment) {
343
345
  ${this.QueryReturnFieldList}
344
346
  }
345
347
  }
346
- `,l={QueryName:e};t!==void 0&&(l.CategoryID=t),r!==void 0&&(l.CategoryPath=r),n!==void 0&&(l.Parameters=n),o!==void 0&&(l.MaxRows=o),i!==void 0&&(l.StartRow=i),a!==void 0&&(l.Enrichment=a);const h=await this.ExecuteGQL(y,l);if(h&&h.GetQueryDataByName)return this.TransformQueryPayload(h.GetQueryDataByName)}get QueryReturnFieldList(){return`
348
+ `,g={QueryName:e};t!==void 0&&(g.CategoryID=t),r!==void 0&&(g.CategoryPath=r),n!==void 0&&(g.Parameters=n),o!==void 0&&(g.MaxRows=o),i!==void 0&&(g.StartRow=i),a!==void 0&&(g.Enrichment=a);const h=await this.ExecuteGQL(m,g);if(h&&h.GetQueryDataByName)return this.TransformQueryPayload(h.GetQueryDataByName)}get QueryReturnFieldList(){return`
347
349
  Success
348
350
  QueryID
349
351
  QueryName
@@ -368,14 +370,14 @@
368
370
  }
369
371
  }
370
372
  }
371
- `,o=(await this.ExecuteGQL(s,{input:r}))?.RunQueriesWithCacheCheck;if(!o)return{success:!1,results:[],errorMessage:"No response from server"};const i=o.results.map(a=>{if((a.status==="stale"||a.status==="no_validation")&&a.Results){const y=JSON.parse(a.Results);return{queryIndex:a.queryIndex,queryId:a.queryId,status:a.status,results:y,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}}return{queryIndex:a.queryIndex,queryId:a.queryId,status:a.status,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}});return{success:o.success,results:i,errorMessage:o.errorMessage}}catch(r){return c.LogError(`Error in RunQueriesWithCacheCheck: ${r}`),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async InternalRunView(e,t){try{let r="",s="";if(e){const n={};let o,i;if(e.ViewEntity)i=e.ViewEntity,o=i.Entity;else{const{entityName:p,v:E}=await this.getEntityNameAndUserView(e,t);i=E,o=p}const a=this.EntityByName(o);if(!a)throw new Error(`Entity ${o} not found in metadata`);let y=!1;const l=c.getGraphQLTypeNameBase(a);e.ViewID?(r=`Run${l}ViewByID`,s="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(r=`Run${l}ViewByName`,s="RunViewByNameInput",n.ViewName=e.ViewName):(y=!0,r=`Run${l}DynamicView`,s="RunDynamicViewInput",n.EntityName=e.EntityName),n.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",n.OrderBy=e.OrderBy?e.OrderBy:"",n.UserSearchString=e.UserSearchString?e.UserSearchString:"",n.Fields=e.Fields,n.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,e.MaxRows!==void 0&&(n.MaxRows=e.MaxRows),e.StartRow!==void 0&&(n.StartRow=e.StartRow),n.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,n.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(n.AuditLogDescription=e.AuditLogDescription),e.BypassCache!==void 0&&(n.BypassCache=e.BypassCache),y||(n.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",n.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,n.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",n.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1),e.Aggregates&&e.Aggregates.length>0&&(n.Aggregates=e.Aggregates.map(p=>({expression:p.expression,alias:p.alias})));const h=this.getViewRunTimeFieldList(a,i,e,y),f=e.Aggregates&&e.Aggregates.length>0?`
373
+ `,o=(await this.ExecuteGQL(s,{input:r}))?.RunQueriesWithCacheCheck;if(!o)return{success:!1,results:[],errorMessage:"No response from server"};const i=o.results.map(a=>{if((a.status==="stale"||a.status==="no_validation")&&a.Results){const m=JSON.parse(a.Results);return{queryIndex:a.queryIndex,queryId:a.queryId,status:a.status,results:m,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}}return{queryIndex:a.queryIndex,queryId:a.queryId,status:a.status,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}});return{success:o.success,results:i,errorMessage:o.errorMessage}}catch(r){return c.LogError(`Error in RunQueriesWithCacheCheck: ${r}`),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async InternalRunView(e,t){try{let r="",s="";if(e){const n={};let o,i;if(e.ViewEntity)i=e.ViewEntity,o=i.Entity;else{const{entityName:p,v:E}=await this.getEntityNameAndUserView(e,t);i=E,o=p}const a=this.EntityByName(o);if(!a)throw new Error(`Entity ${o} not found in metadata`);let m=!1;const g=c.getGraphQLTypeNameBase(a);e.ViewID?(r=`Run${g}ViewByID`,s="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(r=`Run${g}ViewByName`,s="RunViewByNameInput",n.ViewName=e.ViewName):(m=!0,r=`Run${g}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),m||(n.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",n.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,n.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",n.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1),e.Aggregates&&e.Aggregates.length>0&&(n.Aggregates=e.Aggregates.map(p=>({expression:p.expression,alias:p.alias})));const h=this.getViewRunTimeFieldList(a,i,e,m),f=e.Aggregates&&e.Aggregates.length>0?`
372
374
  AggregateResults {
373
375
  alias
374
376
  expression
375
377
  value
376
378
  error
377
379
  }
378
- AggregateExecutionTime`:"",g=u.gql`
380
+ AggregateExecutionTime`:"",y=u.gql`
379
381
  query RunViewQuery ($input: ${s}!) {
380
382
  ${r}(input: $input) {
381
383
  Results {
@@ -389,7 +391,7 @@
389
391
  Success
390
392
  ErrorMessage${f}
391
393
  }
392
- }`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:o,queryName:r,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const S=await this.ExecuteGQL(g,{input:n});if(S&&S[r]){const p=S[r].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:o,aggregateResultCount:p?.length||0,aggregateResults:p,aggregateExecutionTime:S[r].AggregateExecutionTime});const E=S[r].Results;if(E&&E.length>0){const v=a.Fields.filter(C=>C.CodeName!==C.Name&&C.CodeName!==void 0);E.forEach(C=>{this.ConvertBackToMJFields(C),v.forEach(N=>{C[N.Name]=C[N.CodeName]})})}return S[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw c.LogError(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],n=[];for(const l of e){let h="",f="";const g={};let S=null,p=null;if(l.ViewEntity)p=l.ViewEntity,S=p.Get("Entity");else{const{entityName:C,v:N}=await this.getEntityNameAndUserView(l,t);p=N,S=C}const E=this.EntityByName(S);if(!E)throw new Error(`Entity ${S} not found in metadata`);s.push(E);let R=!1;const v=c.getGraphQLTypeNameBase(E);l.ViewID?(h=`Run${v}ViewByID`,f="RunViewByIDInput",g.ViewID=l.ViewID):l.ViewName?(h=`Run${v}ViewByName`,f="RunViewByNameInput",g.ViewName=l.ViewName):(R=!0,h=`Run${v}DynamicView`,f="RunDynamicViewInput",g.EntityName=l.EntityName),g.ExtraFilter=l.ExtraFilter||"",g.OrderBy=l.OrderBy||"",g.UserSearchString=l.UserSearchString||"",g.Fields=l.Fields,g.IgnoreMaxRows=l.IgnoreMaxRows||!1,l.MaxRows!==void 0&&(g.MaxRows=l.MaxRows),l.StartRow!==void 0&&(g.StartRow=l.StartRow),l.AfterKey&&(g.AfterKey={KeyValuePairs:l.AfterKey.KeyValuePairs}),g.ForceAuditLog=l.ForceAuditLog||!1,g.ResultType=l.ResultType||"simple",l.AuditLogDescription&&l.AuditLogDescription.length>0&&(g.AuditLogDescription=l.AuditLogDescription),l.BypassCache!==void 0&&(g.BypassCache=l.BypassCache),R||(g.ExcludeUserViewRunID=l.ExcludeUserViewRunID||"",g.ExcludeDataFromAllPriorViewRuns=l.ExcludeDataFromAllPriorViewRuns||!1,g.OverrideExcludeFilter=l.OverrideExcludeFilter||"",g.SaveViewResults=l.SaveViewResults||!1),l.Aggregates&&l.Aggregates.length>0&&(g.Aggregates=l.Aggregates.map(C=>({expression:C.expression,alias:C.alias}))),r.push(g),n.push(...this.getViewRunTimeFieldList(E,p,l,R))}const i=e.some(l=>l.Aggregates&&l.Aggregates.length>0)?`
394
+ }`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:o,queryName:r,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const S=await this.ExecuteGQL(y,{input:n});if(S&&S[r]){const p=S[r].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:o,aggregateResultCount:p?.length||0,aggregateResults:p,aggregateExecutionTime:S[r].AggregateExecutionTime});const E=S[r].Results;if(E&&E.length>0){const v=a.Fields.filter(C=>C.CodeName!==C.Name&&C.CodeName!==void 0);E.forEach(C=>{this.ConvertBackToMJFields(C),v.forEach(N=>{C[N.Name]=C[N.CodeName]})})}return S[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw c.LogError(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],n=[];for(const g of e){let h="",f="";const y={};let S=null,p=null;if(g.ViewEntity)p=g.ViewEntity,S=p.Get("Entity");else{const{entityName:C,v:N}=await this.getEntityNameAndUserView(g,t);p=N,S=C}const E=this.EntityByName(S);if(!E)throw new Error(`Entity ${S} not found in metadata`);s.push(E);let R=!1;const v=c.getGraphQLTypeNameBase(E);g.ViewID?(h=`Run${v}ViewByID`,f="RunViewByIDInput",y.ViewID=g.ViewID):g.ViewName?(h=`Run${v}ViewByName`,f="RunViewByNameInput",y.ViewName=g.ViewName):(R=!0,h=`Run${v}DynamicView`,f="RunDynamicViewInput",y.EntityName=g.EntityName),y.ExtraFilter=g.ExtraFilter||"",y.OrderBy=g.OrderBy||"",y.UserSearchString=g.UserSearchString||"",y.Fields=g.Fields,y.IgnoreMaxRows=g.IgnoreMaxRows||!1,g.MaxRows!==void 0&&(y.MaxRows=g.MaxRows),g.StartRow!==void 0&&(y.StartRow=g.StartRow),g.AfterKey&&(y.AfterKey={KeyValuePairs:g.AfterKey.KeyValuePairs}),y.ForceAuditLog=g.ForceAuditLog||!1,y.ResultType=g.ResultType||"simple",g.AuditLogDescription&&g.AuditLogDescription.length>0&&(y.AuditLogDescription=g.AuditLogDescription),g.BypassCache!==void 0&&(y.BypassCache=g.BypassCache),R||(y.ExcludeUserViewRunID=g.ExcludeUserViewRunID||"",y.ExcludeDataFromAllPriorViewRuns=g.ExcludeDataFromAllPriorViewRuns||!1,y.OverrideExcludeFilter=g.OverrideExcludeFilter||"",y.SaveViewResults=g.SaveViewResults||!1),g.Aggregates&&g.Aggregates.length>0&&(y.Aggregates=g.Aggregates.map(C=>({expression:C.expression,alias:C.alias}))),r.push(y),n.push(...this.getViewRunTimeFieldList(E,p,g,R))}const i=e.some(g=>g.Aggregates&&g.Aggregates.length>0)?`
393
395
  AggregateResults {
394
396
  alias
395
397
  expression
@@ -414,7 +416,7 @@
414
416
  Success
415
417
  ErrorMessage${i}
416
418
  }
417
- }`,y=await this.ExecuteGQL(a,{input:r});if(y&&y.RunViews){const l=y.RunViews;for(const[h,f]of l.entries())f.Results=f.Results.map(g=>{let S=JSON.parse(g.Data);return this.ConvertBackToMJFields(S),S});return l}return null}catch(r){throw c.LogError(r),r}}async RunViewsWithCacheCheck(e,t){try{const r=e.map(a=>({params:{EntityName:a.params.EntityName||"",ExtraFilter:a.params.ExtraFilter||"",OrderBy:a.params.OrderBy||"",Fields:a.params.Fields,UserSearchString:a.params.UserSearchString||"",IgnoreMaxRows:a.params.IgnoreMaxRows||!1,MaxRows:a.params.MaxRows,StartRow:a.params.StartRow,AfterKey:a.params.AfterKey?{KeyValuePairs:a.params.AfterKey.KeyValuePairs}:null,ForceAuditLog:a.params.ForceAuditLog||!1,AuditLogDescription:a.params.AuditLogDescription||"",ResultType:a.params.ResultType||"simple",Aggregates:a.params.Aggregates??null},cacheStatus:a.cacheStatus?{maxUpdatedAt:a.cacheStatus.maxUpdatedAt,rowCount:a.cacheStatus.rowCount}:null})),s=u.gql`
419
+ }`,m=await this.ExecuteGQL(a,{input:r});if(m&&m.RunViews){const g=m.RunViews;for(const[h,f]of g.entries())f.Results=f.Results.map(y=>{let S=JSON.parse(y.Data);return this.ConvertBackToMJFields(S),S});return g}return null}catch(r){throw c.LogError(r),r}}async RunViewsWithCacheCheck(e,t){try{const r=e.map(a=>({params:{EntityName:a.params.EntityName||"",ExtraFilter:a.params.ExtraFilter||"",OrderBy:a.params.OrderBy||"",Fields:a.params.Fields,UserSearchString:a.params.UserSearchString||"",IgnoreMaxRows:a.params.IgnoreMaxRows||!1,MaxRows:a.params.MaxRows,StartRow:a.params.StartRow,AfterKey:a.params.AfterKey?{KeyValuePairs:a.params.AfterKey.KeyValuePairs}:null,ForceAuditLog:a.params.ForceAuditLog||!1,AuditLogDescription:a.params.AuditLogDescription||"",ResultType:a.params.ResultType||"simple",Aggregates:a.params.Aggregates??null},cacheStatus:a.cacheStatus?{maxUpdatedAt:a.cacheStatus.maxUpdatedAt,rowCount:a.cacheStatus.rowCount}:null})),s=u.gql`
418
420
  query RunViewsWithCacheCheckQuery($input: [RunViewWithCacheCheckInput!]!) {
419
421
  RunViewsWithCacheCheck(input: $input) {
420
422
  success
@@ -453,7 +455,7 @@
453
455
  }
454
456
  }
455
457
  }
456
- `,o=(await this.ExecuteGQL(s,{input:r}))?.RunViewsWithCacheCheck;if(!o)return{success:!1,results:[],errorMessage:"No response from server"};const i=o.results.map((a,y)=>{const l=e[y];if(a.status==="differential"&&a.differentialData){const h=a.differentialData.updatedRows.map(f=>{const g=JSON.parse(f.Data);return this.ConvertBackToMJFields(g),g});return{viewIndex:a.viewIndex,status:a.status,results:void 0,differentialData:{updatedRows:h,deletedRecordIDs:a.differentialData.deletedRecordIDs},maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}}if(a.status==="stale"&&a.Results){const h=a.Results.map(g=>{const S=JSON.parse(g.Data);return this.ConvertBackToMJFields(S),S}),f=a.aggregateResults?.map(g=>({expression:g.expression,alias:g.alias,value:g.value!==void 0&&g.value!==null?JSON.parse(g.value):null,error:g.error}));return{viewIndex:a.viewIndex,status:a.status,results:h,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage,aggregateResults:f}}return{viewIndex:a.viewIndex,status:a.status,results:void 0,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}});return{success:o.success,results:i,errorMessage:o.errorMessage}}catch(r){return c.LogError(r),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async getEntityNameAndUserView(e,t){let r,s;if(e.EntityName)r=e.EntityName;else if(e.ViewID)s=await q.ViewInfo.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await q.ViewInfo.GetViewEntityByName(e.ViewName,t),r=s.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:r,v:s}}getViewRunTimeFieldList(e,t,r,s){const n=[];if(r.Fields){for(const o of e.PrimaryKeys)r.Fields.find(i=>i.trim().toLowerCase()===o.Name.toLowerCase())===void 0&&n.push(o.Name);r.Fields.forEach(o=>{n.push(A.MapFieldName(o))})}else if(s)e.Fields.forEach(o=>{o.IsBinaryFieldType||n.push(A.MapFieldName(o.CodeName))});else{for(const o of e.PrimaryKeys)n.find(i=>i.trim().toLowerCase()===o.Name.toLowerCase())===void 0&&n.push(o.Name);t.Columns.forEach(o=>{o.hidden===!1&&!n.find(i=>i.trim().toLowerCase()===o.EntityField?.Name.trim().toLowerCase())&&o.EntityField&&n.push(A.MapFieldName(o.EntityField.CodeName))})}return n}get ProviderType(){return c.ProviderType.Network}async GetRecordChanges(e,t){try{const r={EntityName:"MJ: Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},s=await this.RunView(r);return s?s.Results.sort((n,o)=>n.ChangedAt>o.ChangedAt?-1:1):null}catch(r){throw c.LogError(r),r}}async GetRecordDependencies(e,t){try{const r=u.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
458
+ `,o=(await this.ExecuteGQL(s,{input:r}))?.RunViewsWithCacheCheck;if(!o)return{success:!1,results:[],errorMessage:"No response from server"};const i=o.results.map((a,m)=>{const g=e[m];if(a.status==="differential"&&a.differentialData){const h=a.differentialData.updatedRows.map(f=>{const y=JSON.parse(f.Data);return this.ConvertBackToMJFields(y),y});return{viewIndex:a.viewIndex,status:a.status,results:void 0,differentialData:{updatedRows:h,deletedRecordIDs:a.differentialData.deletedRecordIDs},maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}}if(a.status==="stale"&&a.Results){const h=a.Results.map(y=>{const S=JSON.parse(y.Data);return this.ConvertBackToMJFields(S),S}),f=a.aggregateResults?.map(y=>({expression:y.expression,alias:y.alias,value:y.value!==void 0&&y.value!==null?JSON.parse(y.value):null,error:y.error}));return{viewIndex:a.viewIndex,status:a.status,results:h,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage,aggregateResults:f}}return{viewIndex:a.viewIndex,status:a.status,results:void 0,maxUpdatedAt:a.maxUpdatedAt,rowCount:a.rowCount,errorMessage:a.errorMessage}});return{success:o.success,results:i,errorMessage:o.errorMessage}}catch(r){return c.LogError(r),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async getEntityNameAndUserView(e,t){let r,s;if(e.EntityName)r=e.EntityName;else if(e.ViewID)s=await V.ViewInfo.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await V.ViewInfo.GetViewEntityByName(e.ViewName,t),r=s.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:r,v:s}}getViewRunTimeFieldList(e,t,r,s){const n=[];if(r.Fields){for(const o of e.PrimaryKeys)r.Fields.find(i=>i.trim().toLowerCase()===o.Name.toLowerCase())===void 0&&n.push(o.Name);r.Fields.forEach(o=>{n.push(A.MapFieldName(o))})}else if(s)e.Fields.forEach(o=>{o.IsBinaryFieldType||n.push(A.MapFieldName(o.CodeName))});else{for(const o of e.PrimaryKeys)n.find(i=>i.trim().toLowerCase()===o.Name.toLowerCase())===void 0&&n.push(o.Name);t.Columns.forEach(o=>{o.hidden===!1&&!n.find(i=>i.trim().toLowerCase()===o.EntityField?.Name.trim().toLowerCase())&&o.EntityField&&n.push(A.MapFieldName(o.EntityField.CodeName))})}return n}get ProviderType(){return c.ProviderType.Network}async GetRecordChanges(e,t){try{const r={EntityName:"MJ: Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},s=await this.RunView(r);return s?s.Results.sort((n,o)=>n.ChangedAt>o.ChangedAt?-1:1):null}catch(r){throw c.LogError(r),r}}async GetRecordDependencies(e,t){try{const r=u.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
457
459
  GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
458
460
  EntityName
459
461
  RelatedEntityName
@@ -511,7 +513,7 @@
511
513
  handle
512
514
  errorMessage
513
515
  }
514
- }`;let n,o;r.onProgress&&(n=this.GenerateUUID(),o=this.subscribe(re,{channelId:n}).subscribe({next:d(i=>{const a=i?.RemoteOperationProgress?.ProgressJSON;if(a)try{r.onProgress(JSON.parse(a))}catch{}},"next"),error:d(()=>{},"error")}),await new Promise(i=>setTimeout(i,400)));try{const a=(await this.ExecuteGQL(s,{operationKey:e,inputJSON:JSON.stringify(t??null),invokeMode:r.mode??"attached",progressChannelId:n??null}))?.ExecuteRemoteOperation;return a?{Success:!!a.success,ResultCode:a.resultCode??void 0,Output:a.outputJSON!=null?JSON.parse(a.outputJSON):void 0,Handle:a.handle??void 0,ErrorMessage:a.errorMessage??void 0}:{Success:!1,ResultCode:"NO_RESPONSE",ErrorMessage:"No response from ExecuteRemoteOperation"}}catch(i){return{Success:!1,ResultCode:"TRANSPORT_ERROR",ErrorMessage:i instanceof Error?i.message:String(i)}}finally{o?.unsubscribe()}}async MergeRecords(e,t,r){const s=this.Entities.find(n=>n.Name.trim().toLowerCase()===e.EntityName.trim().toLowerCase());if(!s||!s.AllowRecordMerge)throw new Error(`Entity ${e.EntityName} does not allow record merging, check the AllowRecordMerge property in the entity metadata`);try{const n=u.gql`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
516
+ }`;let n,o;r.onProgress&&(n=this.GenerateUUID(),o=this.subscribe(ge,{channelId:n}).subscribe({next:d(i=>{const a=i?.RemoteOperationProgress?.ProgressJSON;if(a)try{r.onProgress(JSON.parse(a))}catch{}},"next"),error:d(()=>{},"error")}),await new Promise(i=>setTimeout(i,400)));try{const a=(await this.ExecuteGQL(s,{operationKey:e,inputJSON:JSON.stringify(t??null),invokeMode:r.mode??"attached",progressChannelId:n??null}))?.ExecuteRemoteOperation;return a?{Success:!!a.success,ResultCode:a.resultCode??void 0,Output:a.outputJSON!=null?JSON.parse(a.outputJSON):void 0,Handle:a.handle??void 0,ErrorMessage:a.errorMessage??void 0}:{Success:!1,ResultCode:"NO_RESPONSE",ErrorMessage:"No response from ExecuteRemoteOperation"}}catch(i){return{Success:!1,ResultCode:"TRANSPORT_ERROR",ErrorMessage:i instanceof Error?i.message:String(i)}}finally{o?.unsubscribe()}}async MergeRecords(e,t,r){const s=this.Entities.find(n=>n.Name.trim().toLowerCase()===e.EntityName.trim().toLowerCase());if(!s||!s.AllowRecordMerge)throw new Error(`Entity ${e.EntityName} does not allow record merging, check the AllowRecordMerge property in the entity metadata`);try{const n=u.gql`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
515
517
  MergeRecords(request: $request) {
516
518
  Success
517
519
  OverallStatus
@@ -528,32 +530,32 @@
528
530
  Message
529
531
  }
530
532
  }
531
- }`,o={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(a=>({FieldName:a.FieldName,Value:a.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(a=>a.Copy())};return(await this.ExecuteGQL(n,{request:o}))?.MergeRecords}catch(n){return c.LogError(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){if(r?.IsParentEntitySave){const n=new c.BaseEntityResult;return n.StartedAt=new Date,n.EndedAt=new Date,n.Type=e.IsSaved?"update":"create",n.Success=!0,n.NewValues=e.GetAll(),e.RegisterResultHistoryEntry(n),n.NewValues}const s=new c.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const n={input:{}},o=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=c.getGraphQLTypeNameBase(e.EntityInfo),a=`${o}${i}`,y=e.Fields.filter(g=>!g.ReadOnly||g.IsPrimaryKey&&e.IsSaved),l=` ${a}(input: $input) {
532
- ${e.Fields.map(g=>A.MapFieldName(g.CodeName)).join(`
533
+ }`,o={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(a=>({FieldName:a.FieldName,Value:a.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(a=>a.Copy())};return(await this.ExecuteGQL(n,{request:o}))?.MergeRecords}catch(n){return c.LogError(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){if(r?.IsParentEntitySave){const n=new c.BaseEntityResult;return n.StartedAt=new Date,n.EndedAt=new Date,n.Type=e.IsSaved?"update":"create",n.Success=!0,n.NewValues=e.GetAll(),e.RegisterResultHistoryEntry(n),n.NewValues}const s=new c.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const n={input:{}},o=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(y=>({FieldName:y.CodeName,Value:y.Value})),e.RegisterResultHistoryEntry(s);const i=c.getGraphQLTypeNameBase(e.EntityInfo),a=`${o}${i}`,m=e.Fields.filter(y=>!y.ReadOnly||y.IsPrimaryKey&&e.IsSaved),g=` ${a}(input: $input) {
534
+ ${e.Fields.map(y=>A.MapFieldName(y.CodeName)).join(`
533
535
  `)}
534
536
  }`,h=u.gql`mutation ${o}${i} ($input: ${a}Input!) {
535
- ${l}
537
+ ${g}
536
538
  }
537
- `;for(let g=0;g<y.length;g++){const S=y[g];let p=e.Get(S.Name);if(p)switch(S.EntityFieldInfo.TSType){case c.EntityFieldTSType.Date:p=p.getTime();break;case c.EntityFieldTSType.Boolean:typeof p!="boolean"&&(p=parseInt(p)!==0);break;case c.EntityFieldTSType.Number:if(typeof p!="number"){const E=Number(p);isNaN(E)||(p=E)}break}p===null&&S.EntityFieldInfo.AllowsNull===!1&&(S.EntityFieldInfo.DefaultValue!==null?p=S.EntityFieldInfo.DefaultValue:S.FieldType===c.EntityFieldTSType.Number||S.FieldType===c.EntityFieldTSType.Boolean?p=0:p=""),n.input[A.MapFieldName(S.CodeName)]=p}const f=e.RestoreContext;if(f&&(n.input.RestoreContext___={SourceChangeID:f.SourceChangeID,Reason:f.Reason}),o.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const g=[];e.Fields.forEach(S=>{let p=null;S.OldValue!==null&&S.OldValue!==void 0&&(S.EntityFieldInfo.TSType===c.EntityFieldTSType.Date?p=S.OldValue.getTime().toString():S.EntityFieldInfo.TSType===c.EntityFieldTSType.Boolean?p=S.OldValue===!0?"1":"0":typeof S.OldValue!="string"?p=S.OldValue.toString():p=S.OldValue),g.push({Key:A.MapFieldName(S.CodeName),Value:p})}),n.input.OldValues___=g}if(e.TransactionGroup){const g=[{varName:"input",inputType:a+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,s.Type==="create"?"Create":"Update",l,n,{mutationName:a,mutationInputTypes:g},(S,p)=>{s.EndedAt=new Date,p&&S?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(S)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const g=await this.ExecuteGQL(h,n);if(g&&g[a])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(g[a]),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(n){return s.Success=!1,s.EndedAt=new Date,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,c.LogError(n),null}}async Load(e,t,r=null,s){try{const n={};let o="",i="";for(let f=0;f<t.KeyValuePairs.length;f++){const g=e.Fields.find(E=>E.Name.trim().toLowerCase()===t.KeyValuePairs[f].FieldName.trim().toLowerCase()).EntityFieldInfo,S=t.GetValueByIndex(f),p=g.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${g.CodeName}: ${p}!`,o.length>0&&(o+=", "),o+=`${g.CodeName}: $${g.CodeName}`,g.TSType===c.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(f)))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 a=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",y=c.getGraphQLTypeNameBase(e.EntityInfo),l=u.gql`query Single${y}${a.length>0?"Full":""} (${i}) {
538
- ${y}(${o}) {
539
+ `;for(let y=0;y<m.length;y++){const S=m[y];let p=e.Get(S.Name);if(p)switch(S.EntityFieldInfo.TSType){case c.EntityFieldTSType.Date:p=p.getTime();break;case c.EntityFieldTSType.Boolean:typeof p!="boolean"&&(p=parseInt(p)!==0);break;case c.EntityFieldTSType.Number:if(typeof p!="number"){const E=Number(p);isNaN(E)||(p=E)}break}p===null&&S.EntityFieldInfo.AllowsNull===!1&&(S.EntityFieldInfo.DefaultValue!==null?p=S.EntityFieldInfo.DefaultValue:S.FieldType===c.EntityFieldTSType.Number||S.FieldType===c.EntityFieldTSType.Boolean?p=0:p=""),n.input[A.MapFieldName(S.CodeName)]=p}const f=e.RestoreContext;if(f&&(n.input.RestoreContext___={SourceChangeID:f.SourceChangeID,Reason:f.Reason}),o.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const y=[];e.Fields.forEach(S=>{let p=null;S.OldValue!==null&&S.OldValue!==void 0&&(S.EntityFieldInfo.TSType===c.EntityFieldTSType.Date?p=S.OldValue.getTime().toString():S.EntityFieldInfo.TSType===c.EntityFieldTSType.Boolean?p=S.OldValue===!0?"1":"0":typeof S.OldValue!="string"?p=S.OldValue.toString():p=S.OldValue),y.push({Key:A.MapFieldName(S.CodeName),Value:p})}),n.input.OldValues___=y}if(e.TransactionGroup){const y=[{varName:"input",inputType:a+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,s.Type==="create"?"Create":"Update",g,n,{mutationName:a,mutationInputTypes:y},(S,p)=>{s.EndedAt=new Date,p&&S?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(S)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const y=await this.ExecuteGQL(h,n);if(y&&y[a])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(y[a]),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(n){return s.Success=!1,s.EndedAt=new Date,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,c.LogError(n),null}}async Load(e,t,r=null,s){try{const n={};let o="",i="";for(let f=0;f<t.KeyValuePairs.length;f++){const y=e.Fields.find(E=>E.Name.trim().toLowerCase()===t.KeyValuePairs[f].FieldName.trim().toLowerCase()).EntityFieldInfo,S=t.GetValueByIndex(f),p=y.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${y.CodeName}: ${p}!`,o.length>0&&(o+=", "),o+=`${y.CodeName}: $${y.CodeName}`,y.TSType===c.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(f)))throw new Error(`Primary Key value ${S} (${y.Name}) is not a valid number`);n[y.CodeName]=parseInt(S)}else n[y.CodeName]=S}const a=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",m=c.getGraphQLTypeNameBase(e.EntityInfo),g=u.gql`query Single${m}${a.length>0?"Full":""} (${i}) {
540
+ ${m}(${o}) {
539
541
  ${e.Fields.filter(f=>!f.EntityFieldInfo.IsBinaryFieldType).map(f=>f.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?f.CodeName.replace("__mj_","_mj__"):f.CodeName).join(`
540
542
  `)}
541
543
  ${a}
542
544
  }
543
545
  }
544
- `,h=await this.ExecuteGQL(l,n);return h&&h[y]?this.ConvertBackToMJFields(h[y]):null}catch(n){return c.LogError(n),null}}ConvertBackToMJFields(e){return A.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],o=this.EntityByID(n.RelatedEntityID);let i="";n.Type.toLowerCase().trim()==="many to many"?i=`${n.RelatedEntityCodeName}_${n.JoinEntityJoinField.replace(/\s/g,"")}`:i=`${n.RelatedEntityCodeName}_${n.RelatedEntityJoinField.replace(/\s/g,"")}`,r+=`
546
+ `,h=await this.ExecuteGQL(g,n);return h&&h[m]?this.ConvertBackToMJFields(h[m]):null}catch(n){return c.LogError(n),null}}ConvertBackToMJFields(e){return A.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],o=this.EntityByID(n.RelatedEntityID);let i="";n.Type.toLowerCase().trim()==="many to many"?i=`${n.RelatedEntityCodeName}_${n.JoinEntityJoinField.replace(/\s/g,"")}`:i=`${n.RelatedEntityCodeName}_${n.RelatedEntityJoinField.replace(/\s/g,"")}`,r+=`
545
547
  ${i} {
546
548
  ${o.Fields.map(a=>a.CodeName).join(`
547
549
  `)}
548
550
  }
549
- `}return r}async Delete(e,t,r){const s=new c.BaseEntityResult;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(S=>({FieldName:S.CodeName,Value:S.Value})),e.RegisterResultHistoryEntry(s);const n={},o=[];let i="",a="",y="";for(let S of e.PrimaryKey.KeyValuePairs){const p=e.Fields.find(E=>E.Name.trim().toLowerCase()===S.FieldName.trim().toLowerCase());n[p.CodeName]=p.Value,o.push({varName:p.CodeName,inputType:p.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${p.CodeName}: $${p.CodeName}`,a.length>0&&(a+=", "),a+=`$${p.CodeName}: ${p.EntityFieldInfo.GraphQLType}!`,y.length>0&&(y+=`
550
- `),y+=`${p.CodeName}`}o.push({varName:"options___",inputType:"DeleteOptionsInput!"}),n.options___={SkipEntityAIActions:t?.SkipEntityAIActions??!1,SkipEntityActions:t?.SkipEntityActions??!1,ReplayOnly:t?.ReplayOnly??!1,IsParentEntityDelete:t?.IsParentEntityDelete??!1};const h="Delete"+c.getGraphQLTypeNameBase(e.EntityInfo),f=u.gql`${h}(${i}, options___: $options___) {
551
- ${y}
551
+ `}return r}async Delete(e,t,r){const s=new c.BaseEntityResult;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(S=>({FieldName:S.CodeName,Value:S.Value})),e.RegisterResultHistoryEntry(s);const n={},o=[];let i="",a="",m="";for(let S of e.PrimaryKey.KeyValuePairs){const p=e.Fields.find(E=>E.Name.trim().toLowerCase()===S.FieldName.trim().toLowerCase());n[p.CodeName]=p.Value,o.push({varName:p.CodeName,inputType:p.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${p.CodeName}: $${p.CodeName}`,a.length>0&&(a+=", "),a+=`$${p.CodeName}: ${p.EntityFieldInfo.GraphQLType}!`,m.length>0&&(m+=`
552
+ `),m+=`${p.CodeName}`}o.push({varName:"options___",inputType:"DeleteOptionsInput!"}),n.options___={SkipEntityAIActions:t?.SkipEntityAIActions??!1,SkipEntityActions:t?.SkipEntityActions??!1,ReplayOnly:t?.ReplayOnly??!1,IsParentEntityDelete:t?.IsParentEntityDelete??!1};const h="Delete"+c.getGraphQLTypeNameBase(e.EntityInfo),f=u.gql`${h}(${i}, options___: $options___) {
553
+ ${m}
552
554
  }
553
- `,g=u.gql`mutation ${h} (${a}, $options___: DeleteOptionsInput!) {
555
+ `,y=u.gql`mutation ${h} (${a}, $options___: DeleteOptionsInput!) {
554
556
  ${f}
555
557
  }
556
- `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,"Delete",f,n,{mutationName:h,mutationInputTypes:o},(S,p)=>{if(s.EndedAt=new Date,p&&S){let E=!0;for(const R of e.PrimaryKey.KeyValuePairs)R.Value!==S[R.FieldName]&&(E=!1);E?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const S=await this.ExecuteGQL(g,n);if(S&&S[h]){const p=S[h];for(let E of e.PrimaryKey.KeyValuePairs){let R=p[E.FieldName],v=E.Value;if(typeof v=="number"&&(v=v.toString()),typeof R=="number"&&(R=R.toString()),v!==R)throw new Error(`Primary key value mismatch in server Delete response. Field: ${E.FieldName}, Original: ${v}, 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,c.LogError(n),!1}}async GetDatasetByName(e,t){const r=u.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
558
+ `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,"Delete",f,n,{mutationName:h,mutationInputTypes:o},(S,p)=>{if(s.EndedAt=new Date,p&&S){let E=!0;for(const R of e.PrimaryKey.KeyValuePairs)R.Value!==S[R.FieldName]&&(E=!1);E?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const S=await this.ExecuteGQL(y,n);if(S&&S[h]){const p=S[h];for(let E of e.PrimaryKey.KeyValuePairs){let R=p[E.FieldName],v=E.Value;if(typeof v=="number"&&(v=v.toString()),typeof R=="number"&&(R=R.toString()),v!==R)throw new Error(`Primary key value mismatch in server Delete response. Field: ${E.FieldName}, Original: ${v}, 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,c.LogError(n),!1}}async GetDatasetByName(e,t){const r=u.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
557
559
  GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
558
560
  DatasetID
559
561
  DatasetName
@@ -580,7 +582,7 @@
580
582
  LatestUpdateDate
581
583
  EntityUpdateDates
582
584
  }
583
- }`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetStatusByName&&s.GetDatasetStatusByName.Success?{DatasetID:s.GetDatasetStatusByName.DatasetID,DatasetName:s.GetDatasetStatusByName.DatasetName,Success:s.GetDatasetStatusByName.Success,Status:s.GetDatasetStatusByName.Status,LatestUpdateDate:new Date(s.GetDatasetStatusByName.LatestUpdateDate),EntityUpdateDates:JSON.parse(s.GetDatasetStatusByName.EntityUpdateDates)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,EntityUpdateDates:null}}async CreateTransactionGroup(){return new G(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const n=this.EntityByName(t);if(!n)throw new Error(`Entity ${t} not found in metadata`);const o=u.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
585
+ }`,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 _(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const n=this.EntityByName(t);if(!n)throw new Error(`Entity ${t} not found in metadata`);const o=u.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
584
586
  GetRecordFavoriteStatus(params: $params) {
585
587
  Success
586
588
  IsFavorite
@@ -620,16 +622,16 @@
620
622
  ErrorMessage
621
623
  Result
622
624
  }
623
- }`,r=await this.ExecuteGQL(t,{DataContextItemID:e});if(r&&r.GetDataContextItemData){if(r.GetDataContextItemData.Success)return JSON.parse(r.GetDataContextItemData.Result);throw new Error(r.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw c.LogError(t),t}}static async ExecuteGQL(e,t,r=!0){return I.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(console.error("[GraphQL] ExecuteGQL error caught:",{hasResponse:!!s?.response,hasErrors:!!s?.response?.errors,errorCount:s?.response?.errors?.length,firstError:s?.response?.errors?.[0],errorCode:s?.response?.errors?.[0]?.extensions?.code,errorMessage:s?.response?.errors?.[0]?.message,fullError:s}),s&&s.response&&s.response.errors?.length>0)if(s.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw c.LogError("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw c.LogError(s),s}}async RefreshToken(){const e=I.Instance&&I.Instance._configData===this._configData;if(e&&I.Instance._refreshPromise)return I.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(I.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&I.Instance&&(I.Instance._refreshPromise=null)}}async performTokenRefresh(){if(this._configData.Data.RefreshTokenFunction)try{const e=await this._configData.Data.RefreshTokenFunction();if(e){this._configData.Token=e;const t=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey,this._configData.UserAPIKey);this._client=t,I.Instance&&I.Instance._configData===this._configData&&(I.Instance._client=t)}else{const t=new Error("Refresh token function returned null or undefined token");throw this.notifyAuthenticationError(t),t}}catch(e){const t=e instanceof Error?e:new Error(String(e));throw this.notifyAuthenticationError(t),e}else{const e=new Error("No refresh token function provided");throw this.notifyAuthenticationError(e),e}}notifyAuthenticationError(e){try{const t=this._configData?.OnAuthenticationError;t&&t(e)}catch(t){console.error("[GraphQLDataProvider] Error in OnAuthenticationError callback:",t)}}static async RefreshToken(){return I.Instance.RefreshToken()}static async clearClientCache(e=new Set){const t=[];for(let r=0;r<localStorage.length;r++){const s=localStorage.key(r);s&&!e.has(s)&&t.push(s)}t.forEach(r=>localStorage.removeItem(r)),await new Promise(r=>{const s=indexedDB.deleteDatabase("MJ_Metadata");s.onsuccess=()=>r(),s.onerror=()=>r(),s.onblocked=()=>r()})}CreateNewGraphQLClient(e,t,r,s,n){const o={"x-session-id":r};t&&(o.authorization="Bearer "+t),s&&(o["x-mj-api-key"]=s),n&&(o["x-api-key"]=n);const i=new u.GraphQLClient(e,{headers:o});for(const[a,y]of this._dynamicHeaders)i.setHeader(a,y);return i}userInfoString(){return this.infoString(new c.UserInfo(null,null))}userRoleInfoString(){return this.infoString(new c.UserRoleInfo(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
625
+ }`,r=await this.ExecuteGQL(t,{DataContextItemID:e});if(r&&r.GetDataContextItemData){if(r.GetDataContextItemData.Success)return JSON.parse(r.GetDataContextItemData.Result);throw new Error(r.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw c.LogError(t),t}}static async ExecuteGQL(e,t,r=!0){return I.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){const n=Q(s,this._configData?.LogVariableValues===!0);console.error("[GraphQL] ExecuteGQL error caught:",n);const o=j(s);if(s&&s.response&&s.response.errors?.length>0)if(s.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw c.LogError("JWT_EXPIRED and refreshTokenIfNeeded is false"),o}else throw o;else throw c.LogError(JSON.stringify(n)),o}}async RefreshToken(){const e=I.Instance&&I.Instance._configData===this._configData;if(e&&I.Instance._refreshPromise)return I.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(I.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&I.Instance&&(I.Instance._refreshPromise=null)}}async performTokenRefresh(){if(this._configData.Data.RefreshTokenFunction)try{const e=await this._configData.Data.RefreshTokenFunction();if(e){this._configData.Token=e;const t=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey,this._configData.UserAPIKey);this._client=t,I.Instance&&I.Instance._configData===this._configData&&(I.Instance._client=t)}else{const t=new Error("Refresh token function returned null or undefined token");throw this.notifyAuthenticationError(t),t}}catch(e){const t=e instanceof Error?e:new Error(String(e));throw this.notifyAuthenticationError(t),e}else{const e=new Error("No refresh token function provided");throw this.notifyAuthenticationError(e),e}}notifyAuthenticationError(e){try{const t=this._configData?.OnAuthenticationError;t&&t(e)}catch(t){console.error("[GraphQLDataProvider] Error in OnAuthenticationError callback:",t)}}static async RefreshToken(){return I.Instance.RefreshToken()}static async clearClientCache(e=new Set){const t=[];for(let r=0;r<localStorage.length;r++){const s=localStorage.key(r);s&&!e.has(s)&&t.push(s)}t.forEach(r=>localStorage.removeItem(r)),await new Promise(r=>{const s=indexedDB.deleteDatabase("MJ_Metadata");s.onsuccess=()=>r(),s.onerror=()=>r(),s.onblocked=()=>r()})}CreateNewGraphQLClient(e,t,r,s,n){const o={"x-session-id":r};t&&(o.authorization="Bearer "+t),s&&(o["x-mj-api-key"]=s),n&&(o["x-api-key"]=n);const i=new u.GraphQLClient(e,{headers:o});for(const[a,m]of this._dynamicHeaders)i.setHeader(a,m);return i}userInfoString(){return this.infoString(new c.UserInfo(null,null))}userRoleInfoString(){return this.infoString(new c.UserRoleInfo(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
624
626
  `:s.startsWith("_")||(t+=s+`
625
- `);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new O:this._localStorageProvider=new c.InMemoryLocalStorageProvider),this._localStorageProvider}get Metadata(){return this}get SocketConnectivity$(){return this._socketStateSubject.asObservable()}get SocketConnectionState(){return this._socketStateSubject.value}ForceSocketReconnect(){this.disposeWSClient()}getOrCreateWSClient(){const e=Date.now();return this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&this._activeSubscriptionCount===0&&this.disposeWSClient(),this._wsClient||(this._isDisposingSocketIntentionally=!1,this._wsClient=J.createClient({url:this.ConfigData.WSURL,connectionParams:d(()=>({Authorization:"Bearer "+this.ConfigData.Token,...this.ConfigData.MJAPIKey?{"x-mj-api-key":this.ConfigData.MJAPIKey}:{},...this.ConfigData.UserAPIKey?{"x-mj-user-api-key":this.ConfigData.UserAPIKey}:{}}),"connectionParams"),keepAlive:3e4,retryAttempts:3,shouldRetry:d(()=>!0,"shouldRetry")}),this._wsClientCreatedAt=e,this._wsClient.on("connected",()=>{this._socketStateSubject.next("connected")}),this._wsClient.on("closed",t=>{if(this._isDisposingSocketIntentionally)return;this._socketStateSubject.next("disconnected"),t?.code===4403&&this._configData.Data.RefreshTokenFunction&&this.RefreshToken().catch(()=>{})}),this._subscriptionCleanupTimer||(this._subscriptionCleanupTimer=setInterval(()=>{this.cleanupStaleSubscriptions()},this.SUBSCRIPTION_CLEANUP_INTERVAL_MS))),this._wsClient}disposeWSClient(){if(this._wsClient){this._isDisposingSocketIntentionally=!0;try{this._wsClient.dispose()}catch(e){console.error("[GraphQLDataProvider] Error disposing WebSocket client:",e)}this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject.next("unknown")}}completeAllSubjects(){this._pushStatusSubjects.forEach((e,t)=>{try{e.subject.complete(),e.subscription.unsubscribe()}catch(r){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,r)}}),this._pushStatusSubjects.clear()}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,o])=>{const i=e-o.lastRequestedAt,a=e-o.lastEmissionAt;o.activeSubscribers===0&&i>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&a>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${n} for cleanup: activeSubscribers=${o.activeSubscribers}, timeSinceRequested=${Math.round(i/1e3)}s, timeSinceEmission=${Math.round(a/1e3)}s`),s.push(n))}),s.forEach(n=>{const o=this._pushStatusSubjects.get(n);if(o)try{o.subject.complete(),o.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 L.Observable(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=s.subscribe({query:e,variables:t},{next:d(o=>{r.next(o.data)},"next"),error:d(async o=>{const i=o;if(i?.extensions?.code==="JWT_EXPIRED"||i?.message?.includes("token has expired")||i?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] WebSocket JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),r.complete()}catch(y){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",y),r.error(y)}}else r.error(o)},"error"),complete:d(()=>{r.complete()},"complete")});return()=>{this._activeSubscriptionCount--,n()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),r=this._pushStatusSubjects.get(e);if(r)return r.lastRequestedAt=t,new L.Observable(a=>{r.activeSubscribers++;const y=r.subject.subscribe(a);return()=>{const l=this._pushStatusSubjects.get(e);l&&l.activeSubscribers>0&&l.activeSubscribers--,y.unsubscribe()}});const s=u.gql`subscription StatusUpdates($sessionId: String!) {
627
+ `);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new B:this._localStorageProvider=new c.InMemoryLocalStorageProvider),this._localStorageProvider}get Metadata(){return this}get SocketConnectivity$(){return this._socketStateSubject.asObservable()}get SocketConnectionState(){return this._socketStateSubject.value}ForceSocketReconnect(){this.disposeWSClient()}getOrCreateWSClient(){const e=Date.now();return this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&this._activeSubscriptionCount===0&&this.disposeWSClient(),this._wsClient||(this._isDisposingSocketIntentionally=!1,this._wsClient=X.createClient({url:this.ConfigData.WSURL,connectionParams:d(()=>({Authorization:"Bearer "+this.ConfigData.Token,...this.ConfigData.MJAPIKey?{"x-mj-api-key":this.ConfigData.MJAPIKey}:{},...this.ConfigData.UserAPIKey?{"x-mj-user-api-key":this.ConfigData.UserAPIKey}:{}}),"connectionParams"),keepAlive:3e4,retryAttempts:3,shouldRetry:d(()=>!0,"shouldRetry")}),this._wsClientCreatedAt=e,this._wsClient.on("connected",()=>{this._socketStateSubject.next("connected")}),this._wsClient.on("closed",t=>{if(this._isDisposingSocketIntentionally)return;this._socketStateSubject.next("disconnected"),t?.code===4403&&this._configData.Data.RefreshTokenFunction&&this.RefreshToken().catch(()=>{})}),this._subscriptionCleanupTimer||(this._subscriptionCleanupTimer=setInterval(()=>{this.cleanupStaleSubscriptions()},this.SUBSCRIPTION_CLEANUP_INTERVAL_MS))),this._wsClient}disposeWSClient(){if(this._wsClient){this._isDisposingSocketIntentionally=!0;try{this._wsClient.dispose()}catch(e){console.error("[GraphQLDataProvider] Error disposing WebSocket client:",e)}this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject.next("unknown")}}completeAllSubjects(){this._pushStatusSubjects.forEach((e,t)=>{try{e.subject.complete(),e.subscription.unsubscribe()}catch(r){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,r)}}),this._pushStatusSubjects.clear()}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,o])=>{const i=e-o.lastRequestedAt,a=e-o.lastEmissionAt;o.activeSubscribers===0&&i>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&a>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${n} for cleanup: activeSubscribers=${o.activeSubscribers}, timeSinceRequested=${Math.round(i/1e3)}s, timeSinceEmission=${Math.round(a/1e3)}s`),s.push(n))}),s.forEach(n=>{const o=this._pushStatusSubjects.get(n);if(o)try{o.subject.complete(),o.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 L.Observable(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=s.subscribe({query:e,variables:t},{next:d(o=>{r.next(o.data)},"next"),error:d(async o=>{const i=o;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(m){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",m),r.error(m)}}else r.error(o)},"error"),complete:d(()=>{r.complete()},"complete")});return()=>{this._activeSubscriptionCount--,n()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),r=this._pushStatusSubjects.get(e);if(r)return r.lastRequestedAt=t,new L.Observable(a=>{r.activeSubscribers++;const m=r.subject.subscribe(a);return()=>{const g=this._pushStatusSubjects.get(e);g&&g.activeSubscribers>0&&g.activeSubscribers--,m.unsubscribe()}});const s=u.gql`subscription StatusUpdates($sessionId: String!) {
626
628
  statusUpdates(sessionId: $sessionId) {
627
629
  date
628
630
  message
629
631
  sessionId
630
632
  }
631
633
  }
632
- `,n=new L.Subject,o=this.getOrCreateWSClient(),i=new L.Subscription;return i.add(new L.Observable(a=>{const y=o.subscribe({query:s,variables:{sessionId:e}},{next:d(l=>{const h=this._pushStatusSubjects.get(e);h&&(h.lastEmissionAt=Date.now()),a.next(l.data.statusUpdates.message)},"next"),error:d(async l=>{const h=l;if(h?.extensions?.code==="JWT_EXPIRED"||h?.message?.includes("token has expired")||h?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),a.complete()}catch(g){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",g),a.error(g)}}else a.error(l)},"error"),complete:d(()=>{a.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,y()}}).subscribe({next:d(a=>n.next(a),"next"),error:d(a=>{n.error(a),this._pushStatusSubjects.delete(e)},"error"),complete:d(()=>{n.complete(),this._pushStatusSubjects.delete(e)},"complete")})),this._pushStatusSubjects.set(e,{subject:n,subscription:i,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new L.Observable(a=>{const y=this._pushStatusSubjects.get(e);y&&y.activeSubscribers++;const l=n.subscribe(a);return()=>{const h=this._pushStatusSubjects.get(e);h&&h.activeSubscribers>0&&h.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(`
634
+ `,n=new L.Subject,o=this.getOrCreateWSClient(),i=new L.Subscription;return i.add(new L.Observable(a=>{const m=o.subscribe({query:s,variables:{sessionId:e}},{next:d(g=>{const h=this._pushStatusSubjects.get(e);h&&(h.lastEmissionAt=Date.now()),a.next(g.data.statusUpdates.message)},"next"),error:d(async g=>{const h=g;if(h?.extensions?.code==="JWT_EXPIRED"||h?.message?.includes("token has expired")||h?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),a.complete()}catch(y){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",y),a.error(y)}}else a.error(g)},"error"),complete:d(()=>{a.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,m()}}).subscribe({next:d(a=>n.next(a),"next"),error:d(a=>{n.error(a),this._pushStatusSubjects.delete(e)},"error"),complete:d(()=>{n.complete(),this._pushStatusSubjects.delete(e)},"complete")})),this._pushStatusSubjects.set(e,{subject:n,subscription:i,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new L.Observable(a=>{const m=this._pushStatusSubjects.get(e);m&&m.activeSubscribers++;const g=n.subscribe(a);return()=>{const h=this._pushStatusSubjects.get(e);h&&h.activeSubscribers>0&&h.activeSubscribers--,g.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.UnsubscribeFromCacheInvalidation(),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}ClientToolRequests(e){return this.subscribe(`
633
635
  subscription ClientToolRequest($sessionID: String!) {
634
636
  ClientToolRequest(sessionID: $sessionID) {
635
637
  AgentRunID
@@ -663,7 +665,7 @@
663
665
  ChildEntityNames
664
666
  ErrorMessage
665
667
  }
666
- }`;try{const n=await this.ExecuteGQL(s,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntities?.Success&&n.FindISAChildEntities.ChildEntityNames?n.FindISAChildEntities.ChildEntityNames.map(o=>({ChildEntityName:o})):[]}catch(n){return c.LogError(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function ne(m){const e=new I;return c.SetProvider(e),await e.Config(m),await e.preValidateAndRefresh(),D.MJGlobal.Instance.RaiseEvent({event:D.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),await c.StartupManager.Instance.Startup(),e}d(ne,"setupGraphQLClient");class oe{static{d(this,"SyncRolesAndUsersResult")}}class ae{static{d(this,"RoleInput")}}class ie{static{d(this,"UserInput")}}class ce{static{d(this,"RolesAndUsersInput")}}var k=(m=>(m.Create="Create",m.Update="Update",m.CreateOrUpdate="CreateOrUpdate",m.Delete="Delete",m.DeleteWithFilter="DeleteWithFilter",m))(k||{});class ue{static{d(this,"ActionItemInput")}}class le{static{d(this,"SyncDataResult")}constructor(){this.Results=[]}}class de{static{d(this,"ActionItemOutput")}}class ge{static{d(this,"GraphQLSystemUserClient")}get Client(){return this._client}constructor(e,t,r,s){const n={"x-session-id":r};this._sessionId=r,t&&(n.authorization="Bearer "+t),s&&(n["x-mj-api-key"]=s),this._client=new u.GraphQLClient(e,{headers:n})}resolvePlatformSQL(e){if(e!=null)return c.IsPlatformSQL(e)?e.default:e}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
668
+ }`;try{const n=await this.ExecuteGQL(s,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntities?.Success&&n.FindISAChildEntities.ChildEntityNames?n.FindISAChildEntities.ChildEntityNames.map(o=>({ChildEntityName:o})):[]}catch(n){return c.LogError(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function me(l){const e=new I;return c.SetProvider(e),await e.Config(l),await e.preValidateAndRefresh(),D.MJGlobal.Instance.RaiseEvent({event:D.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),await c.StartupManager.Instance.Startup(),e}d(me,"setupGraphQLClient");class Se{static{d(this,"SyncRolesAndUsersResult")}}class pe{static{d(this,"RoleInput")}}class he{static{d(this,"UserInput")}}class Ie{static{d(this,"RolesAndUsersInput")}}var J=(l=>(l.Create="Create",l.Update="Update",l.CreateOrUpdate="CreateOrUpdate",l.Delete="Delete",l.DeleteWithFilter="DeleteWithFilter",l))(J||{});class fe{static{d(this,"ActionItemInput")}}class Ee{static{d(this,"SyncDataResult")}constructor(){this.Results=[]}}class Re{static{d(this,"ActionItemOutput")}}class De{static{d(this,"GraphQLSystemUserClient")}get Client(){return this._client}constructor(e,t,r,s){const n={"x-session-id":r};this._sessionId=r,t&&(n.authorization="Bearer "+t),s&&(n["x-mj-api-key"]=s),this._client=new u.GraphQLClient(e,{headers:n})}resolvePlatformSQL(e){if(e!=null)return c.IsPlatformSQL(e)?e.default:e}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
667
669
  GetData(input: $input) {
668
670
  Success
669
671
  ErrorMessages
@@ -1176,7 +1178,7 @@
1176
1178
  ErrorMessage
1177
1179
  }
1178
1180
  }
1179
- `,s={EntityNames:e,UserEmail:t},n=await this.Client.request(r,s);if(n?.CheckEntityPermissionsSystemUser){const o=n.CheckEntityPermissionsSystemUser;return{Success:o.Success,Results:(o.Results||[]).map(i=>({EntityName:i.EntityName,CanRead:i.CanRead})),ErrorMessage:o.ErrorMessage}}return{Success:!1,Results:[],ErrorMessage:"Invalid response from server"}}catch(r){return c.LogError(`GraphQLSystemUserClient::CheckEntityPermissionsSystemUser - Error checking entity permissions - ${r}`),{Success:!1,Results:[],ErrorMessage:r instanceof Error?r.message:String(r)}}}}class ye{static{d(this,"GetDataOutput")}}class me{static{d(this,"SimpleRemoteEntityOutput")}}class Se{static{d(this,"SimpleRemoteEntity")}}class pe{static{d(this,"SimpleRemoteEntityField")}}class he{static{d(this,"GraphQLActionClient")}constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),n=this.createActionVariables(e,s,r),o=await this.executeActionMutation(n);return this.processActionResult(o,t)}catch(s){return this.handleActionError(s,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{...t,Value:r}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=u.gql`
1181
+ `,s={EntityNames:e,UserEmail:t},n=await this.Client.request(r,s);if(n?.CheckEntityPermissionsSystemUser){const o=n.CheckEntityPermissionsSystemUser;return{Success:o.Success,Results:(o.Results||[]).map(i=>({EntityName:i.EntityName,CanRead:i.CanRead})),ErrorMessage:o.ErrorMessage}}return{Success:!1,Results:[],ErrorMessage:"Invalid response from server"}}catch(r){return c.LogError(`GraphQLSystemUserClient::CheckEntityPermissionsSystemUser - Error checking entity permissions - ${r}`),{Success:!1,Results:[],ErrorMessage:r instanceof Error?r.message:String(r)}}}}class ve{static{d(this,"GetDataOutput")}}class Ce{static{d(this,"SimpleRemoteEntityOutput")}}class we{static{d(this,"SimpleRemoteEntity")}}class $e{static{d(this,"SimpleRemoteEntityField")}}class Pe{static{d(this,"GraphQLActionClient")}constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),n=this.createActionVariables(e,s,r),o=await this.executeActionMutation(n);return this.processActionResult(o,t)}catch(s){return this.handleActionError(s,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{...t,Value:r}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=u.gql`
1180
1182
  mutation RunAction($input: RunActionInput!) {
1181
1183
  RunAction(input: $input) {
1182
1184
  Success
@@ -1193,14 +1195,14 @@
1193
1195
  ResultData
1194
1196
  }
1195
1197
  }
1196
- `;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(r){c.LogError(`Failed to parse entity action result data: ${r}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return c.LogError(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}}class Ie{static{d(this,"GraphQLListsClient")}constructor(e){this.dataProvider=e}async PreviewListDelta(e){const t=u.gql`
1198
+ `;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(r){c.LogError(`Failed to parse entity action result data: ${r}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return c.LogError(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}}class Le{static{d(this,"GraphQLListsClient")}constructor(e){this.dataProvider=e}async PreviewListDelta(e){const t=u.gql`
1197
1199
  query PreviewListDelta($input: ComputeDeltaInput!) {
1198
1200
  PreviewListDelta(input: $input) {
1199
1201
  ...ListDeltaFields
1200
1202
  }
1201
1203
  }
1202
- ${K}
1203
- `,r=await this.dataProvider.ExecuteGQL(t,{input:{Target:e.Target,Source:Q(e.Source),Mode:e.Mode}});return B(r?.PreviewListDelta)}async ApplyListDelta(e){const t=u.gql`
1204
+ ${W}
1205
+ `,r=await this.dataProvider.ExecuteGQL(t,{input:{Target:e.Target,Source:U(e.Source),Mode:e.Mode}});return z(r?.PreviewListDelta)}async ApplyListDelta(e){const t=u.gql`
1204
1206
  mutation ApplyListDelta($input: ApplyDeltaInput!) {
1205
1207
  ApplyListDelta(input: $input) {
1206
1208
  ...ApplyResultFields
@@ -1234,22 +1236,22 @@
1234
1236
  ...ListDeltaFields
1235
1237
  }
1236
1238
  }
1237
- ${K}
1238
- `,r=await this.dataProvider.ExecuteGQL(t,{input:{Op:e.Op,Inputs:e.Inputs.map(Q),Target:e.Target?Q(e.Target):null}});return B(r?.ComposeLists)}async Share(e){const t=u.gql`
1239
+ ${W}
1240
+ `,r=await this.dataProvider.ExecuteGQL(t,{input:{Op:e.Op,Inputs:e.Inputs.map(U),Target:e.Target?U(e.Target):null}});return z(r?.ComposeLists)}async Share(e){const t=u.gql`
1239
1241
  mutation ShareList($input: ShareListInput!) {
1240
1242
  ShareList(input: $input) {
1241
1243
  ...ShareResultFields
1242
1244
  }
1243
1245
  }
1244
- ${x}
1245
- `,r=await this.dataProvider.ExecuteGQL(t,{input:{ListID:e.ListID,Target:fe(e.Target),PermissionLevel:e.PermissionLevel}});return F(r?.ShareList)}async Unshare(e){const t=u.gql`
1246
+ ${q}
1247
+ `,r=await this.dataProvider.ExecuteGQL(t,{input:{ListID:e.ListID,Target:Ae(e.Target),PermissionLevel:e.PermissionLevel}});return G(r?.ShareList)}async Unshare(e){const t=u.gql`
1246
1248
  mutation UnshareList($permissionId: String!) {
1247
1249
  UnshareList(permissionId: $permissionId) {
1248
1250
  ...ShareResultFields
1249
1251
  }
1250
1252
  }
1251
- ${x}
1252
- `,r=await this.dataProvider.ExecuteGQL(t,{permissionId:e});return F(r?.UnshareList)}async Invite(e){const t=u.gql`
1253
+ ${q}
1254
+ `,r=await this.dataProvider.ExecuteGQL(t,{permissionId:e});return G(r?.UnshareList)}async Invite(e){const t=u.gql`
1253
1255
  mutation InviteToList($input: InviteToListInput!) {
1254
1256
  InviteToList(input: $input) {
1255
1257
  Success
@@ -1276,8 +1278,8 @@
1276
1278
  ...ShareResultFields
1277
1279
  }
1278
1280
  }
1279
- ${x}
1280
- `,r=await this.dataProvider.ExecuteGQL(t,{invitationId:e});return F(r?.RevokeListInvitation)}async GetSharesForList(e){const t=u.gql`
1281
+ ${q}
1282
+ `,r=await this.dataProvider.ExecuteGQL(t,{invitationId:e});return G(r?.RevokeListInvitation)}async GetSharesForList(e){const t=u.gql`
1281
1283
  query ListSharesForList($listId: String!) {
1282
1284
  ListSharesForList(listId: $listId) {
1283
1285
  PermissionID
@@ -1293,7 +1295,7 @@
1293
1295
  CreatedAt
1294
1296
  }
1295
1297
  }
1296
- `;return((await this.dataProvider.ExecuteGQL(t,{listId:e}))?.ListSharesForList??[]).map(Ee)}async ListsSharedWithMe(){const e=u.gql`
1298
+ `;return((await this.dataProvider.ExecuteGQL(t,{listId:e}))?.ListSharesForList??[]).map(Ne)}async ListsSharedWithMe(){const e=u.gql`
1297
1299
  query ListsSharedWithMe {
1298
1300
  ListsSharedWithMe {
1299
1301
  ListID
@@ -1303,7 +1305,7 @@
1303
1305
  SharedAt
1304
1306
  }
1305
1307
  }
1306
- `;return((await this.dataProvider.ExecuteGQL(e,{}))?.ListsSharedWithMe??[]).map(s=>({ListID:s.ListID,ListName:s.ListName,PermissionLevel:s.PermissionLevel,SharedByUserID:s.SharedByUserID??null,SharedAt:new Date(s.SharedAt)}))}}const K=u.gql`
1308
+ `;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 W=u.gql`
1307
1309
  fragment ListDeltaFields on ListDeltaType {
1308
1310
  TargetListId
1309
1311
  EntityName
@@ -1336,14 +1338,14 @@
1336
1338
  FailedCount
1337
1339
  Errors
1338
1340
  }
1339
- `,x=u.gql`
1341
+ `,q=u.gql`
1340
1342
  fragment ShareResultFields on ShareResultType {
1341
1343
  Success
1342
1344
  ResultCode
1343
1345
  Message
1344
1346
  PermissionID
1345
1347
  }
1346
- `;function fe(m){return m.kind==="user"?{Kind:"user",UserID:m.userId}:{Kind:"role",RoleID:m.roleId}}d(fe,"serializeShareTarget");function F(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}}d(F,"parseShareResult");function Ee(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)}}d(Ee,"parseShareSummary");function Q(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}}}d(Q,"serializeListSource");function B(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(Re),DeltaToken:e.DeltaToken}}d(B,"parseListDelta");function Re(m){let e;if(m.DetailsJSON)try{e=JSON.parse(m.DetailsJSON)}catch(t){c.LogError(`GraphQLListsClient: failed to parse warning details JSON: ${t}`)}return{Code:m.Code,Message:m.Message,Details:e}}d(Re,"parseWarning");function T(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}}d(T,"parseApplyResult");class De{static{d(this,"GraphQLEncryptionClient")}constructor(e){this._dataProvider=e}async CreateAPIKey(e){try{const t=this.createAPIKeyVariables(e),r=await this.executeCreateAPIKeyMutation(t);return this.processCreateAPIKeyResult(r)}catch(t){return this.handleCreateAPIKeyError(t)}}createAPIKeyVariables(e){return{input:{Label:e.Label,Description:e.Description,ExpiresAt:e.ExpiresAt?.toISOString(),ScopeIDs:e.ScopeIDs}}}async executeCreateAPIKeyMutation(e){const t=u.gql`
1348
+ `;function Ae(l){return l.kind==="user"?{Kind:"user",UserID:l.userId}:{Kind:"role",RoleID:l.roleId}}d(Ae,"serializeShareTarget");function G(l){if(!l||typeof l!="object")throw new Error("GraphQLListsClient: empty/invalid ShareResult response");const e=l;return{Success:e.Success,ResultCode:e.ResultCode,Message:e.Message,PermissionID:e.PermissionID??void 0}}d(G,"parseShareResult");function Ne(l){const e=l,t=e.Target.Kind==="user"?{kind:"user",userId:e.Target.UserID}:{kind:"role",roleId:e.Target.RoleID};return{PermissionID:e.PermissionID,ListID:e.ListID,Target:t,PermissionLevel:e.PermissionLevel,Status:e.Status,SharedByUserID:e.SharedByUserID??null,CreatedAt:new Date(e.CreatedAt)}}d(Ne,"parseShareSummary");function U(l){switch(l.kind){case"list":return{Kind:"list",ListID:l.listId};case"view":return{Kind:"view",ViewID:l.viewId};case"adhoc":return{Kind:"adhoc",EntityName:l.entityName,ExtraFilter:l.extraFilter}}}d(U,"serializeListSource");function z(l){if(!l||typeof l!="object")throw new Error("GraphQLListsClient: empty/invalid ListDelta response from server");const e=l;return{TargetListId:e.TargetListId,EntityName:e.EntityName,ToAdd:e.ToAdd,ToRemove:e.ToRemove,Unchanged:e.Unchanged,Counts:e.Counts,Warnings:e.Warnings.map(Me),DeltaToken:e.DeltaToken}}d(z,"parseListDelta");function Me(l){let e;if(l.DetailsJSON)try{e=JSON.parse(l.DetailsJSON)}catch(t){c.LogError(`GraphQLListsClient: failed to parse warning details JSON: ${t}`)}return{Code:l.Code,Message:l.Message,Details:e}}d(Me,"parseWarning");function T(l){if(!l||typeof l!="object")throw new Error("GraphQLListsClient: empty/invalid ApplyResult response from server");const e=l;return{Success:e.Success,ResultCode:e.ResultCode,Message:e.Message,CreatedListId:e.CreatedListId??void 0,TargetListId:e.TargetListId??void 0,Counts:e.AddedCount!=null||e.RemovedCount!=null||e.FailedCount!=null?{Added:e.AddedCount??0,Removed:e.RemovedCount??0,Failed:e.FailedCount??0}:void 0,Errors:e.Errors??void 0}}d(T,"parseApplyResult");class be{static{d(this,"GraphQLEncryptionClient")}constructor(e){this._dataProvider=e}async CreateAPIKey(e){try{const t=this.createAPIKeyVariables(e),r=await this.executeCreateAPIKeyMutation(t);return this.processCreateAPIKeyResult(r)}catch(t){return this.handleCreateAPIKeyError(t)}}createAPIKeyVariables(e){return{input:{Label:e.Label,Description:e.Description,ExpiresAt:e.ExpiresAt?.toISOString(),ScopeIDs:e.ScopeIDs}}}async executeCreateAPIKeyMutation(e){const t=u.gql`
1347
1349
  mutation CreateAPIKey($input: CreateAPIKeyInput!) {
1348
1350
  CreateAPIKey(input: $input) {
1349
1351
  Success
@@ -1359,7 +1361,7 @@
1359
1361
  Error
1360
1362
  }
1361
1363
  }
1362
- `,s=await this._dataProvider.ExecuteGQL(t,{apiKeyId:e});return s?.RevokeAPIKey?{Success:s.RevokeAPIKey.Success,Error:s.RevokeAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}catch(t){const r=t;return c.LogError(`Error revoking API key: ${r.message}`),{Success:!1,Error:`Error: ${r.message}`}}}}class ve{static{d(this,"GraphQLClusterClient")}constructor(e){this._dataProvider=e}async RunClusterAnalysis(e){try{const t=u.gql`
1364
+ `,s=await this._dataProvider.ExecuteGQL(t,{apiKeyId:e});return s?.RevokeAPIKey?{Success:s.RevokeAPIKey.Success,Error:s.RevokeAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}catch(t){const r=t;return c.LogError(`Error revoking API key: ${r.message}`),{Success:!1,Error:`Error: ${r.message}`}}}}class Te{static{d(this,"GraphQLClusterClient")}constructor(e){this._dataProvider=e}async RunClusterAnalysis(e){try{const t=u.gql`
1363
1365
  mutation RunClusterAnalysis($input: RunClusterAnalysisInput!) {
1364
1366
  RunClusterAnalysis(input: $input) {
1365
1367
  Success
@@ -1375,7 +1377,7 @@
1375
1377
  AnalysisID
1376
1378
  }
1377
1379
  }
1378
- `,s=(await this._dataProvider.ExecuteGQL(t,{input:e}))?.RunClusterAnalysis;if(!s)throw new Error("Invalid response from server");return this.parseResult(s)}catch(t){const r=t;return c.LogError("GraphQLClusterClient.RunClusterAnalysis failed",void 0,r),this.errorResult(r.message||"Unknown error occurred")}}parseResult(e){const t=this.parseMetrics(e),r=D.SafeJSONParse(e.ClustersJSON)??[],s=D.SafeJSONParse(e.PointsJSON)??[];return{Success:e.Success,ErrorMessage:e.ErrorMessage,Metrics:t,Clusters:r,Points:s,AnalysisID:e.AnalysisID}}parseMetrics(e){const t=D.SafeJSONParse(e.MetricsJSON);return t||{SilhouetteScore:e.SilhouetteScore,ClusterCount:e.ClusterCount,ComputationTimeMs:e.ComputationTimeMs,RecordCount:e.RecordCount,OutlierCount:e.OutlierCount}}errorResult(e){return{Success:!1,ErrorMessage:e,Metrics:{SilhouetteScore:0,ClusterCount:0,ComputationTimeMs:0,RecordCount:0,OutlierCount:0},Clusters:[],Points:[]}}}class Ce{static{d(this,"GraphQLLiveKitClient")}constructor(e){this._dataProvider=e}async MintClientToken(e){try{const t=u.gql`
1380
+ `,s=(await this._dataProvider.ExecuteGQL(t,{input:e}))?.RunClusterAnalysis;if(!s)throw new Error("Invalid response from server");return this.parseResult(s)}catch(t){const r=t;return c.LogError("GraphQLClusterClient.RunClusterAnalysis failed",void 0,r),this.errorResult(r.message||"Unknown error occurred")}}parseResult(e){const t=this.parseMetrics(e),r=D.SafeJSONParse(e.ClustersJSON)??[],s=D.SafeJSONParse(e.PointsJSON)??[];return{Success:e.Success,ErrorMessage:e.ErrorMessage,Metrics:t,Clusters:r,Points:s,AnalysisID:e.AnalysisID}}parseMetrics(e){const t=D.SafeJSONParse(e.MetricsJSON);return t||{SilhouetteScore:e.SilhouetteScore,ClusterCount:e.ClusterCount,ComputationTimeMs:e.ComputationTimeMs,RecordCount:e.RecordCount,OutlierCount:e.OutlierCount}}errorResult(e){return{Success:!1,ErrorMessage:e,Metrics:{SilhouetteScore:0,ClusterCount:0,ComputationTimeMs:0,RecordCount:0,OutlierCount:0},Clusters:[],Points:[]}}}class xe{static{d(this,"GraphQLLiveKitClient")}constructor(e){this._dataProvider=e}async MintClientToken(e){try{const t=u.gql`
1379
1381
  mutation MintLiveKitClientToken($input: MintLiveKitClientTokenInput!) {
1380
1382
  MintLiveKitClientToken(input: $input) {
1381
1383
  Success
@@ -1440,7 +1442,7 @@
1440
1442
  RecordingFileID
1441
1443
  }
1442
1444
  }
1443
- `,{egressID:e},"StopLiveKitRecording",e)}async runRecordingMutation(e,t,r,s){try{const o=(await this._dataProvider.ExecuteGQL(e,t))?.[r];if(!o)throw new Error("Invalid response from server");return o}catch(n){const o=n;return c.LogError(`GraphQLLiveKitClient.${r} failed`,void 0,o),{Success:!1,ErrorMessage:o.message||"Unknown error",EgressID:s,Status:""}}}}class we{static{d(this,"GraphQLClassifyClient")}constructor(e){this._dataProvider=e}async GenerateSeedTaxonomy(e){try{const t=u.gql`
1445
+ `,{egressID:e},"StopLiveKitRecording",e)}async runRecordingMutation(e,t,r,s){try{const o=(await this._dataProvider.ExecuteGQL(e,t))?.[r];if(!o)throw new Error("Invalid response from server");return o}catch(n){const o=n;return c.LogError(`GraphQLLiveKitClient.${r} failed`,void 0,o),{Success:!1,ErrorMessage:o.message||"Unknown error",EgressID:s,Status:""}}}}class Fe{static{d(this,"GraphQLClassifyClient")}constructor(e){this._dataProvider=e}async GenerateSeedTaxonomy(e){try{const t=u.gql`
1444
1446
  mutation GenerateSeedTaxonomy($sourceID: String!, $sampleSize: Int!) {
1445
1447
  GenerateSeedTaxonomy(sourceID: $sourceID, sampleSize: $sampleSize) {
1446
1448
  Success
@@ -1450,7 +1452,7 @@
1450
1452
  NodesJSON
1451
1453
  }
1452
1454
  }
1453
- `,s=(await this._dataProvider.ExecuteGQL(t,{sourceID:e.SourceID,sampleSize:e.SampleSize}))?.GenerateSeedTaxonomy;if(!s)throw new Error("Invalid response from server");return this.parseResult(s)}catch(t){const r=t;return c.LogError("GraphQLClassifyClient.GenerateSeedTaxonomy failed",void 0,r),this.errorResult(r.message||"Unknown error occurred")}}parseResult(e){const t=D.SafeJSONParse(e.NodesJSON)??[];return{Success:e.Success,ErrorMessage:e.ErrorMessage,Method:e.Method,SampleSize:e.SampleSize,Nodes:t}}errorResult(e){return{Success:!1,ErrorMessage:e,SampleSize:0,Nodes:[]}}}class $e{static{d(this,"GraphQLTestingClient")}constructor(e){this._dataProvider=e}async RunTest(e){try{const t=this.buildRunTestMutation(),r=this.buildRunTestVariables(e),s={};return await w.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTest",operationLabel:"RunTest",validateAck:d(n=>n?.success===!0,"validateAck"),isCompletionEvent:d(n=>this.isTestCompletionEvent(n,e.testId),"isCompletionEvent"),extractResult:d(n=>this.extractTestResult(n),"extractResult"),onMessage:d(n=>{this.captureTestRunId(n,s),e.onProgress&&this.forwardTestProgress(n,e.onProgress)},"onMessage"),onStall:d(()=>this.reconcileTestRun(s),"onStall"),createErrorResult:d(n=>({success:!1,errorMessage:n,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTest")}}async RunTestSuite(e){try{const t=this.buildRunTestSuiteMutation(),r=this.buildRunTestSuiteVariables(e);return await w.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTestSuite",operationLabel:"RunTestSuite",validateAck:d(s=>s?.success===!0,"validateAck"),isCompletionEvent:d(s=>this.isSuiteCompletionEvent(s,e.suiteId),"isCompletionEvent"),extractResult:d(s=>this.extractSuiteResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardTestProgress(s,e.onProgress):void 0,createErrorResult:d(s=>({success:!1,errorMessage:s,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTestSuite")}}async IsTestRunning(e){try{const t=u.gql`
1455
+ `,s=(await this._dataProvider.ExecuteGQL(t,{sourceID:e.SourceID,sampleSize:e.SampleSize}))?.GenerateSeedTaxonomy;if(!s)throw new Error("Invalid response from server");return this.parseResult(s)}catch(t){const r=t;return c.LogError("GraphQLClassifyClient.GenerateSeedTaxonomy failed",void 0,r),this.errorResult(r.message||"Unknown error occurred")}}parseResult(e){const t=D.SafeJSONParse(e.NodesJSON)??[];return{Success:e.Success,ErrorMessage:e.ErrorMessage,Method:e.Method,SampleSize:e.SampleSize,Nodes:t}}errorResult(e){return{Success:!1,ErrorMessage:e,SampleSize:0,Nodes:[]}}}class Qe{static{d(this,"GraphQLTestingClient")}constructor(e){this._dataProvider=e}async RunTest(e){try{const t=this.buildRunTestMutation(),r=this.buildRunTestVariables(e),s={};return await w.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTest",operationLabel:"RunTest",validateAck:d(n=>n?.success===!0,"validateAck"),isCompletionEvent:d(n=>this.isTestCompletionEvent(n,e.testId),"isCompletionEvent"),extractResult:d(n=>this.extractTestResult(n),"extractResult"),onMessage:d(n=>{this.captureTestRunId(n,s),e.onProgress&&this.forwardTestProgress(n,e.onProgress)},"onMessage"),onStall:d(()=>this.reconcileTestRun(s),"onStall"),createErrorResult:d(n=>({success:!1,errorMessage:n,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTest")}}async RunTestSuite(e){try{const t=this.buildRunTestSuiteMutation(),r=this.buildRunTestSuiteVariables(e);return await w.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTestSuite",operationLabel:"RunTestSuite",validateAck:d(s=>s?.success===!0,"validateAck"),isCompletionEvent:d(s=>this.isSuiteCompletionEvent(s,e.suiteId),"isCompletionEvent"),extractResult:d(s=>this.extractSuiteResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardTestProgress(s,e.onProgress):void 0,createErrorResult:d(s=>({success:!1,errorMessage:s,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTestSuite")}}async IsTestRunning(e){try{const t=u.gql`
1454
1456
  query IsTestRunning($testId: String!) {
1455
1457
  IsTestRunning(testId: $testId)
1456
1458
  }
@@ -1508,7 +1510,7 @@
1508
1510
  result
1509
1511
  }
1510
1512
  }
1511
- `}buildRunTestVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0;return{testId:e.testId,verbose:e.verbose,environment:e.environment,tags:t,variables:r,fireAndForget:!0}}buildRunTestSuiteVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0,s=e.selectedTestIds&&e.selectedTestIds.length>0?JSON.stringify(e.selectedTestIds):void 0;return{suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel,tags:t,variables:r,selectedTestIds:s,sequenceStart:e.sequenceStart,sequenceEnd:e.sequenceEnd,fireAndForget:!0}}isTestCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetComplete"&&r?.type==="complete"&&r?.testId===t}isSuiteCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetSuiteComplete"&&r?.type==="complete"&&r?.suiteId===t}captureTestRunId(e,t){if(e.resolver!=="RunTestResolver")return;const s=e.data?.testRunId;s&&(t.id=s)}async reconcileTestRun(e){if(!e.id)return"continue";const t=await this._dataProvider.RunView({EntityName:"MJ: Test Runs",ExtraFilter:`ID='${e.id}'`,ResultType:"entity_object",BypassCache:!0}),r=t.Success?t.Results?.[0]:void 0;if(!r||r.Status==="Pending"||r.Status==="Running")return"continue";const s=r.Status==="Passed";return{resolve:{success:s,errorMessage:s?void 0:`Test run ${r.Status}`,result:null}}}extractTestResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?D.SafeJSONParse(t.result):null}}extractSuiteResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?D.SafeJSONParse(t.result):null}}forwardTestProgress(e,t){if(e.resolver==="RunTestResolver"&&e.type==="TestExecutionProgress"&&e.status==="ok"){const s=e.data?.progress;s&&t(s)}}handleError(e,t){const r=e.message;return c.LogError(`${t} failed: ${r}`),{success:!1,errorMessage:r.includes("Failed to fetch")||r.includes("NetworkError")?"Lost connection to the server. The test may still be running. Please refresh to check the latest status.":r,result:null}}}class Pe{static{d(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=u.gql`
1513
+ `}buildRunTestVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0;return{testId:e.testId,verbose:e.verbose,environment:e.environment,tags:t,variables:r,fireAndForget:!0}}buildRunTestSuiteVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0,s=e.selectedTestIds&&e.selectedTestIds.length>0?JSON.stringify(e.selectedTestIds):void 0;return{suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel,tags:t,variables:r,selectedTestIds:s,sequenceStart:e.sequenceStart,sequenceEnd:e.sequenceEnd,fireAndForget:!0}}isTestCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetComplete"&&r?.type==="complete"&&r?.testId===t}isSuiteCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetSuiteComplete"&&r?.type==="complete"&&r?.suiteId===t}captureTestRunId(e,t){if(e.resolver!=="RunTestResolver")return;const s=e.data?.testRunId;s&&(t.id=s)}async reconcileTestRun(e){if(!e.id)return"continue";const t=await this._dataProvider.RunView({EntityName:"MJ: Test Runs",ExtraFilter:`ID='${e.id}'`,ResultType:"entity_object",BypassCache:!0}),r=t.Success?t.Results?.[0]:void 0;if(!r||r.Status==="Pending"||r.Status==="Running")return"continue";const s=r.Status==="Passed";return{resolve:{success:s,errorMessage:s?void 0:`Test run ${r.Status}`,result:null}}}extractTestResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?D.SafeJSONParse(t.result):null}}extractSuiteResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?D.SafeJSONParse(t.result):null}}forwardTestProgress(e,t){if(e.resolver==="RunTestResolver"&&e.type==="TestExecutionProgress"&&e.status==="ok"){const s=e.data?.progress;s&&t(s)}}handleError(e,t){const r=e.message;return c.LogError(`${t} failed: ${r}`),{success:!1,errorMessage:r.includes("Failed to fetch")||r.includes("NetworkError")?"Lost connection to the server. The test may still be running. Please refresh to check the latest status.":r,result:null}}}class qe{static{d(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=u.gql`
1512
1514
  query GetRegistryComponent(
1513
1515
  $registryName: String!,
1514
1516
  $namespace: String!,
@@ -1592,7 +1594,7 @@
1592
1594
  error
1593
1595
  }
1594
1596
  }
1595
- `,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return c.LogError(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}}class Le{static{d(this,"GraphQLVersionHistoryClient")}constructor(e){this._dataProvider=e}async CreateLabel(e){let t;try{e.OnProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(o=>{try{const i=JSON.parse(o);i.resolver==="VersionHistoryResolver"&&i.type==="CreateLabelProgress"&&i.status==="ok"&&i.data&&e.OnProgress(i.data)}catch{}}));const r=u.gql`
1597
+ `,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return c.LogError(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}}class Ge{static{d(this,"GraphQLVersionHistoryClient")}constructor(e){this._dataProvider=e}async CreateLabel(e){let t;try{e.OnProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(o=>{try{const i=JSON.parse(o);i.resolver==="VersionHistoryResolver"&&i.type==="CreateLabelProgress"&&i.status==="ok"&&i.data&&e.OnProgress(i.data)}catch{}}));const r=u.gql`
1596
1598
  mutation CreateVersionLabel($input: CreateVersionLabelInput!, $sessionId: String) {
1597
1599
  CreateVersionLabel(input: $input, sessionId: $sessionId) {
1598
1600
  Success
@@ -1608,7 +1610,7 @@
1608
1610
  }
1609
1611
  }
1610
1612
  }
1611
- `,s={input:this.buildInput(e),sessionId:this._dataProvider.sessionId},n=await this._dataProvider.ExecuteGQL(r,s);return this.processResult(n)}catch(r){const s=r instanceof Error?r.message:String(r);return c.LogError(`GraphQLVersionHistoryClient.CreateLabel error: ${s}`),{Success:!1,Error:s}}finally{t&&t.unsubscribe()}}buildInput(e){const t={Name:e.Name};return e.Description!=null&&(t.Description=e.Description),e.Scope!=null&&(t.Scope=e.Scope),e.EntityName!=null&&(t.EntityName=e.EntityName),e.ParentID!=null&&(t.ParentID=e.ParentID),e.ExternalSystemID!=null&&(t.ExternalSystemID=e.ExternalSystemID),e.IncludeDependencies!=null&&(t.IncludeDependencies=e.IncludeDependencies),e.MaxDepth!=null&&(t.MaxDepth=e.MaxDepth),e.ExcludeEntities!=null&&(t.ExcludeEntities=e.ExcludeEntities),e.RecordKeys&&e.RecordKeys.length>0&&(t.RecordKeys=e.RecordKeys.map(r=>({Key:r.Key,Value:r.Value}))),t}processResult(e){const t=e?.CreateVersionLabel;if(!t)return{Success:!1,Error:"Invalid response from server."};const r=Array.isArray(t.CaptureErrors)?t.CaptureErrors.map(s=>({EntityName:s.EntityName??"",RecordID:s.RecordID??"",ErrorMessage:s.ErrorMessage??""})):void 0;return{Success:t.Success,LabelID:t.LabelID,LabelName:t.LabelName,ItemsCaptured:t.ItemsCaptured,SyntheticSnapshotsCreated:t.SyntheticSnapshotsCreated,Error:t.Error,CaptureErrors:r}}}class Ae{static{d(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const s=u.gql`
1613
+ `,s={input:this.buildInput(e),sessionId:this._dataProvider.sessionId},n=await this._dataProvider.ExecuteGQL(r,s);return this.processResult(n)}catch(r){const s=r instanceof Error?r.message:String(r);return c.LogError(`GraphQLVersionHistoryClient.CreateLabel error: ${s}`),{Success:!1,Error:s}}finally{t&&t.unsubscribe()}}buildInput(e){const t={Name:e.Name};return e.Description!=null&&(t.Description=e.Description),e.Scope!=null&&(t.Scope=e.Scope),e.EntityName!=null&&(t.EntityName=e.EntityName),e.ParentID!=null&&(t.ParentID=e.ParentID),e.ExternalSystemID!=null&&(t.ExternalSystemID=e.ExternalSystemID),e.IncludeDependencies!=null&&(t.IncludeDependencies=e.IncludeDependencies),e.MaxDepth!=null&&(t.MaxDepth=e.MaxDepth),e.ExcludeEntities!=null&&(t.ExcludeEntities=e.ExcludeEntities),e.RecordKeys&&e.RecordKeys.length>0&&(t.RecordKeys=e.RecordKeys.map(r=>({Key:r.Key,Value:r.Value}))),t}processResult(e){const t=e?.CreateVersionLabel;if(!t)return{Success:!1,Error:"Invalid response from server."};const r=Array.isArray(t.CaptureErrors)?t.CaptureErrors.map(s=>({EntityName:s.EntityName??"",RecordID:s.RecordID??"",ErrorMessage:s.ErrorMessage??""})):void 0;return{Success:t.Success,LabelID:t.LabelID,LabelName:t.LabelName,ItemsCaptured:t.ItemsCaptured,SyntheticSnapshotsCreated:t.SyntheticSnapshotsCreated,Error:t.Error,CaptureErrors:r}}}class Ue{static{d(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const s=u.gql`
1612
1614
  query ListStorageObjects($input: ListStorageObjectsInput!) {
1613
1615
  ListStorageObjects(input: $input) {
1614
1616
  objects {
@@ -1692,7 +1694,7 @@
1692
1694
  failedAccounts
1693
1695
  }
1694
1696
  }
1695
- `,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:r?.maxResultsPerAccount,FileTypes:r?.fileTypes,SearchContent:r?.searchContent}},o=await this._dataProvider.ExecuteGQL(s,n);if(!o?.SearchAcrossAccounts)throw new Error("Invalid response from server");const i=o.SearchAcrossAccounts;return{accountResults:i.accountResults.map(a=>({accountId:a.accountID,accountName:a.accountName,success:a.success,errorMessage:a.errorMessage,results:a.results.map(y=>({path:y.path,name:y.name,size:y.size,contentType:y.contentType,lastModified:new Date(y.lastModified),relevance:y.relevance,excerpt:y.excerpt,matchInFilename:y.matchInFilename,objectId:y.objectId})),totalMatches:a.totalMatches,hasMore:a.hasMore,nextPageToken:a.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(s){const n=s;return c.LogError(`Error searching across accounts: ${n}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}class Ne{static{d(this,"GraphQLSearchClient")}constructor(e){this._dataProvider=e}async ExecuteSearch(e){try{const t=this.buildSearchKnowledgeMutation(),r=this.prepareSearchVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processSearchKnowledgeResult(s)}catch(t){return this.handleSearchError(t)}}async PreviewSearch(e,t){try{const r=this.buildPreviewSearchMutation(),s=this.preparePreviewVariables(e,t),n=await this._dataProvider.ExecuteGQL(r,s);return this.processPreviewSearchResult(n)}catch(r){return this.handleSearchError(r)}}buildSearchKnowledgeMutation(){return u.gql`
1697
+ `,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:r?.maxResultsPerAccount,FileTypes:r?.fileTypes,SearchContent:r?.searchContent}},o=await this._dataProvider.ExecuteGQL(s,n);if(!o?.SearchAcrossAccounts)throw new Error("Invalid response from server");const i=o.SearchAcrossAccounts;return{accountResults:i.accountResults.map(a=>({accountId:a.accountID,accountName:a.accountName,success:a.success,errorMessage:a.errorMessage,results:a.results.map(m=>({path:m.path,name:m.name,size:m.size,contentType:m.contentType,lastModified:new Date(m.lastModified),relevance:m.relevance,excerpt:m.excerpt,matchInFilename:m.matchInFilename,objectId:m.objectId})),totalMatches:a.totalMatches,hasMore:a.hasMore,nextPageToken:a.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(s){const n=s;return c.LogError(`Error searching across accounts: ${n}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}class Ve{static{d(this,"GraphQLSearchClient")}constructor(e){this._dataProvider=e}async ExecuteSearch(e){try{const t=this.buildSearchKnowledgeMutation(),r=this.prepareSearchVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processSearchKnowledgeResult(s)}catch(t){return this.handleSearchError(t)}}async PreviewSearch(e,t){try{const r=this.buildPreviewSearchMutation(),s=this.preparePreviewVariables(e,t),n=await this._dataProvider.ExecuteGQL(r,s);return this.processPreviewSearchResult(n)}catch(r){return this.handleSearchError(r)}}buildSearchKnowledgeMutation(){return u.gql`
1696
1698
  mutation SearchKnowledge($query: String!, $maxResults: Float, $filters: SearchFiltersInput, $minScore: Float, $scopeIDs: [ID!], $searchContext: SearchContextInput) {
1697
1699
  SearchKnowledge(query: $query, maxResults: $maxResults, filters: $filters, minScore: $minScore, scopeIDs: $scopeIDs, searchContext: $searchContext) {
1698
1700
  Success
@@ -1831,7 +1833,7 @@
1831
1833
  ElapsedMs
1832
1834
  ErrorMessage
1833
1835
  }
1834
- }`;n=this._dataProvider.subscribe(a,{streamID:i.StreamID}).subscribe({next:d(y=>{const l=y?.SearchStreamEvents;l&&(t.next(l),l.Phase==="final"?(t.complete(),n?.unsubscribe()):l.Phase==="error"&&(t.error(new Error(l.ErrorMessage??"Stream error")),n?.unsubscribe()))},"next"),error:d(y=>t.error(y),"error")})}catch(o){t.error(o)}})(),()=>{n?.unsubscribe()}})}prepareFilters(e){const t={};return e.EntityNames!==void 0&&e.EntityNames.length>0&&(t.EntityNames=e.EntityNames),e.SourceTypes!==void 0&&e.SourceTypes.length>0&&(t.SourceTypes=e.SourceTypes),e.Tags!==void 0&&e.Tags.length>0&&(t.Tags=e.Tags),t}preparePreviewVariables(e,t){const r={query:e};return t!==void 0&&(r.maxResults=t),r}processSearchKnowledgeResult(e){if(!e?.SearchKnowledge)throw new Error("Invalid response from server");const t=e.SearchKnowledge;return this.mapSearchResponse(t)}processPreviewSearchResult(e){if(!e?.PreviewSearch)throw new Error("Invalid response from server");const t=e.PreviewSearch;return this.mapSearchResponse(t)}mapSearchResponse(e){return{Success:e.Success,Results:(e.Results||[]).map(t=>this.mapResultItem(t)),TotalCount:e.TotalCount,ElapsedMs:e.ElapsedMs,SourceCounts:this.mapSourceCounts(e.SourceCounts),Providers:(e.Providers||[]).map(t=>({ID:t.ID,Name:t.Name,DisplayName:t.DisplayName,Icon:t.Icon,SourceType:t.SourceType,Priority:t.Priority})),ErrorMessage:e.ErrorMessage}}mapResultItem(e){return{ID:e.ID,EntityName:e.EntityName,RecordID:e.RecordID,SourceType:e.SourceType,ResultType:e.ResultType,Title:e.Title,Snippet:e.Snippet,Score:e.Score,ScoreBreakdown:this.mapScoreBreakdown(e.ScoreBreakdown),Tags:e.Tags||[],EntityIcon:e.EntityIcon,RecordName:e.RecordName,MatchedAt:e.MatchedAt,RawMetadata:e.RawMetadata,ProviderId:e.ProviderId,ProviderLabel:e.ProviderLabel,ProviderIcon:e.ProviderIcon}}mapScoreBreakdown(e){if(!e)return{};const t={};return e.Vector!==void 0&&(t.Vector=e.Vector),e.FullText!==void 0&&(t.FullText=e.FullText),e.Entity!==void 0&&(t.Entity=e.Entity),e.Storage!==void 0&&(t.Storage=e.Storage),t}mapSourceCounts(e){return e?{Vector:e.Vector??0,FullText:e.FullText??0,Entity:e.Entity??0,Storage:e.Storage??0}:{Vector:0,FullText:0,Entity:0,Storage:0}}handleSearchError(e){const t=e;return c.LogError(`Error executing search: ${t}`),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,SourceCounts:{Vector:0,FullText:0,Entity:0,Storage:0},Providers:[],ErrorMessage:`Error: ${t.message}`}}}class Me{static{d(this,"GraphQLIntegrationClient")}constructor(e){this._dataProvider=e}async DiscoverObjects(e){try{const t=u.gql`
1836
+ }`;n=this._dataProvider.subscribe(a,{streamID:i.StreamID}).subscribe({next:d(m=>{const g=m?.SearchStreamEvents;g&&(t.next(g),g.Phase==="final"?(t.complete(),n?.unsubscribe()):g.Phase==="error"&&(t.error(new Error(g.ErrorMessage??"Stream error")),n?.unsubscribe()))},"next"),error:d(m=>t.error(m),"error")})}catch(o){t.error(o)}})(),()=>{n?.unsubscribe()}})}prepareFilters(e){const t={};return e.EntityNames!==void 0&&e.EntityNames.length>0&&(t.EntityNames=e.EntityNames),e.SourceTypes!==void 0&&e.SourceTypes.length>0&&(t.SourceTypes=e.SourceTypes),e.Tags!==void 0&&e.Tags.length>0&&(t.Tags=e.Tags),t}preparePreviewVariables(e,t){const r={query:e};return t!==void 0&&(r.maxResults=t),r}processSearchKnowledgeResult(e){if(!e?.SearchKnowledge)throw new Error("Invalid response from server");const t=e.SearchKnowledge;return this.mapSearchResponse(t)}processPreviewSearchResult(e){if(!e?.PreviewSearch)throw new Error("Invalid response from server");const t=e.PreviewSearch;return this.mapSearchResponse(t)}mapSearchResponse(e){return{Success:e.Success,Results:(e.Results||[]).map(t=>this.mapResultItem(t)),TotalCount:e.TotalCount,ElapsedMs:e.ElapsedMs,SourceCounts:this.mapSourceCounts(e.SourceCounts),Providers:(e.Providers||[]).map(t=>({ID:t.ID,Name:t.Name,DisplayName:t.DisplayName,Icon:t.Icon,SourceType:t.SourceType,Priority:t.Priority})),ErrorMessage:e.ErrorMessage}}mapResultItem(e){return{ID:e.ID,EntityName:e.EntityName,RecordID:e.RecordID,SourceType:e.SourceType,ResultType:e.ResultType,Title:e.Title,Snippet:e.Snippet,Score:e.Score,ScoreBreakdown:this.mapScoreBreakdown(e.ScoreBreakdown),Tags:e.Tags||[],EntityIcon:e.EntityIcon,RecordName:e.RecordName,MatchedAt:e.MatchedAt,RawMetadata:e.RawMetadata,ProviderId:e.ProviderId,ProviderLabel:e.ProviderLabel,ProviderIcon:e.ProviderIcon}}mapScoreBreakdown(e){if(!e)return{};const t={};return e.Vector!==void 0&&(t.Vector=e.Vector),e.FullText!==void 0&&(t.FullText=e.FullText),e.Entity!==void 0&&(t.Entity=e.Entity),e.Storage!==void 0&&(t.Storage=e.Storage),t}mapSourceCounts(e){return e?{Vector:e.Vector??0,FullText:e.FullText??0,Entity:e.Entity??0,Storage:e.Storage??0}:{Vector:0,FullText:0,Entity:0,Storage:0}}handleSearchError(e){const t=e;return c.LogError(`Error executing search: ${t}`),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,SourceCounts:{Vector:0,FullText:0,Entity:0,Storage:0},Providers:[],ErrorMessage:`Error: ${t.message}`}}}class _e{static{d(this,"GraphQLIntegrationClient")}constructor(e){this._dataProvider=e}async DiscoverObjects(e){try{const t=u.gql`
1835
1837
  query IntegrationDiscoverObjects($companyIntegrationID: String!) {
1836
1838
  IntegrationDiscoverObjects(companyIntegrationID: $companyIntegrationID) {
1837
1839
  Success
@@ -1982,7 +1984,7 @@
1982
1984
  PipelineSteps { Name Status DurationMs Message }
1983
1985
  GitCommitSuccess APIRestarted
1984
1986
  }
1985
- }`,y={Connectors:e.map(h=>({CompanyIntegrationID:h.CompanyIntegrationID,SourceObjects:h.SourceObjects.map(f=>({SourceObjectID:f.SourceObjectID??null,SourceObjectName:f.SourceObjectName??null,Fields:f.Fields??null}))})),StartSync:t,FullSync:r,SyncScope:s},l=(await this._dataProvider.ExecuteGQL(a,{input:y,platform:n,skipGitCommit:o,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(h=>h.Warnings??[])}:{Success:!1,Message:"No response"}}catch(a){return{Success:!1,Message:a.message}}}async ApplyAll(e,t,r="sqlserver",s=!1,n=!1){try{const o=u.gql`mutation IntegrationApplyAll(
1987
+ }`,m={Connectors:e.map(h=>({CompanyIntegrationID:h.CompanyIntegrationID,SourceObjects:h.SourceObjects.map(f=>({SourceObjectID:f.SourceObjectID??null,SourceObjectName:f.SourceObjectName??null,Fields:f.Fields??null}))})),StartSync:t,FullSync:r,SyncScope:s},g=(await this._dataProvider.ExecuteGQL(a,{input:m,platform:n,skipGitCommit:o,skipRestart:i}))?.IntegrationApplyAllBatch;return g?{Success:g.Success,Message:g.Message,Steps:g.PipelineSteps,GitCommitSuccess:g.GitCommitSuccess,APIRestarted:g.APIRestarted,EntityMapsCreated:g.ConnectorResults?.[0]?.EntityMapsCreated,SyncRunID:g.ConnectorResults?.[0]?.SyncRunID,Warnings:g.ConnectorResults?.flatMap(h=>h.Warnings??[])}:{Success:!1,Message:"No response"}}catch(a){return{Success:!1,Message:a.message}}}async ApplyAll(e,t,r="sqlserver",s=!1,n=!1){try{const o=u.gql`mutation IntegrationApplyAll(
1986
1988
  $input: ApplyAllInput!, $platform: String!, $skipGitCommit: Boolean!, $skipRestart: Boolean!
1987
1989
  ) {
1988
1990
  IntegrationApplyAll(input: $input, platform: $platform, skipGitCommit: $skipGitCommit, skipRestart: $skipRestart) {
@@ -2024,5 +2026,5 @@
2024
2026
  IntegrationGetConnectorCapabilities(companyIntegrationID: $companyIntegrationID) {
2025
2027
  Success Message SupportsGet SupportsCreate SupportsUpdate SupportsDelete SupportsSearch
2026
2028
  }
2027
- }`;return(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationGetConnectorCapabilities??{Success:!1,Message:"No response"}}catch(t){return{Success:!1,Message:t.message}}}handleError(e,t){const r=e;return c.LogError(`Error in integration discovery: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Data:t}}}Object.defineProperty(exports,"gql",{enumerable:!0,get:d(function(){return u.gql},"get")}),exports.ActionItemInput=ue,exports.ActionItemOutput=de,exports.BrowserIndexedDBStorageProvider=O,exports.BrowserStorageProviderBase=V,exports.FieldMapper=P,exports.FireAndForgetHelper=w,exports.GetDataOutput=ye,exports.GraphQLAIClient=U,exports.GraphQLActionClient=he,exports.GraphQLClassifyClient=we,exports.GraphQLClusterClient=ve,exports.GraphQLComponentRegistryClient=Pe,exports.GraphQLDataProvider=I,exports.GraphQLEncryptionClient=De,exports.GraphQLFileStorageClient=Ae,exports.GraphQLIntegrationClient=Me,exports.GraphQLListsClient=Ie,exports.GraphQLLiveKitClient=Ce,exports.GraphQLProviderConfigData=se,exports.GraphQLSearchClient=Ne,exports.GraphQLSystemUserClient=ge,exports.GraphQLTestingClient=$e,exports.GraphQLTransactionGroup=G,exports.GraphQLVersionHistoryClient=Le,exports.PACKAGE_VERSION=M,exports.RoleInput=ae,exports.RolesAndUsersInput=ce,exports.SimpleRemoteEntity=Se,exports.SimpleRemoteEntityField=pe,exports.SimpleRemoteEntityOutput=me,exports.SyncDataAction=k,exports.SyncDataResult=le,exports.SyncRolesAndUsersResult=oe,exports.UserInput=ie,exports.setupGraphQLClient=ne;
2029
+ }`;return(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationGetConnectorCapabilities??{Success:!1,Message:"No response"}}catch(t){return{Success:!1,Message:t.message}}}handleError(e,t){const r=e;return c.LogError(`Error in integration discovery: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Data:t}}}Object.defineProperty(exports,"gql",{enumerable:!0,get:d(function(){return u.gql},"get")}),exports.ActionItemInput=fe,exports.ActionItemOutput=Re,exports.BrowserIndexedDBStorageProvider=B,exports.BrowserStorageProviderBase=k,exports.FieldMapper=P,exports.FireAndForgetHelper=w,exports.GetDataOutput=ve,exports.GraphQLAIClient=O,exports.GraphQLActionClient=Pe,exports.GraphQLClassifyClient=Fe,exports.GraphQLClusterClient=Te,exports.GraphQLComponentRegistryClient=qe,exports.GraphQLDataProvider=I,exports.GraphQLEncryptionClient=be,exports.GraphQLFileStorageClient=Ue,exports.GraphQLIntegrationClient=_e,exports.GraphQLListsClient=Le,exports.GraphQLLiveKitClient=xe,exports.GraphQLProviderConfigData=ye,exports.GraphQLSearchClient=Ve,exports.GraphQLSystemUserClient=De,exports.GraphQLTestingClient=Qe,exports.GraphQLTransactionGroup=_,exports.GraphQLVersionHistoryClient=Ge,exports.PACKAGE_VERSION=M,exports.RoleInput=pe,exports.RolesAndUsersInput=Ie,exports.SafeGraphQLError=x,exports.SanitizeGraphQLError=Q,exports.SimpleRemoteEntity=we,exports.SimpleRemoteEntityField=$e,exports.SimpleRemoteEntityOutput=Ce,exports.SyncDataAction=J,exports.SyncDataResult=Ee,exports.SyncRolesAndUsersResult=Se,exports.ToSafeGraphQLError=j,exports.UserInput=he,exports.setupGraphQLClient=me;
2028
2030
  //# sourceMappingURL=index.cjs.map