UNPKG

@ddex-workbench/sdk

Version:

Official SDK for DDEX Workbench - Open-source DDEX validation and processing tools

3 lines 5.84 kB
"use strict";var g=Object.create;var d=Object.defineProperty;var v=Object.getOwnPropertyDescriptor;var R=Object.getOwnPropertyNames;var V=Object.getPrototypeOf,w=Object.prototype.hasOwnProperty;var D=(s,e)=>{for(var t in e)d(s,t,{get:e[t],enumerable:!0})},E=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of R(e))!w.call(s,i)&&i!==t&&d(s,i,{get:()=>e[i],enumerable:!(r=v(e,i))||r.enumerable});return s};var A=(s,e,t)=>(t=s!=null?g(V(s)):{},E(e||!s||!s.__esModule?d(t,"default",{value:s,enumerable:!0}):t,s)),x=s=>E(d({},"__esModule",{value:!0}),s);var P={};D(P,{DDEXClient:()=>c,DDEXError:()=>n,DDEXValidator:()=>o,RateLimitError:()=>a});module.exports=x(P);var l=A(require("axios"));var n=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)}},a=class extends n{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 o=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 c=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=l.default.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 o(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 l.default.get(e,{responseType:"text",timeout:this.config.timeout});return this.validate(i.data,t)}catch(i){throw l.default.isAxiosError(i)&&((r=i.response)==null?void 0:r.status)===404?new n(`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,u,p,h;if(l.default.isAxiosError(e)){let m=(t=e.response)==null?void 0:t.status,y=((u=(i=(r=e.response)==null?void 0:r.data)==null?void 0:i.error)==null?void 0:u.message)||e.message;if(m===429){let f=(p=e.response)==null?void 0:p.headers["retry-after"];return new a(y,f?parseInt(f):void 0)}return new n(y,"API_ERROR",m,(h=e.response)==null?void 0:h.data)}return e}getEnvironment(){var e;return typeof window!="undefined"?"browser":typeof process!="undefined"&&((e=process.versions)!=null&&e.node)?`node/${process.version}`:"unknown"}}; if (typeof window !== 'undefined' && !window.DDEXWorkbench) { window.DDEXWorkbench = DDEXWorkbench; } //# sourceMappingURL=index.js.map