socaity
Version:
SDK for Generative AI. Build AI-powered applications with ease
3 lines (2 loc) • 22.7 kB
JavaScript
(function(l,o){typeof exports=="object"&&typeof module<"u"?o(exports,require("@socaity/media-toolkit")):typeof define=="function"&&define.amd?define(["exports","@socaity/media-toolkit"],o):(l=typeof globalThis<"u"?globalThis:l||self,o(l.socaity={},l.MediaToolkit))})(this,function(l,o){"use strict";var z=Object.defineProperty;var x=(l,o,C)=>o in l?z(l,o,{enumerable:!0,configurable:!0,writable:!0,value:C}):l[o]=C;var n=(l,o,C)=>x(l,typeof o!="symbol"?o+"":o,C);class C extends Error{constructor(e="Invalid API key format. API keys should start with 'sk_' and be 67 characters long."){super(e),this.name="ApiKeyError",Error.captureStackTrace&&Error.captureStackTrace(this,C)}}const I=class I{constructor(e={}){n(this,"apiKey");n(this,"baseUrl");n(this,"pollInterval");n(this,"maxRetries");this.apiKey=e.apiKey,this.baseUrl=e.baseUrl||"https://api.socaity.ai/v1",this.pollInterval=e.pollInterval||5e3,this.maxRetries=e.maxRetries||3}static getInstance(){return I.instance||(I.instance=new I),I.instance}static update(e){if(e.apiKey!==void 0){if(!e.apiKey.startsWith("sk_")&&!e.apiKey.startsWith("tk_")&&!e.apiKey.startsWith("ey"))throw new C("Invalid authentication token. Use either a Socaity API key from https://www.socaity.ai or a valid JWT token.");if(e.apiKey.startsWith("sk_")&&!e.apiKey.startsWith("tk_")&&e.apiKey.length!==67)throw new C("Invalid API key format. API keys should be 67 characters long. Get your API key from https://www.socaity.ai")}const t=I.getInstance();Object.assign(t,e)}};n(I,"instance");let D=I;const g={INITIALIZING:"INITIALIZING",SENDING:"SENDING",TRACKING:"TRACKING",PROCESSING_RESULT:"PROCESSING_RESULT",COMPLETED:"COMPLETED",FAILED:"FAILED"},u={CREATED:"CREATED",QUEUED:"QUEUED",PROCESSING:"PROCESSING",COMPLETED:"COMPLETED",FAILED:"FAILED",CANCELLED:"CANCELLED",UNKNOWN:"UNKNOWN"};class G{parse(e){if(e==null)return this.errorJob("No response received");if(typeof e=="string")try{return this.parseObject(JSON.parse(e))}catch{return{id:"",status:u.COMPLETED,progress:1,message:null,result:e,createdAt:new Date,updatedAt:new Date}}return this.parseObject(e)}parseObject(e){if(typeof e!="object"||e===null)return this.errorJob("Invalid response format");const t=e,s=this.str(t.job_id)||this.str(t.id)||"",r=this.status(t.status),i=this.progress(t.progress,r),c=this.str(t.message),a=this.str(t.error);let h;const f=t.links;if(f)h={status:f.status,cancel:f.cancel};else{const m=this.str(t.refresh_job_url),E=this.str(t.cancel_job_url);(m||E)&&(h={status:m||void 0,cancel:E||void 0})}return{id:s,status:r,progress:i,message:c,result:t.result,error:a,createdAt:this.date(t.createdAt??t.created_at),updatedAt:this.date(t.updatedAt??t.updated_at),links:h}}errorJob(e){const t=new Date;return{id:"",status:u.FAILED,progress:0,message:e,result:null,error:e,createdAt:t,updatedAt:t}}str(e){return typeof e=="string"?e:null}date(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){const t=new Date(e);if(!isNaN(t.getTime()))return t}return new Date}status(e){return typeof e!="string"||!e?u.UNKNOWN:{COMPLETED:u.COMPLETED,SUCCEEDED:u.COMPLETED,FINISHED:u.COMPLETED,CREATED:u.CREATED,FAILED:u.FAILED,ERROR:u.FAILED,IN_PROGRESS:u.PROCESSING,PROCESSING:u.PROCESSING,RUNNING:u.PROCESSING,BOOTING:u.PROCESSING,QUEUED:u.QUEUED,PENDING:u.QUEUED,IN_QUEUE:u.QUEUED,STARTING:u.QUEUED,CANCELLED:u.CANCELLED,CANCELED:u.CANCELLED}[e.toUpperCase()]||u.UNKNOWN}progress(e,t){let s=0;if(typeof e=="number")s=e;else if(typeof e=="string")s=parseFloat(e)||0;else if(e&&typeof e=="object"){const r=e;s=typeof r.progress=="number"?r.progress:parseFloat(String(r.progress))||0}return isNaN(s)&&(s=0),s=Math.max(0,Math.min(1,s)),t===u.COMPLETED&&(s=1),s}}const U=class U{constructor(){n(this,"config");n(this,"abortController");n(this,"responseParser");this.config=D.getInstance(),this.abortController=new AbortController,this.responseParser=new G}resolveGatewayUrl(e){if(e.startsWith("http://")||e.startsWith("https://"))return e;try{return`${new URL(this.config.baseUrl).origin}${e.startsWith("/")?"":"/"}${e}`}catch{return`${this.config.baseUrl}/${e.replace(/^\//,"")}`}}buildQueryString(e){if(!e||Object.keys(e).length===0)return"";const t=new URLSearchParams;for(const[s,r]of Object.entries(e))if(r!=null)if(r instanceof o.MediaList){const i=r.toBase64(!0);t.append(s,i.length===1?i[0]:JSON.stringify(i))}else typeof r=="object"?t.append(s,JSON.stringify(r)):t.append(s,String(r));return t.toString()}requireApiKey(e){const t=e||this.config.apiKey;if(!t)throw new Error("API key not provided");return t}authHeaders(e){return{Authorization:`Bearer ${e}`}}isFileTypeParam(e){const t=["file","image","audio","video"];return e.definition&&!Array.isArray(e.definition)?!!(e.definition.format&&t.includes(e.definition.format)):Array.isArray(e.definition)?e.definition.some(s=>!!(s.format&&t.includes(s.format))):!1}async prepareRequest(e,t){var c;const s={queryParams:{},bodyParams:{},fileParams:{}};if(!((c=e.parameters)!=null&&c.length))return s;const r={},i={};for(const a of e.parameters){const h=t[a.name]??a.default;if(h===void 0&&a.required)throw new Error(`Required parameter '${a.name}' is missing`);h!==void 0&&(i[a.name]=a.location==="query"?"query":"body",this.isFileTypeParam(a)?r[a.name]=h:a.location==="query"?s.queryParams[a.name]=h:s.bodyParams[a.name]=h)}if(Object.keys(r).length>0){const{fileParams:a,nonFileParams:h}=await this.processFileParams(r);s.fileParams=a;for(const[f,m]of Object.entries(h))i[f]==="query"?s.queryParams[f]=m:s.bodyParams[f]=m}return s.bodyParams.is_public=t.is_public??!1,s.bodyParams.keep=t.keep??!1,s}async processFileParams(e){const t=new o.MediaDict({downloadFiles:!1,readSystemFiles:!0,fileName:"fileParams"});await t.fromAny(e);const s=t.getNonFileParams(!1),r=t.getProcessableFiles({ignoreErrors:!0,silent:!0}),i=t.getUrlFiles();if(r.length>0){const c=this.prepareFilesForSend(r);for(const a of r.keys())a in c||(s[a]=e[a]);Object.assign(i,c)}return{fileParams:i,nonFileParams:s}}prepareFilesForSend(e){const t={};for(const s of e.keys()){const r=e.get(s);if(r instanceof o.MediaDict){const c=r.getProcessableFiles({ignoreErrors:!0,silent:!0});c.length>0&&(t[s]=this.prepareFilesForSend(c));continue}if(r instanceof o.MediaList){const c=r.getProcessableFiles({ignoreErrors:!0,silent:!0});if(c.length>0){const a=c.toBlob();t[s]=c.length===1?a[0]:a}continue}const i=new o.MediaList({files:[r]});t[s]=i.toBlob()[0]}return t}async sendRequest(e,t="POST",s={},r={},i={},c){const a=this.requireApiKey(c);this.abortController=new AbortController;const{signal:h}=this.abortController,f=this.authHeaders(a);let m=`${this.config.baseUrl}/${e}`,E=null;if(t==="GET"){const y={...s,...r,...i},p=this.buildQueryString(y);p&&(m+=`?${p}`)}else{const y=this.buildQueryString(s);y&&(m+=`?${y}`);const p=new FormData;for(const[P,w]of Object.entries({...r,...i}))w!=null&&(w instanceof Blob||w instanceof File?p.append(P,w):Array.isArray(w)?w.forEach(N=>{N instanceof Blob||N instanceof File?p.append(P,N):typeof N=="object"?p.append(P,new Blob([JSON.stringify(N)],{type:"application/json"})):p.append(P,String(N))}):typeof w=="object"?p.append(P,new Blob([JSON.stringify(w)],{type:"application/json"})):p.append(P,String(w)));E=p}try{const y=setTimeout(()=>this.abort(),U.DEFAULT_TIMEOUT_MS),p=await fetch(m,{method:t,headers:f,body:E,signal:h});if(clearTimeout(y),!p.ok)throw await this.formatError(p);const P=p.headers.get("content-type");return P!=null&&P.includes("application/json")?await p.json():await p.text()}catch(y){throw y instanceof DOMException&&y.name==="AbortError"?new Error("Request canceled"):y instanceof Error?y:new Error(`Network error: ${String(y)}`)}}async requestEndpoint(e,t,s){const r=await this.prepareRequest(e,t),i=await this.sendRequest(e.path,e.method,r.queryParams,r.bodyParams,r.fileParams,s);return this.responseParser.parse(i)}async refreshStatus(e,t){var a;const s=t||`/gateway/v1/status/${e}`,r=this.resolveGatewayUrl(s),i=await this.gatewayRequest(r,"GET"),c=(a=i.headers.get("content-type"))!=null&&a.includes("application/json")?await i.json():await i.text();return this.responseParser.parse(c)}async cancelJob(e,t){const s=t||`/gateway/v1/cancel/${e}`,r=this.resolveGatewayUrl(s),i=await this.gatewayRequest(r,"POST");if(!i.ok)throw await this.formatError(i)}async gatewayRequest(e,t="GET",s=6e4){const r=this.requireApiKey();this.abortController=new AbortController;const{signal:i}=this.abortController,c=setTimeout(()=>this.abort(),s);try{const a=await fetch(e,{method:t,headers:this.authHeaders(r),signal:i});if(clearTimeout(c),!a.ok)throw await this.formatError(a);return a}catch(a){throw clearTimeout(c),a instanceof DOMException&&a.name==="AbortError"?new Error("Request canceled"):a instanceof Error?a:new Error(`Network error: ${String(a)}`)}}async formatError(e){let t;try{const s=e.headers.get("content-type");t=s!=null&&s.includes("application/json")?JSON.stringify(await e.json()):await e.text()}catch{t="Could not parse error response"}return new Error(`API error (${e.status}): ${t}`)}abort(){this.abortController.abort(),this.abortController=new AbortController}};n(U,"DEFAULT_TIMEOUT_MS",12e4);let T=U;const M=typeof process<"u"&&process.stdout&&process.stdout.clearLine;let A;if(M)try{A=require("cli-progress")}catch{console.warn("cli-progress package not found. Using basic console output for progress.")}const j=class j{constructor(){n(this,"multiBar");n(this,"bars",new Map);n(this,"isInitialized",!1);M&&A&&(this.multiBar=new A.MultiBar({clearOnComplete:!1,hideCursor:!0,format:"{bar} {percentage}% | {jobId} | {phase} | {message}"}),this.isInitialized=!0)}static getInstance(){return j.instance||(j.instance=new j),j.instance}createBar(e,t){if(!this.isInitialized)return null;const s=this.multiBar.create(100,0,{jobId:e,phase:t,message:"Starting..."});return this.bars.set(e,s),s}updateBar(e,t,s){const r=this.bars.get(e);r&&r.update(t,s)}removeBar(e){const t=this.bars.get(e);t&&(t.stop(),this.multiBar.remove(t),this.bars.delete(e))}stopAll(){this.isInitialized&&(this.multiBar.stop(),this.bars.clear())}};n(j,"instance");let F=j;class R{constructor(e,t,s,r,i=!0){n(this,"jobData");n(this,"endpoint");n(this,"processingState");n(this,"jobManager");n(this,"_result",null);n(this,"_error",null);n(this,"completed",!1);n(this,"resolvePromise");n(this,"rejectPromise");n(this,"promise");n(this,"eventListeners",new Map);n(this,"verbose");n(this,"progressBar",null);n(this,"progressBarManager");n(this,"parseResultCallbacks",[]);n(this,"pollErrorCount",0);n(this,"lastLoggedMessage",null);this.jobData=e,this.jobManager=t,this.endpoint=s,this.verbose=i,this.processingState={phase:g.INITIALIZING,progress:0},this.progressBarManager=F.getInstance(),this.promise=new Promise((c,a)=>{this.resolvePromise=c,this.rejectPromise=a}),r&&this.onParseResult(r),this.verbose&&this.initProgressDisplay(),setTimeout(()=>this.startTracking(),0)}initProgressDisplay(){this.verbose&&(M&&A?(this.progressBar=this.progressBarManager.createBar(this.jobData.id||"initializing",this.processingState.phase),this.updateProgressDisplay()):this.logProgress())}updateProgressDisplay(){if(!this.verbose)return;const e=this.calculateProgressPercent(),t=this.formatProgressMessage();M&&A&&this.progressBar?this.progressBarManager.updateBar(this.jobData.id,e,{phase:this.processingState.phase,message:t.replace(/^.*\| /,"")}):this.logProgress()}calculateProgressPercent(){return this.processingState.phase===g.TRACKING&&this.jobData.progress>0?Math.round(this.jobData.progress*100):{[g.INITIALIZING]:0,[g.SENDING]:10,[g.TRACKING]:15,[g.PROCESSING_RESULT]:90,[g.COMPLETED]:100,[g.FAILED]:100}[this.processingState.phase]??0}formatProgressMessage(){const{phase:e}=this.processingState,t=this.jobData.id||"initializing",s=this.endpoint.path;if(e===g.INITIALIZING||e===g.SENDING)return`${e} job | API: ${s}`;if(e===g.TRACKING){const r=this.jobData.progress>0?`${Math.round(this.jobData.progress*100)}%`:"unknown";let i=`Job ${t} | Progress: ${r} | API: ${s}`;return this.jobData.message&&(i+=` | ${this.jobData.message}`),i}return`Job ${t} | ${e} | API: ${s}`}logProgress(){const e=this.formatProgressMessage();this.lastLoggedMessage!==e&&(console.log(e),this.lastLoggedMessage=e)}stopProgressDisplay(){this.verbose&&(M&&A&&this.progressBar&&(this.progressBarManager.removeBar(this.jobData.id),this.progressBar=null),this.processingState.phase===g.COMPLETED?console.log(`Job ${this.jobData.id} completed successfully (${this.endpoint.path})`):this.processingState.phase===g.FAILED&&console.log(`Job ${this.jobData.id} failed: ${this.processingState.message} (${this.endpoint.path})`))}on(e,t){return this.eventListeners.has(e)||this.eventListeners.set(e,[]),this.eventListeners.get(e).push(t),this}emit(e,...t){var s;(s=this.eventListeners.get(e))==null||s.forEach(r=>r(...t))}startTracking(){this.setPhase(g.TRACKING,0,"Tracking job status"),this.pollJobStatus()}async pollJobStatus(){var e,t,s;if(!(this.completed||!this.jobData.id))try{const r=await this.jobManager.refreshStatus(this.jobData.id,(e=this.jobData.links)==null?void 0:e.status);if(!r){this.scheduleNextPoll();return}if(r.links||(r.links={}),r.links.status=r.links.status||((t=this.jobData.links)==null?void 0:t.status),r.links.cancel=r.links.cancel||((s=this.jobData.links)==null?void 0:s.cancel),this.jobData=r,this.pollErrorCount=0,this.emitJobUpdate(),this.verbose&&this.updateProgressDisplay(),r.status===u.COMPLETED){this.setPhase(g.PROCESSING_RESULT,.9,"Processing result");try{this._result=await o.parseSocaityAPIJobResult(r.result),this._result=await this.runParseResultCallbacks(this._result),this.complete()}catch(i){this.fail(i instanceof Error?i:new Error(String(i)))}}else r.status===u.FAILED?this.fail(new Error(r.error||"Job failed with no error message")):r.status===u.CANCELLED?this.fail(new Error("Job was cancelled")):this.scheduleNextPoll()}catch(r){if(console.error("Network error while polling job status:",r),this.pollErrorCount++,this.pollErrorCount>=5){this.fail(new Error(`Network polling failed after ${this.pollErrorCount} attempts: ${r instanceof Error?r.message:String(r)}`));return}this.scheduleNextPoll()}}scheduleNextPoll(){setTimeout(()=>this.pollJobStatus(),this.jobManager.config.pollInterval)}complete(){this.setPhase(g.COMPLETED,1,"Job completed"),this.cleanup(),this.completed=!0,this.emit("completed",this._result),this.resolvePromise(this._result)}fail(e){this.setPhase(g.FAILED,1,e.message),this.cleanup(),this.completed=!0,this._error=e,this.emit("failed",e),this.rejectPromise(e)}cleanup(){this.stopProgressDisplay()}setPhase(e,t,s){this.processingState={phase:e,progress:t,message:s},this.verbose&&this.updateProgressDisplay(),this.emit("processingUpdated",this.processingState)}emitJobUpdate(){this.emit("progressUpdated",{progress:this.jobData.progress,message:this.jobData.message}),this.emit("statusUpdated",this.jobData.status)}setVerbose(e){return this.verbose=e,e&&!this.progressBar&&!this.completed?this.initProgressDisplay():!e&&this.progressBar&&this.stopProgressDisplay(),this}onCompleted(e){return this.on("completed",e),this.completed&&this._result!==null&&setTimeout(()=>e(this._result),0),this}onFailed(e){return this.on("failed",e),this.completed&&this._error!==null&&setTimeout(()=>e(this._error),0),this}onProgress(e){return this.on("progressUpdated",e),setTimeout(()=>e({progress:this.jobData.progress,message:this.jobData.message}),0),this}onStatus(e){return this.on("statusUpdated",e),setTimeout(()=>e(this.jobData.status),0),this}onProcessingUpdated(e){return this.on("processingUpdated",e),setTimeout(()=>e(this.processingState),0),this}onParseResult(e){return this.parseResultCallbacks.push(e),this}async runParseResultCallbacks(e){let t=e;for(const s of this.parseResultCallbacks){const r=await s(t);r!==void 0&&(t=r)}return t}async cancel(){var e;try{const t=await this.jobManager.cancelJob(this.jobData.id,(e=this.jobData.links)==null?void 0:e.cancel);return t&&this.fail(new Error("Job cancelled by user")),t}catch{return!1}}get id(){return this.jobData.id}get status(){return this.jobData.status}get progress(){return this.jobData.progress}get message(){return this.jobData.message}get phase(){return this.processingState.phase}then(e,t){return this.promise.then(e,t)}}const S=class S{constructor(e){n(this,"requestHandler");n(this,"config");n(this,"jobs");n(this,"trackedJobs");this.requestHandler=e,this.config=D.getInstance(),this.jobs=new Map,this.trackedJobs=new Map}static getInstance(e){return S.instance||(S.instance=new S(e??new T)),S.instance}async submitJob(e,t,s){const r=await this.requestHandler.requestEndpoint(e,t,s);return this.jobs.set(r.id,r),r}async refreshStatus(e,t){return this.requestHandler.refreshStatus(e,t)}async cancelJob(e,t){var r,i;const s=t||((i=(r=this.jobs.get(e))==null?void 0:r.links)==null?void 0:i.cancel);try{return await this.requestHandler.cancelJob(e,s),this.jobs.delete(e),this.trackedJobs.delete(e),!0}catch{return!1}}getTrackedJob(e){return this.trackedJobs.get(e)}createTrackedJob(e,t,s,r=!0){const i=new R(e,this,t,s,r);return e.id&&(this.trackedJobs.set(e.id,i),this.jobs.set(e.id,e)),i}getOrCreateTrackedJob(e,t,s,r=!0){const i=e.id?this.getTrackedJob(e.id):void 0;return i||this.createTrackedJob(e,t,s,r)}getAllJobs(){return Array.from(this.trackedJobs.values())}getJob(e){return this.trackedJobs.get(e)}clearCompletedJobs(){for(const[e,t]of this.jobs.entries())(t.status===u.COMPLETED||t.status===u.FAILED)&&(this.jobs.delete(e),this.trackedJobs.delete(e))}};n(S,"instance");let L=S;function q(d,e,t,s){let r=d.toLowerCase();r=r.replace(/\\/g,"/");const i=E=>E.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c=i(t),a=new RegExp(`[^a-z0-9${c}]+`,"g");r=r.replace(a,e);const h=new Set(t+e);for(const E of h){const y=i(E),p=new RegExp(`${y}+`,"g");r=r.replace(p,E)}const f=i(s+e),m=new RegExp(`^[${f}]+|[${f}]+$`,"g");return r=r.replace(m,""),r}function J(d,e=!1){let t=q(d,"-",e?"/":"","-");return t=t.replace(/^\/+|\/+$/g,""),t.length===0?"no_name":t}class v{constructor(e){n(this,"requestHandler");n(this,"config");n(this,"endpoints");n(this,"jobManager");n(this,"serviceId");n(this,"name");this.serviceId=e,this.name=J(e,!0),this.config=D.getInstance(),this.requestHandler=new T,this.endpoints=new Map,this.jobManager=L.getInstance(this.requestHandler),this.registerEndpoints(),O.registerClient(this)}registerEndpoint(e){const t={...e},s=J(t.path,!0);t.path=`${this.serviceId}/${s}`,this.endpoints.set(s,t)}getEndpoint(e){const t=J(e,!0),s=this.endpoints.get(t);if(!s)throw new Error(`Unknown endpoint: ${e}`);return s}updateConfig(e){D.update(e)}async submitTrackedJob(e,t,s,r,i=!0){const c=await this.jobManager.submitJob(e,t,r);return new R(c,this.jobManager,e,s,i)}async runEndpoint(e,t,s,r,i=!0,c){const a=this.getEndpoint(e),h=await this.jobManager.submitJob(a,t,s),f=this.jobManager.getOrCreateTrackedJob(h,a,r,i);return this.wireCallbacks(f,c),await f}async resumeJobTracking(e,t,s,r=!0,i){const c=this.getEndpoint(e),h=this.jobManager.getTrackedJob(t)??this.jobManager.getOrCreateTrackedJob({id:t,status:u.QUEUED,progress:0,message:null},c,s,r);return this.wireCallbacks(h,i),await h}wireCallbacks(e,t){t&&(t.onProgress&&e.onProgress(t.onProgress),t.onStatus&&e.onStatus(t.onStatus),t.onProcessingUpdated&&e.onProcessingUpdated(t.onProcessingUpdated),t.onCompleted&&e.onCompleted(t.onCompleted),t.onFailed&&e.onFailed(t.onFailed),t.onJobSubmitted&&t.onJobSubmitted(e))}getJobs(){return this.jobManager.getAllJobs()}getJob(e){return this.jobManager.getJob(e)}async cancelJob(e){return this.jobManager.cancelJob(e)}}class B extends v{constructor(t,s){super(t);n(this,"eps");this.eps=s,this.registerEndpoints()}registerEndpoints(){if(this.eps)for(const t of this.eps)this.registerEndpoint(t)}}const b=class b{constructor(){n(this,"registeredClients",new Map);n(this,"clientConstructors",new Map)}static getInstance(){return b.instance||(b.instance=new b),b.instance}static registerClientType(e,t){const s=b.getInstance(),r=b.normalizeClientName(e);s.clientConstructors.set(r,t)}static registerClient(e){const t=b.getInstance(),s=b.normalizeClientName(e.name);t.registeredClients.set(s,e)}static getClient(e){const t=b.getInstance(),s=b.normalizeClientName(e);let r=t.registeredClients.get(s);if(!r){const i=t.clientConstructors.get(s);if(!i)throw new Error(`Client "${e}" not found. Available clients: ${Array.from(t.clientConstructors.keys()).join(", ")}`);r=new i,t.registeredClients.set(s,r)}return r}static getAvailableClients(){const e=b.getInstance();return Array.from(e.clientConstructors.keys())}static normalizeClientName(e){return e.toLowerCase().replace(/[^a-z0-9-]/g,"")}static createDynamicClient(e,t){const s=new B(e,t);return this.registerClient(s),s}};n(b,"instance");let O=b;class K{constructor(e={}){D.update(e)}getAvailableModels(){return O.getAvailableClients()}}class k extends K{constructor(t={}){super(t);n(this,"_jobManager")}get jobManager(){return this._jobManager||(this._jobManager=L.getInstance()),this._jobManager}setApiKey(t){D.update({apiKey:t})}setBaseUrl(t){D.update({baseUrl:t})}getJobs(){return this.jobManager.getAllJobs()}getJob(t){return this.jobManager.getJob(t)}async cancelJob(t){return this.jobManager.cancelJob(t)}}const $=new k;typeof window<"u"&&(window.socaity=$),typeof process<"u"&&process.on&&typeof process.on=="function"&&process.on("uncaughtException",d=>{if(d.name==="ApiKeyError")console.error(`${d.name}: ${d.message}`),process.exit(1);else throw d}),Object.defineProperty(l,"Asset3DFile",{enumerable:!0,get:()=>o.Asset3DFile}),Object.defineProperty(l,"AudioFile",{enumerable:!0,get:()=>o.AudioFile}),Object.defineProperty(l,"MediaFile",{enumerable:!0,get:()=>o.MediaFile}),Object.defineProperty(l,"MediaFileFactory",{enumerable:!0,get:()=>o.MediaFileFactory}),Object.defineProperty(l,"MediaList",{enumerable:!0,get:()=>o.MediaList}),Object.defineProperty(l,"VideoFile",{enumerable:!0,get:()=>o.VideoFile}),Object.defineProperty(l,"detectCategoryFromMimeType",{enumerable:!0,get:()=>o.detectCategoryFromMimeType}),Object.defineProperty(l,"detectMimeTypeFromUrl",{enumerable:!0,get:()=>o.detectMimeTypeFromUrl}),Object.defineProperty(l,"getAcceptedTypes",{enumerable:!0,get:()=>o.getAcceptedTypes}),Object.defineProperty(l,"getCategoryDisplayName",{enumerable:!0,get:()=>o.getCategoryDisplayName}),Object.defineProperty(l,"getMimeTypeFromExtension",{enumerable:!0,get:()=>o.getMimeTypeFromExtension}),Object.defineProperty(l,"isFileReaderObject",{enumerable:!0,get:()=>o.isFileReaderObject}),Object.defineProperty(l,"isFileResult",{enumerable:!0,get:()=>o.isFileResult}),Object.defineProperty(l,"isUrl",{enumerable:!0,get:()=>o.isUrl}),l.APIClient=v,l.APIClientFactory=O,l.SocaitySDK=k,l.socaity=$,Object.defineProperty(l,Symbol.toStringTag,{value:"Module"})});
//# sourceMappingURL=socaity.umd.js.map