UNPKG

aem-mcp-server

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