UNPKG

aem-mcp-server

Version:
2 lines (1 loc) 2.64 kB
"use strict";import{getAccessToken as u}from"./aem.auth.js";import{LOGGER as h}from"../utils/logger.js";export class AEMFetch{fetch;config;token;tokenExpiry;constructor(t){this.config=t,this.fetch=null,this.token="",this.tokenExpiry=0}async init(){this.token=await this.getAuthToken(this.config.auth),this.fetch=this.getFetchInstance()}getFetchInstance(){return(t,e={})=>{const n=new Headers(e.headers||{});return n.set("Authorization",`Basic ${this.token}`),n.set("Accept","application/json"),n.has("Content-Type")||n.set("Content-Type","application/json"),fetch(t,{...e,headers:n})}}async getAuthToken(t){if(t.clientId&&t.clientSecret){const e=Date.now();if(this.token&&e<this.tokenExpiry)return this.token;const n=await u(t.clientId,t.clientSecret,t.scope);return this.token=n.access_token,this.tokenExpiry=e+(n.expires_in-60)*1e3,this.token}if(t.username&&t.password)return Buffer.from(`${t.username}:${t.password}`).toString("base64");throw new Error("No authentication credentials provided")}async refreshAuthToken(){this.token="",this.tokenExpiry=0,this.token=await this.getAuthToken(this.config.auth)}getTimeoutOptions(t){let e,n,s;const i=t||this.config.timeout;return i&&(e=new AbortController,s=e.signal,n=setTimeout(()=>e.abort(),i)),{signal:s,timeoutId:n}}buildUrlWithParams(t,e){const n=this.config.host.endsWith("/")?this.config.host.slice(0,-1):this.config.host,s=t.startsWith("/")?t:`/${t}`,i=`${n}${s}`;if(!e||Object.keys(e).length===0)return i;const o=new URL(i);return Object.entries(e).forEach(([r,a])=>{a!=null&&o.searchParams.append(r,String(a))}),o.toString()}async request(t,e={},n,s){if(!this.fetch)throw new Error("AEMFetch not initialized. Call await init(config) before making requests.");const{timeoutId:i,signal:o}=this.getTimeoutOptions(n);n&&(e.signal=o);let r;try{if(h.log("AEM Request:",t,e),r=await this.fetch(t,e),r.status===401&&(h.warn(`AEM request to ${t} returned 401 Unauthorized. Attempting to refresh token...`),await this.refreshAuthToken(),r=await this.fetch(t,e)),!r.ok)throw new Error(`AEM ${e.method||"GET"} failed: ${r.status}`);return s?r.text():r.json()}finally{i&&clearTimeout(i)}}async get(t,e,n={},s,i){const o=this.buildUrlWithParams(t,e);return this.request(o,n,s,i)}async post(t,e,n={},s){let i,o=new Headers(n.headers||{});e instanceof URLSearchParams?(i=e,o.set("Content-Type","application/x-www-form-urlencoded")):(i=JSON.stringify(e),o.set("Content-Type","application/json"));const r=this.buildUrlWithParams(t);return this.request(r,{...n,method:"POST",body:i,headers:o},s)}async delete(t,e={},n){const s=this.buildUrlWithParams(t);return this.request(s,{...e,method:"DELETE"},n)}}