@ddex-workbench/sdk
Version:
Official SDK for DDEX Workbench - Open-source DDEX validation and processing tools
3 lines • 5.2 kB
JavaScript
import o from"axios";var s=class extends Error{constructor(e,t="DDEX_ERROR",r,i){super(e),this.name="DDEXError",this.code=t,this.statusCode=r,this.details=i,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},n=class extends s{constructor(e="Rate limit exceeded",t){super(e,"RATE_LIMIT_EXCEEDED",429),this.name="RateLimitError",this.retryAfter=t}getRetryMessage(){return this.retryAfter?`Please retry after ${this.retryAfter} seconds`:"Please retry later"}};var a=class{constructor(e){this.client=e}async validateERN43(e,t){return this.client.validate(e,{type:"ERN",version:"4.3",profile:t})}async validateERN42(e,t){return this.client.validate(e,{type:"ERN",version:"4.2",profile:t})}async validateERN382(e,t){return this.client.validate(e,{type:"ERN",version:"3.8.2",profile:t})}async validateAuto(e){let t=this.detectVersion(e);return t?this.client.validate(e,{type:"ERN",version:t}):{valid:!1,errors:[{line:0,column:0,message:"Unable to detect ERN version from XML content",severity:"error",rule:"Version-Detection"}],warnings:[],metadata:{processingTime:0,schemaVersion:"unknown",validatedAt:new Date().toISOString(),errorCount:1,warningCount:0,validationSteps:[]}}}async validateBatch(e){return(await Promise.allSettled(e.map(r=>this.client.validate(r.content,r.options)))).map((r,i)=>r.status==="fulfilled"?r.value:{valid:!1,errors:[{line:0,column:0,message:`Validation failed: ${r.reason.message}`,severity:"error",rule:"Batch-Validation"}],warnings:[],metadata:{processingTime:0,schemaVersion:e[i].options.version,validatedAt:new Date().toISOString(),errorCount:1,warningCount:0,validationSteps:[]}})}async isValid(e,t){return(await this.client.validate(e,t)).valid}async getErrors(e,t){return(await this.client.validate(e,t)).errors}detectVersion(e){return e.includes('xmlns:ern="http://ddex.net/xml/ern/43"')||e.includes('MessageSchemaVersionId="ern/43"')?"4.3":e.includes('xmlns:ern="http://ddex.net/xml/ern/42"')||e.includes('MessageSchemaVersionId="ern/42"')?"4.2":e.includes('xmlns:ern="http://ddex.net/xml/ern/382"')||e.includes('MessageSchemaVersionId="ern/382"')?"3.8.2":null}};var d=class{constructor(e={}){this.config={baseURL:e.baseURL||"https://api.ddex-workbench.org/v1",apiKey:e.apiKey,timeout:e.timeout||3e4,environment:e.environment||"production",maxRetries:e.maxRetries||3,retryDelay:e.retryDelay||1e3,...e},this.client=o.create({baseURL:this.config.baseURL,timeout:this.config.timeout,headers:{"Content-Type":"application/json","User-Agent":`ddex-workbench-sdk/1.0.1 (${this.getEnvironment()})`}}),this.config.apiKey&&(this.client.defaults.headers.common["X-API-Key"]=this.config.apiKey),this.setupInterceptors(),this.validator=new a(this)}async validate(e,t){try{return(await this.client.post("/validate",{content:e,type:t.type||"ERN",version:t.version,profile:t.profile})).data}catch(r){throw this.handleError(r)}}async validateURL(e,t){var r;try{let i=await o.get(e,{responseType:"text",timeout:this.config.timeout});return this.validate(i.data,t)}catch(i){throw o.isAxiosError(i)&&((r=i.response)==null?void 0:r.status)===404?new s(`XML file not found at URL: ${e}`,"FILE_NOT_FOUND"):this.handleError(i)}}async getSupportedFormats(){try{return(await this.client.get("/formats")).data}catch(e){throw this.handleError(e)}}async checkHealth(){try{return(await this.client.get("/health")).data}catch(e){throw this.handleError(e)}}async listApiKeys(e){try{return(await this.client.get("/keys",{headers:{Authorization:`Bearer ${e}`}})).data}catch(t){throw this.handleError(t)}}async createApiKey(e,t){try{return(await this.client.post("/keys",{name:e},{headers:{Authorization:`Bearer ${t}`}})).data}catch(r){throw this.handleError(r)}}async revokeApiKey(e,t){try{await this.client.delete(`/keys/${e}`,{headers:{Authorization:`Bearer ${t}`}})}catch(r){throw this.handleError(r)}}setApiKey(e){this.config.apiKey=e,this.client.defaults.headers.common["X-API-Key"]=e}clearApiKey(){this.config.apiKey=void 0,delete this.client.defaults.headers.common["X-API-Key"]}setupInterceptors(){this.client.interceptors.response.use(e=>e,async e=>{let t=e.config;if(!t||t.__retryCount>=this.config.maxRetries||!this.shouldRetry(e))return Promise.reject(e);t.__retryCount=t.__retryCount||0,t.__retryCount++;let r=this.config.retryDelay*Math.pow(2,t.__retryCount-1);return await new Promise(i=>setTimeout(i,r)),this.client(t)})}shouldRetry(e){return!e.response||e.response.status>=500&&e.response.status<600}handleError(e){var t,r,i,c,u,p;if(o.isAxiosError(e)){let h=(t=e.response)==null?void 0:t.status,m=((c=(i=(r=e.response)==null?void 0:r.data)==null?void 0:i.error)==null?void 0:c.message)||e.message;if(h===429){let y=(u=e.response)==null?void 0:u.headers["retry-after"];return new n(m,y?parseInt(y):void 0)}return new s(m,"API_ERROR",h,(p=e.response)==null?void 0:p.data)}return e}getEnvironment(){var e;return typeof window!="undefined"?"browser":typeof process!="undefined"&&((e=process.versions)!=null&&e.node)?`node/${process.version}`:"unknown"}};export{d as DDEXClient,s as DDEXError,a as DDEXValidator,n as RateLimitError};
if (typeof window !== 'undefined' && !window.DDEXWorkbench) { window.DDEXWorkbench = DDEXWorkbench; }
//# sourceMappingURL=index.mjs.map