@mynthio/sdk 0.0.40 → 0.0.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +20 -4
  2. package/dist/convex/index.d.ts +39 -100
  3. package/dist/convex/index.js +41 -2
  4. package/dist/handler.d.ts +28 -0
  5. package/dist/handler.js +121 -0
  6. package/dist/index.d.ts +701 -360
  7. package/dist/index.js +1514 -2
  8. package/dist/next/index.d.ts +14 -24
  9. package/dist/next/index.js +25 -2
  10. package/dist/tanstack-start/index.d.ts +18 -23
  11. package/dist/tanstack-start/index.js +11 -2
  12. package/dist/types.d.ts +609 -660
  13. package/package.json +16 -21
  14. package/dist/client.d.ts +0 -41
  15. package/dist/client.d.ts.map +0 -1
  16. package/dist/constants.d.ts +0 -95
  17. package/dist/constants.d.ts.map +0 -1
  18. package/dist/convex/index.d.ts.map +0 -1
  19. package/dist/convex/utils.d.ts +0 -2
  20. package/dist/convex/utils.d.ts.map +0 -1
  21. package/dist/image-alt-result.d.ts +0 -19
  22. package/dist/image-alt-result.d.ts.map +0 -1
  23. package/dist/image-generation-result.d.ts +0 -58
  24. package/dist/image-generation-result.d.ts.map +0 -1
  25. package/dist/image-rate-result.d.ts +0 -21
  26. package/dist/image-rate-result.d.ts.map +0 -1
  27. package/dist/image-remove-background-result.d.ts +0 -24
  28. package/dist/image-remove-background-result.d.ts.map +0 -1
  29. package/dist/image-review-result.d.ts +0 -28
  30. package/dist/image-review-result.d.ts.map +0 -1
  31. package/dist/index-apss16tr.js +0 -3
  32. package/dist/index-ty295921.js +0 -3
  33. package/dist/index.d.ts.map +0 -1
  34. package/dist/next/index.d.ts.map +0 -1
  35. package/dist/tanstack-start/index.d.ts.map +0 -1
  36. package/dist/task-async.d.ts +0 -95
  37. package/dist/task-async.d.ts.map +0 -1
  38. package/dist/types.d.ts.map +0 -1
  39. package/dist/uploads.d.ts +0 -31
  40. package/dist/uploads.d.ts.map +0 -1
  41. package/dist/video-generation-result.d.ts +0 -46
  42. package/dist/video-generation-result.d.ts.map +0 -1
  43. package/dist/webhooks/utils.d.ts +0 -5
  44. package/dist/webhooks/utils.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1,2 +1,1514 @@
1
- // @bun
2
- var R="https://api.mynth.io",H="MYNTH_API_KEY",g="MYNTH_DESTINATION",_="/image/generate",M="/image/upload",q="/image/rate",m="/image/alt",y="/image/review",k="/image/remove-background",h="/video/generate",E="/video/generate/estimate",T="/models";var I=(J)=>`/tasks/${J}`;var c=(J)=>`/tasks/${J}/status`,ZJ=[{id:"auto",label:"Auto",capabilities:[]},{id:"alibaba/qwen-image-2.0",label:"Qwen Image 2.0",capabilities:["inputs","native_enhance_prompt"]},{id:"alibaba/qwen-image-2.0-pro",label:"Qwen Image 2.0 Pro",capabilities:["inputs","native_enhance_prompt"]},{id:"alibaba/qwen-image-3.0",label:"Qwen Image 3.0",capabilities:["inputs","native_enhance_prompt"]},{id:"alibaba/qwen-image-3.0-pro",label:"Qwen Image 3.0 Pro",capabilities:["inputs","native_enhance_prompt"]},{id:"bytedance/seedream-5.0-lite",label:"Seedream 5.0 Lite",capabilities:["inputs"]},{id:"bytedance/seedream-pro",label:"Seedream Pro",capabilities:["inputs"]},{id:"black-forest-labs/flux.1-dev",label:"FLUX.1 Dev",capabilities:[]},{id:"black-forest-labs/flux-1-schnell",label:"FLUX.1 Schnell",capabilities:[]},{id:"tongyi-mai/z-image",label:"Z Image",capabilities:["inputs"]},{id:"tongyi-mai/z-image-turbo",label:"Z Image Turbo",capabilities:[]},{id:"black-forest-labs/flux.2-dev",label:"FLUX.2 Dev",capabilities:["inputs"]},{id:"black-forest-labs/flux.2-pro",label:"FLUX.2 Pro",capabilities:["inputs"]},{id:"black-forest-labs/flux.2-flex",label:"FLUX.2 Flex",capabilities:["inputs"]},{id:"black-forest-labs/flux.2-max",label:"FLUX.2 Max",capabilities:["inputs"]},{id:"black-forest-labs/flux.2-klein-4b",label:"FLUX.2 Klein 4B",capabilities:["inputs"]},{id:"bria/fibo-edit-1.5",label:"FIBO Edit 1.5",capabilities:["inputs"]},{id:"bria/fibo-generate-1.5",label:"FIBO Generate 1.5",capabilities:[]},{id:"circlestone-labs/anima",label:"Anima",capabilities:["inputs"]},{id:"john6666/bismuth-illustrious-mix",label:"Bismuth Illustrious Mix",capabilities:["negative_prompt"]},{id:"maxfeifei8/one-obsession",label:"One obsession",capabilities:["negative_prompt"]},{id:"klingai/kling-image-3.0",label:"Kling IMAGE 3.0",capabilities:["inputs"]},{id:"klingai/kling-image-o3",label:"Kling IMAGE O3",capabilities:["inputs","4k"]},{id:"krea/krea-2-turbo",label:"Krea 2 Turbo",capabilities:["inputs"]},{id:"krea/krea-2-medium",label:"Krea 2 Medium",capabilities:["inputs"]},{id:"krea/krea-2-large",label:"Krea 2 Large",capabilities:["inputs"]},{id:"luma/uni-1",label:"Luma UNI-1",capabilities:["inputs"]},{id:"luma/uni-1-max",label:"Luma UNI-1 Max",capabilities:["inputs"]},{id:"meta/muse-image",label:"Muse Image",capabilities:["inputs"]},{id:"microsoft/mai-image-2.6",label:"MAI Image 2.6",capabilities:["inputs"]},{id:"microsoft/mai-image-2.6-flash",label:"MAI Image 2.6 Flash",capabilities:["inputs"]},{id:"minimax/h3",label:"MiniMax H3",capabilities:["inputs"]},{id:"purplesmartai/pony-diffusion-v6-xl",label:"Pony Diffusion V6 XL",capabilities:["negative_prompt"]},{id:"recraft/recraft-v4",label:"Recraft V4",capabilities:[]},{id:"recraft/recraft-v4-pro",label:"Recraft V4 Pro",capabilities:[]},{id:"reve/reve",label:"Reve",capabilities:["inputs"]},{id:"reve/reve-remix",label:"Reve Remix",capabilities:["inputs"]},{id:"sourceful/riverflow-2.0-pro",label:"Riverflow 2.0 Pro",capabilities:["inputs","4k","native_enhance_prompt"]},{id:"google/gemini-3.1-flash-lite-image",label:"Nano Banana 2 Lite",capabilities:["inputs","native_enhance_prompt"]},{id:"google/gemini-3.1-flash-image",label:"Nano Banana 2",capabilities:["inputs","4k","native_enhance_prompt"]},{id:"google/gemini-3-pro-image-preview",label:"Nano Banana Pro",capabilities:["inputs","4k","native_enhance_prompt"]},{id:"imagineart/imagineart-1.5-pro",label:"ImagineArt 1.5 Pro",capabilities:["4k"]},{id:"imagineart/imagineart-2.0",label:"ImagineArt 2.0",capabilities:["inputs"]},{id:"openai/gpt-image-2",label:"GPT Image 2",capabilities:["inputs"]},{id:"openai/gpt-image-2.5-flare",label:"GPT Image 2.5 Flare",capabilities:["inputs"]},{id:"openai/gpt-image-2.5-sunburst",label:"GPT Image 2.5 Sunburst",capabilities:["inputs"]},{id:"wan/wan2.6-image",label:"Wan 2.6 Image",capabilities:[]},{id:"wan/wan2.7-image",label:"Wan 2.7 Image",capabilities:["inputs"]},{id:"wan/wan2.7-image-pro",label:"Wan 2.7 Image Pro",capabilities:["inputs","4k"]},{id:"xai/grok-imagine-image",label:"Grok Imagine Image",capabilities:["inputs"]},{id:"xai/grok-imagine-image-2.0",label:"Grok Imagine Image 2.0",capabilities:["inputs"]},{id:"xai/grok-imagine-image-quality",label:"Grok Imagine Image Quality",capabilities:["inputs"]}],A={timeoutMs:3600000,fastDurationMs:0,intervalMs:1e4},$J=[{id:"bytedance/seedance-2.0-mini",label:"Seedance 2.0 Mini",resolutions:["480p","720p"],defaultResolution:"720p",duration:{default:5,min:4,max:15},audio:!0,inputs:["first_frame","last_frame"],maxInputs:2},{id:"google/gemini-omni-flash-1.1",label:"Gemini Omni Flash 1.1",resolutions:["720p","1080p","4k"],defaultResolution:"720p",duration:{default:8,min:3,max:10},audio:!0,inputs:["first_frame","last_frame"],maxInputs:2},{id:"prunaai/p-video",label:"P-Video",resolutions:["720p","1080p"],defaultResolution:"720p",duration:{default:5,min:1,max:10},audio:!0,inputs:["first_frame"],maxInputs:1}];class N extends Error{status;code;constructor(J,Q,Z){super(J);this.name="MynthAPIError",this.status=Q,this.code=Z}}function l(J,Q){let Z=J,W=Z.error||Z.message||`Request failed with status ${Q}`;return new N(W,Q,Z.code)}class w{apiKey;baseUrl;constructor(J){this.apiKey=J.apiKey,this.baseUrl=J.baseUrl?J.baseUrl.endsWith("/")?J.baseUrl.slice(0,-1):J.baseUrl:R}getAuthHeaders(J){if(J?.auth===!1)return{};let Q=J?.accessToken??this.apiKey;return Q?{Authorization:`Bearer ${Q}`}:{}}getUrl(J){return`${this.baseUrl}${J}`}async post(J,Q){let Z=typeof FormData<"u"&&Q instanceof FormData,W=await fetch(this.getUrl(J),{method:"POST",headers:{...Z?{}:{"Content-Type":"application/json"},...this.getAuthHeaders()},body:Z?Q:JSON.stringify(Q)}),X=await W.json();if(!W.ok)throw l(X,W.status);return X}async get(J,{headers:Q,accessToken:Z,auth:W}={}){let X=await fetch(this.getUrl(J),{headers:{...this.getAuthHeaders({accessToken:Z,auth:W}),...Q}});return{data:await X.json(),status:X.status,ok:X.ok}}async getOrThrow(J,Q={}){let Z=await this.get(J,Q);if(!Z.ok)throw l(Z.data,Z.status);return Z.data}}class C{taskId;cost;alt;constructor(J){this.taskId=J.taskId,this.cost=J.cost,this.alt=J.alt}static fromTaskData(J){if(J.status!=="completed"||J.result===null)throw Error(`Image alt task ${J.id} is not completed`);if(J.cost===null)throw Error(`Image alt task ${J.id} is missing cost`);return new C({taskId:J.id,cost:J.cost,alt:J.result.alt})}}class V{data;constructor(J){this.data=J}get id(){return this.data.id}get status(){return this.data.status}get result(){return this.data.result}get isCompleted(){return this.data.status==="completed"}get isFailed(){return this.data.status==="failed"}get urls(){return this.data.result?.images.filter((J)=>J.status==="success").map((J)=>J.url).filter((J)=>J!==null)??[]}getImages(J={}){if(J.includeFailed)return this.data.result?.images??[];return this.data.result?.images.filter((Q)=>Q.status==="success")??[]}getMetadata(){return this.data.request?.metadata}}class K{taskId;cost;level;constructor(J){this.taskId=J.taskId,this.cost=J.cost,this.level=J.level}static fromTaskData(J){if(J.status!=="completed"||J.result===null)throw Error(`Image rate task ${J.id} is not completed`);if(J.cost===null)throw Error(`Image rate task ${J.id} is missing cost`);return new K({taskId:J.id,cost:J.cost,level:J.result.level})}}class S{taskId;cost;image;metadata;constructor(J){this.taskId=J.taskId,this.cost=J.cost,this.image=J.image,this.metadata=J.metadata}static fromTaskData(J){if(J.status!=="completed"||J.result===null)throw Error(`Image remove background task ${J.id} is not completed`);if(J.cost===null)throw Error(`Image remove background task ${J.id} is missing cost`);return new S({taskId:J.id,cost:J.cost,image:J.result.image,metadata:J.request.metadata})}}class U{taskId;cost;score;summary;findings;strengths;constructor(J){this.taskId=J.taskId,this.cost=J.cost,this.score=J.score,this.summary=J.summary,this.findings=J.findings,this.strengths=J.strengths}static fromTaskData(J){if(J.status!=="completed"||J.result===null)throw Error(`Image review task ${J.id} is not completed`);if(J.cost===null)throw Error(`Image review task ${J.id} is missing cost`);return new U({taskId:J.id,cost:J.cost,...J.result})}}var d=1800000,WJ=12000,XJ=2500,jJ=5000,p=20;class f extends Error{constructor(J,Q=d){super(`Task ${J} polling timed out after ${Q}ms`);this.name="TaskAsyncTimeoutError"}}class F extends Error{constructor(J){super(`Unauthorized access to task ${J}`);this.name="TaskAsyncUnauthorizedError"}}class O extends Error{constructor(J,Q){super(`Failed to fetch status for task ${J} after multiple retries`);this.name="TaskAsyncFetchError",this.cause=Q}}class D extends Error{constructor(J,Q,Z){let W=Q?` (status ${Q})`:"";super(`Failed to fetch task ${J}${W}`);this.name="TaskAsyncTaskFetchError",this.cause=Z}}class P extends Error{constructor(J){super(`Task ${J} failed`);this.name="TaskAsyncTaskFailedError"}}class z{id;client;_access;resultFactory;polling;_completionPromise=null;constructor(J,Q){this.id=J,this.client=Q.client,this._access={publicAccessToken:Q.pat},this.resultFactory=Q.resultFactory,this.polling={timeoutMs:Q.polling?.timeoutMs??d,fastDurationMs:Q.polling?.fastDurationMs??WJ,fastIntervalMs:Q.polling?.fastIntervalMs??XJ,intervalMs:Q.polling?.intervalMs??jJ}}get access(){return this._access}toString(){return this.id}async wait(){if(!this._completionPromise)this._completionPromise=this.pollUntilCompleted();return this._completionPromise}async pollUntilCompleted(){let{timeoutMs:J,fastDurationMs:Q,fastIntervalMs:Z,intervalMs:W}=this.polling,X=Date.now(),$=0,j=!1,Y;while(!0){let b=Date.now()-X;if(b>=J)throw new f(this.id,J);let x=await this.fetchStatus(j);if(x.ok)if(x.status==="completed"){let B=await this.fetchTask();if(B.ok)return this.resultFactory(B.data);if(B.unauthorized)throw new F(this.id);if($++,!B.retryable||$>=p)throw new D(this.id,B.status,B.error)}else if(x.status==="failed")throw new P(this.id);else $=0;else{if((x.unauthorized||x.notFound)&&this._access.publicAccessToken&&!j){j=!0;continue}if(x.unauthorized)throw new F(this.id);if(x.retryable){if($++,Y=x.error,$>=p)throw new O(this.id,Y)}}let a=b<Q?Z:W,e=Math.random()*500,t=a+e,JJ=J-b,QJ=Math.min(t,JJ);await this.sleep(QJ)}}async fetchStatus(J){let Q=J||!this._access.publicAccessToken?void 0:this._access.publicAccessToken;try{let Z=await this.client.get(c(this.id),{accessToken:Q});if(Z.ok)return{ok:!0,status:Z.data.data.status};if(Z.status===401||Z.status===403)return{ok:!1,unauthorized:!0,retryable:!1};if(Z.status===404)return{ok:!1,unauthorized:!1,retryable:!0,notFound:!0};if(Z.status>=500)return{ok:!1,unauthorized:!1,retryable:!0};return{ok:!1,unauthorized:!1,retryable:!1}}catch(Z){return{ok:!1,unauthorized:!1,retryable:!0,error:Z instanceof Error?Z:Error(String(Z))}}}async fetchTask(){try{let J=await this.client.get(I(this.id));if(J.ok)return{ok:!0,data:J.data.data};if(J.status===401||J.status===403)return{ok:!1,unauthorized:!0,retryable:!1};if(J.status===404||J.status>=500)return{ok:!1,unauthorized:!1,retryable:!0,status:J.status};return{ok:!1,unauthorized:!1,retryable:!1,status:J.status}}catch(J){return{ok:!1,unauthorized:!1,retryable:!0,error:J instanceof Error?J:Error(String(J))}}}sleep(J){return new Promise((Q)=>setTimeout(Q,J))}}var xJ="images",zJ="image";function u(J){return typeof Blob<"u"&&J instanceof Blob}async function G(J,Q){let Z=new FormData,W=Array.isArray(Q)?Q:[Q];for(let $ of W)Z.append(xJ,$,typeof File<"u"&&$ instanceof File?$.name:zJ);return(await J.post(M,Z)).data}async function L(J,Q){if(!Q?.length)return;let Z=Q.flatMap(($)=>{if(u($))return[$];if(typeof $!=="string"&&$.source.type==="file")return[$.source.file];return[]}),W=Z.length?(await G(J,Z)).urls:[],X=0;return Q.map(($)=>{if(typeof $==="string")return $;if(u($))return W[X++];if($.source.type==="file")return{type:"image",as:$.as,source:{type:"url",url:W[X++]}};return{type:"image",as:$.as,source:$.source}})}class v{data;constructor(J){this.data=J}get id(){return this.data.id}get status(){return this.data.status}get result(){return this.data.result}get isCompleted(){return this.data.status==="completed"}get isFailed(){return this.data.status==="failed"}get urls(){return this.getVideos().map((J)=>J.url)}getVideos(J={}){if(J.includeFailed)return this.data.result?.videos??[];return this.data.result?.videos.filter((Q)=>Q.status==="success")??[]}getMetadata(){return this.data.request?.metadata}}function i(){if(typeof process<"u"&&process.env)return process.env[H];return}function YJ(){if(typeof process<"u"&&process.env)return process.env[g];return}class n{client;defaultDestination;constructor(J={}){let Q=J.apiKey??i();if(!Q)throw Error(`Mynth API key is required. Either pass it as an option or set the ${H} environment variable.`);this.defaultDestination=J.destination??YJ(),this.client=new w({apiKey:Q,baseUrl:J.baseUrl})}async generate(J){return(await this.createGenerationTask(J)).wait()}async upload(J){return G(this.client,J)}async generateAsync(J){return this.createGenerationTask(J)}async createGenerationTask(J){let Q=await L(this.client,J.inputs),W=(await this.client.post(_,{...J,inputs:Q,destination:J.destination??this.defaultDestination})).data;return new z(W.taskId,{client:this.client,pat:W.access?.publicAccessToken,resultFactory:($)=>new V($)})}async rate(J){return(await this.createRateTask(J)).wait()}async rateAsync(J){return this.createRateTask(J)}async resolveUrlOrFile(J){if(J.file!==void 0){let{urls:Q}=await this.upload(J.file),Z=Q[0];if(!Z)throw Error("Image upload returned no URL");return Z}return J.url}async createRateTask(J){let Q=await this.resolveUrlOrFile(J),{file:Z,url:W,...X}=J,j=(await this.client.post(q,{...X,url:Q})).data;return new z(j.taskId,{client:this.client,resultFactory:(b)=>K.fromTaskData(b)})}async alt(J){return(await this.createAltTask(J)).wait()}async altAsync(J){return this.createAltTask(J)}async createAltTask(J){let Q=await this.resolveUrlOrFile(J),W=(await this.client.post(m,{url:Q})).data;return new z(W.taskId,{client:this.client,resultFactory:($)=>C.fromTaskData($)})}async review(J){return(await this.createReviewTask(J)).wait()}async reviewAsync(J){return this.createReviewTask(J)}async createReviewTask(J){let Q=await this.resolveUrlOrFile(J),{file:Z,url:W,...X}=J,j=(await this.client.post(y,{...X,url:Q})).data;return new z(j.taskId,{client:this.client,resultFactory:(Y)=>U.fromTaskData(Y)})}async removeBackground(J){return(await this.createRemoveBackgroundTask(J)).wait()}async removeBackgroundAsync(J){return this.createRemoveBackgroundTask(J)}async createRemoveBackgroundTask(J){let Q=await this.resolveUrlOrFile(J),{file:Z,url:W,...X}=J,j=(await this.client.post(k,{...X,url:Q,destination:J.destination??this.defaultDestination})).data;return new z(j.taskId,{client:this.client,pat:j.access?.publicAccessToken,resultFactory:(Y)=>S.fromTaskData(Y)})}}class o{client;constructor(J={}){let Q=J.apiKey??i();if(!Q)throw Error(`Mynth API key is required. Either pass it as an option or set the ${H} environment variable.`);this.client=new w({apiKey:Q,baseUrl:J.baseUrl})}async generate(J){return(await this.createGenerationTask(J)).wait()}async generateAsync(J){return this.createGenerationTask(J)}async upload(J){return G(this.client,J)}async estimate(J){return(await this.client.post(E,await this.toRequestBody(J))).data}async toRequestBody(J){let Q=await L(this.client,J.inputs);return{...J,inputs:Q}}async createGenerationTask(J){let Z=(await this.client.post(h,await this.toRequestBody(J))).data;return new z(Z.taskId,{client:this.client,pat:Z.access?.publicAccessToken,polling:A,resultFactory:(W)=>new v(W)})}}class r{client;constructor(J={}){this.client=new w({baseUrl:J.baseUrl})}async list(){return(await this.client.getOrThrow(T,{auth:!1})).data}}class s{models;options;imageClient;videoClient;constructor(J={}){this.options=J,this.models=new r({baseUrl:J.baseUrl})}get image(){return this.imageClient??=new n(this.options),this.imageClient}get video(){return this.videoClient??=new o(this.options),this.videoClient}}var kJ=s;export{kJ as default,v as VideoGenerationResult,F as TaskAsyncUnauthorizedError,f as TaskAsyncTimeoutError,D as TaskAsyncTaskFetchError,P as TaskAsyncTaskFailedError,O as TaskAsyncFetchError,z as TaskAsync,o as MynthVideo,r as MynthModels,n as MynthImage,N as MynthAPIError,s as Mynth,U as ImageReviewResult,S as ImageRemoveBackgroundResult,K as ImageRateResult,V as ImageGenerationResult,C as ImageAltResult,$J as AVAILABLE_VIDEO_MODELS,ZJ as AVAILABLE_MODELS};
1
+ //#region src/constants.ts
2
+ /** Base URL for the Mynth API */
3
+ const API_URL = "https://api.mynth.io";
4
+ /** Environment variable name for the API key */
5
+ const API_KEY_ENV_VAR = "MYNTH_API_KEY";
6
+ /** Environment variable name for the default destination (by name/slug) */
7
+ const DESTINATION_ENV_VAR = "MYNTH_DESTINATION";
8
+ const GENERATE_IMAGE_PATH = "/image/generate";
9
+ const UPLOAD_IMAGE_PATH = "/image/upload";
10
+ const RATE_IMAGE_PATH = "/image/rate";
11
+ const ALT_IMAGE_PATH = "/image/alt";
12
+ const REVIEW_IMAGE_PATH = "/image/review";
13
+ const REMOVE_BACKGROUND_IMAGE_PATH = "/image/remove-background";
14
+ const GENERATE_VIDEO_PATH = "/video/generate";
15
+ const ESTIMATE_VIDEO_PATH = "/video/generate/estimate";
16
+ const MODELS_PATH = "/models";
17
+ const TASK_PATH = "/tasks";
18
+ const TASK_DETAILS_PATH = (id) => `${TASK_PATH}/${id}`;
19
+ const TASK_STATUS_PATH = (id) => `${TASK_PATH}/${id}/status`;
20
+ /**
21
+ * List of all available image generation models with their capabilities.
22
+ * Use this to build model selectors or validate model IDs.
23
+ */
24
+ const AVAILABLE_MODELS = [
25
+ {
26
+ id: "auto",
27
+ label: "Auto",
28
+ capabilities: []
29
+ },
30
+ {
31
+ id: "alibaba/qwen-image-2.0",
32
+ label: "Qwen Image 2.0",
33
+ capabilities: ["inputs"]
34
+ },
35
+ {
36
+ id: "alibaba/qwen-image-2.0-pro",
37
+ label: "Qwen Image 2.0 Pro",
38
+ capabilities: ["inputs"]
39
+ },
40
+ {
41
+ id: "alibaba/qwen-image-3.0",
42
+ label: "Qwen Image 3.0",
43
+ capabilities: ["inputs"]
44
+ },
45
+ {
46
+ id: "alibaba/qwen-image-3.0-pro",
47
+ label: "Qwen Image 3.0 Pro",
48
+ capabilities: ["inputs"]
49
+ },
50
+ {
51
+ id: "bytedance/seedream-5.0-lite",
52
+ label: "Seedream 5.0 Lite",
53
+ capabilities: ["inputs"]
54
+ },
55
+ {
56
+ id: "bytedance/seedream-pro",
57
+ label: "Seedream Pro",
58
+ capabilities: ["inputs"]
59
+ },
60
+ {
61
+ id: "black-forest-labs/flux.1-dev",
62
+ label: "FLUX.1 Dev",
63
+ capabilities: []
64
+ },
65
+ {
66
+ id: "black-forest-labs/flux-1-schnell",
67
+ label: "FLUX.1 Schnell",
68
+ capabilities: []
69
+ },
70
+ {
71
+ id: "tongyi-mai/z-image",
72
+ label: "Z Image",
73
+ capabilities: ["inputs"]
74
+ },
75
+ {
76
+ id: "tongyi-mai/z-image-turbo",
77
+ label: "Z Image Turbo",
78
+ capabilities: []
79
+ },
80
+ {
81
+ id: "black-forest-labs/flux.2-dev",
82
+ label: "FLUX.2 Dev",
83
+ capabilities: ["inputs"]
84
+ },
85
+ {
86
+ id: "black-forest-labs/flux.2-pro",
87
+ label: "FLUX.2 Pro",
88
+ capabilities: ["inputs"]
89
+ },
90
+ {
91
+ id: "black-forest-labs/flux.2-flex",
92
+ label: "FLUX.2 Flex",
93
+ capabilities: ["inputs"]
94
+ },
95
+ {
96
+ id: "black-forest-labs/flux.2-max",
97
+ label: "FLUX.2 Max",
98
+ capabilities: ["inputs"]
99
+ },
100
+ {
101
+ id: "black-forest-labs/flux.2-klein-4b",
102
+ label: "FLUX.2 Klein 4B",
103
+ capabilities: ["inputs"]
104
+ },
105
+ {
106
+ id: "bria/fibo-edit-1.5",
107
+ label: "FIBO Edit 1.5",
108
+ capabilities: ["inputs"]
109
+ },
110
+ {
111
+ id: "bria/fibo-generate-1.5",
112
+ label: "FIBO Generate 1.5",
113
+ capabilities: []
114
+ },
115
+ {
116
+ id: "circlestone-labs/anima",
117
+ label: "Anima",
118
+ capabilities: ["inputs"]
119
+ },
120
+ {
121
+ id: "john6666/bismuth-illustrious-mix",
122
+ label: "Bismuth Illustrious Mix",
123
+ capabilities: ["negative_prompt"]
124
+ },
125
+ {
126
+ id: "maxfeifei8/one-obsession",
127
+ label: "One obsession",
128
+ capabilities: ["negative_prompt"]
129
+ },
130
+ {
131
+ id: "klingai/kling-image-3.0",
132
+ label: "Kling IMAGE 3.0",
133
+ capabilities: ["inputs"]
134
+ },
135
+ {
136
+ id: "klingai/kling-image-o3",
137
+ label: "Kling IMAGE O3",
138
+ capabilities: ["inputs", "4k"]
139
+ },
140
+ {
141
+ id: "krea/krea-2-turbo",
142
+ label: "Krea 2 Turbo",
143
+ capabilities: ["inputs"]
144
+ },
145
+ {
146
+ id: "krea/krea-2-medium",
147
+ label: "Krea 2 Medium",
148
+ capabilities: ["inputs"]
149
+ },
150
+ {
151
+ id: "krea/krea-2-large",
152
+ label: "Krea 2 Large",
153
+ capabilities: ["inputs"]
154
+ },
155
+ {
156
+ id: "luma/uni-1",
157
+ label: "Luma UNI-1",
158
+ capabilities: ["inputs"]
159
+ },
160
+ {
161
+ id: "luma/uni-1-max",
162
+ label: "Luma UNI-1 Max",
163
+ capabilities: ["inputs"]
164
+ },
165
+ {
166
+ id: "meta/muse-image",
167
+ label: "Muse Image",
168
+ capabilities: ["inputs"]
169
+ },
170
+ {
171
+ id: "microsoft/mai-image-2.6",
172
+ label: "MAI Image 2.6",
173
+ capabilities: ["inputs"]
174
+ },
175
+ {
176
+ id: "microsoft/mai-image-2.6-flash",
177
+ label: "MAI Image 2.6 Flash",
178
+ capabilities: ["inputs"]
179
+ },
180
+ {
181
+ id: "minimax/h3",
182
+ label: "MiniMax H3",
183
+ capabilities: ["inputs"]
184
+ },
185
+ {
186
+ id: "purplesmartai/pony-diffusion-v6-xl",
187
+ label: "Pony Diffusion V6 XL",
188
+ capabilities: ["negative_prompt"]
189
+ },
190
+ {
191
+ id: "recraft/recraft-v4",
192
+ label: "Recraft V4",
193
+ capabilities: []
194
+ },
195
+ {
196
+ id: "recraft/recraft-v4-pro",
197
+ label: "Recraft V4 Pro",
198
+ capabilities: []
199
+ },
200
+ {
201
+ id: "reve/reve",
202
+ label: "Reve",
203
+ capabilities: ["inputs"]
204
+ },
205
+ {
206
+ id: "reve/reve-remix",
207
+ label: "Reve Remix",
208
+ capabilities: ["inputs"]
209
+ },
210
+ {
211
+ id: "sourceful/riverflow-2.0-pro",
212
+ label: "Riverflow 2.0 Pro",
213
+ capabilities: ["inputs", "4k"]
214
+ },
215
+ {
216
+ id: "google/gemini-3.1-flash-lite-image",
217
+ label: "Nano Banana 2 Lite",
218
+ capabilities: ["inputs"]
219
+ },
220
+ {
221
+ id: "google/gemini-3.1-flash-image",
222
+ label: "Nano Banana 2",
223
+ capabilities: ["inputs", "4k"]
224
+ },
225
+ {
226
+ id: "google/gemini-3-pro-image-preview",
227
+ label: "Nano Banana Pro",
228
+ capabilities: ["inputs", "4k"]
229
+ },
230
+ {
231
+ id: "imagineart/imagineart-1.5-pro",
232
+ label: "ImagineArt 1.5 Pro",
233
+ capabilities: ["4k"]
234
+ },
235
+ {
236
+ id: "imagineart/imagineart-2.0",
237
+ label: "ImagineArt 2.0",
238
+ capabilities: ["inputs"]
239
+ },
240
+ {
241
+ id: "openai/gpt-image-2",
242
+ label: "GPT Image 2",
243
+ capabilities: ["inputs"]
244
+ },
245
+ {
246
+ id: "openai/gpt-image-2.5-flare",
247
+ label: "GPT Image 2.5 Flare",
248
+ capabilities: ["inputs"]
249
+ },
250
+ {
251
+ id: "openai/gpt-image-2.5-sunburst",
252
+ label: "GPT Image 2.5 Sunburst",
253
+ capabilities: ["inputs"]
254
+ },
255
+ {
256
+ id: "wan/wan2.6-image",
257
+ label: "Wan 2.6 Image",
258
+ capabilities: []
259
+ },
260
+ {
261
+ id: "wan/wan2.7-image",
262
+ label: "Wan 2.7 Image",
263
+ capabilities: ["inputs"]
264
+ },
265
+ {
266
+ id: "wan/wan2.7-image-pro",
267
+ label: "Wan 2.7 Image Pro",
268
+ capabilities: ["inputs", "4k"]
269
+ },
270
+ {
271
+ id: "xai/grok-imagine-image",
272
+ label: "Grok Imagine Image",
273
+ capabilities: ["inputs"]
274
+ },
275
+ {
276
+ id: "xai/grok-imagine-image-2.0",
277
+ label: "Grok Imagine Image 2.0",
278
+ capabilities: ["inputs"]
279
+ },
280
+ {
281
+ id: "xai/grok-imagine-image-quality",
282
+ label: "Grok Imagine Image Quality",
283
+ capabilities: ["inputs"]
284
+ }
285
+ ];
286
+ /**
287
+ * Polling profile for video tasks.
288
+ *
289
+ * Video generation runs for minutes rather than seconds, so there is no fast
290
+ * opening phase to spend requests on, the steady interval is longer, and the
291
+ * wait budget is an hour instead of the 30 minutes image tasks get.
292
+ */
293
+ const VIDEO_POLLING = {
294
+ timeoutMs: 36e5,
295
+ fastDurationMs: 0,
296
+ intervalMs: 1e4
297
+ };
298
+ /**
299
+ * List of all available video generation models with their capabilities.
300
+ * Unlike images, video generation has no `auto` model: pick one explicitly.
301
+ */
302
+ const AVAILABLE_VIDEO_MODELS = [
303
+ {
304
+ id: "bytedance/seedance-2.0-mini",
305
+ label: "Seedance 2.0 Mini",
306
+ resolutions: ["480p", "720p"],
307
+ defaultResolution: "720p",
308
+ duration: {
309
+ default: 5,
310
+ min: 4,
311
+ max: 15
312
+ },
313
+ audio: true,
314
+ inputs: ["first_frame", "last_frame"],
315
+ maxInputs: 2
316
+ },
317
+ {
318
+ id: "google/gemini-omni-flash-1.1",
319
+ label: "Gemini Omni Flash 1.1",
320
+ resolutions: [
321
+ "720p",
322
+ "1080p",
323
+ "4k"
324
+ ],
325
+ defaultResolution: "720p",
326
+ duration: {
327
+ default: 8,
328
+ min: 3,
329
+ max: 10
330
+ },
331
+ audio: true,
332
+ inputs: ["first_frame", "last_frame"],
333
+ maxInputs: 2
334
+ },
335
+ {
336
+ id: "prunaai/p-video",
337
+ label: "P-Video",
338
+ resolutions: ["720p", "1080p"],
339
+ defaultResolution: "720p",
340
+ duration: {
341
+ default: 5,
342
+ min: 1,
343
+ max: 10
344
+ },
345
+ audio: true,
346
+ inputs: ["first_frame"],
347
+ maxInputs: 1
348
+ }
349
+ ];
350
+ //#endregion
351
+ //#region src/client.ts
352
+ /**
353
+ * Error thrown when an API request fails.
354
+ */
355
+ var MynthAPIError = class extends Error {
356
+ /** HTTP status code of the failed request */
357
+ status;
358
+ /** Error code from the API response, if available */
359
+ code;
360
+ constructor(message, status, code) {
361
+ super(message);
362
+ this.name = "MynthAPIError";
363
+ this.status = status;
364
+ this.code = code;
365
+ }
366
+ };
367
+ function createApiError(data, status) {
368
+ const errorResponse = data;
369
+ return new MynthAPIError(errorResponse.error || errorResponse.message || `Request failed with status ${status}`, status, errorResponse.code);
370
+ }
371
+ /**
372
+ * Internal HTTP client for making API requests.
373
+ * @internal
374
+ */
375
+ var MynthClient = class {
376
+ apiKey;
377
+ baseUrl;
378
+ constructor(options) {
379
+ this.apiKey = options.apiKey;
380
+ this.baseUrl = options.baseUrl ? options.baseUrl.endsWith("/") ? options.baseUrl.slice(0, -1) : options.baseUrl : API_URL;
381
+ }
382
+ getAuthHeaders(override) {
383
+ if (override?.auth === false) return {};
384
+ const token = override?.accessToken ?? this.apiKey;
385
+ return token ? { Authorization: `Bearer ${token}` } : {};
386
+ }
387
+ getUrl(path) {
388
+ return `${this.baseUrl}${path}`;
389
+ }
390
+ async post(path, data, { signal } = {}) {
391
+ const isFormData = typeof FormData !== "undefined" && data instanceof FormData;
392
+ const response = await fetch(this.getUrl(path), {
393
+ method: "POST",
394
+ headers: {
395
+ ...isFormData ? {} : { "Content-Type": "application/json" },
396
+ ...this.getAuthHeaders()
397
+ },
398
+ body: isFormData ? data : JSON.stringify(data),
399
+ ...signal ? { signal } : {}
400
+ });
401
+ const json = await response.json();
402
+ if (!response.ok) throw createApiError(json, response.status);
403
+ return json;
404
+ }
405
+ async get(path, { headers, accessToken, auth, signal } = {}) {
406
+ const response = await fetch(this.getUrl(path), {
407
+ headers: {
408
+ ...this.getAuthHeaders({
409
+ accessToken,
410
+ auth
411
+ }),
412
+ ...headers
413
+ },
414
+ ...signal ? { signal } : {}
415
+ });
416
+ return {
417
+ data: await response.json(),
418
+ status: response.status,
419
+ ok: response.ok
420
+ };
421
+ }
422
+ async getOrThrow(path, options = {}) {
423
+ const response = await this.get(path, options);
424
+ if (!response.ok) throw createApiError(response.data, response.status);
425
+ return response.data;
426
+ }
427
+ };
428
+ //#endregion
429
+ //#region src/image-alt-result.ts
430
+ /**
431
+ * Represents the result of a completed image alt text task.
432
+ */
433
+ var ImageAltResult = class ImageAltResult {
434
+ /** The task ID created for this alt text request */
435
+ taskId;
436
+ /** Cost charged for the completed task */
437
+ cost;
438
+ /** Generated alt text */
439
+ alt;
440
+ constructor(data) {
441
+ this.taskId = data.taskId;
442
+ this.cost = data.cost;
443
+ this.alt = data.alt;
444
+ }
445
+ static fromTaskData(data) {
446
+ if (data.status !== "completed" || data.result === null) throw new Error(`Image alt task ${data.id} is not completed`);
447
+ if (data.cost === null) throw new Error(`Image alt task ${data.id} is missing cost`);
448
+ return new ImageAltResult({
449
+ taskId: data.id,
450
+ cost: data.cost,
451
+ alt: data.result.alt
452
+ });
453
+ }
454
+ };
455
+ //#endregion
456
+ //#region src/image-generation-result.ts
457
+ /**
458
+ * Represents a completed image generation task.
459
+ *
460
+ * @template MetadataT - Type of the metadata attached to the request
461
+ * @template RatingT - Type of the rating response
462
+ */
463
+ var ImageGenerationResult = class {
464
+ /** Raw task data from the API */
465
+ data;
466
+ constructor(data) {
467
+ this.data = data;
468
+ }
469
+ /** Unique identifier for this task */
470
+ get id() {
471
+ return this.data.id;
472
+ }
473
+ /** Current status of the task */
474
+ get status() {
475
+ return this.data.status;
476
+ }
477
+ /**
478
+ * The generation result containing images, cost, and model info.
479
+ * Returns `null` if the task hasn't completed yet.
480
+ */
481
+ get result() {
482
+ return this.data.result;
483
+ }
484
+ /** Whether the task completed successfully */
485
+ get isCompleted() {
486
+ return this.data.status === "completed";
487
+ }
488
+ /** Whether the task failed */
489
+ get isFailed() {
490
+ return this.data.status === "failed";
491
+ }
492
+ /**
493
+ * Get all successfully generated image URLs.
494
+ * Convenience method that extracts just the URLs from successful images.
495
+ * Images delivered only to a user destination may have a `null` url and are omitted here;
496
+ * use `getImages()` and read `mynth_url` to access the CDN URL directly.
497
+ */
498
+ get urls() {
499
+ return this.data.result?.images.filter((img) => img.status === "success").map((img) => img.url).filter((url) => url !== null) ?? [];
500
+ }
501
+ getImages(options = {}) {
502
+ if (options.includeFailed) return this.data.result?.images ?? [];
503
+ return this.data.result?.images.filter((image) => image.status === "success") ?? [];
504
+ }
505
+ /**
506
+ * Get the metadata that was attached to the generation request.
507
+ */
508
+ getMetadata() {
509
+ return this.data.request?.metadata;
510
+ }
511
+ };
512
+ //#endregion
513
+ //#region src/image-rate-result.ts
514
+ /**
515
+ * Represents the result of a completed image content rating task.
516
+ *
517
+ * @template LevelT - Union of possible rating level strings (e.g. `"sfw" | "nsfw"`)
518
+ */
519
+ var ImageRateResult = class ImageRateResult {
520
+ /** The task ID created for this rating request */
521
+ taskId;
522
+ /** Cost charged for the completed task */
523
+ cost;
524
+ /** Assigned rating level */
525
+ level;
526
+ constructor(data) {
527
+ this.taskId = data.taskId;
528
+ this.cost = data.cost;
529
+ this.level = data.level;
530
+ }
531
+ static fromTaskData(data) {
532
+ if (data.status !== "completed" || data.result === null) throw new Error(`Image rate task ${data.id} is not completed`);
533
+ if (data.cost === null) throw new Error(`Image rate task ${data.id} is missing cost`);
534
+ return new ImageRateResult({
535
+ taskId: data.id,
536
+ cost: data.cost,
537
+ level: data.result.level
538
+ });
539
+ }
540
+ };
541
+ //#endregion
542
+ //#region src/image-remove-background-result.ts
543
+ /**
544
+ * Represents the result of a completed image background removal task.
545
+ *
546
+ * @template MetadataT - Type of the metadata attached to the request
547
+ */
548
+ var ImageRemoveBackgroundResult = class ImageRemoveBackgroundResult {
549
+ /** The task ID created for this request */
550
+ taskId;
551
+ /** Cost charged for the completed task */
552
+ cost;
553
+ /** The image with its background removed */
554
+ image;
555
+ /** Metadata attached to the request */
556
+ metadata;
557
+ constructor(data) {
558
+ this.taskId = data.taskId;
559
+ this.cost = data.cost;
560
+ this.image = data.image;
561
+ this.metadata = data.metadata;
562
+ }
563
+ static fromTaskData(data) {
564
+ if (data.status !== "completed" || data.result === null) throw new Error(`Image remove background task ${data.id} is not completed`);
565
+ if (data.cost === null) throw new Error(`Image remove background task ${data.id} is missing cost`);
566
+ return new ImageRemoveBackgroundResult({
567
+ taskId: data.id,
568
+ cost: data.cost,
569
+ image: data.result.image,
570
+ metadata: data.request.metadata
571
+ });
572
+ }
573
+ };
574
+ //#endregion
575
+ //#region src/image-review-result.ts
576
+ /**
577
+ * Represents the result of a completed image quality review task.
578
+ */
579
+ var ImageReviewResult = class ImageReviewResult {
580
+ /** The task ID created for this review request */
581
+ taskId;
582
+ /** Cost charged for the completed task */
583
+ cost;
584
+ /** Median reviewer score from 1 to 4. Higher is better. */
585
+ score;
586
+ /** Review summary */
587
+ summary;
588
+ /** Defects found by the reviewer panel */
589
+ findings;
590
+ /** Strengths identified by the reviewer panel */
591
+ strengths;
592
+ constructor(data) {
593
+ this.taskId = data.taskId;
594
+ this.cost = data.cost;
595
+ this.score = data.score;
596
+ this.summary = data.summary;
597
+ this.findings = data.findings;
598
+ this.strengths = data.strengths;
599
+ }
600
+ static fromTaskData(data) {
601
+ if (data.status !== "completed" || data.result === null) throw new Error(`Image review task ${data.id} is not completed`);
602
+ if (data.cost === null) throw new Error(`Image review task ${data.id} is missing cost`);
603
+ return new ImageReviewResult({
604
+ taskId: data.id,
605
+ cost: data.cost,
606
+ ...data.result
607
+ });
608
+ }
609
+ };
610
+ //#endregion
611
+ //#region src/task-async.ts
612
+ const POLLING_TIMEOUT_MS = 18e5;
613
+ const FAST_POLLING_DURATION_MS = 12e3;
614
+ const FAST_POLLING_INTERVAL_MS = 2500;
615
+ const SLOW_POLLING_INTERVAL_MS = 5e3;
616
+ const MAX_RETRY_COUNT = 20;
617
+ /**
618
+ * Error thrown when task polling exceeds the maximum timeout duration.
619
+ */
620
+ var TaskAsyncTimeoutError = class extends Error {
621
+ constructor(taskId, timeoutMs = POLLING_TIMEOUT_MS) {
622
+ super(`Task ${taskId} polling timed out after ${timeoutMs}ms`);
623
+ this.name = "TaskAsyncTimeoutError";
624
+ }
625
+ };
626
+ /**
627
+ * Error thrown when access to a task is denied (invalid API key or PAT).
628
+ */
629
+ var TaskAsyncUnauthorizedError = class extends Error {
630
+ constructor(taskId) {
631
+ super(`Unauthorized access to task ${taskId}`);
632
+ this.name = "TaskAsyncUnauthorizedError";
633
+ }
634
+ };
635
+ /**
636
+ * Error thrown when fetching task status fails after multiple retries.
637
+ */
638
+ var TaskAsyncFetchError = class extends Error {
639
+ constructor(taskId, cause) {
640
+ super(`Failed to fetch status for task ${taskId} after multiple retries`);
641
+ this.name = "TaskAsyncFetchError";
642
+ this.cause = cause;
643
+ }
644
+ };
645
+ /**
646
+ * Error thrown when fetching full task data fails.
647
+ */
648
+ var TaskAsyncTaskFetchError = class extends Error {
649
+ constructor(taskId, status, cause) {
650
+ const suffix = status ? ` (status ${status})` : "";
651
+ super(`Failed to fetch task ${taskId}${suffix}`);
652
+ this.name = "TaskAsyncTaskFetchError";
653
+ this.cause = cause;
654
+ }
655
+ };
656
+ /**
657
+ * Error thrown when a task fails before completion.
658
+ */
659
+ var TaskAsyncTaskFailedError = class extends Error {
660
+ constructor(taskId) {
661
+ super(`Task ${taskId} failed`);
662
+ this.name = "TaskAsyncTaskFailedError";
663
+ }
664
+ };
665
+ /**
666
+ * Represents an async task that can be polled for completion.
667
+ * Use `wait()` to poll until completion and get the typed result.
668
+ *
669
+ * @template ResultT - The result type returned once the task completes
670
+ */
671
+ var TaskAsync = class {
672
+ /** The unique identifier for this task */
673
+ id;
674
+ client;
675
+ _access;
676
+ resultFactory;
677
+ polling;
678
+ poll = null;
679
+ constructor(id, options) {
680
+ this.id = id;
681
+ this.client = options.client;
682
+ this._access = { publicAccessToken: options.pat };
683
+ this.resultFactory = options.resultFactory;
684
+ this.polling = {
685
+ timeoutMs: options.polling?.timeoutMs ?? POLLING_TIMEOUT_MS,
686
+ fastDurationMs: options.polling?.fastDurationMs ?? FAST_POLLING_DURATION_MS,
687
+ fastIntervalMs: options.polling?.fastIntervalMs ?? FAST_POLLING_INTERVAL_MS,
688
+ intervalMs: options.polling?.intervalMs ?? SLOW_POLLING_INTERVAL_MS
689
+ };
690
+ }
691
+ /**
692
+ * Public access information for client-side polling.
693
+ * Contains the public access token if one was generated.
694
+ */
695
+ get access() {
696
+ return this._access;
697
+ }
698
+ toString() {
699
+ return this.id;
700
+ }
701
+ /**
702
+ * Polls the task until completion and returns the typed result.
703
+ * Concurrent calls share one polling loop and settle with the same result.
704
+ *
705
+ * @param options.signal - Stops this wait when aborted (see {@link TaskAsyncWaitOptions})
706
+ * @throws {TaskAsyncTimeoutError} If polling exceeds the timeout
707
+ * @throws {TaskAsyncUnauthorizedError} If access is denied
708
+ * @throws {TaskAsyncFetchError} If fetching status fails repeatedly
709
+ * @throws {TaskAsyncTaskFetchError} If fetching the completed task fails
710
+ * @throws {TaskAsyncTaskFailedError} If the task fails before completion
711
+ */
712
+ async wait({ signal } = {}) {
713
+ signal?.throwIfAborted();
714
+ const poll = this.poll ??= this.startPoll();
715
+ if (!signal) {
716
+ poll.pinned = true;
717
+ return poll.promise;
718
+ }
719
+ poll.abortableWaiters++;
720
+ return new Promise((resolve, reject) => {
721
+ const onAbort = () => {
722
+ poll.abortableWaiters--;
723
+ reject(signal.reason);
724
+ if (poll.abortableWaiters === 0 && !poll.pinned) {
725
+ poll.controller.abort(signal.reason);
726
+ if (this.poll === poll) this.poll = null;
727
+ }
728
+ };
729
+ signal.addEventListener("abort", onAbort, { once: true });
730
+ poll.promise.then((result) => {
731
+ signal.removeEventListener("abort", onAbort);
732
+ resolve(result);
733
+ }, (error) => {
734
+ signal.removeEventListener("abort", onAbort);
735
+ reject(error);
736
+ });
737
+ });
738
+ }
739
+ startPoll() {
740
+ const controller = new AbortController();
741
+ const promise = this.pollUntilCompleted(controller.signal);
742
+ promise.catch(() => {});
743
+ return {
744
+ promise,
745
+ controller,
746
+ abortableWaiters: 0,
747
+ pinned: false
748
+ };
749
+ }
750
+ async pollUntilCompleted(signal) {
751
+ const { timeoutMs, fastDurationMs, fastIntervalMs, intervalMs } = this.polling;
752
+ const startTime = Date.now();
753
+ let retryCount = 0;
754
+ let useApiKeyFallback = false;
755
+ let lastError;
756
+ while (true) {
757
+ const elapsed = Date.now() - startTime;
758
+ if (elapsed >= timeoutMs) throw new TaskAsyncTimeoutError(this.id, timeoutMs);
759
+ const result = await this.fetchStatus(useApiKeyFallback, signal);
760
+ if (result.ok) {
761
+ if (result.status === "completed") {
762
+ const fetched = await this.fetchTask(signal);
763
+ if (fetched.ok) return this.resultFactory(fetched.data);
764
+ if (fetched.unauthorized) throw new TaskAsyncUnauthorizedError(this.id);
765
+ retryCount++;
766
+ if (!fetched.retryable || retryCount >= MAX_RETRY_COUNT) throw new TaskAsyncTaskFetchError(this.id, fetched.status, fetched.error);
767
+ } else if (result.status === "failed") throw new TaskAsyncTaskFailedError(this.id);
768
+ else retryCount = 0;
769
+ } else {
770
+ if ((result.unauthorized || result.notFound) && this._access.publicAccessToken && !useApiKeyFallback) {
771
+ useApiKeyFallback = true;
772
+ continue;
773
+ }
774
+ if (result.unauthorized) throw new TaskAsyncUnauthorizedError(this.id);
775
+ if (result.retryable) {
776
+ retryCount++;
777
+ lastError = result.error;
778
+ if (retryCount >= MAX_RETRY_COUNT) throw new TaskAsyncFetchError(this.id, lastError);
779
+ }
780
+ }
781
+ const interval = (elapsed < fastDurationMs ? fastIntervalMs : intervalMs) + Math.random() * 500;
782
+ const remainingTime = timeoutMs - elapsed;
783
+ const waitTime = Math.min(interval, remainingTime);
784
+ await this.sleep(waitTime, signal);
785
+ }
786
+ }
787
+ async fetchStatus(useApiKey, signal) {
788
+ const accessToken = useApiKey || !this._access.publicAccessToken ? void 0 : this._access.publicAccessToken;
789
+ try {
790
+ const response = await this.client.get(TASK_STATUS_PATH(this.id), {
791
+ accessToken,
792
+ signal
793
+ });
794
+ if (response.ok) return {
795
+ ok: true,
796
+ status: response.data.data.status
797
+ };
798
+ if (response.status === 401 || response.status === 403) return {
799
+ ok: false,
800
+ unauthorized: true,
801
+ retryable: false
802
+ };
803
+ if (response.status === 404) return {
804
+ ok: false,
805
+ unauthorized: false,
806
+ retryable: true,
807
+ notFound: true
808
+ };
809
+ if (response.status >= 500) return {
810
+ ok: false,
811
+ unauthorized: false,
812
+ retryable: true
813
+ };
814
+ return {
815
+ ok: false,
816
+ unauthorized: false,
817
+ retryable: false
818
+ };
819
+ } catch (error) {
820
+ signal.throwIfAborted();
821
+ return {
822
+ ok: false,
823
+ unauthorized: false,
824
+ retryable: true,
825
+ error: error instanceof Error ? error : new Error(String(error))
826
+ };
827
+ }
828
+ }
829
+ async fetchTask(signal) {
830
+ try {
831
+ const response = await this.client.get(TASK_DETAILS_PATH(this.id), { signal });
832
+ if (response.ok) return {
833
+ ok: true,
834
+ data: response.data.data
835
+ };
836
+ if (response.status === 401 || response.status === 403) return {
837
+ ok: false,
838
+ unauthorized: true,
839
+ retryable: false
840
+ };
841
+ if (response.status === 404 || response.status >= 500) return {
842
+ ok: false,
843
+ unauthorized: false,
844
+ retryable: true,
845
+ status: response.status
846
+ };
847
+ return {
848
+ ok: false,
849
+ unauthorized: false,
850
+ retryable: false,
851
+ status: response.status
852
+ };
853
+ } catch (error) {
854
+ signal.throwIfAborted();
855
+ return {
856
+ ok: false,
857
+ unauthorized: false,
858
+ retryable: true,
859
+ error: error instanceof Error ? error : new Error(String(error))
860
+ };
861
+ }
862
+ }
863
+ sleep(ms, signal) {
864
+ return new Promise((resolve, reject) => {
865
+ signal.throwIfAborted();
866
+ const onAbort = () => {
867
+ clearTimeout(timer);
868
+ reject(signal.reason);
869
+ };
870
+ const timer = setTimeout(() => {
871
+ signal.removeEventListener("abort", onAbort);
872
+ resolve();
873
+ }, ms);
874
+ signal.addEventListener("abort", onAbort, { once: true });
875
+ });
876
+ }
877
+ };
878
+ //#endregion
879
+ //#region src/uploads.ts
880
+ const UPLOAD_FIELD_NAME = "images";
881
+ const UPLOAD_FILENAME = "image";
882
+ function isUploadInput(value) {
883
+ return typeof Blob !== "undefined" && value instanceof Blob;
884
+ }
885
+ /**
886
+ * Upload images to Mynth temporary input storage.
887
+ * Image and video generation share this endpoint: video inputs are images.
888
+ */
889
+ async function uploadImages(client, input, { signal } = {}) {
890
+ const form = new FormData();
891
+ const inputs = Array.isArray(input) ? input : [input];
892
+ for (const upload of inputs) form.append(UPLOAD_FIELD_NAME, upload, typeof File !== "undefined" && upload instanceof File ? upload.name : UPLOAD_FILENAME);
893
+ return (await client.post(UPLOAD_IMAGE_PATH, form, { signal })).data;
894
+ }
895
+ /**
896
+ * Turn caller inputs into wire inputs, uploading any local files first.
897
+ * All files go up in a single request, and the returned URLs are slotted back
898
+ * into their original positions so input order (and role) is preserved.
899
+ */
900
+ async function resolveInputs(client, inputs, { signal } = {}) {
901
+ if (!inputs?.length) return;
902
+ const files = inputs.flatMap((input) => {
903
+ if (isUploadInput(input)) return [input];
904
+ if (typeof input !== "string" && input.source.type === "file") return [input.source.file];
905
+ return [];
906
+ });
907
+ const urls = files.length ? (await uploadImages(client, files, { signal })).urls : [];
908
+ let i = 0;
909
+ return inputs.map((input) => {
910
+ if (typeof input === "string") return input;
911
+ if (isUploadInput(input)) return urls[i++];
912
+ const source = input.source.type === "file" ? {
913
+ type: "url",
914
+ url: urls[i++]
915
+ } : input.source;
916
+ return input.as === void 0 ? {
917
+ type: "image",
918
+ source
919
+ } : {
920
+ type: "image",
921
+ as: input.as,
922
+ source
923
+ };
924
+ });
925
+ }
926
+ //#endregion
927
+ //#region src/video-generation-result.ts
928
+ /**
929
+ * Represents a completed video generation task.
930
+ *
931
+ * @template MetadataT - Type of the metadata attached to the request
932
+ */
933
+ var VideoGenerationResult = class {
934
+ /** Raw task data from the API */
935
+ data;
936
+ constructor(data) {
937
+ this.data = data;
938
+ }
939
+ /** Unique identifier for this task */
940
+ get id() {
941
+ return this.data.id;
942
+ }
943
+ /** Current status of the task */
944
+ get status() {
945
+ return this.data.status;
946
+ }
947
+ /**
948
+ * The generation result containing videos and model info.
949
+ * Returns `null` if the task hasn't completed yet.
950
+ */
951
+ get result() {
952
+ return this.data.result;
953
+ }
954
+ /** Whether the task completed successfully */
955
+ get isCompleted() {
956
+ return this.data.status === "completed";
957
+ }
958
+ /** Whether the task failed */
959
+ get isFailed() {
960
+ return this.data.status === "failed";
961
+ }
962
+ /**
963
+ * Get all successfully generated video URLs.
964
+ * Convenience method that extracts just the URLs from successful videos.
965
+ */
966
+ get urls() {
967
+ return this.getVideos().map((video) => video.url);
968
+ }
969
+ getVideos(options = {}) {
970
+ if (options.includeFailed) return this.data.result?.videos ?? [];
971
+ return this.data.result?.videos.filter((video) => video.status === "success") ?? [];
972
+ }
973
+ /**
974
+ * Get the metadata that was attached to the generation request.
975
+ */
976
+ getMetadata() {
977
+ return this.data.request?.metadata;
978
+ }
979
+ };
980
+ //#endregion
981
+ //#region src/index.ts
982
+ /**
983
+ * Attempts to read the API key from environment variables.
984
+ * Works in Node.js, Bun, Deno, and edge runtimes that support process.env.
985
+ */
986
+ function getApiKeyFromEnv() {
987
+ if (typeof process !== "undefined" && process.env) return process.env[API_KEY_ENV_VAR];
988
+ }
989
+ /**
990
+ * Attempts to read the default destination from environment variables.
991
+ * Works in Node.js, Bun, Deno, and edge runtimes that support process.env.
992
+ */
993
+ function getDestinationFromEnv() {
994
+ if (typeof process !== "undefined" && process.env) return process.env[DESTINATION_ENV_VAR];
995
+ }
996
+ /**
997
+ * Client for interacting with the Mynth image generation and analysis APIs.
998
+ *
999
+ * @example
1000
+ * ```typescript
1001
+ * // Using environment variable (MYNTH_API_KEY)
1002
+ * const image = new MynthImage();
1003
+ *
1004
+ * // Or with explicit API key
1005
+ * const image = new MynthImage({ apiKey: "mak_..." });
1006
+ *
1007
+ * // Generate an image
1008
+ * const result = await image.generate({
1009
+ * prompt: "A beautiful sunset over mountains",
1010
+ * model: "black-forest-labs/flux.1-dev",
1011
+ * });
1012
+ *
1013
+ * console.log(result.urls); // ["https://..."]
1014
+ * ```
1015
+ */
1016
+ var MynthImage = class {
1017
+ client;
1018
+ defaultDestination;
1019
+ /**
1020
+ * Creates a new MynthImage client instance.
1021
+ *
1022
+ * @param options - Configuration options
1023
+ * @param options.apiKey - Your API key (defaults to MYNTH_API_KEY env var)
1024
+ * @param options.baseUrl - Custom API base URL
1025
+ * @param options.destination - Default destination name (defaults to MYNTH_DESTINATION env var)
1026
+ * @throws {Error} If no API key is provided and MYNTH_API_KEY is not set
1027
+ */
1028
+ constructor(options = {}) {
1029
+ const apiKey = options.apiKey ?? getApiKeyFromEnv();
1030
+ if (!apiKey) throw new Error(`Mynth API key is required. Either pass it as an option or set the ${API_KEY_ENV_VAR} environment variable.`);
1031
+ this.defaultDestination = options.destination ?? getDestinationFromEnv();
1032
+ this.client = new MynthClient({
1033
+ apiKey,
1034
+ baseUrl: options.baseUrl
1035
+ });
1036
+ }
1037
+ /**
1038
+ * Generate images from a text prompt.
1039
+ *
1040
+ * @param request - Image generation request parameters
1041
+ * @param options.signal - Aborts the upload, the create request, or the wait for completion
1042
+ * @returns A completed ImageGenerationResult with the generation results
1043
+ *
1044
+ * @example
1045
+ * ```typescript
1046
+ * const result = await image.generate({
1047
+ * prompt: "A serene lake at dawn",
1048
+ * model: "black-forest-labs/flux.1-dev",
1049
+ * });
1050
+ * console.log(result.urls);
1051
+ * ```
1052
+ */
1053
+ async generate(request, options = {}) {
1054
+ return (await this.createGenerationTask(request, options)).wait(options);
1055
+ }
1056
+ /**
1057
+ * Upload one or more images to Mynth temporary input storage.
1058
+ *
1059
+ * Accepts File/Blob or an array of File/Blob inputs.
1060
+ *
1061
+ * @param input - Image input or inputs to upload
1062
+ * @returns Uploaded image URLs that can be passed to generation `inputs`
1063
+ *
1064
+ * @example
1065
+ * ```typescript
1066
+ * const { urls } = await image.upload(file);
1067
+ * await image.generate({ prompt: "Use this reference", inputs: urls });
1068
+ * ```
1069
+ */
1070
+ async upload(input) {
1071
+ return uploadImages(this.client, input);
1072
+ }
1073
+ /**
1074
+ * Start image generation without waiting for completion.
1075
+ *
1076
+ * @param request - Image generation request parameters
1077
+ * @param options.signal - Aborts the upload or the create request. Pass a signal to `.wait()` to abort the wait.
1078
+ * @returns A TaskAsync that can be polled for completion via `.wait()`
1079
+ *
1080
+ * @example
1081
+ * ```typescript
1082
+ * const taskAsync = await image.generateAsync({
1083
+ * prompt: "A futuristic cityscape",
1084
+ * });
1085
+ *
1086
+ * return { id: taskAsync.id, access: taskAsync.access };
1087
+ * ```
1088
+ */
1089
+ async generateAsync(request, options = {}) {
1090
+ return this.createGenerationTask(request, options);
1091
+ }
1092
+ async createGenerationTask(request, { signal }) {
1093
+ const inputs = await resolveInputs(this.client, request.inputs, { signal });
1094
+ const data = (await this.client.post(GENERATE_IMAGE_PATH, {
1095
+ ...request,
1096
+ inputs,
1097
+ destination: request.destination ?? this.defaultDestination
1098
+ }, { signal })).data;
1099
+ return new TaskAsync(data.taskId, {
1100
+ client: this.client,
1101
+ pat: data.access?.publicAccessToken,
1102
+ resultFactory: (data) => new ImageGenerationResult(data)
1103
+ });
1104
+ }
1105
+ /**
1106
+ * Rate the content of a single image.
1107
+ *
1108
+ * Uses AI classification to assign a rating level. Mode defaults to
1109
+ * `"nsfw_sfw"` (`"sfw"` / `"nsfw"`); pass custom `levels` to define your own scale.
1110
+ *
1111
+ * @param request - Image URL or local file, and optional rating mode
1112
+ * @returns An ImageRateResult with the assigned level
1113
+ *
1114
+ * @example
1115
+ * ```typescript
1116
+ * // Default sfw/nsfw (mode optional)
1117
+ * const result = await image.rate({ url: "https://..." });
1118
+ * console.log(result.level); // "sfw" | "nsfw"
1119
+ *
1120
+ * // Custom levels
1121
+ * const result = await image.rate({
1122
+ * url: "https://...",
1123
+ * mode: "custom",
1124
+ * levels: [
1125
+ * { value: "safe", description: "No explicit content" },
1126
+ * { value: "mature", description: "Adult themes, no nudity" },
1127
+ * { value: "explicit", description: "Contains nudity or graphic content" },
1128
+ * ] as const,
1129
+ * });
1130
+ * console.log(result.level); // "safe" | "mature" | "explicit"
1131
+ * ```
1132
+ */
1133
+ async rate(request) {
1134
+ return (await this.createRateTask(request)).wait();
1135
+ }
1136
+ /**
1137
+ * Start image content rating without waiting for completion.
1138
+ *
1139
+ * @param request - Image URL or local file, and optional rating mode
1140
+ * @returns A TaskAsync that can be polled for completion via `.wait()`
1141
+ *
1142
+ * @example
1143
+ * ```typescript
1144
+ * const taskAsync = await image.rateAsync({ url: "https://..." });
1145
+ *
1146
+ * const result = await taskAsync.wait();
1147
+ * console.log(result.level);
1148
+ * ```
1149
+ */
1150
+ async rateAsync(request) {
1151
+ return this.createRateTask(request);
1152
+ }
1153
+ async resolveUrlOrFile(request) {
1154
+ if (request.file !== void 0) {
1155
+ const { urls } = await this.upload(request.file);
1156
+ const url = urls[0];
1157
+ if (!url) throw new Error("Image upload returned no URL");
1158
+ return url;
1159
+ }
1160
+ return request.url;
1161
+ }
1162
+ async createRateTask(request) {
1163
+ const url = await this.resolveUrlOrFile(request);
1164
+ const { file: _, url: __, ...rest } = request;
1165
+ const data = (await this.client.post(RATE_IMAGE_PATH, {
1166
+ ...rest,
1167
+ url
1168
+ })).data;
1169
+ return new TaskAsync(data.taskId, {
1170
+ client: this.client,
1171
+ resultFactory: (taskData) => ImageRateResult.fromTaskData(taskData)
1172
+ });
1173
+ }
1174
+ /**
1175
+ * Generate alt text for a single image.
1176
+ *
1177
+ * Uses AI image analysis to produce short alt text for the image.
1178
+ *
1179
+ * @param request - Image URL or local file
1180
+ * @returns An ImageAltResult with the generated alt text
1181
+ *
1182
+ * @example
1183
+ * ```typescript
1184
+ * const result = await image.alt({ url: "https://..." });
1185
+ * console.log(result.alt);
1186
+ * ```
1187
+ */
1188
+ async alt(request) {
1189
+ return (await this.createAltTask(request)).wait();
1190
+ }
1191
+ /**
1192
+ * Start image alt text generation without waiting for completion.
1193
+ *
1194
+ * @param request - Image URL or local file
1195
+ * @returns A TaskAsync that can be polled for completion via `.wait()`
1196
+ *
1197
+ * @example
1198
+ * ```typescript
1199
+ * const taskAsync = await image.altAsync({ url: "https://..." });
1200
+ *
1201
+ * const result = await taskAsync.wait();
1202
+ * console.log(result.alt);
1203
+ * ```
1204
+ */
1205
+ async altAsync(request) {
1206
+ return this.createAltTask(request);
1207
+ }
1208
+ async createAltTask(request) {
1209
+ const url = await this.resolveUrlOrFile(request);
1210
+ const data = (await this.client.post(ALT_IMAGE_PATH, { url })).data;
1211
+ return new TaskAsync(data.taskId, {
1212
+ client: this.client,
1213
+ resultFactory: (taskData) => ImageAltResult.fromTaskData(taskData)
1214
+ });
1215
+ }
1216
+ /**
1217
+ * Review a single image with a multi-model quality panel.
1218
+ *
1219
+ * @param request - Image URL or local file, and optional review effort
1220
+ * @returns An ImageReviewResult with the score, summary, findings, and strengths
1221
+ *
1222
+ * @example
1223
+ * ```typescript
1224
+ * const result = await image.review({ url: "https://..." });
1225
+ * console.log(result.score); // 1–4, higher is better
1226
+ * console.log(result.findings);
1227
+ * ```
1228
+ */
1229
+ async review(request) {
1230
+ return (await this.createReviewTask(request)).wait();
1231
+ }
1232
+ /**
1233
+ * Start an image quality review without waiting for completion.
1234
+ *
1235
+ * @param request - Image URL or local file, and optional review effort
1236
+ * @returns A TaskAsync that can be polled for completion via `.wait()`
1237
+ */
1238
+ async reviewAsync(request) {
1239
+ return this.createReviewTask(request);
1240
+ }
1241
+ async createReviewTask(request) {
1242
+ const url = await this.resolveUrlOrFile(request);
1243
+ const { file: _, url: __, ...rest } = request;
1244
+ const data = (await this.client.post(REVIEW_IMAGE_PATH, {
1245
+ ...rest,
1246
+ url
1247
+ })).data;
1248
+ return new TaskAsync(data.taskId, {
1249
+ client: this.client,
1250
+ resultFactory: (taskData) => ImageReviewResult.fromTaskData(taskData)
1251
+ });
1252
+ }
1253
+ /**
1254
+ * Remove the background from a single image.
1255
+ *
1256
+ * Mynth picks the model. The result keeps the provider's format unless
1257
+ * `output.format` asks for `png` or `webp`.
1258
+ *
1259
+ * @param request - Image URL or local file, plus optional output, destination, webhook, and metadata
1260
+ * @returns An ImageRemoveBackgroundResult with the transparent image
1261
+ *
1262
+ * @example
1263
+ * ```typescript
1264
+ * const result = await image.removeBackground({ url: "https://..." });
1265
+ * console.log(result.image.url);
1266
+ * ```
1267
+ */
1268
+ async removeBackground(request) {
1269
+ return (await this.createRemoveBackgroundTask(request)).wait();
1270
+ }
1271
+ /**
1272
+ * Start background removal without waiting for completion.
1273
+ *
1274
+ * @param request - Image URL or local file, plus optional output, destination, webhook, and metadata
1275
+ * @returns A TaskAsync that can be polled for completion via `.wait()`
1276
+ *
1277
+ * @example
1278
+ * ```typescript
1279
+ * const taskAsync = await image.removeBackgroundAsync({ url: "https://..." });
1280
+ *
1281
+ * return { id: taskAsync.id, access: taskAsync.access };
1282
+ * ```
1283
+ */
1284
+ async removeBackgroundAsync(request) {
1285
+ return this.createRemoveBackgroundTask(request);
1286
+ }
1287
+ async createRemoveBackgroundTask(request) {
1288
+ const url = await this.resolveUrlOrFile(request);
1289
+ const { file: _, url: __, ...rest } = request;
1290
+ const data = (await this.client.post(REMOVE_BACKGROUND_IMAGE_PATH, {
1291
+ ...rest,
1292
+ url,
1293
+ destination: request.destination ?? this.defaultDestination
1294
+ })).data;
1295
+ return new TaskAsync(data.taskId, {
1296
+ client: this.client,
1297
+ pat: data.access?.publicAccessToken,
1298
+ resultFactory: (taskData) => ImageRemoveBackgroundResult.fromTaskData(taskData)
1299
+ });
1300
+ }
1301
+ };
1302
+ /**
1303
+ * Client for interacting with the Mynth video generation API.
1304
+ *
1305
+ * Mirrors {@link MynthImage}: `generate()` waits, `generateAsync()` hands you a
1306
+ * pollable task, and local files passed in `inputs` are uploaded for you.
1307
+ * Video tasks run for minutes, so waits use a longer, slower polling profile.
1308
+ *
1309
+ * @example
1310
+ * ```typescript
1311
+ * const video = new MynthVideo({ apiKey: "mak_..." });
1312
+ *
1313
+ * const result = await video.generate({
1314
+ * model: "google/gemini-omni-flash-1.1",
1315
+ * prompt: "A cat surfing a wave at sunset",
1316
+ * duration: 8,
1317
+ * resolution: "1080p",
1318
+ * });
1319
+ *
1320
+ * console.log(result.urls); // ["https://..."]
1321
+ * ```
1322
+ */
1323
+ var MynthVideo = class {
1324
+ client;
1325
+ /**
1326
+ * Creates a new MynthVideo client instance.
1327
+ *
1328
+ * @param options - Configuration options
1329
+ * @param options.apiKey - Your API key (defaults to MYNTH_API_KEY env var)
1330
+ * @param options.baseUrl - Custom API base URL
1331
+ * @throws {Error} If no API key is provided and MYNTH_API_KEY is not set
1332
+ */
1333
+ constructor(options = {}) {
1334
+ const apiKey = options.apiKey ?? getApiKeyFromEnv();
1335
+ if (!apiKey) throw new Error(`Mynth API key is required. Either pass it as an option or set the ${API_KEY_ENV_VAR} environment variable.`);
1336
+ this.client = new MynthClient({
1337
+ apiKey,
1338
+ baseUrl: options.baseUrl
1339
+ });
1340
+ }
1341
+ /**
1342
+ * Generate a video from a text prompt, optionally guided by input images.
1343
+ *
1344
+ * Waits for the task to complete. Video generation is slow: this poll can
1345
+ * legitimately run for many minutes. Use `generateAsync()` (or a webhook)
1346
+ * when you cannot hold a request open that long.
1347
+ *
1348
+ * @param request - Video generation request parameters
1349
+ * @returns A completed VideoGenerationResult
1350
+ *
1351
+ * @example
1352
+ * ```typescript
1353
+ * const result = await video.generate({
1354
+ * model: "bytedance/seedance-2.0-mini",
1355
+ * prompt: "A drone shot over a misty forest at dawn",
1356
+ * });
1357
+ * console.log(result.urls);
1358
+ * ```
1359
+ */
1360
+ async generate(request) {
1361
+ return (await this.createGenerationTask(request)).wait();
1362
+ }
1363
+ /**
1364
+ * Start video generation without waiting for completion.
1365
+ *
1366
+ * The preferred entry point for server code: hand `taskAsync.id` and
1367
+ * `taskAsync.access.publicAccessToken` to the browser, or register a webhook,
1368
+ * instead of holding a connection open for the length of a render.
1369
+ *
1370
+ * @param request - Video generation request parameters
1371
+ * @returns A TaskAsync that can be polled for completion via `.wait()`
1372
+ *
1373
+ * @example
1374
+ * ```typescript
1375
+ * const taskAsync = await video.generateAsync({
1376
+ * model: "prunaai/p-video",
1377
+ * prompt: "A neon city street in the rain",
1378
+ * });
1379
+ *
1380
+ * return { id: taskAsync.id, access: taskAsync.access };
1381
+ * ```
1382
+ */
1383
+ async generateAsync(request) {
1384
+ return this.createGenerationTask(request);
1385
+ }
1386
+ /**
1387
+ * Upload one or more images to Mynth temporary input storage.
1388
+ *
1389
+ * Video inputs are images, so this is the same storage `image.upload()` uses.
1390
+ * Passing files straight to `generate()` uploads them for you; call this
1391
+ * directly only when you want to reuse the URLs across several requests.
1392
+ *
1393
+ * @param input - Image input or inputs to upload
1394
+ * @returns Uploaded image URLs that can be passed to generation `inputs`
1395
+ */
1396
+ async upload(input) {
1397
+ return uploadImages(this.client, input);
1398
+ }
1399
+ /**
1400
+ * Price a video generation request without generating anything.
1401
+ *
1402
+ * The request is validated exactly as `generate()` would validate it, so an
1403
+ * unsupported duration, resolution or input combination throws here too —
1404
+ * making this a cheap pre-flight check as well as a cost lookup. Because
1405
+ * video pins a concrete model, the returned estimate is exact.
1406
+ *
1407
+ * @param request - The same request you would pass to `generate()`
1408
+ * @returns The estimated cost in USD
1409
+ *
1410
+ * @example
1411
+ * ```typescript
1412
+ * const { estimatedCost } = await video.estimate({
1413
+ * model: "google/gemini-omni-flash-1.1",
1414
+ * prompt: "A timelapse of clouds over a canyon",
1415
+ * duration: 10,
1416
+ * resolution: "4k",
1417
+ * });
1418
+ * ```
1419
+ */
1420
+ async estimate(request) {
1421
+ return (await this.client.post(ESTIMATE_VIDEO_PATH, await this.toRequestBody(request))).data;
1422
+ }
1423
+ async toRequestBody(request) {
1424
+ const { inputs: clientInputs, ...rest } = request;
1425
+ const inputs = await resolveInputs(this.client, clientInputs);
1426
+ return inputs ? {
1427
+ ...rest,
1428
+ inputs
1429
+ } : rest;
1430
+ }
1431
+ async createGenerationTask(request) {
1432
+ const data = (await this.client.post(GENERATE_VIDEO_PATH, await this.toRequestBody(request))).data;
1433
+ return new TaskAsync(data.taskId, {
1434
+ client: this.client,
1435
+ pat: data.access?.publicAccessToken,
1436
+ polling: VIDEO_POLLING,
1437
+ resultFactory: (taskData) => new VideoGenerationResult(taskData)
1438
+ });
1439
+ }
1440
+ };
1441
+ /**
1442
+ * Client for interacting with the public Mynth model catalog.
1443
+ */
1444
+ var MynthModels = class {
1445
+ client;
1446
+ /**
1447
+ * Creates a new MynthModels client instance.
1448
+ *
1449
+ * @param options - Configuration options
1450
+ * @param options.baseUrl - Custom API base URL
1451
+ */
1452
+ constructor(options = {}) {
1453
+ this.client = new MynthClient({ baseUrl: options.baseUrl });
1454
+ }
1455
+ /**
1456
+ * List available image generation models.
1457
+ *
1458
+ * This endpoint is public and does not require a Mynth API key.
1459
+ *
1460
+ * @returns Available image and video models with display names, served modes, and pricing
1461
+ *
1462
+ * @example
1463
+ * ```typescript
1464
+ * const models = await mynth.models.list();
1465
+ * console.log(models[0]?.id);
1466
+ * ```
1467
+ */
1468
+ async list() {
1469
+ return (await this.client.getOrThrow(MODELS_PATH, { auth: false })).data;
1470
+ }
1471
+ };
1472
+ /**
1473
+ * Bundled Mynth client providing access to all media type clients.
1474
+ *
1475
+ * @example
1476
+ * ```typescript
1477
+ * const mynth = new Mynth({ apiKey: "mak_..." });
1478
+ *
1479
+ * // Generate an image
1480
+ * const result = await mynth.image.generate({
1481
+ * prompt: "A beautiful sunset over mountains",
1482
+ * });
1483
+ * ```
1484
+ */
1485
+ var Mynth = class {
1486
+ /** Public model catalog client */
1487
+ models;
1488
+ options;
1489
+ imageClient;
1490
+ videoClient;
1491
+ /**
1492
+ * Creates a new Mynth client instance.
1493
+ *
1494
+ * @param options - Configuration options
1495
+ * @param options.apiKey - Your API key (defaults to MYNTH_API_KEY env var)
1496
+ * @param options.baseUrl - Custom API base URL
1497
+ */
1498
+ constructor(options = {}) {
1499
+ this.options = options;
1500
+ this.models = new MynthModels({ baseUrl: options.baseUrl });
1501
+ }
1502
+ /** Image generation and analysis client */
1503
+ get image() {
1504
+ this.imageClient ??= new MynthImage(this.options);
1505
+ return this.imageClient;
1506
+ }
1507
+ /** Video generation client */
1508
+ get video() {
1509
+ this.videoClient ??= new MynthVideo(this.options);
1510
+ return this.videoClient;
1511
+ }
1512
+ };
1513
+ //#endregion
1514
+ export { AVAILABLE_MODELS, AVAILABLE_VIDEO_MODELS, ImageAltResult, ImageGenerationResult, ImageRateResult, ImageRemoveBackgroundResult, ImageReviewResult, Mynth, Mynth as default, MynthAPIError, MynthImage, MynthModels, MynthVideo, TaskAsync, TaskAsyncFetchError, TaskAsyncTaskFailedError, TaskAsyncTaskFetchError, TaskAsyncTimeoutError, TaskAsyncUnauthorizedError, VideoGenerationResult };