socaity
Version:
SDK for Generative AI. Build AI-powered applications with ease
19 lines (18 loc) • 44.8 kB
JavaScript
(function(u,y){typeof exports=="object"&&typeof module<"u"?y(exports):typeof define=="function"&&define.amd?define(["exports"],y):(u=typeof globalThis<"u"?globalThis:u||self,y(u.socaity={}))})(this,function(u){"use strict";var gt=Object.defineProperty;var yt=(u,y,w)=>y in u?gt(u,y,{enumerable:!0,configurable:!0,writable:!0,value:w}):u[y]=w;var a=(u,y,w)=>yt(u,typeof y!="symbol"?y+"":y,w);class y extends Error{constructor(t="Invalid API key format. API keys should start with 'sk_' and be 67 characters long."){super(t),this.name="ApiKeyError",Error.captureStackTrace&&Error.captureStackTrace(this,y)}}const S=class S{constructor(t={}){a(this,"apiKey");a(this,"baseUrl");a(this,"pollInterval");a(this,"maxRetries");this.apiKey=t.apiKey,this.baseUrl="https://api.socaity.ai/v1",this.pollInterval=t.pollInterval||5e3,this.maxRetries=t.maxRetries||3}static getInstance(){return S.instance||(S.instance=new S),S.instance}static update(t){if(t.apiKey!==void 0){if(!t.apiKey.startsWith("sk_")&&!t.apiKey.startsWith("tk_")&&!t.apiKey.startsWith("ey"))throw new y("Invalid authentication token. Use either a Socaity API key from https://www.socaity.ai or a valid JWT token.");if(t.apiKey.startsWith("sk_")&&!t.apiKey.startsWith("tk_")&&t.apiKey.length!==67)throw new y("Invalid API key format. API keys should be 67 characters long. Get your API key from https://www.socaity.ai")}const e=S.getInstance();Object.assign(e,t)}};a(S,"instance");let w=S;var p=(n=>(n.CREATED="CREATED",n.QUEUED="QUEUED",n.PROCESSING="PROCESSING",n.COMPLETED="COMPLETED",n.FAILED="FAILED",n.UNKNOWN="UNKNOWN",n))(p||{}),f=(n=>(n.INITIALIZING="INITIALIZING",n.PREPARING="PREPARING",n.SENDING="SENDING",n.TRACKING="TRACKING",n.PROCESSING_RESULT="PROCESSING_RESULT",n.COMPLETED="COMPLETED",n.FAILED="FAILED",n))(f||{});class et{async parse(t){if(t==null)return this.createErrorJob("No response received");if(typeof t=="string")try{const e=JSON.parse(t);return this.parseObject(e)}catch{return{id:"",status:p.COMPLETED,progress:{progress:1,message:null},result:t,createdAt:new Date,updatedAt:new Date}}return this.parseObject(t)}async parseObject(t){if(typeof t!="object"||t===null)return this.createErrorJob("Invalid response format");const e=t,r=typeof e.id=="string"?e.id:"",s=this.parseStatus(e.status),i=this.parseProgress(e,s),o=typeof e.error=="string"?e.error:null,c=typeof e.refresh_job_url=="string"?e.refresh_job_url:void 0,d=this.parseDate(e.createdAt),l=this.parseDate(e.updatedAt);return{id:r,status:s,progress:i,result:e.result,error:o,createdAt:d,updatedAt:l,refresh_job_url:c}}createErrorJob(t){const e=new Date;return{id:"",status:p.FAILED,progress:{progress:0,message:t},result:null,error:t,createdAt:e,updatedAt:e}}parseDate(t){if(t instanceof Date)return t;if(typeof t=="string"||typeof t=="number"){const e=new Date(t);if(!isNaN(e.getTime()))return e}return new Date}parseStatus(t){if(typeof t!="string"||!t)return p.UNKNOWN;const e=t.toUpperCase();return{COMPLETED:p.COMPLETED,SUCCEEDED:p.COMPLETED,FINISHED:p.COMPLETED,CREATED:p.CREATED,FAILED:p.FAILED,ERROR:p.FAILED,IN_PROGRESS:p.PROCESSING,PROCESSING:p.PROCESSING,RUNNING:p.PROCESSING,BOOTING:p.PROCESSING,QUEUED:p.QUEUED,PENDING:p.QUEUED,IN_QUEUE:p.QUEUED,STARTING:p.QUEUED}[e]||p.UNKNOWN}parseProgress(t,e){let r=0,s=null;const i=t.progress;if(typeof i=="number")r=i;else if(typeof i=="string")try{r=parseFloat(i)}catch{r=0}else if(i&&typeof i=="object"){const o=i;if(typeof o.progress=="number")r=o.progress;else if(typeof o.progress=="string")try{r=parseFloat(o.progress)}catch{r=0}s=typeof o.message=="string"?o.message:null}return isNaN(r)&&(r=0),r=Math.max(0,Math.min(1,r)),e===p.COMPLETED&&(r=1),!s&&typeof t.message=="string"&&(s=t.message),{progress:r,message:s}}}var rt=Object.defineProperty,st=(n,t,e)=>t in n?rt(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,G=(n,t,e)=>st(n,typeof t!="symbol"?t+"":t,e);function J(n){return n&&typeof n=="object"&&"file_name"in n&&"content_type"in n&&"content"in n}const A={mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",aac:"audio/aac",flac:"audio/flac",m4a:"audio/mp4",webm:"audio/webm"},E={mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",mkv:"video/x-matroska",wmv:"video/x-ms-wmv",webm:"video/webm","3gp":"video/3gpp",flv:"video/x-flv"},_={jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",tiff:"image/tiff",tif:"image/tiff",avif:"image/avif"},it={pdf:"application/pdf",txt:"text/plain",html:"text/html",htm:"text/html",json:"application/json",js:"application/javascript",css:"text/css",xml:"application/xml",zip:"application/zip",csv:"text/csv",npz:"application/octet-stream"},Z={...A,...E,..._,...it};function nt(n){const t=[];switch(n){case"audio":t.push(...Object.values(A)),t.push(...Object.keys(A).map(e=>`.${e}`));break;case"video":t.push(...Object.values(E)),t.push(...Object.keys(E).map(e=>`.${e}`));break;case"image":t.push(...Object.values(_)),t.push(...Object.keys(_).map(e=>`.${e}`));break;case"file":default:return["*/*"]}return t}function ot(n){return{audio:"Audio",video:"Video",image:"Images",file:"Files"}[n]||n}function at(n){return Object.values(A).includes(n)?"audio":Object.values(E).includes(n)?"video":Object.values(_).includes(n)?"image":null}function z(n){const t=(n.startsWith(".")?n.slice(1):n).toLowerCase();return t in Z?Z[t]:null}const C=typeof window>"u";function R(n){try{const t=new URL(n);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function ct(n){if(typeof n!="string"||!R(n))return null;try{const t=((new URL(n).pathname||"").split("/").pop()||"").split("?")[0].split("#")[0].split("."),e=t.length>1?t.pop().toLowerCase():"";return e?z(e):null}catch{return null}}function lt(n){return n.startsWith("data:")||ut(n)}function ut(n){return/^[A-Za-z0-9+/=]+$/.test(n)&&n.length%4===0}async function pt(n){if(!C)return!1;try{return(await(await import("fs/promises")).stat(n)).isFile()}catch{return!1}}function K(n){return n&&typeof n=="object"&&typeof n.data=="string"&&typeof n.type=="string"&&typeof n.name=="string"}async function Y(n){if(n==null)return null;if(Array.isArray(n)){const t=n.map(e=>Y(e));return Promise.all(t)}if(J(n))try{return await new h().fromDict(n)}catch{return n}return n}class U{static async create(t){if(t==null)throw new Error("Cannot create MediaFile from null or undefined data");const e=await U._detectContentType(t);let r=j.default;return e&&e.startsWith("image/")?r=j.image:e&&e.startsWith("audio/")?r=j.audio:e&&e.startsWith("video/")&&(r=j.video),new r().fromAny(t)}static async _detectContentType(t){var e;if(t instanceof h)return t.getContentType();if(J(t))return t.content_type;if(K(t))return t.type;if(typeof t=="string"&&R(t)){const r=(e=new URL(t).pathname.split(".").pop())==null?void 0:e.toLowerCase();if(r){const s=U._getMimeTypeFromExtension(r);if(s)return s}try{const s=await fetch(t,{method:"HEAD",headers:{"User-Agent":"MediaFile/1.0.0"}});if(s.ok){const i=s.headers.get("content-type");if(i)return i}}catch{}}if(typeof t=="string"&&t.startsWith("data:")){const r=t.match(/^data:([^;,]+)/);if(r&&r[1])return r[1]}if(typeof t=="string"&&typeof window>"u")try{const r=await import("fs/promises"),s=await import("path");await r.access(t);const i=s.extname(t).slice(1).toLowerCase();if(i){const o=U._getMimeTypeFromExtension(i);if(o)return o}}catch{}return typeof Blob<"u"&&t instanceof Blob?t.type:null}static _getMimeTypeFromExtension(t){return z(t)}}class h{constructor(t="file",e="application/octet-stream"){G(this,"content_type"),G(this,"file_name"),G(this,"_content",null),this.content_type=e,this.file_name=t}static async create(t){return U.create(t)}async fromAny(t){if(t==null)throw new Error("Cannot create MediaFile from null or undefined data");if(t instanceof h)return t;if(K(t)){if(this.file_name=t.name||"file",this.content_type=t.type,typeof t.data=="string")return this.fromBase64(t.data);throw new Error("Invalid data format in FileReader object")}if(C&&this._isBuffer(t))return this.fromBytes(t);if(typeof File<"u"&&t instanceof File){this.file_name=t.name,this.content_type=t.type||"application/octet-stream";const e=await t.arrayBuffer();return this.fromBytes(e)}if(typeof Blob<"u"&&t instanceof Blob){const e=await t.arrayBuffer();return this.fromBytes(e)}if(t instanceof ArrayBuffer||t instanceof Uint8Array)return this.fromBytes(t);if(typeof t=="string"){if(R(t))return await this.fromUrl(t);if(lt(t))return this.fromBase64(t);if(await pt(t))return await this.fromFile(t);throw typeof t=="string"?new Error("Invalid data type for MediaFile "+t):new Error("Invalid data type for MediaFile")}return J(t)?await this.fromDict(t):this}async fromFile(t){if(!C)throw new Error("Loading from file path is only supported in Node.js environment");try{const e=await(await import("fs/promises")).readFile(t),r=await import("path");return this.file_name=r.basename(t),this._content=this._bufferToArrayBuffer(e),this._setContentTypeFromFileName(),this}catch(e){throw new Error(`Failed to load file from path: ${t}. ${e.message}`)}}async fromUrl(t,e){const r=async(s,i)=>await fetch(s,{headers:i||{"User-Agent":"MediaFile/1.0.0"}});try{let s=await r(t,e);if(!s.ok){if(s.status===401||s.status===403){const o=new URL(t);o.search="",s=await r(o.toString(),e)}if(!s.ok)throw new Error(`HTTP error! Status: ${s.status}`)}this.content_type=s.headers.get("content-type")||"application/octet-stream";const i=s.headers.get("content-disposition");if(i){const o=i.match(/filename=(?:['"]?)([^'";\n]+)/i);o&&o[1]&&(this.file_name=o[1])}if(!this.file_name||this.file_name==="file"){const o=new URL(t).pathname.split("/"),c=o[o.length-1];c&&c.trim()!==""?this.file_name=decodeURIComponent(c):this.file_name="downloaded_file"}return this._content=await s.arrayBuffer(),this}catch(s){throw new Error(`Failed to load file from URL: ${t}. ${s.message}`)}}fromBase64(t){const{data:e,mediaType:r}=this._parseBase64Uri(t);r&&(this.content_type=r);try{return this._content=C?this._decodeBase64NodeJs(e):this._decodeBase64Browser(e),this}catch(s){throw new Error(`Failed to decode base64 data: ${s.message}`)}}fromBytes(t){if(typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){const e=new Uint8Array(t),r=new ArrayBuffer(e.byteLength);return new Uint8Array(r).set(e),this._content=r,this}if(t instanceof Uint8Array)if(typeof SharedArrayBuffer<"u"&&t.buffer instanceof SharedArrayBuffer){const e=new Uint8Array(t);this._content=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}else this._content=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);else if(C&&Buffer.isBuffer(t))if(typeof SharedArrayBuffer<"u"&&t.buffer instanceof SharedArrayBuffer){const e=new Uint8Array(t);this._content=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}else this._content=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);else this._content=new Uint8Array(t).buffer;return this}async fromDict(t){if(!t.content)throw new Error("Invalid FileResult object: missing content");return this.file_name=t.file_name,this.content_type=t.content_type,await this.fromAny(t.content)}toBlob(){if(this._ensureContent(),typeof Blob>"u")throw new Error("Blob is not available in this environment");return new Blob([new Uint8Array(this._content)],{type:this.content_type})}toArrayBuffer(){return this._ensureContent(),typeof SharedArrayBuffer<"u"&&this._content instanceof SharedArrayBuffer?this._content.slice(0):this._content}toUint8Array(){return this._ensureContent(),new Uint8Array(this._content)}toBuffer(){if(this._ensureContent(),!C)throw new Error("Buffer is only available in Node.js environment");return Buffer.from(this._content)}toBase64(t=!0){this._ensureContent();let e;if(C)e=Buffer.from(this._content).toString("base64");else{const r=new Uint8Array(this._content);let s="";const i=10240;for(let o=0;o<r.length;o+=i){const c=r.subarray(o,Math.min(o+i,r.length));s+=String.fromCharCode.apply(null,Array.from(c))}e=btoa(s)}return t?`data:${this.content_type};base64,${e}`:e}toJson(){return{file_name:this.file_name,content_type:this.content_type,content:this.toBase64()}}async save(t){this._ensureContent();const e=t||this.file_name;if(C)try{const r=await import("fs/promises").then(o=>o.default||o),s=await import("path").then(o=>o.default||o);if(!s||typeof s.dirname!="function")throw new Error("Failed to load 'path' module.");const i=s.dirname(e);i!=="."&&await r.mkdir(i,{recursive:!0}).catch(()=>{}),await r.writeFile(e,Buffer.from(this._content))}catch(r){throw new Error(`Failed to save file: ${r.message}`)}else{const r=this.toBlob(),s=URL.createObjectURL(r),i=document.createElement("a");i.href=s,i.download=e,document.body.appendChild(i),i.click(),setTimeout(()=>{document.body.removeChild(i),URL.revokeObjectURL(s)},100)}}fileSize(t="bytes"){if(!this._content)return 0;const e=this._content.byteLength;switch(t){case"kb":return e/1024;case"mb":return e/(1024*1024);case"gb":return e/(1024*1024*1024);default:return e}}get extension(){var t;if(this.content_type&&this.content_type!=="application/octet-stream"){const e={"image/jpeg":"jpg","image/png":"png","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","audio/mpeg":"mp3","audio/wav":"wav","audio/ogg":"ogg","video/mp4":"mp4","video/quicktime":"mov","application/pdf":"pdf","text/plain":"txt","text/html":"html","application/json":"json",npz:"npz"};if(this.content_type in e)return e[this.content_type];if(C)try{const r=require("mime-types").extension(this.content_type);if(r)return r}catch{}}return this.file_name&&this.file_name.includes(".")&&((t=this.file_name.split(".").pop())==null?void 0:t.toLowerCase())||null}getFileName(){return this.file_name}setFileName(t){this.file_name=t}getContentType(){return this.content_type}setContentType(t){this.content_type=t}read(){return this._ensureContent(),this._content}isEmpty(){return!this._content||this._content.byteLength===0}getInfo(){return{fileName:this.file_name,contentType:this.content_type,size:this.fileSize(),extension:this.extension}}_setContentTypeFromFileName(){var t;if(!this.file_name)return;const e=(t=this.file_name.split(".").pop())==null?void 0:t.toLowerCase();if(!e)return;if(C)try{const s=require("mime-types").lookup(this.file_name);if(s){this.content_type=s;return}}catch{}const r={jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",mp4:"video/mp4",mov:"video/quicktime",pdf:"application/pdf",txt:"text/plain",html:"text/html",htm:"text/html",json:"application/json",js:"application/javascript",css:"text/css",xml:"application/xml",zip:"application/zip"};e in r&&(this.content_type=r[e])}_parseBase64Uri(t){if(t.startsWith("data:")){const[e,r]=t.split(",",2),s=e.match(/^data:([^;,]+)/),i=s?s[1]:null;return{data:r,mediaType:i}}return{data:t,mediaType:null}}_ensureContent(){if(!this._content)throw new Error("No content available. Load content first using fromFile, fromUrl, etc.")}_isBuffer(t){return C&&Buffer.isBuffer(t)}_decodeBase64NodeJs(t){const e=Buffer.from(t,"base64");return this._bufferToArrayBuffer(e)}_decodeBase64Browser(t){const e=atob(t),r=new Uint8Array(e.length);for(let s=0;s<e.length;s++)r[s]=e.charCodeAt(s);return r.buffer}_bufferToArrayBuffer(t){if(typeof SharedArrayBuffer<"u"&&t.buffer instanceof SharedArrayBuffer){const e=new ArrayBuffer(t.byteLength);return new Uint8Array(e).set(new Uint8Array(t)),e}else return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}class B extends h{constructor(t="image",e="image/png"){super(t,e)}static async create(t){if(t==null)throw new Error("Cannot create ImageFile from null or undefined data");return new B().fromAny(t)}async fromAny(t){if(t instanceof B)return t;if(t instanceof h&&!(t instanceof B)){if(t.isEmpty())throw new Error("Cannot create ImageFile from empty MediaFile");return this.file_name=t.getFileName()||"image",this.content_type=t.getContentType(),this._content=t.read(),this._validateImageContentType(),this}const e=await super.fromAny(t);return e.file_name=e.file_name||"image",e._validateImageContentType(),e}toImageElement(t={}){if(typeof window>"u")throw new Error("Image elements are only available in browser environments");this._ensureContent();const e=this.toBase64(),{width:r,height:s,alt:i="",className:o=""}=t,c=r?` width="${r}"`:"",d=s?` height="${s}"`:"",l=o?` class="${o}"`:"";return`<img src="${e}" alt="${i}"${c}${d}${l}>`}toDOMImageElement(t={}){if(typeof window>"u")throw new Error("DOM Image elements are only available in browser environments");this._ensureContent();const e=this.toBlob(),r=URL.createObjectURL(e),s=new Image;return t.width&&(s.width=t.width),t.height&&(s.height=t.height),t.alt&&(s.alt=t.alt),t.className&&(s.className=t.className),s.src=r,s.addEventListener("load",()=>{setTimeout(()=>URL.revokeObjectURL(r),1e3)}),s}async getDimensions(){if(typeof window>"u")throw new Error("Getting image dimensions is only available in browser environments");return new Promise((t,e)=>{const r=new Image;r.onload=()=>{t({width:r.naturalWidth,height:r.naturalHeight})},r.onerror=()=>{e(new Error("Failed to load image for dimension calculation"))};const s=this.toBlob(),i=URL.createObjectURL(s);r.src=i,r.addEventListener("load",()=>{URL.revokeObjectURL(i)},{once:!0})})}_validateImageContentType(){var t;if(this.content_type.startsWith("image/"))return;const e=(t=this.extension)==null?void 0:t.toLowerCase();if(e&&e in _){this.content_type=_[e];return}this._content&&this._detectImageFormat()}_detectImageFormat(){const t=new Uint8Array(this._content).slice(0,12);if(t[0]===255&&t[1]===216&&t[2]===255){this.content_type=_.jpeg;return}if(t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10){this.content_type=_.png;return}if(t[0]===71&&t[1]===73&&t[2]===70&&t[3]===56&&(t[4]===55||t[4]===57)&&t[5]===97){this.content_type=_.gif;return}if(t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80){this.content_type=_.webp;return}if(this._content.byteLength>100&&new TextDecoder().decode(new Uint8Array(this._content.slice(0,100))).indexOf("<svg")!==-1){this.content_type=_.svg;return}this.content_type=_.png}}class L extends h{constructor(t="audio",e="audio/wav"){super(t,e)}static async create(t){if(t==null)throw new Error("Cannot create AudioFile from null or undefined data");return new L().fromAny(t)}async fromAny(t){if(t instanceof L)return t;if(t instanceof h&&!(t instanceof L)){if(t.isEmpty())throw new Error("Cannot create AudioFile from empty MediaFile");return this.file_name=t.getFileName()||"audio",this.content_type=t.getContentType(),this._content=t.read(),this._validateAudioContentType(),this}const e=await super.fromAny(t);return e.file_name=e.file_name||"audio",e._validateAudioContentType(),e}toAudioElement(){if(typeof window>"u")throw new Error("Audio elements are only available in browser environments");this._ensureContent();const t=this.toBlob(),e=URL.createObjectURL(t),r=new Audio(e);return r.addEventListener("canplaythrough",()=>{setTimeout(()=>URL.revokeObjectURL(e),1e3)}),r}async play(){if(typeof window>"u")throw new Error("Audio playback is only available in browser environments");const t=this.toAudioElement();return new Promise((e,r)=>{t.addEventListener("play",()=>e()),t.addEventListener("error",s=>r(new Error(`Audio playback error: ${s}`))),t.play().catch(r)})}async getDuration(){if(typeof window>"u")throw new Error("Getting audio duration is only available in browser environments");const t=this.toAudioElement();return new Promise(e=>{if(t.duration&&!isNaN(t.duration)){e(t.duration);return}t.addEventListener("loadedmetadata",()=>{e(t.duration)})})}toHTMLPlayer(t={}){const e=this.toBase64(),{controls:r=!0,autoplay:s=!1,loop:i=!1}=t;return`<audio
src="${e}"
${r?"controls":""}
${s?"autoplay":""}
${i?"loop":""}>
Your browser does not support the audio element.
</audio>`}_validateAudioContentType(){var t;if(this.content_type.startsWith("audio/"))return;const e=(t=this.extension)==null?void 0:t.toLowerCase();if(e&&e in A){this.content_type=A[e];return}this._content&&this._detectAudioFormat()}_detectAudioFormat(){const t=new Uint8Array(this._content).slice(0,12);if(t[0]===73&&t[1]===68&&t[2]===51){this.content_type=A.mp3;return}if(t[0]===255&&(t[1]&224)===224){this.content_type=A.mp3;return}if(t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===65&&t[10]===86&&t[11]===69){this.content_type=A.wav;return}if(t[0]===79&&t[1]===103&&t[2]===103&&t[3]===83){this.content_type=A.ogg;return}if(t[0]===102&&t[1]===76&&t[2]===97&&t[3]===67){this.content_type=A.flac;return}this.content_type=A.mp3}}class F extends h{constructor(t="video",e="video/mp4"){super(t,e)}static async create(t){if(t==null)throw new Error("Cannot create VideoFile from null or undefined data");return new F().fromAny(t)}async fromAny(t){if(t instanceof F)return t;if(t instanceof h&&!(t instanceof F)){if(t.isEmpty())throw new Error("Cannot create VideoFile from empty MediaFile");return this.file_name=t.getFileName()||"video",this.content_type=t.getContentType(),this._content=t.read(),this._validateVideoContentType(),this}const e=await super.fromAny(t);return e.file_name=e.file_name||"video",e._validateVideoContentType(),e}toVideoElement(){if(typeof window>"u")throw new Error("Video elements are only available in browser environments");this._ensureContent();const t=this.toBlob(),e=URL.createObjectURL(t),r=document.createElement("video");return r.src=e,r.addEventListener("loadedmetadata",()=>{setTimeout(()=>URL.revokeObjectURL(e),1e3)}),r}async play(){if(typeof window>"u")throw new Error("Video playback is only available in browser environments");const t=this.toVideoElement();return new Promise((e,r)=>{t.addEventListener("play",()=>e()),t.addEventListener("error",s=>r(new Error(`Video playback error: ${s}`))),t.play().catch(r)})}async getDuration(){if(typeof window>"u")throw new Error("Getting video duration is only available in browser environments");const t=this.toVideoElement();return new Promise(e=>{if(t.duration&&!isNaN(t.duration)){e(t.duration);return}t.addEventListener("loadedmetadata",()=>{e(t.duration)})})}async getDimensions(){if(typeof window>"u")throw new Error("Getting video dimensions is only available in browser environments");const t=this.toVideoElement();return new Promise(e=>{if(t.videoWidth&&t.videoHeight){e({width:t.videoWidth,height:t.videoHeight});return}t.addEventListener("loadedmetadata",()=>{e({width:t.videoWidth,height:t.videoHeight})})})}async createThumbnail(t=0){if(typeof window>"u")throw new Error("Creating thumbnails is only available in browser environments");const e=this.toVideoElement();return new Promise((r,s)=>{e.addEventListener("loadedmetadata",async()=>{try{e.currentTime=t,await new Promise(c=>{const d=()=>{e.removeEventListener("seeked",d),c()};e.addEventListener("seeked",d)});const i=document.createElement("canvas");i.width=e.videoWidth,i.height=e.videoHeight;const o=i.getContext("2d");if(!o)throw new Error("Failed to get canvas context");o.drawImage(e,0,0,i.width,i.height),i.toBlob(c=>{c?r(c):s(new Error("Failed to create thumbnail blob"))},"image/jpeg",.95)}catch(i){s(i)}}),e.addEventListener("error",i=>{s(new Error(`Video loading error: ${i}`))})})}toHtmlPlayer(t={}){const e=this.toBase64(),{controls:r=!0,autoplay:s=!1,loop:i=!1,muted:o=!1,width:c,height:d,poster:l}=t;return`<video
src="${e}"
${r?"controls":""}
${s?"autoplay":""}
${i?"loop":""}
${o?"muted":""}
${c?`width="${c}"`:""}
${d?`height="${d}"`:""}
${l?`poster="${l}"`:""}>
Your browser does not support the video element.
</video>`}_validateVideoContentType(){var t;if(this.content_type.startsWith("video/"))return;const e=(t=this.extension)==null?void 0:t.toLowerCase();if(e&&e in E){this.content_type=E[e];return}this._content&&this._detectVideoFormat()}_detectVideoFormat(){const t=new Uint8Array(this._content).slice(0,16);if(t[4]===102&&t[5]===116&&t[6]===121&&t[7]===112){this.content_type=E.mp4;return}if(t[4]===119&&t[5]===105&&t[6]===100&&t[7]===101||t[4]===109&&t[5]===100&&t[6]===97&&t[7]===116||t[4]===102&&t[5]===114&&t[6]===101&&t[7]===101||t[4]===112&&t[5]===110&&t[6]===111&&t[7]===116||t[4]===115&&t[5]===107&&t[6]===105&&t[7]===112||t[4]===109&&t[5]===111&&t[6]===111&&t[7]===118){this.content_type=E.mov;return}if(t[0]===26&&t[1]===69&&t[2]===223&&t[3]===163){this.content_type=E.webm;return}if(t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===65&&t[9]===86&&t[10]===73&&t[11]===32){this.content_type=E.avi;return}if(t[0]===70&&t[1]===76&&t[2]===86){this.content_type=E.flv;return}if(t[4]===102&&t[5]===116&&t[6]===121&&t[7]===112&&t[8]===51&&t[9]===103&&t[10]===112){this.content_type=E["3gp"];return}this.content_type=E.mp4}}const j={};j.default=h,j.image=B,j.audio=L,j.video=F,j.media=h,typeof window<"u"&&(window.MediaFile=h,window.ImageFile=B,window.AudioFile=L,window.AudioFile=F),typeof module<"u"&&typeof module.exports<"u"&&(module.exports={MediaFile:h,ImageFile:B,AudioFile:L,VideoFile:F,MediaFileFactory:U});class ht{constructor(t){a(this,"uploadEndpoint");a(this,"apiKey");a(this,"defaultTimeout",6e4);this.uploadEndpoint=t.uploadEndpoint||"https://api.socaity.ai/sdk/v1/files",this.apiKey=t.apiKey}setApiKey(t){this.apiKey=t}getAuthHeaders(){return{Authorization:`Bearer ${this.apiKey}`}}async processUploadResponse(t){if(t.status===401)throw new Error("Unauthorized: Invalid API key");if(!t.ok)throw console.error("Failed to get temporary upload URL:",t),new Error(`Failed to get temporary upload URL: ${t.status} ${t.statusText}`);try{const e=await t.text(),r=JSON.parse(e);return Array.isArray(r)?r:[r]}catch(e){throw console.error("Error parsing response:",e),new Error("Failed to parse response body as JSON")}}async uploadToTemporaryUrl(t,e){const r={"x-ms-blob-type":"BlockBlob","x-ms-if-none-match":"*"},s=e instanceof h?await e.toArrayBuffer():e,i=await fetch(t,{method:"PUT",headers:r,body:s});if(i.status!==201)throw new Error(`Failed to upload to temporary URL ${t}. Response: ${i.statusText}`)}async upload(t){const e=Array.isArray(t)?t:[t],r=e.map(l=>l.extension).filter(l=>l!==null),s={"Content-Type":"application/json",...this.getAuthHeaders()},i=await fetch(this.uploadEndpoint,{method:"POST",headers:s,body:JSON.stringify({n_files:e.length,file_extensions:r.length>0?r:void 0}),signal:AbortSignal.timeout(this.defaultTimeout)}),o=await this.processUploadResponse(i),c=o.map((l,I)=>this.uploadToTemporaryUrl(l,e[I]));return await Promise.all(c),o.map(l=>l.split("?")[0])}async download(t,e){const r=await new h(t).fromUrl(t,this.getAuthHeaders());return e?(await r.save(e),e):r}}class X{constructor(){a(this,"config");a(this,"uploadFileThresholdMB",1);a(this,"maxFileUploadLimitMB",1e3);a(this,"fastCloud");a(this,"abortController");a(this,"responseParser");this.config=w.getInstance(),this.abortController=new AbortController,this.responseParser=new et,this.fastCloud=new ht({uploadEndpoint:`${this.config.baseUrl}/sdk/files`,apiKey:this.config.apiKey?this.config.apiKey:""})}isFileType(t,e){const r=["file","image","audio","video"];if(typeof t.type=="string"){const s=this.getBaseType(t.type);if(r.includes(s))return!0}return Array.isArray(t.type)&&t.type.some(i=>{const o=this.getBaseType(i);return r.includes(o)})||e instanceof h?!0:e==null?!1:!!(e instanceof File||e instanceof Blob||typeof e=="string"&&R(e))}getBaseType(t){if(!t)return"string";const e=t.match(/^List\[(.+)\]$/i);return e&&e[1]?e[1].toLowerCase():t.toLowerCase()}async formatRequestParams(t,e){const r={queryParams:{},bodyParams:{},fileParams:{},headers:{},url:""};if(!t.parameters||t.parameters.length===0)return r.url=this.buildRequestUrl(t.path,r.queryParams),r;for(const s of t.parameters){const i=e[s.name]??s.default;if(i===void 0&&s.required)throw new Error(`Required parameter '${s.name}' is missing`);if(i===void 0)continue;if(this.isFileType(s,i)){if(i==null){r.bodyParams[s.name]=null;continue}if(typeof i=="string"&&R(i))r.fileParams[s.name]=i;else try{const c=i instanceof h?i:await U.create(i);c instanceof h&&(r.fileParams[s.name]=c)}catch(c){console.warn(`Failed to convert ${s.name} to MediaFile:`,c),s.location==="query"?r.queryParams[s.name]=i:r.bodyParams[s.name]=i}}else s.location==="query"?r.queryParams[s.name]=i:r.bodyParams[s.name]=i}return r.fileParams=await this.processFileParams(r.fileParams),r.url=this.buildRequestUrl(t.path,r.queryParams),r}async processFileParams(t){const e={};let r=0;const s={};for(const[i,o]of Object.entries(t))typeof o=="string"&&R(o)?e[i]=o:o instanceof h&&(s[i]=o,r+=o.fileSize("mb"));if(r>this.maxFileUploadLimitMB)throw new Error(`Total file size exceeds maximum limit of ${this.maxFileUploadLimitMB}MB`);if(r>this.uploadFileThresholdMB){const i=Object.values(s),o=await this.fastCloud.upload(i);Object.keys(s).forEach((c,d)=>{e[c]=o[d]})}else for(const[i,o]of Object.entries(s))e[i]=o.toBlob();return e}buildRequestUrl(t,e){let r=`${this.config.baseUrl}/${t}`;const s=this.buildQueryString(e);return s?`${r}?${s}`:r}matchParams(t,e){const r={};for(const[s,i]of Object.entries(t))s in e?r[s]=e[s]:i!==void 0&&(r[s]=i);return r}validateAPIKey(t){const e=t||this.config.apiKey;if(!e)throw new Error("API key not provided");return this.fastCloud.setApiKey(e),e}buildQueryString(t){if(!t||Object.keys(t).length===0)return"";const e=new URLSearchParams;for(const[s,i]of Object.entries(t))i!=null&&(i instanceof h?e.append(s,i.toBase64()):typeof i=="object"?e.append(s,JSON.stringify(i)):e.append(s,String(i)));const r=e.toString();return r?`?${r}`:""}async formatErrorResponse(t){const e=t.status;let r;try{const s=t.headers.get("content-type");if(s&&s.includes("application/json")){const i=await t.json();r=JSON.stringify(i)}else r=await t.text()}catch(s){console.log("error",s),r="Could not parse error response"}return console.log("errorText",r),new Error(`API error (${e}): ${r}`)}async sendRequest(t,e="POST",r={},s={},i={},o){const c=this.validateAPIKey(o);this.abortController=new AbortController;const{signal:d}=this.abortController,l={Authorization:`Bearer ${c}`};let I=`${this.config.baseUrl}/${t}`,g=null;if(e==="GET"){const m={...r,...s,...i};I+=this.buildQueryString(m)}else{I+=this.buildQueryString(r);const m=new FormData,T={...s,...i};for(const[v,P]of Object.entries(T))P!=null&&(P instanceof Blob||P instanceof File?m.append(v,P):typeof P=="object"?m.append(v,new Blob([JSON.stringify(P)],{type:"application/json"})):m.append(v,String(P)));g=m}try{const m=setTimeout(()=>this.abort(),3e4);console.log("Sending request to:",I,g);const T=await fetch(I,{method:e,headers:l,body:g,signal:d});if(clearTimeout(m),!T.ok)throw await this.formatErrorResponse(T);const v=T.headers.get("content-type");return v!=null&&v.includes("application/json")?await T.json():await T.text()}catch(m){throw m instanceof DOMException&&m.name==="AbortError"?new Error("Request canceled"):m instanceof Error?m:new Error(`Network error: ${String(m)}`)}}async request_endpoint(t,e,r){const s=await this.formatRequestParams(t,e),i=await this.sendRequest(t.path,t.method,s.queryParams,s.bodyParams,s.fileParams,r);return this.responseParser.parse(i)}async refresh_status(t,e){let r;if(e){console.log("refresh_url",e);const s=await this.requestUrl(e,"POST");if(!s.ok)throw await this.formatErrorResponse(s);const i=s.headers.get("content-type");i!=null&&i.includes("application/json")?r=await s.json():r=await s.text()}else r=await this.sendRequest("status","POST",{job_id:t});return this.responseParser.parse(r)}async requestUrl(t,e="GET",r,s=60,i,o){const c=this.validateAPIKey(i);!t.startsWith("http://")&&!t.startsWith("https://")&&(t=`${this.config.baseUrl}/${t.replace(/^\//,"")}`),console.log("Request URL:",t,o);const d={Authorization:`Bearer ${c}`};this.abortController=new AbortController;const{signal:l}=this.abortController,I=setTimeout(()=>{this.abort()},s*1e3);try{const g=e.toUpperCase();let m={method:g,headers:d,signal:l};if(g==="GET"){if(o){const v=this.buildQueryString(o);t+=v?`?${v}`:""}}else if(r){const v=new FormData;Object.entries(r).forEach(([P,Q])=>{Q!=null&&v.append(P,Q)}),m.body=v}else o&&(d["Content-Type"]="application/json",m.body=JSON.stringify(o));const T=await fetch(t,m);return clearTimeout(I),T}catch(g){throw clearTimeout(I),g instanceof DOMException&&g.name==="AbortError"?new Error("Request canceled"):g instanceof Error?g:new Error(`Network error: ${String(g)}`)}}abort(){this.abortController.abort(),this.abortController=new AbortController}}const N=class N{constructor(t){a(this,"requestHandler");a(this,"config");a(this,"jobs");a(this,"mediaHandler");this.requestHandler=t,this.config=w.getInstance(),this.jobs=new Map,this.mediaHandler=new h}static getInstance(t){return N.instance||(t||(t=new X),N.instance=new N(t)),N.instance}async submitJob(t,e,r){try{const s=await this.requestHandler.request_endpoint(t,e,r);return this.jobs.set(s.id,s),s}catch(s){throw s instanceof Error?s:new Error(`Failed to submit job: ${String(s)}`)}}getAllJobs(){return Array.from(this.jobs.values())}getJob(t){return this.jobs.get(t)}async cancelJob(t){try{return await this.requestHandler.sendRequest("cancel","GET",{job_id:t}),this.jobs.delete(t),!0}catch{return!1}}clearCompletedJobs(){for(const[t,e]of this.jobs.entries())(e.status===p.COMPLETED||e.status===p.FAILED)&&this.jobs.delete(t)}};a(N,"instance");let k=N;const D=typeof process<"u"&&process.stdout&&process.stdout.clearLine;let M;if(D)try{M=require("cli-progress")}catch{console.warn("cli-progress package not found. Using basic console output for progress.")}const O=class O{constructor(){a(this,"multiBar");a(this,"bars",new Map);a(this,"isInitialized",!1);D&&M&&(this.multiBar=new M.MultiBar({clearOnComplete:!1,hideCursor:!0,format:"{bar} {percentage}% | {jobId} | {phase} | {message}"}),this.isInitialized=!0)}static getInstance(){return O.instance||(O.instance=new O),O.instance}createBar(t,e){if(!this.isInitialized)return null;const r=this.multiBar.create(100,0,{jobId:t,phase:e,message:"Starting..."});return this.bars.set(t,r),r}updateBar(t,e,r){const s=this.bars.get(t);s&&s.update(e,r)}removeBar(t){const e=this.bars.get(t);e&&(e.stop(),this.multiBar.remove(e),this.bars.delete(t))}stopAll(){this.isInitialized&&(this.multiBar.stop(),this.bars.clear())}};a(O,"instance");let W=O;class tt{constructor(t,e,r,s,i=!0){a(this,"apiJob");a(this,"endpoint");a(this,"processingState");a(this,"jobManager");a(this,"result",null);a(this,"error",null);a(this,"completed",!1);a(this,"resolvePromise");a(this,"rejectPromise");a(this,"promise");a(this,"eventListeners",new Map);a(this,"verbose");a(this,"progressBar",null);a(this,"progressBarManager");a(this,"parseResultCallbacks",[]);a(this,"_pollErrorCount",0);a(this,"_lastLoggedMessage",null);this.apiJob=t,this.jobManager=e,this.endpoint=r,this.verbose=i,this.processingState={phase:f.INITIALIZING,progress:0},this.progressBarManager=W.getInstance(),this.eventListeners=new Map,this.promise=new Promise((o,c)=>{this.resolvePromise=o,this.rejectPromise=c}),s&&this.onParseResult(s),this.verbose&&this.initProgressDisplay(),setTimeout(()=>this.startTracking(),0)}initProgressDisplay(){this.verbose&&(D&&M?(this.progressBar=this.progressBarManager.createBar(this.apiJob.id||"initializing",this.processingState.phase),this.updateProgressDisplay()):this.logProgress())}updateProgressDisplay(){if(!this.verbose)return;const t=this.processingState.phase,e=this.calculateProgressPercent(),r=this.formatProgressMessage();D&&M&&this.progressBar?this.progressBarManager.updateBar(this.apiJob.id,e,{phase:t,message:r.replace(/^.*\| /,"")}):this.logProgress()}calculateProgressPercent(){var e;const t=this.processingState.phase;if(t===f.TRACKING&&((e=this.apiJob.progress)!=null&&e.progress))return Math.round(this.apiJob.progress.progress*100);switch(t){case f.INITIALIZING:return 0;case f.PREPARING:return 5;case f.SENDING:return 10;case f.TRACKING:return 15;case f.PROCESSING_RESULT:return 90;case f.COMPLETED:return 100;case f.FAILED:return 100;default:return 0}}formatProgressMessage(){var r;const t=this.processingState.phase,e=this.apiJob.id||"initializing";if(t===f.INITIALIZING||t===f.PREPARING||t===f.SENDING)return`${t} job | API: ${this.endpoint.path}`;if(t===f.TRACKING){const s=this.apiJob.progress?`${Math.round(this.apiJob.progress.progress*100)}%`:"unknown";let i=`Job ${e} | Progress: ${s} | API: ${this.endpoint.path}`;return(r=this.apiJob.progress)!=null&&r.message&&(i+=` | ${this.apiJob.progress.message}`),i}else return`Job ${e} | ${t} | API: ${this.endpoint.path}`}logProgress(){const t=this.formatProgressMessage();(!this._lastLoggedMessage||this._lastLoggedMessage!==t)&&(console.log(t),this._lastLoggedMessage=t)}stopProgressDisplay(){if(!this.verbose)return;D&&M&&this.progressBar&&(this.progressBarManager.removeBar(this.apiJob.id),this.progressBar=null);const t=this.processingState.phase;t===f.COMPLETED?console.log(`✓ Job ${this.apiJob.id} completed successfully (${this.endpoint.path})`):t===f.FAILED&&console.log(`✗ Job ${this.apiJob.id} failed: ${this.processingState.message} (${this.endpoint.path})`)}on(t,e){return this.eventListeners.has(t)||this.eventListeners.set(t,[]),this.eventListeners.get(t).push(e),this}emit(t,...e){const r=this.eventListeners.get(t);r&&r.forEach(s=>s(...e))}async pollJobStatus(){if(!(this.completed||!this.apiJob.id))try{console.log("Polling job status for:",this.apiJob);const t=await this.jobManager.requestHandler.refresh_status(this.apiJob.id,this.apiJob.refresh_job_url);if(!t){setTimeout(()=>this.pollJobStatus(),this.jobManager.config.pollInterval);return}if(this.apiJob=t,this._pollErrorCount=0,this.emitJobUpdate(),this.verbose&&this.updateProgressDisplay(),t.status===p.COMPLETED){this.updateProcessingState(f.PROCESSING_RESULT,.9,"Processing result");try{this.result=await Y(t.result),this.result=await this.runParseResultCallbacks(this.result),this.complete()}catch(e){this.fail(e instanceof Error?e:new Error(String(e)))}}else t.status===p.FAILED?(this.updateProcessingState(f.FAILED,1,t.error||"Job failed"),this.fail(new Error(t.error||"Job failed with no error message"))):setTimeout(()=>this.pollJobStatus(),this.jobManager.config.pollInterval)}catch(t){if(console.error("Network error while polling job status:",t),this._pollErrorCount++,this._pollErrorCount>=5){console.error("Too many consecutive network errors, stopping job tracking"),this.fail(new Error(`Network polling failed after ${this._pollErrorCount} attempts: ${t instanceof Error?t.message:String(t)}`));return}setTimeout(()=>this.pollJobStatus(),this.jobManager.config.pollInterval)}}startTracking(){this.updateProcessingState(f.TRACKING,0,"Tracking job status"),this.pollJobStatus()}complete(){this.updateProcessingState(f.COMPLETED,1,"Job completed"),this.cleanup(),this.completed=!0,this.emit("completed",this.result),this.resolvePromise(this.result)}fail(t){this.updateProcessingState(f.FAILED,1,t.message),this.cleanup(),this.completed=!0,this.error=t,this.emit("failed",t),this.rejectPromise(t)}cleanup(){this.stopProgressDisplay()}updateProcessingState(t,e,r){this.processingState={phase:t,progress:e,message:r},this.verbose&&this.updateProgressDisplay(),this.emit("processingUpdated",this.processingState)}emitJobUpdate(){this.emit("progressUpdated",this.apiJob.progress),this.emit("statusUpdated",this.apiJob.status)}setVerbose(t){return this.verbose=t,t&&!this.progressBar&&!this.completed?this.initProgressDisplay():!t&&this.progressBar&&this.stopProgressDisplay(),this}onCompleted(t){return this.on("completed",t),this.completed&&this.result!==null&&setTimeout(()=>t(this.result),0),this}onFailed(t){return this.on("failed",t),this.completed&&this.error!==null&&setTimeout(()=>t(this.error),0),this}onProgress(t){return this.on("progressUpdated",t),setTimeout(()=>t(this.apiJob.progress),0),this}onStatus(t){return this.on("statusUpdated",t),setTimeout(()=>t(this.apiJob.status),0),this}onProcessingUpdated(t){return this.on("processingUpdated",t),setTimeout(()=>t(this.processingState),0),this}onParseResult(t){return this.parseResultCallbacks.push(t),this}async runParseResultCallbacks(t){let e=t;for(const r of this.parseResultCallbacks){const s=await r(e);s!==void 0&&(e=s)}return e}async cancel(){try{const t=await this.jobManager.cancelJob(this.apiJob.id);return t&&(this.cleanup(),this.fail(new Error("Job cancelled by user"))),t}catch{return!1}}get id(){return this.apiJob.id}get status(){return this.apiJob.status}get progress(){return this.apiJob.progress||null}get phase(){return this.processingState.phase}then(t,e){return this.promise.then(t,e)}}function ft(n,t,e,r){let s=n.toLowerCase();s=s.replace(/\\/g,"/");const i=g=>g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=i(e),c=new RegExp(`[^a-z0-9${o}]+`,"g");s=s.replace(c,t);const d=new Set(e+t);for(const g of d){const m=i(g),T=new RegExp(`${m}+`,"g");s=s.replace(T,g)}const l=i(r+t),I=new RegExp(`^[${l}]+|[${l}]+$`,"g");return s=s.replace(I,""),s&&/^\d/.test(s)&&(s=t+s),s}function x(n,t=!1){let e=ft(n,"-",t?"/":"","-");return e=e.replace(/^\/+|\/+$/g,""),e.length===0?"no_name":e}class H{constructor(t){a(this,"requestHandler");a(this,"config");a(this,"endpoints");a(this,"jobManager");a(this,"name");this.name=x(t,!0),this.config=w.getInstance(),this.requestHandler=new X,this.endpoints=new Map,this.jobManager=k.getInstance(this.requestHandler),this.registerEndpoints(),$.registerClient(this)}registerEndpoint(t){const e={...t},r=x(e.path,!0);e.path=x(this.name+"/"+r,!0),this.endpoints.set(r,e)}getEndpoint(t){t=x(t,!0);const e=this.endpoints.get(t);if(!e)throw new Error(`Unknown endpoint: ${t}`);return e}updateConfig(t){w.update(t)}async submitTrackedJob(t,e,r,s,i=!0){const o=await this.jobManager.submitJob(t,e,s);return new tt(o,this.jobManager,t,r,i)}async runEndpoint(t,e,r,s,i=!0,o){const c=this.getEndpoint(t);if(!c)throw new Error(`Unknown endpoint: ${t}`);const d=await this.jobManager.submitJob(c,e,r),l=new tt(d,this.jobManager,c,s,i);return o&&(o.onProgress&&l.onProgress(o.onProgress),o.onStatus&&l.onStatus(o.onStatus),o.onProcessingUpdated&&l.onProcessingUpdated(o.onProcessingUpdated),o.onCompleted&&l.onCompleted(o.onCompleted),o.onFailed&&l.onFailed(o.onFailed)),await l}getJobs(){return this.jobManager.getAllJobs()}getJob(t){return this.jobManager.getJob(t)}async cancelJob(t){return this.jobManager.cancelJob(t)}}class dt extends H{constructor(e,r){super(e);a(this,"eps");this.eps=r,this.registerEndpoints()}registerEndpoints(){if(this.eps)for(let e of this.eps)this.registerEndpoint(e)}}const b=class b{constructor(){a(this,"registeredClients",new Map);a(this,"clientConstructors",new Map)}static getInstance(){return b.instance||(b.instance=new b),b.instance}static registerClientType(t,e){const r=b.getInstance(),s=b.normalizeClientName(t);r.clientConstructors.set(s,e)}static registerClient(t){const e=b.getInstance(),r=b.normalizeClientName(t.name);e.registeredClients.set(r,t)}static getClient(t){const e=b.getInstance(),r=b.normalizeClientName(t);let s=e.registeredClients.get(r);if(!s){const i=e.clientConstructors.get(r);if(!i)throw new Error(`Client "${t}" not found. Available clients: ${Array.from(e.clientConstructors.keys()).join(", ")}`);s=new i,e.registeredClients.set(r,s)}return s}static getAvailableClients(){const t=b.getInstance();return Array.from(t.clientConstructors.keys())}static normalizeClientName(t){return t.toLowerCase().replace(/[^a-z0-9-]/g,"")}static createDynamicClient(t,e){const r=new dt(t,e);return this.registerClient(r),r}};a(b,"instance");let $=b;class mt{constructor(t={}){w.update(t)}getAvailableModels(){return $.getAvailableClients()}}class V extends mt{constructor(e={}){super(e);a(this,"_jobManager")}get jobManager(){return this._jobManager||(this._jobManager=k.getInstance()),this._jobManager}setApiKey(e){w.update({apiKey:e})}setBaseUrl(e){w.update({baseUrl:e})}getJobs(){return this.jobManager.getAllJobs()}getJob(e){return this.jobManager.getJob(e)}async cancelJob(e){return this.jobManager.cancelJob(e)}}const q=new V;typeof window<"u"&&(window.socaity=q),typeof module<"u"&&typeof module.exports<"u"&&(module.exports={socaity:q,SocaitySDK:V,APIClientFactory:$,APIClient:H},module.exports.default=q),typeof process<"u"&&process.on&&typeof process.on=="function"&&process.on("uncaughtException",n=>{if(n.name==="ApiKeyError")console.error(`${n.name}: ${n.message}`),process.exit(1);else throw n}),u.APIClient=H,u.APIClientFactory=$,u.AudioFile=L,u.MediaFile=h,u.MediaFileFactory=U,u.SocaitySDK=V,u.VideoFile=F,u.detectCategoryFromMimeType=at,u.detectMimeTypeFromUrl=ct,u.getAcceptedTypes=nt,u.getCategoryDisplayName=ot,u.getMimeTypeFromExtension=z,u.isFileReaderObject=K,u.isFileResult=J,u.isUrl=R,u.socaity=q,Object.defineProperty(u,Symbol.toStringTag,{value:"Module"})});
//# sourceMappingURL=socaity.umd.js.map