| 1 | import { createStore } from "/js/AlpineStore.js"; |
| 2 | import { callJsonApi } from "/js/api.js"; |
| 3 | import { getCurrentUserISOString } from "/js/time-utils.js"; |
| 4 | |
| 5 | function buildBannersContext() { |
| 6 | return { |
| 7 | url: window.location.href, |
| 8 | protocol: window.location.protocol, |
| 9 | hostname: window.location.hostname, |
| 10 | port: window.location.port, |
| 11 | browser: navigator.userAgent, |
| 12 | timestamp: getCurrentUserISOString(), |
| 13 | }; |
| 14 | } |
| 15 | |
| 16 | export const store = createStore("composerBanner", { |
| 17 | missingApiKeys: [], |
| 18 | hasMissingApiKeyBanner: false, |
| 19 | loading: false, |
| 20 | lastRefresh: 0, |
| 21 | _modalCloseBound: false, |
| 22 | |
| 23 | get hasMissingApiKeys() { |
| 24 | return this.hasMissingApiKeyBanner; |
| 25 | }, |
| 26 | |
| 27 | get missingApiKeysSummaryText() { |
| 28 | if (!this.hasMissingApiKeys) return ""; |
| 29 | if (!Array.isArray(this.missingApiKeys) || this.missingApiKeys.length === 0) { |
| 30 | return "Configure your model provider API keys to continue."; |
| 31 | } |
| 32 | return this.missingApiKeys |
| 33 | .map((p) => `${p.model_type} (${p.provider})`) |
| 34 | .join(", "); |
| 35 | }, |
| 36 | |
| 37 | init() { |
| 38 | if (this._modalCloseBound) return; |
| 39 | this._modalCloseBound = true; |
| 40 | document.addEventListener("modal-closed", () => { |
| 41 | this.refresh(true); |
| 42 | }); |
| 43 | }, |
| 44 | |
| 45 | async refresh(force = false) { |
| 46 | const now = Date.now(); |
| 47 | if (!force && now - this.lastRefresh < 1000) return; |
| 48 | this.lastRefresh = now; |
| 49 | this.loading = true; |
| 50 | try { |
| 51 | const response = await callJsonApi("/banners", { |
| 52 | banners: [], |
| 53 | context: buildBannersContext(), |
| 54 | }); |
| 55 | const banners = Array.isArray(response?.banners) ? response.banners : []; |
| 56 | const missingApiKeyBanner = banners.find((banner) => banner?.id === "missing-api-key"); |
| 57 | this.hasMissingApiKeyBanner = !!missingApiKeyBanner; |
| 58 | this.missingApiKeys = Array.isArray(missingApiKeyBanner?.missing_providers) |
| 59 | ? missingApiKeyBanner.missing_providers |
| 60 | : []; |
| 61 | } catch (e) { |
| 62 | console.error("composerBanner refresh failed", e); |
| 63 | this.hasMissingApiKeyBanner = false; |
| 64 | this.missingApiKeys = []; |
| 65 | } finally { |
| 66 | this.loading = false; |
| 67 | } |
| 68 | }, |
| 69 | }); |