UNPKG

socaity

Version:

SDK for Generative AI. Build AI-powered applications with ease

1 lines 92.2 kB
(function(S,I){typeof exports=="object"&&typeof module<"u"?I(exports):typeof define=="function"&&define.amd?define(["exports"],I):(S=typeof globalThis<"u"?globalThis:S||self,I(S.socaity={}))})(this,function(S){"use strict";var Ps=Object.defineProperty;var Rs=(S,I,P)=>I in S?Ps(S,I,{enumerable:!0,configurable:!0,writable:!0,value:P}):S[I]=P;var m=(S,I,P)=>Rs(S,typeof I!="symbol"?I+"":I,P);class I 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,I)}}const H=class H{constructor(e={}){m(this,"apiKey");m(this,"baseUrl");m(this,"pollInterval");m(this,"maxRetries");this.apiKey=e.apiKey,this.baseUrl="https://api.socaity.ai/v0",this.pollInterval=e.pollInterval||5e3,this.maxRetries=e.maxRetries||3}static getInstance(){return H.instance||(H.instance=new H),H.instance}static update(e){if(e.apiKey!==void 0&&(!e.apiKey.startsWith("sk_")||e.apiKey.length!=67))throw new I("API key is wrong. Get your API key from the Socaity https://www.socaity.ai dashboard.");const t=H.getInstance();Object.assign(t,e)}};m(H,"instance");let P=H;var x=(r=>(r.CREATED="CREATED",r.QUEUED="QUEUED",r.PROCESSING="PROCESSING",r.COMPLETED="COMPLETED",r.FAILED="FAILED",r.UNKNOWN="UNKNOWN",r))(x||{}),T=(r=>(r.INITIALIZING="INITIALIZING",r.PREPARING="PREPARING",r.SENDING="SENDING",r.TRACKING="TRACKING",r.PROCESSING_RESULT="PROCESSING_RESULT",r.COMPLETED="COMPLETED",r.FAILED="FAILED",r))(T||{});class _t{async parse(e){if(e==null)return this.createErrorJob("No response received");if(typeof e=="string")try{const t=JSON.parse(e);return this.parseObject(t)}catch{return{id:"",status:x.COMPLETED,progress:{progress:1,message:null},result:e,createdAt:new Date,updatedAt:new Date}}return this.parseObject(e)}async parseObject(e){if(typeof e!="object"||e===null)return this.createErrorJob("Invalid response format");const t=e,s=typeof t.id=="string"?t.id:"",n=this.parseStatus(t.status),a=this.parseProgress(t,n),i=typeof t.error=="string"?t.error:null,o=this.parseDate(t.createdAt),l=this.parseDate(t.updatedAt);return{id:s,status:n,progress:a,result:t.result,error:i,createdAt:o,updatedAt:l}}createErrorJob(e){const t=new Date;return{id:"",status:x.FAILED,progress:{progress:0,message:e},result:null,error:e,createdAt:t,updatedAt:t}}parseDate(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}parseStatus(e){if(typeof e!="string"||!e)return x.UNKNOWN;const t=e.toUpperCase();return{COMPLETED:x.COMPLETED,SUCCEEDED:x.COMPLETED,FINISHED:x.COMPLETED,CREATED:x.CREATED,FAILED:x.FAILED,ERROR:x.FAILED,IN_PROGRESS:x.PROCESSING,PROCESSING:x.PROCESSING,RUNNING:x.PROCESSING,BOOTING:x.PROCESSING,QUEUED:x.QUEUED,PENDING:x.QUEUED,IN_QUEUE:x.QUEUED,STARTING:x.QUEUED}[t]||x.UNKNOWN}parseProgress(e,t){let s=0,n=null;const a=e.progress;if(typeof a=="number")s=a;else if(typeof a=="string")try{s=parseFloat(a)}catch{s=0}else if(a&&typeof a=="object"){const i=a;if(typeof i.progress=="number")s=i.progress;else if(typeof i.progress=="string")try{s=parseFloat(i.progress)}catch{s=0}n=typeof i.message=="string"?i.message:null}return isNaN(s)&&(s=0),s=Math.max(0,Math.min(1,s)),t===x.COMPLETED&&(s=1),!n&&typeof e.message=="string"&&(n=e.message),{progress:s,message:n}}}function He(r){return r&&typeof r=="object"&&"file_name"in r&&"content_type"in r&&"content"in r}function vt(r){try{const e=new URL(r);return e.protocol==="http:"||e.protocol==="https:"}catch{return!1}}function bt(r){return r.startsWith("data:")||wt(r)}function wt(r){return/^[A-Za-z0-9+/=]+$/.test(r)&&r.length%4===0}async function Qe(r){if(r==null)return null;if(Array.isArray(r)){const e=r.map(t=>Qe(t));return Promise.all(e)}if(He(r))try{return await new E().fromDict(r)}catch{return r}return r}class E{constructor(e="file",t="application/octet-stream"){m(this,"content_type");m(this,"file_name");m(this,"_content",null);m(this,"_isNode");this.content_type=t,this.file_name=e,this._isNode=typeof window>"u"}static async create(e){if(e==null)throw new Error("Cannot create MediaFile from null or undefined data");return new E().fromAny(e)}async fromAny(e){if(e instanceof E)return e;if(this._isNode&&this._isBuffer(e))return this.fromBytes(e);if(typeof Blob<"u"&&e instanceof Blob){const t=await e.arrayBuffer();return this.fromBytes(t)}if(e instanceof ArrayBuffer||e instanceof Uint8Array)return this.fromBytes(e);if(typeof e=="string"){if(vt(e))return await this.fromUrl(e);if(bt(e))return this.fromBase64(e);if(await this._isValidFilePath(e))return await this.fromFile(e);throw new Error("Invalid data type for MediaFile")}return He(e)?await this.fromDict(e):this}async fromFile(e){if(!this._isNode)throw new Error("Loading from file path is only supported in Node.js environment");try{const s=await(await import("fs/promises")).readFile(e),n=await import("path");return this.file_name=n.basename(e),this._content=this._bufferToArrayBuffer(s),this._setContentTypeFromFileName(),this}catch(t){throw new Error(`Failed to load file from path: ${e}. ${t.message}`)}}async fromUrl(e,t){try{const s=await fetch(e,{headers:t||{"User-Agent":"MediaFile/1.0.0"}});if(!s.ok)throw new Error(`HTTP error! Status: ${s.status}`);this.content_type=s.headers.get("content-type")||"application/octet-stream";const n=s.headers.get("content-disposition");if(n){const a=n.match(/filename=(?:['"]?)([^'";\n]+)/i);a&&a[1]&&(this.file_name=a[1])}if(!this.file_name||this.file_name==="file"){const i=new URL(e).pathname.split("/"),o=i[i.length-1];o&&o.trim()!==""?this.file_name=decodeURIComponent(o):this.file_name="downloaded_file"}return this._content=await s.arrayBuffer(),this}catch(s){throw new Error(`Failed to load file from URL: ${e}. ${s.message}`)}}fromBase64(e){const{data:t,mediaType:s}=this._parseBase64Uri(e);s&&(this.content_type=s);try{return this._content=this._isNode?this._decodeBase64NodeJs(t):this._decodeBase64Browser(t),this}catch(n){throw new Error(`Failed to decode base64 data: ${n.message}`)}}fromBytes(e){if(e instanceof SharedArrayBuffer){const t=new Uint8Array(e),s=new ArrayBuffer(t.byteLength);return new Uint8Array(s).set(t),this._content=s,this}if(e instanceof Uint8Array)if(e.buffer instanceof SharedArrayBuffer){const t=new Uint8Array(e);this._content=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}else this._content=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);else if(this._isNode&&Buffer.isBuffer(e))if(e.buffer instanceof SharedArrayBuffer){const t=new Uint8Array(e);this._content=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}else this._content=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);else this._content=new Uint8Array(e).buffer;return this}async fromDict(e){if(!e.content)throw new Error("Invalid FileResult object: missing content");return this.file_name=e.file_name,this.content_type=e.content_type,await this.fromAny(e.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(),this._content instanceof SharedArrayBuffer?this._content.slice(0):this._content}toUint8Array(){return this._ensureContent(),new Uint8Array(this._content)}toBuffer(){if(this._ensureContent(),!this._isNode)throw new Error("Buffer is only available in Node.js environment");return Buffer.from(this._content)}toBase64(e=!0){this._ensureContent();let t;if(this._isNode)t=Buffer.from(this._content).toString("base64");else{const s=new Uint8Array(this._content);let n="";const a=10240;for(let i=0;i<s.length;i+=a){const o=s.subarray(i,Math.min(i+a,s.length));n+=String.fromCharCode.apply(null,Array.from(o))}t=btoa(n)}return e?`data:${this.content_type};base64,${t}`:t}toJson(){return{file_name:this.file_name,content_type:this.content_type,content:this.toBase64()}}async save(e){this._ensureContent();const t=e||this.file_name;if(this._isNode)try{const s=await import("fs/promises").then(i=>i.default||i),n=await import("path").then(i=>i.default||i);if(!n||typeof n.dirname!="function")throw new Error("Failed to load 'path' module.");const a=n.dirname(t);a!=="."&&await s.mkdir(a,{recursive:!0}).catch(()=>{}),await s.writeFile(t,Buffer.from(this._content))}catch(s){throw new Error(`Failed to save file: ${s.message}`)}else{const s=this.toBlob(),n=URL.createObjectURL(s),a=document.createElement("a");a.href=n,a.download=t,document.body.appendChild(a),a.click(),setTimeout(()=>{document.body.removeChild(a),URL.revokeObjectURL(n)},100)}}fileSize(e="bytes"){if(!this._content)return 0;const t=this._content.byteLength;switch(e){case"kb":return t/1024;case"mb":return t/(1024*1024);case"gb":return t/(1024*1024*1024);default:return t}}get extension(){var e;if(this.content_type&&this.content_type!=="application/octet-stream"){const t={"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"};if(this.content_type in t)return t[this.content_type];if(this._isNode)try{const n=require("mime-types").extension(this.content_type);if(n)return n}catch{}}return this.file_name&&this.file_name.includes(".")&&((e=this.file_name.split(".").pop())==null?void 0:e.toLowerCase())||null}getFileName(){return this.file_name}setFileName(e){this.file_name=e}getContentType(){return this.content_type}setContentType(e){this.content_type=e}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 s;if(!this.file_name)return;const e=(s=this.file_name.split(".").pop())==null?void 0:s.toLowerCase();if(!e)return;if(this._isNode)try{const a=require("mime-types").lookup(this.file_name);if(a){this.content_type=a;return}}catch{}const t={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 t&&(this.content_type=t[e])}_parseBase64Uri(e){if(e.startsWith("data:")){const[t,s]=e.split(",",2),n=t.match(/^data:([^;,]+)/),a=n?n[1]:null;return{data:s,mediaType:a}}return{data:e,mediaType:null}}_ensureContent(){if(!this._content)throw new Error("No content available. Load content first using fromFile, fromUrl, etc.")}async _isValidFilePath(e){if(!this._isNode)return!1;try{return(await(await import("fs/promises")).stat(e)).isFile()}catch{return!1}}_isBuffer(e){return this._isNode&&Buffer.isBuffer(e)}_decodeBase64NodeJs(e){const t=Buffer.from(e,"base64");return this._bufferToArrayBuffer(t)}_decodeBase64Browser(e){const t=atob(e),s=new Uint8Array(t.length);for(let n=0;n<t.length;n++)s[n]=t.charCodeAt(n);return s.buffer}_bufferToArrayBuffer(e){if(e.buffer instanceof SharedArrayBuffer){const t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(new Uint8Array(e)),t}else return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}}class xt{constructor(e){m(this,"uploadEndpoint");m(this,"apiKey");m(this,"defaultTimeout",6e4);this.uploadEndpoint=e.uploadEndpoint||"https://api.socaity.ai/v0/files",this.apiKey=e.apiKey}getAuthHeaders(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}async processUploadResponse(e){if(!e.ok)throw new Error(`Failed to get temporary upload URL: ${e.status} ${e.statusText}`);const t=await e.json();return Array.isArray(t)?t:[t]}async uploadToTemporaryUrl(e,t){const s={"x-ms-blob-type":"BlockBlob","x-ms-if-none-match":"*"},n=t instanceof E?await t.toArrayBuffer():t,a=await fetch(e,{method:"PUT",headers:s,body:n});if(a.status!==201)throw new Error(`Failed to upload to temporary URL ${e}. Response: ${a.statusText}`)}async upload(e){const t=Array.isArray(e)?e:[e],s=t.map(o=>o.extension).filter(o=>o!==null),n=await fetch(this.uploadEndpoint,{method:"POST",headers:this.getAuthHeaders(),body:JSON.stringify({n_files:t.length,file_extensions:s.length>0?s:void 0}),signal:AbortSignal.timeout(this.defaultTimeout)}),a=await this.processUploadResponse(n),i=a.map((o,l)=>this.uploadToTemporaryUrl(o,t[l]));return await Promise.all(i),t.length===1?a[0]:a}async download(e,t){const s=await new E(e).fromUrl(e,this.getAuthHeaders());return t?(await s.save(t),t):s}}class Le{constructor(){m(this,"config");m(this,"uploadFileThresholdMB",1);m(this,"maxFileUploadLimitMB",1e3);m(this,"fastCloud");m(this,"abortController");m(this,"responseParser");this.config=P.getInstance(),this.abortController=new AbortController,this.responseParser=new _t,this.fastCloud=new xt({uploadEndpoint:`${this.config.baseUrl}/v0/files`,apiKey:this.config.apiKey?this.config.apiKey:""})}matchParams(e,t){const s={};for(const[n,a]of Object.entries(e))n in t?s[n]=t[n]:a!==void 0&&(s[n]=a);return s}parseQueryParams(e,t){return e.queryParams?this.matchParams(e.queryParams,t):{}}parseBodyParams(e,t){return e.bodyParams?this.matchParams(e.bodyParams,t):{}}async parseFileParams(e,t){if(!e.fileParams)return{};const s=this.matchParams(e.fileParams,t),n={};try{let a=0;const i={};for(const[o,l]of Object.entries(s))if(typeof l=="string"&&l.startsWith("http"))n[o]=l;else{let d=l;try{d=l instanceof E?l:await E.create(l)}catch(p){console.log(`Failed to convert ${o} to MediaFile`,p)}if(!(d instanceof E))continue;i[o]=d,a+=d.fileSize("mb")}if(a>this.maxFileUploadLimitMB)throw new Error(`Total file size exceeds maximum limit of ${this.maxFileUploadLimitMB}MB`);if(a>this.uploadFileThresholdMB)if(Object.keys(i).length>1){const o=Object.values(i),l=await this.fastCloud.upload(o);Object.keys(i).forEach((d,p)=>{n[d]=l[p]})}else for(const[o,l]of Object.entries(i))n[o]=await this.fastCloud.upload(l);else for(const[o,l]of Object.entries(i))n[o]=l.toBlob();return n}catch(a){throw new Error(`File parameter processing failed: ${a instanceof Error?a.message:String(a)}`)}}validateAPIKey(e){const t=e||this.config.apiKey;if(!t)throw new Error("API key not provided");return t}buildQueryString(e){if(!e||Object.keys(e).length===0)return"";const t=new URLSearchParams;for(const[n,a]of Object.entries(e))a!=null&&(typeof a=="object"?t.append(n,JSON.stringify(a)):t.append(n,String(a)));const s=t.toString();return s?`?${s}`:""}async formatErrorResponse(e){const t=e.status;let s;try{const n=e.headers.get("content-type");if(n&&n.includes("application/json")){const a=await e.json();s=JSON.stringify(a)}else s=await e.text()}catch{s="Could not parse error response"}return new Error(`API error (${t}): ${s}`)}async sendRequest(e,t="POST",s={},n={},a={},i){const o=this.validateAPIKey(i);this.abortController=new AbortController;const{signal:l}=this.abortController,d={Authorization:`Bearer ${o}`};let p=`${this.config.baseUrl}/${e}`,A=null;if(t==="GET"){const O={...s,...n,...a};p+=this.buildQueryString(O)}else if(Object.keys(a).length>0){p+=this.buildQueryString({...s,...n});const M=new FormData;Object.entries(a).forEach(([Be,We])=>{We!=null&&M.append(Be,We)}),A=M}else p+=this.buildQueryString(s),d["Content-Type"]="application/json",A=Object.keys(n).length>0?JSON.stringify(n):null;try{const O=setTimeout(()=>{this.abort()},3e4),M=await fetch(p,{method:t,headers:d,body:A,signal:l});if(clearTimeout(O),!M.ok)throw await this.formatErrorResponse(M);const Be=M.headers.get("content-type");return Be&&Be.includes("application/json")?await M.json():await M.text()}catch(O){throw O instanceof DOMException&&O.name==="AbortError"?new Error("Request canceled"):O instanceof Error?O:new Error(`Network error: ${String(O)}`)}}async request_endpoint(e,t,s){const n=this.parseQueryParams(e,t),a=this.parseBodyParams(e,t),i=await this.parseFileParams(e,t),o=await this.sendRequest(e.path,e.method,n,a,i,s);return this.responseParser.parse(o)}async refresh_status(e){const t=await this.sendRequest("status","POST",{job_id:e});return this.responseParser.parse(t)}abort(){this.abortController.abort(),this.abortController=new AbortController}}const te=class te{constructor(e){m(this,"requestHandler");m(this,"config");m(this,"jobs");m(this,"mediaHandler");this.requestHandler=e,this.config=P.getInstance(),this.jobs=new Map,this.mediaHandler=new E}static getInstance(e){return te.instance||(e||(e=new Le),te.instance=new te(e)),te.instance}async submitJob(e,t,s){try{const n=await this.requestHandler.request_endpoint(e,t,s);return this.jobs.set(n.id,n),n}catch(n){throw n instanceof Error?n:new Error(`Failed to submit job: ${String(n)}`)}}getAllJobs(){return Array.from(this.jobs.values())}getJob(e){return this.jobs.get(e)}async trackJobToCompletion(e){let t=0;for(;t<this.config.maxRetries;)try{const s=await this.requestHandler.refresh_status(e.id);if(this.jobs.set(e.id,s),s.status===x.COMPLETED)return s.result;if(s.status===x.FAILED)throw new Error(`Job failed: ${s.error}`);await new Promise(n=>setTimeout(n,this.config.pollInterval))}catch(s){if(t++,t>=this.config.maxRetries)throw s;await new Promise(n=>setTimeout(n,this.config.pollInterval*t))}throw new Error("Max retries exceeded while tracking job")}async cancelJob(e){try{return await this.requestHandler.sendRequest("cancel","GET",{job_id:e}),this.jobs.delete(e),!0}catch{return!1}}clearCompletedJobs(){for(const[e,t]of this.jobs.entries())(t.status===x.COMPLETED||t.status===x.FAILED)&&this.jobs.delete(e)}};m(te,"instance");let Se=te;const de=typeof process<"u"&&process.stdout&&process.stdout.clearLine;let re;if(de)try{re=require("cli-progress")}catch{console.warn("cli-progress package not found. Using basic console output for progress.")}const se=class se{constructor(){m(this,"multiBar");m(this,"bars",new Map);m(this,"isInitialized",!1);de&&re&&(this.multiBar=new re.MultiBar({clearOnComplete:!1,hideCursor:!0,format:"{bar} {percentage}% | {jobId} | {phase} | {message}"}),this.isInitialized=!0)}static getInstance(){return se.instance||(se.instance=new se),se.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 n=this.bars.get(e);n&&n.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())}};m(se,"instance");let $e=se;class kt{constructor(e,t,s,n,a=!0){m(this,"apiJob");m(this,"endpoint");m(this,"processingState");m(this,"jobManager");m(this,"result",null);m(this,"error",null);m(this,"completed",!1);m(this,"resolvePromise");m(this,"rejectPromise");m(this,"promise");m(this,"eventListeners",new Map);m(this,"verbose");m(this,"progressBar",null);m(this,"progressBarManager");m(this,"parseResultCallbacks",[]);m(this,"_lastLoggedMessage",null);this.apiJob=e,this.jobManager=t,this.endpoint=s,this.verbose=a,this.processingState={phase:T.INITIALIZING,progress:0},this.progressBarManager=$e.getInstance(),this.promise=new Promise((i,o)=>{this.resolvePromise=i,this.rejectPromise=o}),n&&this.onParseResult(n),setTimeout(()=>this.startTracking(),0),this.verbose&&this.initProgressDisplay()}initProgressDisplay(){this.verbose&&(de&&re?(this.progressBar=this.progressBarManager.createBar(this.apiJob.id||"initializing",this.processingState.phase),this.updateProgressDisplay()):this.logProgress())}updateProgressDisplay(){if(!this.verbose)return;const e=this.processingState.phase,t=this.calculateProgressPercent(),s=this.formatProgressMessage();de&&re&&this.progressBar?this.progressBarManager.updateBar(this.apiJob.id,t,{phase:e,message:s.replace(/^.*\| /,"")}):this.logProgress()}calculateProgressPercent(){var t;const e=this.processingState.phase;if(e===T.TRACKING&&((t=this.apiJob.progress)!=null&&t.progress))return Math.round(this.apiJob.progress.progress*100);switch(e){case T.INITIALIZING:return 0;case T.PREPARING:return 5;case T.SENDING:return 10;case T.TRACKING:return 15;case T.PROCESSING_RESULT:return 90;case T.COMPLETED:return 100;case T.FAILED:return 100;default:return 0}}formatProgressMessage(){var s;const e=this.processingState.phase,t=this.apiJob.id||"initializing";if(e===T.INITIALIZING||e===T.PREPARING||e===T.SENDING)return`${e} job | API: ${this.endpoint.path}`;if(e===T.TRACKING){const n=this.apiJob.progress?`${Math.round(this.apiJob.progress.progress*100)}%`:"unknown";let a=`Job ${t} | Progress: ${n} | API: ${this.endpoint.path}`;return(s=this.apiJob.progress)!=null&&s.message&&(a+=` | ${this.apiJob.progress.message}`),a}else return`Job ${t} | ${e} | API: ${this.endpoint.path}`}logProgress(){const e=this.formatProgressMessage();(!this._lastLoggedMessage||this._lastLoggedMessage!==e)&&(console.log(e),this._lastLoggedMessage=e)}stopProgressDisplay(){if(!this.verbose)return;de&&re&&this.progressBar&&(this.progressBarManager.removeBar(this.apiJob.id),this.progressBar=null);const e=this.processingState.phase;e===T.COMPLETED?console.log(`✓ Job ${this.apiJob.id} completed successfully (${this.endpoint.path})`):e===T.FAILED&&console.log(`✗ Job ${this.apiJob.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){const s=this.eventListeners.get(e);s&&s.forEach(n=>n(...t))}async pollJobStatus(){if(!(this.completed||!this.apiJob.id))try{const e=await this.jobManager.requestHandler.refresh_status(this.apiJob.id);if(!e){setTimeout(()=>this.pollJobStatus(),this.jobManager.config.pollInterval);return}if(this.apiJob=e,this.emitJobUpdate(),this.verbose&&this.updateProgressDisplay(),e.status===x.COMPLETED){this.updateProcessingState(T.PROCESSING_RESULT,.9,"Processing result");try{this.result=await Qe(e.result),this.result=await this.runParseResultCallbacks(this.result),this.complete()}catch(t){this.fail(t instanceof Error?t:new Error(String(t)))}}else e.status===x.FAILED?(this.updateProcessingState(T.FAILED,1,e.error||"Job failed"),this.fail(new Error(e.error||"Job failed with no error message"))):setTimeout(()=>this.pollJobStatus(),this.jobManager.config.pollInterval)}catch(e){console.error("Error polling job status:",e),setTimeout(()=>this.pollJobStatus(),this.jobManager.config.pollInterval)}}startTracking(){this.updateProcessingState(T.TRACKING,0,"Tracking job status"),this.pollJobStatus()}complete(){this.updateProcessingState(T.COMPLETED,1,"Job completed"),this.cleanup(),this.completed=!0,this.emit("completed",this.result),this.resolvePromise(this.result)}fail(e){this.updateProcessingState(T.FAILED,1,e.message),this.cleanup(),this.completed=!0,this.error=e,this.emit("failed",e),this.rejectPromise(e)}cleanup(){this.stopProgressDisplay()}updateProcessingState(e,t,s){this.processingState={phase:e,progress:t,message:s},this.verbose&&this.updateProgressDisplay(),this.emit("processingUpdated",this.processingState)}emitJobUpdate(){this.emit("progressUpdated",this.apiJob.progress),this.emit("statusUpdated",this.apiJob.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(this.apiJob.progress),0),this}onStatus(e){return this.on("statusUpdated",e),setTimeout(()=>e(this.apiJob.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 n=await s(t);n!==void 0&&(t=n)}return t}async cancel(){try{const e=await this.jobManager.cancelJob(this.apiJob.id);return e&&(this.cleanup(),this.fail(new Error("Job cancelled by user"))),e}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(e,t){return this.promise.then(e,t)}}const R=class R{constructor(){m(this,"registeredClients",new Map);m(this,"clientConstructors",new Map)}static getInstance(){return R.instance||(R.instance=new R),R.instance}static registerClientType(e,t){const s=R.getInstance(),n=R.normalizeClientName(e);s.clientConstructors.set(n,t)}static registerClient(e){const t=R.getInstance(),s=R.normalizeClientName(e.name);t.registeredClients.set(s,e)}static getClient(e){const t=R.getInstance(),s=R.normalizeClientName(e);let n=t.registeredClients.get(s);if(!n){const a=t.clientConstructors.get(s);if(!a)throw new Error(`Client "${e}" not found. Available clients: ${Array.from(t.clientConstructors.keys()).join(", ")}`);n=new a,t.registeredClients.set(s,n)}return n}static getAvailableClients(){const e=R.getInstance();return Array.from(e.clientConstructors.keys())}static normalizeClientName(e){return e.toLowerCase().replace(/[^a-z0-9-]/g,"")}};m(R,"instance");let Z=R;class Ue{constructor(e){m(this,"requestHandler");m(this,"config");m(this,"endpoints");m(this,"jobManager");m(this,"name");this.name=this.sanitizePath(e),this.config=P.getInstance(),this.requestHandler=new Le,this.endpoints=new Map,this.jobManager=Se.getInstance(this.requestHandler),this.registerEndpoints(),Z.registerClient(this)}sanitizePath(e){return!e||typeof e!="string"?"":e.toLowerCase().trim().replace(/\s+/g," ").replace(/\//g,"-").replace(/[\s_]/g,"-").replace(/[^a-z0-9\-]/g,"").replace(/\-+/g,"-").replace(/^\-+|\-+$/g,"").trim()}registerEndpoint(e){const t=this.sanitizePath(e.path);e.path=this.name+"/"+t,this.endpoints.set(t,e)}getEndpoint(e){e=this.sanitizePath(e);const t=this.endpoints.get(e);if(!t)throw new Error(`Unknown endpoint: ${e}`);return t}updateConfig(e){P.update(e)}async submitTrackedJob(e,t,s,n,a=!0){const i=await this.jobManager.submitJob(e,t,n);return new kt(i,this.jobManager,e,s,a)}getJobs(){return this.jobManager.getAllJobs()}getJob(e){return this.jobManager.getJob(e)}async cancelJob(e){return this.jobManager.cancelJob(e)}}var w;(function(r){r.assertEqual=n=>n;function e(n){}r.assertIs=e;function t(n){throw new Error}r.assertNever=t,r.arrayToEnum=n=>{const a={};for(const i of n)a[i]=i;return a},r.getValidEnumValues=n=>{const a=r.objectKeys(n).filter(o=>typeof n[n[o]]!="number"),i={};for(const o of a)i[o]=n[o];return r.objectValues(i)},r.objectValues=n=>r.objectKeys(n).map(function(a){return n[a]}),r.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{const a=[];for(const i in n)Object.prototype.hasOwnProperty.call(n,i)&&a.push(i);return a},r.find=(n,a)=>{for(const i of n)if(a(i))return i},r.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&isFinite(n)&&Math.floor(n)===n;function s(n,a=" | "){return n.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}r.joinValues=s,r.jsonStringifyReplacer=(n,a)=>typeof a=="bigint"?a.toString():a})(w||(w={}));var Fe;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Fe||(Fe={}));const h=w.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),z=r=>{switch(typeof r){case"undefined":return h.undefined;case"string":return h.string;case"number":return isNaN(r)?h.nan:h.number;case"boolean":return h.boolean;case"function":return h.function;case"bigint":return h.bigint;case"symbol":return h.symbol;case"object":return Array.isArray(r)?h.array:r===null?h.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?h.promise:typeof Map<"u"&&r instanceof Map?h.map:typeof Set<"u"&&r instanceof Set?h.set:typeof Date<"u"&&r instanceof Date?h.date:h.object;default:return h.unknown}},c=w.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Tt=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:");class j extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(a){return a.message},s={_errors:[]},n=a=>{for(const i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(n);else if(i.code==="invalid_return_type")n(i.returnTypeError);else if(i.code==="invalid_arguments")n(i.argumentsError);else if(i.path.length===0)s._errors.push(t(i));else{let o=s,l=0;for(;l<i.path.length;){const d=i.path[l];l===i.path.length-1?(o[d]=o[d]||{_errors:[]},o[d]._errors.push(t(i))):o[d]=o[d]||{_errors:[]},o=o[d],l++}}};return n(this),s}static assert(e){if(!(e instanceof j))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,w.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},s=[];for(const n of this.issues)n.path.length>0?(t[n.path[0]]=t[n.path[0]]||[],t[n.path[0]].push(e(n))):s.push(e(n));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}}j.create=r=>new j(r);const ne=(r,e)=>{let t;switch(r.code){case c.invalid_type:r.received===h.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case c.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,w.jsonStringifyReplacer)}`;break;case c.unrecognized_keys:t=`Unrecognized key(s) in object: ${w.joinValues(r.keys,", ")}`;break;case c.invalid_union:t="Invalid input";break;case c.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${w.joinValues(r.options)}`;break;case c.invalid_enum_value:t=`Invalid enum value. Expected ${w.joinValues(r.options)}, received '${r.received}'`;break;case c.invalid_arguments:t="Invalid function arguments";break;case c.invalid_return_type:t="Invalid function return type";break;case c.invalid_date:t="Invalid date";break;case c.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:w.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case c.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case c.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case c.custom:t="Invalid input";break;case c.invalid_intersection_types:t="Intersection results could not be merged";break;case c.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case c.not_finite:t="Number must be finite";break;default:t=e.defaultError,w.assertNever(r)}return{message:t}};let Ye=ne;function Et(r){Ye=r}function Ie(){return Ye}const Ne=r=>{const{data:e,path:t,errorMaps:s,issueData:n}=r,a=[...t,...n.path||[]],i={...n,path:a};if(n.message!==void 0)return{...n,path:a,message:n.message};let o="";const l=s.filter(d=>!!d).slice().reverse();for(const d of l)o=d(i,{data:e,defaultError:o}).message;return{...n,path:a,message:o}},At=[];function u(r,e){const t=Ie(),s=Ne({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===ne?void 0:ne].filter(n=>!!n)});r.common.issues.push(s)}class C{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const s=[];for(const n of t){if(n.status==="aborted")return y;n.status==="dirty"&&e.dirty(),s.push(n.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,t){const s=[];for(const n of t){const a=await n.key,i=await n.value;s.push({key:a,value:i})}return C.mergeObjectSync(e,s)}static mergeObjectSync(e,t){const s={};for(const n of t){const{key:a,value:i}=n;if(a.status==="aborted"||i.status==="aborted")return y;a.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||n.alwaysSet)&&(s[a.value]=i.value)}return{status:e.value,value:s}}}const y=Object.freeze({status:"aborted"}),ae=r=>({status:"dirty",value:r}),N=r=>({status:"valid",value:r}),ze=r=>r.status==="aborted",Je=r=>r.status==="dirty",Q=r=>r.status==="valid",ue=r=>typeof Promise<"u"&&r instanceof Promise;function Oe(r,e,t,s){if(typeof e=="function"?r!==e||!0:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(r)}function Xe(r,e,t,s,n){if(typeof e=="function"?r!==e||!0:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(r,t),t}typeof SuppressedError=="function"&&SuppressedError;var f;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(f||(f={}));var he,fe;class ${constructor(e,t,s,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=n}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const et=(r,e)=>{if(Q(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new j(r.common.issues);return this._error=t,this._error}}};function v(r){if(!r)return{};const{errorMap:e,invalid_type_error:t,required_error:s,description:n}=r;if(e&&(t||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(i,o)=>{var l,d;const{message:p}=r;return i.code==="invalid_enum_value"?{message:p??o.defaultError}:typeof o.data>"u"?{message:(l=p??s)!==null&&l!==void 0?l:o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:(d=p??t)!==null&&d!==void 0?d:o.defaultError}},description:n}}class b{get description(){return this._def.description}_getType(e){return z(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:z(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new C,ctx:{common:e.parent.common,data:e.data,parsedType:z(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(ue(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){var s;const n={common:{issues:[],async:(s=t==null?void 0:t.async)!==null&&s!==void 0?s:!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:z(e)},a=this._parseSync({data:e,path:n.path,parent:n});return et(n,a)}"~validate"(e){var t,s;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:z(e)};if(!this["~standard"].async)try{const a=this._parseSync({data:e,path:[],parent:n});return Q(a)?{value:a.value}:{issues:n.common.issues}}catch(a){!((s=(t=a==null?void 0:a.message)===null||t===void 0?void 0:t.toLowerCase())===null||s===void 0)&&s.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(a=>Q(a)?{value:a.value}:{issues:n.common.issues})}async parseAsync(e,t){const s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){const s={common:{issues:[],contextualErrorMap:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:z(e)},n=this._parse({data:e,path:s.path,parent:s}),a=await(ue(n)?n:Promise.resolve(n));return et(s,a)}refine(e,t){const s=n=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(n):t;return this._refinement((n,a)=>{const i=e(n),o=()=>a.addIssue({code:c.custom,...s(n)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,t){return this._refinement((s,n)=>e(s)?!0:(n.addIssue(typeof t=="function"?t(s,n):t),!1))}_refinement(e){return new L({schema:this,typeName:g.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return F.create(this,this._def)}nullable(){return W.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return B.create(this)}promise(){return le.create(this,this._def)}or(e){return ye.create([this,e],this._def)}and(e){return _e.create(this,e,this._def)}transform(e){return new L({...v(this._def),schema:this,typeName:g.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new ke({...v(this._def),innerType:this,defaultValue:t,typeName:g.ZodDefault})}brand(){return new Ge({typeName:g.ZodBranded,type:this,...v(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Te({...v(this._def),innerType:this,catchValue:t,typeName:g.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Ee.create(this,e)}readonly(){return Ae.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Ct=/^c[^\s-]{8,}$/i,St=/^[0-9a-z]+$/,It=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Nt=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Ot=/^[a-z0-9_-]{21}$/i,Pt=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Rt=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,jt=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Zt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Ve;const Mt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Dt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Bt=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Lt=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,$t=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ut=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,tt="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Ft=new RegExp(`^${tt}$`);function st(r){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`),e}function zt(r){return new RegExp(`^${st(r)}$`)}function rt(r){let e=`${tt}T${st(r)}`;const t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Jt(r,e){return!!((e==="v4"||!e)&&Mt.test(r)||(e==="v6"||!e)&&Bt.test(r))}function Vt(r,e){if(!Pt.test(r))return!1;try{const[t]=r.split("."),s=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),n=JSON.parse(atob(s));return!(typeof n!="object"||n===null||!n.typ||!n.alg||e&&n.alg!==e)}catch{return!1}}function qt(r,e){return!!((e==="v4"||!e)&&Dt.test(r)||(e==="v6"||!e)&&Lt.test(r))}class D extends b{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==h.string){const a=this._getOrReturnCtx(e);return u(a,{code:c.invalid_type,expected:h.string,received:a.parsedType}),y}const s=new C;let n;for(const a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(n=this._getOrReturnCtx(e,n),u(n,{code:c.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),s.dirty());else if(a.kind==="max")e.data.length>a.value&&(n=this._getOrReturnCtx(e,n),u(n,{code:c.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),s.dirty());else if(a.kind==="length"){const i=e.data.length>a.value,o=e.data.length<a.value;(i||o)&&(n=this._getOrReturnCtx(e,n),i?u(n,{code:c.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&u(n,{code:c.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),s.dirty())}else if(a.kind==="email")jt.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"email",code:c.invalid_string,message:a.message}),s.dirty());else if(a.kind==="emoji")Ve||(Ve=new RegExp(Zt,"u")),Ve.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"emoji",code:c.invalid_string,message:a.message}),s.dirty());else if(a.kind==="uuid")Nt.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"uuid",code:c.invalid_string,message:a.message}),s.dirty());else if(a.kind==="nanoid")Ot.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"nanoid",code:c.invalid_string,message:a.message}),s.dirty());else if(a.kind==="cuid")Ct.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"cuid",code:c.invalid_string,message:a.message}),s.dirty());else if(a.kind==="cuid2")St.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"cuid2",code:c.invalid_string,message:a.message}),s.dirty());else if(a.kind==="ulid")It.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"ulid",code:c.invalid_string,message:a.message}),s.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),u(n,{validation:"url",code:c.invalid_string,message:a.message}),s.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"regex",code:c.invalid_string,message:a.message}),s.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(n=this._getOrReturnCtx(e,n),u(n,{code:c.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),s.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(n=this._getOrReturnCtx(e,n),u(n,{code:c.invalid_string,validation:{startsWith:a.value},message:a.message}),s.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(n=this._getOrReturnCtx(e,n),u(n,{code:c.invalid_string,validation:{endsWith:a.value},message:a.message}),s.dirty()):a.kind==="datetime"?rt(a).test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{code:c.invalid_string,validation:"datetime",message:a.message}),s.dirty()):a.kind==="date"?Ft.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{code:c.invalid_string,validation:"date",message:a.message}),s.dirty()):a.kind==="time"?zt(a).test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{code:c.invalid_string,validation:"time",message:a.message}),s.dirty()):a.kind==="duration"?Rt.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"duration",code:c.invalid_string,message:a.message}),s.dirty()):a.kind==="ip"?Jt(e.data,a.version)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"ip",code:c.invalid_string,message:a.message}),s.dirty()):a.kind==="jwt"?Vt(e.data,a.alg)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"jwt",code:c.invalid_string,message:a.message}),s.dirty()):a.kind==="cidr"?qt(e.data,a.version)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"cidr",code:c.invalid_string,message:a.message}),s.dirty()):a.kind==="base64"?$t.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"base64",code:c.invalid_string,message:a.message}),s.dirty()):a.kind==="base64url"?Ut.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"base64url",code:c.invalid_string,message:a.message}),s.dirty()):w.assertNever(a);return{status:s.value,value:e.data}}_regex(e,t,s){return this.refinement(n=>e.test(n),{validation:t,code:c.invalid_string,...f.errToObj(s)})}_addCheck(e){return new D({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...f.errToObj(e)})}url(e){return this._addCheck({kind:"url",...f.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...f.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...f.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...f.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...f.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...f.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...f.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...f.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...f.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...f.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...f.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...f.errToObj(e)})}datetime(e){var t,s;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(t=e==null?void 0:e.offset)!==null&&t!==void 0?t:!1,local:(s=e==null?void 0:e.local)!==null&&s!==void 0?s:!1,...f.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...f.