@memberjunction/graphql-dataprovider 5.5.0 → 5.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -183,7 +183,7 @@
183
183
  error
184
184
  }
185
185
  }
186
- `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this._dataProvider.ExecuteGQL(t,s);if(!n?.EmbedText)throw new Error("Invalid response from server");const o=n.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?o.embeddings:o.embeddings[0],modelName:o.modelName,vectorDimensions:o.vectorDimensions,error:o.error}}catch(t){const r=t;return u.LogError(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}}const v="default";class T{static{p(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||v;let r=this._storage.get(t);return r||(r=new Map,this._storage.set(t,r)),r}async GetItem(e,t){return this.getCategoryMap(t||v).get(e)??null}async SetItem(e,t,r){this.getCategoryMap(r||v).set(e,t)}async Remove(e,t){this.getCategoryMap(t||v).delete(e)}async ClearCategory(e){const t=e||v;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||v);return t?Array.from(t.keys()):[]}}const k="MJ_Metadata",K=3,M=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"],F="Metadata_KVPairs";class U extends T{static{p(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=_.openDB(k,K,{upgrade(e){try{e.objectStoreNames.contains(F)&&e.deleteObjectStore(F);for(const t of M)e.objectStoreNames.contains(t)||e.createObjectStore(t)}catch(t){u.LogErrorEx({error:t,message:t?.message})}}}),this.dbPromise.then(()=>{this._dbReady=!0}).catch(e=>{u.LogErrorEx({error:e,message:"IndexedDB initialization failed: "+e?.message})})}isKnownCategory(e){const t=`mj:${e}`;return M.includes(t)}getStoreName(e){const t=e||v;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||v;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){u.LogErrorEx({error:s,message:s?.message}),await super.SetItem(e,t,r)}}async GetItem(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t);return await r.transaction(s).objectStore(s).get(n)??null}catch(r){return u.LogErrorEx({error:r,message:r?.message}),await super.GetItem(e,t)}}async Remove(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t),o=r.transaction(s,"readwrite");await o.objectStore(s).delete(n),await o.done}catch(r){u.LogErrorEx({error:r,message:r?.message}),await super.Remove(e,t)}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||v,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 c of a)typeof c=="string"&&c.startsWith(n)&&await i.delete(c);await o.done}}catch(t){u.LogErrorEx({error:t,message:t?.message}),await super.ClearCategory(e)}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||v,s=this.getStoreName(e),i=await t.transaction(s,"readonly").objectStore(s).getAllKeys();if(this.isKnownCategory(r))return i.map(c=>String(c));const a=`[${r}]:`;return i.map(c=>String(c)).filter(c=>c.startsWith(a)).map(c=>c.slice(a.length))}catch(t){return u.LogErrorEx({error:t,message:t?.message}),await super.GetCategoryKeys(e)}}}class B extends u.ProviderConfigDataBase{static{p(this,"GraphQLProviderConfigData")}get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get MJAPIKey(){return this.Data.MJAPIKey}set MJAPIKey(e){this.Data.MJAPIKey=e}get UserAPIKey(){return this.Data.UserAPIKey}set UserAPIKey(e){this.Data.UserAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}constructor(e,t,r,s,n,o,i,a,c){super({Token:e,URL:t,WSURL:r,MJAPIKey:a,UserAPIKey:c,RefreshTokenFunction:s},n,o,i)}}class f extends u.ProviderBase{static{p(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._innerCurrentUserQueryString=`CurrentUser {
186
+ `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this._dataProvider.ExecuteGQL(t,s);if(!n?.EmbedText)throw new Error("Invalid response from server");const o=n.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?o.embeddings:o.embeddings[0],modelName:o.modelName,vectorDimensions:o.vectorDimensions,error:o.error}}catch(t){const r=t;return u.LogError(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}}const C="default";class T{static{p(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||C;let r=this._storage.get(t);return r||(r=new Map,this._storage.set(t,r)),r}async GetItem(e,t){return this.getCategoryMap(t||C).get(e)??null}async SetItem(e,t,r){this.getCategoryMap(r||C).set(e,t)}async Remove(e,t){this.getCategoryMap(t||C).delete(e)}async ClearCategory(e){const t=e||C;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||C);return t?Array.from(t.keys()):[]}}const k="MJ_Metadata",B=3,M=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"],F="Metadata_KVPairs";class Q extends T{static{p(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=_.openDB(k,B,{upgrade(e){try{e.objectStoreNames.contains(F)&&e.deleteObjectStore(F);for(const t of M)e.objectStoreNames.contains(t)||e.createObjectStore(t)}catch(t){u.LogErrorEx({error:t,message:t?.message})}}}),this.dbPromise.then(()=>{this._dbReady=!0}).catch(e=>{u.LogErrorEx({error:e,message:"IndexedDB initialization failed: "+e?.message})})}isKnownCategory(e){const t=`mj:${e}`;return M.includes(t)}getStoreName(e){const t=e||C;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||C;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){u.LogErrorEx({error:s,message:s?.message}),await super.SetItem(e,t,r)}}async GetItem(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t);return await r.transaction(s).objectStore(s).get(n)??null}catch(r){return u.LogErrorEx({error:r,message:r?.message}),await super.GetItem(e,t)}}async Remove(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t),o=r.transaction(s,"readwrite");await o.objectStore(s).delete(n),await o.done}catch(r){u.LogErrorEx({error:r,message:r?.message}),await super.Remove(e,t)}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||C,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 c of a)typeof c=="string"&&c.startsWith(n)&&await i.delete(c);await o.done}}catch(t){u.LogErrorEx({error:t,message:t?.message}),await super.ClearCategory(e)}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||C,s=this.getStoreName(e),i=await t.transaction(s,"readonly").objectStore(s).getAllKeys();if(this.isKnownCategory(r))return i.map(c=>String(c));const a=`[${r}]:`;return i.map(c=>String(c)).filter(c=>c.startsWith(a)).map(c=>c.slice(a.length))}catch(t){return u.LogErrorEx({error:t,message:t?.message}),await super.GetCategoryKeys(e)}}}class K extends u.ProviderConfigDataBase{static{p(this,"GraphQLProviderConfigData")}get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get MJAPIKey(){return this.Data.MJAPIKey}set MJAPIKey(e){this.Data.MJAPIKey=e}get UserAPIKey(){return this.Data.UserAPIKey}set UserAPIKey(e){this.Data.UserAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}constructor(e,t,r,s,n,o,i,a,c){super({Token:e,URL:t,WSURL:r,MJAPIKey:a,UserAPIKey:c,RefreshTokenFunction:s},n,o,i)}}class f extends u.ProviderBase{static{p(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._innerCurrentUserQueryString=`CurrentUser {
187
187
  ${this.userInfoString()}
188
188
  MJUserRoles_UserIDArray {
189
189
  ${this.userRoleInfoString()}
@@ -270,7 +270,7 @@
270
270
  Success
271
271
  ErrorMessage${R}
272
272
  }
273
- }`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:o,queryName:r,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const g=await this.ExecuteGQL(l,{input:n});if(g&&g[r]){const m=g[r].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:o,aggregateResultCount:m?.length||0,aggregateResults:m,aggregateExecutionTime:g[r].AggregateExecutionTime});const I=g[r].Results;if(I&&I.length>0){const C=a.Fields.filter(D=>D.CodeName!==D.Name&&D.CodeName!==void 0);I.forEach(D=>{this.ConvertBackToMJFields(D),C.forEach(N=>{D[N.Name]=D[N.CodeName]})})}return g[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw u.LogError(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],n=[];for(const d of e){let S="",R="";const l={};let g=null,m=null;if(d.ViewEntity)m=d.ViewEntity,g=m.Get("Entity");else{const{entityName:D,v:N}=await this.getEntityNameAndUserView(d,t);m=N,g=D}const I=this.Entities.find(D=>D.Name===g);if(!I)throw new Error(`Entity ${g} not found in metadata`);s.push(I);let E=!1;const C=u.getGraphQLTypeNameBase(I);d.ViewID?(S=`Run${C}ViewByID`,R="RunViewByIDInput",l.ViewID=d.ViewID):d.ViewName?(S=`Run${C}ViewByName`,R="RunViewByNameInput",l.ViewName=d.ViewName):(E=!0,S=`Run${C}DynamicView`,R="RunDynamicViewInput",l.EntityName=d.EntityName),l.ExtraFilter=d.ExtraFilter||"",l.OrderBy=d.OrderBy||"",l.UserSearchString=d.UserSearchString||"",l.Fields=d.Fields,l.IgnoreMaxRows=d.IgnoreMaxRows||!1,d.MaxRows!==void 0&&(l.MaxRows=d.MaxRows),d.StartRow!==void 0&&(l.StartRow=d.StartRow),l.ForceAuditLog=d.ForceAuditLog||!1,l.ResultType=d.ResultType||"simple",d.AuditLogDescription&&d.AuditLogDescription.length>0&&(l.AuditLogDescription=d.AuditLogDescription),E||(l.ExcludeUserViewRunID=d.ExcludeUserViewRunID||"",l.ExcludeDataFromAllPriorViewRuns=d.ExcludeDataFromAllPriorViewRuns||!1,l.OverrideExcludeFilter=d.OverrideExcludeFilter||"",l.SaveViewResults=d.SaveViewResults||!1),d.Aggregates&&d.Aggregates.length>0&&(l.Aggregates=d.Aggregates.map(D=>({expression:D.expression,alias:D.alias}))),r.push(l),n.push(...this.getViewRunTimeFieldList(I,m,d,E))}const i=e.some(d=>d.Aggregates&&d.Aggregates.length>0)?`
273
+ }`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:o,queryName:r,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const g=await this.ExecuteGQL(l,{input:n});if(g&&g[r]){const m=g[r].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:o,aggregateResultCount:m?.length||0,aggregateResults:m,aggregateExecutionTime:g[r].AggregateExecutionTime});const I=g[r].Results;if(I&&I.length>0){const v=a.Fields.filter(D=>D.CodeName!==D.Name&&D.CodeName!==void 0);I.forEach(D=>{this.ConvertBackToMJFields(D),v.forEach(N=>{D[N.Name]=D[N.CodeName]})})}return g[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw u.LogError(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],n=[];for(const d of e){let S="",R="";const l={};let g=null,m=null;if(d.ViewEntity)m=d.ViewEntity,g=m.Get("Entity");else{const{entityName:D,v:N}=await this.getEntityNameAndUserView(d,t);m=N,g=D}const I=this.Entities.find(D=>D.Name===g);if(!I)throw new Error(`Entity ${g} not found in metadata`);s.push(I);let E=!1;const v=u.getGraphQLTypeNameBase(I);d.ViewID?(S=`Run${v}ViewByID`,R="RunViewByIDInput",l.ViewID=d.ViewID):d.ViewName?(S=`Run${v}ViewByName`,R="RunViewByNameInput",l.ViewName=d.ViewName):(E=!0,S=`Run${v}DynamicView`,R="RunDynamicViewInput",l.EntityName=d.EntityName),l.ExtraFilter=d.ExtraFilter||"",l.OrderBy=d.OrderBy||"",l.UserSearchString=d.UserSearchString||"",l.Fields=d.Fields,l.IgnoreMaxRows=d.IgnoreMaxRows||!1,d.MaxRows!==void 0&&(l.MaxRows=d.MaxRows),d.StartRow!==void 0&&(l.StartRow=d.StartRow),l.ForceAuditLog=d.ForceAuditLog||!1,l.ResultType=d.ResultType||"simple",d.AuditLogDescription&&d.AuditLogDescription.length>0&&(l.AuditLogDescription=d.AuditLogDescription),E||(l.ExcludeUserViewRunID=d.ExcludeUserViewRunID||"",l.ExcludeDataFromAllPriorViewRuns=d.ExcludeDataFromAllPriorViewRuns||!1,l.OverrideExcludeFilter=d.OverrideExcludeFilter||"",l.SaveViewResults=d.SaveViewResults||!1),d.Aggregates&&d.Aggregates.length>0&&(l.Aggregates=d.Aggregates.map(D=>({expression:D.expression,alias:D.alias}))),r.push(l),n.push(...this.getViewRunTimeFieldList(I,m,d,E))}const i=e.some(d=>d.Aggregates&&d.Aggregates.length>0)?`
274
274
  AggregateResults {
275
275
  alias
276
276
  expression
@@ -404,7 +404,7 @@
404
404
  `,l=y.gql`mutation ${S} (${a}, $options___: DeleteOptionsInput!) {
405
405
  ${R}
406
406
  }
407
- `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,"Delete",R,n,{mutationName:S,mutationInputTypes:o},(g,m)=>{if(s.EndedAt=new Date,m&&g){let I=!0;for(const E of e.PrimaryKey.KeyValuePairs)E.Value!==g[E.FieldName]&&(I=!1);I?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const g=await this.ExecuteGQL(l,n);if(g&&g[S]){const m=g[S];for(let I of e.PrimaryKey.KeyValuePairs){let E=m[I.FieldName],C=I.Value;if(typeof C=="number"&&(C=C.toString()),typeof E=="number"&&(E=E.toString()),C!==E)throw new Error(`Primary key value mismatch in server Delete response. Field: ${I.FieldName}, Original: ${C}, Returned: ${E}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(n){return s.EndedAt=new Date,s.Success=!1,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,u.LogError(n),!1}}async GetDatasetByName(e,t){const r=y.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
407
+ `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,"Delete",R,n,{mutationName:S,mutationInputTypes:o},(g,m)=>{if(s.EndedAt=new Date,m&&g){let I=!0;for(const E of e.PrimaryKey.KeyValuePairs)E.Value!==g[E.FieldName]&&(I=!1);I?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const g=await this.ExecuteGQL(l,n);if(g&&g[S]){const m=g[S];for(let I of e.PrimaryKey.KeyValuePairs){let E=m[I.FieldName],v=I.Value;if(typeof v=="number"&&(v=v.toString()),typeof E=="number"&&(E=E.toString()),v!==E)throw new Error(`Primary key value mismatch in server Delete response. Field: ${I.FieldName}, Original: ${v}, Returned: ${E}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(n){return s.EndedAt=new Date,s.Success=!1,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,u.LogError(n),!1}}async GetDatasetByName(e,t){const r=y.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
408
408
  GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
409
409
  DatasetID
410
410
  DatasetName
@@ -464,7 +464,7 @@
464
464
  }
465
465
  }`,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 u.LogError(t),t}}static async ExecuteGQL(e,t,r=!0){return f.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 u.LogError("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw u.LogError(s),s}}async RefreshToken(){const e=f.Instance&&f.Instance._configData===this._configData;if(e&&f.Instance._refreshPromise)return f.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(f.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&f.Instance&&(f.Instance._refreshPromise=null)}}async performTokenRefresh(){if(this._configData.Data.RefreshTokenFunction){const e=await this._configData.Data.RefreshTokenFunction();if(e){this._configData.Token=e;const t=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey,this._configData.UserAPIKey);this._client=t,f.Instance&&f.Instance._configData===this._configData&&(f.Instance._client=t)}else throw new Error("Refresh token function returned null or undefined token")}else throw new Error("No refresh token function provided")}static async RefreshToken(){return f.Instance.RefreshToken()}CreateNewGraphQLClient(e,t,r,s,n){const o={"x-session-id":r};return t&&(o.authorization="Bearer "+t),s&&(o["x-mj-api-key"]=s),n&&(o["x-api-key"]=n),new y.GraphQLClient(e,{headers:o})}userInfoString(){return this.infoString(new u.UserInfo(null,null))}userRoleInfoString(){return this.infoString(new u.UserRoleInfo(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
466
466
  `:s.startsWith("_")||(t+=s+`
467
- `);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new U:this._localStorageProvider=new u.InMemoryLocalStorageProvider),this._localStorageProvider}get Metadata(){return this}getOrCreateWSClient(){const e=Date.now();return this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&this._activeSubscriptionCount===0&&this.disposeWSClient(),this._wsClient||(this._wsClient=G.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token},keepAlive:3e4,retryAttempts:3,shouldRetry:p(()=>!0,"shouldRetry")}),this._wsClientCreatedAt=e,this._subscriptionCleanupTimer||(this._subscriptionCleanupTimer=setInterval(()=>{this.cleanupStaleSubscriptions()},this.SUBSCRIPTION_CLEANUP_INTERVAL_MS))),this._wsClient}disposeWSClient(){if(this._wsClient){try{this._wsClient.dispose()}catch(e){console.error("[GraphQLDataProvider] Error disposing WebSocket client:",e)}this._wsClient=null,this._wsClientCreatedAt=null}}completeAllSubjects(){this._pushStatusSubjects.forEach((e,t)=>{try{e.subject.complete(),e.subscription.unsubscribe()}catch(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 $.Observable(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=s.subscribe({query:e,variables:t},{next:p(o=>{r.next(o.data)},"next"),error:p(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(c){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",c),r.error(c)}}else r.error(o)},"error"),complete:p(()=>{r.complete()},"complete")});return()=>{this._activeSubscriptionCount--,n()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),r=this._pushStatusSubjects.get(e);if(r)return r.lastRequestedAt=t,new $.Observable(a=>{r.activeSubscribers++;const c=r.subject.subscribe(a);return()=>{const d=this._pushStatusSubjects.get(e);d&&d.activeSubscribers>0&&d.activeSubscribers--,c.unsubscribe()}});const s=y.gql`subscription StatusUpdates($sessionId: String!) {
467
+ `);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new Q:this._localStorageProvider=new u.InMemoryLocalStorageProvider),this._localStorageProvider}get Metadata(){return this}getOrCreateWSClient(){const e=Date.now();return this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&this._activeSubscriptionCount===0&&this.disposeWSClient(),this._wsClient||(this._wsClient=G.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token},keepAlive:3e4,retryAttempts:3,shouldRetry:p(()=>!0,"shouldRetry")}),this._wsClientCreatedAt=e,this._subscriptionCleanupTimer||(this._subscriptionCleanupTimer=setInterval(()=>{this.cleanupStaleSubscriptions()},this.SUBSCRIPTION_CLEANUP_INTERVAL_MS))),this._wsClient}disposeWSClient(){if(this._wsClient){try{this._wsClient.dispose()}catch(e){console.error("[GraphQLDataProvider] Error disposing WebSocket client:",e)}this._wsClient=null,this._wsClientCreatedAt=null}}completeAllSubjects(){this._pushStatusSubjects.forEach((e,t)=>{try{e.subject.complete(),e.subscription.unsubscribe()}catch(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 $.Observable(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=s.subscribe({query:e,variables:t},{next:p(o=>{r.next(o.data)},"next"),error:p(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(c){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",c),r.error(c)}}else r.error(o)},"error"),complete:p(()=>{r.complete()},"complete")});return()=>{this._activeSubscriptionCount--,n()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),r=this._pushStatusSubjects.get(e);if(r)return r.lastRequestedAt=t,new $.Observable(a=>{r.activeSubscribers++;const c=r.subject.subscribe(a);return()=>{const d=this._pushStatusSubjects.get(e);d&&d.activeSubscribers>0&&d.activeSubscribers--,c.unsubscribe()}});const s=y.gql`subscription StatusUpdates($sessionId: String!) {
468
468
  statusUpdates(sessionId: $sessionId) {
469
469
  date
470
470
  message
@@ -483,7 +483,7 @@
483
483
  ChildEntityNames
484
484
  ErrorMessage
485
485
  }
486
- }`;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 u.LogError(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function j(h){const e=new f;return u.SetProvider(e),await e.Config(h),await u.StartupManager.Instance.Startup(),w.MJGlobal.Instance.RaiseEvent({event:w.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),e}p(j,"setupGraphQLClient");class J{static{p(this,"SyncRolesAndUsersResult")}}class W{static{p(this,"RoleInput")}}class z{static{p(this,"UserInput")}}class H{static{p(this,"RolesAndUsersInput")}}var Q=(h=>(h.Create="Create",h.Update="Update",h.CreateOrUpdate="CreateOrUpdate",h.Delete="Delete",h.DeleteWithFilter="DeleteWithFilter",h))(Q||{});class X{static{p(this,"ActionItemInput")}}class Y{static{p(this,"SyncDataResult")}constructor(){this.Results=[]}}class Z{static{p(this,"ActionItemOutput")}}class ee{static{p(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 y.GraphQLClient(e,{headers:n})}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
486
+ }`;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 u.LogError(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function j(h){const e=new f;return u.SetProvider(e),await e.Config(h),await u.StartupManager.Instance.Startup(),w.MJGlobal.Instance.RaiseEvent({event:w.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),e}p(j,"setupGraphQLClient");class J{static{p(this,"SyncRolesAndUsersResult")}}class W{static{p(this,"RoleInput")}}class z{static{p(this,"UserInput")}}class H{static{p(this,"RolesAndUsersInput")}}var U=(h=>(h.Create="Create",h.Update="Update",h.CreateOrUpdate="CreateOrUpdate",h.Delete="Delete",h.DeleteWithFilter="DeleteWithFilter",h))(U||{});class X{static{p(this,"ActionItemInput")}}class Y{static{p(this,"SyncDataResult")}constructor(){this.Results=[]}}class Z{static{p(this,"ActionItemOutput")}}class ee{static{p(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 y.GraphQLClient(e,{headers:n})}resolvePlatformSQL(e){if(e!=null)return u.IsPlatformSQL(e)?e.default:e}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
487
487
  GetData(input: $input) {
488
488
  Success
489
489
  ErrorMessages
@@ -541,7 +541,7 @@
541
541
  SyncRolesAndUsers(data: $data) {
542
542
  Success
543
543
  }
544
- }`,{data:e});return r&&r.SyncRolesAndUsers?r.SyncRolesAndUsers:{Success:!1}}catch(t){return u.LogError(`GraphQLSystemUserClient::SyncRolesAndUsers - Error syncing roles and users - ${t}`),{Success:!1}}}async RunViewByName(e){try{const r=await this.Client.request(`query RunViewByNameSystemUser($input: RunViewByNameInput!) {
544
+ }`,{data:e});return r&&r.SyncRolesAndUsers?r.SyncRolesAndUsers:{Success:!1}}catch(t){return u.LogError(`GraphQLSystemUserClient::SyncRolesAndUsers - Error syncing roles and users - ${t}`),{Success:!1}}}async RunViewByName(e){try{const t=`query RunViewByNameSystemUser($input: RunViewByNameInput!) {
545
545
  RunViewByNameSystemUser(input: $input) {
546
546
  Results {
547
547
  PrimaryKey {
@@ -558,7 +558,7 @@
558
558
  ErrorMessage
559
559
  Success
560
560
  }
561
- }`,{input:e});return r&&r.RunViewByNameSystemUser?r.RunViewByNameSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by name"}}catch(t){return u.LogError(`GraphQLSystemUserClient::RunViewByNameSystemUser - Error running view by name - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViewByID(e){try{const r=await this.Client.request(`query RunViewByIDSystemUser($input: RunViewByIDInput!) {
561
+ }`,r={...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)},s=await this.Client.request(t,{input:r});return s&&s.RunViewByNameSystemUser?s.RunViewByNameSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by name"}}catch(t){return u.LogError(`GraphQLSystemUserClient::RunViewByNameSystemUser - Error running view by name - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViewByID(e){try{const t=`query RunViewByIDSystemUser($input: RunViewByIDInput!) {
562
562
  RunViewByIDSystemUser(input: $input) {
563
563
  Results {
564
564
  PrimaryKey {
@@ -575,7 +575,7 @@
575
575
  ErrorMessage
576
576
  Success
577
577
  }
578
- }`,{input:e});return r&&r.RunViewByIDSystemUser?r.RunViewByIDSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by ID"}}catch(t){return u.LogError(`GraphQLSystemUserClient::RunViewByIDSystemUser - Error running view by ID - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunDynamicView(e){try{const r=await this.Client.request(`query RunDynamicViewSystemUser($input: RunDynamicViewInput!) {
578
+ }`,r={...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)},s=await this.Client.request(t,{input:r});return s&&s.RunViewByIDSystemUser?s.RunViewByIDSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by ID"}}catch(t){return u.LogError(`GraphQLSystemUserClient::RunViewByIDSystemUser - Error running view by ID - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunDynamicView(e){try{const t=`query RunDynamicViewSystemUser($input: RunDynamicViewInput!) {
579
579
  RunDynamicViewSystemUser(input: $input) {
580
580
  Results {
581
581
  PrimaryKey {
@@ -592,7 +592,7 @@
592
592
  ErrorMessage
593
593
  Success
594
594
  }
595
- }`,{input:e});return r&&r.RunDynamicViewSystemUser?r.RunDynamicViewSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute dynamic view"}}catch(t){return u.LogError(`GraphQLSystemUserClient::RunDynamicViewSystemUser - Error running dynamic view - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViews(e){try{const r=await this.Client.request(`query RunViewsSystemUser($input: [RunViewGenericInput!]!) {
595
+ }`,r={...e,ExtraFilter:this.resolvePlatformSQL(e.ExtraFilter),OrderBy:this.resolvePlatformSQL(e.OrderBy)},s=await this.Client.request(t,{input:r});return s&&s.RunDynamicViewSystemUser?s.RunDynamicViewSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute dynamic view"}}catch(t){return u.LogError(`GraphQLSystemUserClient::RunDynamicViewSystemUser - Error running dynamic view - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViews(e){try{const t=`query RunViewsSystemUser($input: [RunViewGenericInput!]!) {
596
596
  RunViewsSystemUser(input: $input) {
597
597
  Results {
598
598
  PrimaryKey {
@@ -609,7 +609,7 @@
609
609
  ErrorMessage
610
610
  Success
611
611
  }
612
- }`,{input:e});return r&&r.RunViewsSystemUser?r.RunViewsSystemUser:[]}catch(t){return u.LogError(`GraphQLSystemUserClient::RunViewsSystemUser - Error running views - ${t}`),[]}}async GetQueryData(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataSystemUser($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
612
+ }`,r=e.map(n=>({...n,ExtraFilter:this.resolvePlatformSQL(n.ExtraFilter),OrderBy:this.resolvePlatformSQL(n.OrderBy)})),s=await this.Client.request(t,{input:r});return s&&s.RunViewsSystemUser?s.RunViewsSystemUser:[]}catch(t){return u.LogError(`GraphQLSystemUserClient::RunViewsSystemUser - Error running views - ${t}`),[]}}async GetQueryData(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataSystemUser($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
613
613
  GetQueryDataSystemUser(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
614
614
  QueryID
615
615
  QueryName
@@ -1149,5 +1149,5 @@
1149
1149
  failedAccounts
1150
1150
  }
1151
1151
  }
1152
- `,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(c=>({path:c.path,name:c.name,size:c.size,contentType:c.contentType,lastModified:new Date(c.lastModified),relevance:c.relevance,excerpt:c.excerpt,matchInFilename:c.matchInFilename,objectId:c.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 u.LogError(`Error searching across accounts: ${n}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}Object.defineProperty(exports,"gql",{enumerable:!0,get:p(function(){return y.gql},"get")}),exports.ActionItemInput=X,exports.ActionItemOutput=Z,exports.BrowserIndexedDBStorageProvider=U,exports.BrowserStorageProviderBase=T,exports.FieldMapper=A,exports.FireAndForgetHelper=P,exports.GetDataOutput=te,exports.GraphQLAIClient=L,exports.GraphQLActionClient=oe,exports.GraphQLComponentRegistryClient=ue,exports.GraphQLDataProvider=f,exports.GraphQLEncryptionClient=ae,exports.GraphQLFileStorageClient=le,exports.GraphQLProviderConfigData=B,exports.GraphQLSystemUserClient=ee,exports.GraphQLTestingClient=ie,exports.GraphQLTransactionGroup=x,exports.GraphQLVersionHistoryClient=ce,exports.RoleInput=W,exports.RolesAndUsersInput=H,exports.SimpleRemoteEntity=se,exports.SimpleRemoteEntityField=ne,exports.SimpleRemoteEntityOutput=re,exports.SyncDataAction=Q,exports.SyncDataResult=Y,exports.SyncRolesAndUsersResult=J,exports.UserInput=z,exports.setupGraphQLClient=j;
1152
+ `,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(c=>({path:c.path,name:c.name,size:c.size,contentType:c.contentType,lastModified:new Date(c.lastModified),relevance:c.relevance,excerpt:c.excerpt,matchInFilename:c.matchInFilename,objectId:c.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 u.LogError(`Error searching across accounts: ${n}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}Object.defineProperty(exports,"gql",{enumerable:!0,get:p(function(){return y.gql},"get")}),exports.ActionItemInput=X,exports.ActionItemOutput=Z,exports.BrowserIndexedDBStorageProvider=Q,exports.BrowserStorageProviderBase=T,exports.FieldMapper=A,exports.FireAndForgetHelper=P,exports.GetDataOutput=te,exports.GraphQLAIClient=L,exports.GraphQLActionClient=oe,exports.GraphQLComponentRegistryClient=ue,exports.GraphQLDataProvider=f,exports.GraphQLEncryptionClient=ae,exports.GraphQLFileStorageClient=le,exports.GraphQLProviderConfigData=K,exports.GraphQLSystemUserClient=ee,exports.GraphQLTestingClient=ie,exports.GraphQLTransactionGroup=x,exports.GraphQLVersionHistoryClient=ce,exports.RoleInput=W,exports.RolesAndUsersInput=H,exports.SimpleRemoteEntity=se,exports.SimpleRemoteEntityField=ne,exports.SimpleRemoteEntityOutput=re,exports.SyncDataAction=U,exports.SyncDataResult=Y,exports.SyncRolesAndUsersResult=J,exports.UserInput=z,exports.setupGraphQLClient=j;
1153
1153
  //# sourceMappingURL=index.cjs.map