@imgly/plugin-ai-image-generation-web
Version:
AI image generation plugin for the CE.SDK editor
5 lines • 248 kB
JavaScript
var yo=Object.create;var sr=Object.defineProperty;var _o=Object.getOwnPropertyDescriptor;var bo=Object.getOwnPropertyNames;var vo=Object.getPrototypeOf,wo=Object.prototype.hasOwnProperty;var S=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Io=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of bo(t))!wo.call(e,n)&&n!==i&&sr(e,n,{get:()=>t[n],enumerable:!(r=_o(t,n))||r.enumerable});return e};var xo=(e,t,i)=>(i=e!=null?yo(vo(e)):{},Io(t||!e||!e.__esModule?sr(i,"default",{value:e,enumerable:!0}):i,e));var xi=S(Y=>{"use strict";var Fp=Y&&Y.__awaiter||function(e,t,i,r){function n(a){return a instanceof i?a:new i(function(o){o(a)})}return new(i||(i=Promise))(function(a,o){function l(s){try{u(r.next(s))}catch(c){o(c)}}function d(s){try{u(r.throw(s))}catch(c){o(c)}}function u(s){s.done?a(s.value):n(s.value).then(l,d)}u((r=r.apply(e,t||[])).next())})};Object.defineProperty(Y,"__esModule",{value:!0});Y.TARGET_URL_HEADER=void 0;Y.withMiddleware=Rp;Y.withProxy=Np;function Rp(...e){let t=i=>typeof i=="function";return i=>Fp(this,void 0,void 0,function*(){let r=Object.assign({},i);for(let n of e.filter(t))r=yield n(r);return r})}Y.TARGET_URL_HEADER="x-fal-target-url";function Np(e){let t=i=>Promise.resolve(i);return typeof window>"u"?t:i=>i.headers&&Y.TARGET_URL_HEADER in i?t(i):Promise.resolve(Object.assign(Object.assign({},i),{url:e.targetUrl,headers:Object.assign(Object.assign({},i.headers||{}),{[Y.TARGET_URL_HEADER]:i.url})}))}});var Et=S(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.RUNNER_HINT_HEADER=F.QUEUE_PRIORITY_HEADER=F.REQUEST_TIMEOUT_TYPE_HEADER=F.REQUEST_TIMEOUT_HEADER=F.MIN_REQUEST_TIMEOUT_SECONDS=void 0;F.validateTimeoutHeader=tn;F.buildTimeoutHeaders=Bp;F.MIN_REQUEST_TIMEOUT_SECONDS=1;F.REQUEST_TIMEOUT_HEADER="x-fal-request-timeout";F.REQUEST_TIMEOUT_TYPE_HEADER="x-fal-request-timeout-type";F.QUEUE_PRIORITY_HEADER="x-fal-queue-priority";F.RUNNER_HINT_HEADER="x-fal-runner-hint";function tn(e){if(typeof e!="number"||isNaN(e))throw new Error(`Timeout must be a number, got ${e}`);if(e<=F.MIN_REQUEST_TIMEOUT_SECONDS)throw new Error(`Timeout must be greater than ${F.MIN_REQUEST_TIMEOUT_SECONDS} seconds`);return e.toString()}function Bp(e){return e===void 0?{}:{[F.REQUEST_TIMEOUT_HEADER]:tn(e)}}});var se=S(Z=>{"use strict";var rn=Z&&Z.__awaiter||function(e,t,i,r){function n(a){return a instanceof i?a:new i(function(o){o(a)})}return new(i||(i=Promise))(function(a,o){function l(s){try{u(r.next(s))}catch(c){o(c)}}function d(s){try{u(r.throw(s))}catch(c){o(c)}}function u(s){s.done?a(s.value):n(s.value).then(l,d)}u((r=r.apply(e,t||[])).next())})};Object.defineProperty(Z,"__esModule",{value:!0});Z.ValidationError=Z.ApiError=void 0;Z.defaultResponseHandler=an;Z.resultResponseHandler=zp;var Up=Et(),nn="x-fal-request-id",Fe=class extends Error{constructor({message:t,status:i,body:r,requestId:n,timeoutType:a}){super(t),this.name="ApiError",this.status=i,this.body=r,this.requestId=n||"",this.timeoutType=a}get isUserTimeout(){return this.status===504&&this.timeoutType==="user"}};Z.ApiError=Fe;var Tt=class extends Fe{constructor(t){super(t),this.name="ValidationError"}get fieldErrors(){return typeof this.body.detail=="string"?[{loc:["body"],msg:this.body.detail,type:"value_error"}]:this.body.detail||[]}getFieldErrors(t){return this.fieldErrors.filter(i=>i.loc[i.loc.length-1]===t)}};Z.ValidationError=Tt;function an(e){return rn(this,void 0,void 0,function*(){var t;let{status:i,statusText:r}=e,n=(t=e.headers.get("Content-Type"))!==null&&t!==void 0?t:"",a=e.headers.get(nn)||void 0,o=e.headers.get(Up.REQUEST_TIMEOUT_TYPE_HEADER)||void 0;if(!e.ok){if(n.includes("application/json")){let l=yield e.json(),d=i===422?Tt:Fe;throw new d({message:l.message||r,status:i,body:l,requestId:a,timeoutType:o})}throw new Fe({message:`HTTP ${i}: ${r}`,status:i,requestId:a,timeoutType:o})}return n.includes("application/json")?e.json():n.includes("text/html")?e.text():n.includes("application/octet-stream")?e.arrayBuffer():e.text()})}function zp(e){return rn(this,void 0,void 0,function*(){return{data:yield an(e),requestId:e.headers.get(nn)||""}})}});var le=S(G=>{"use strict";var Lp=G&&G.__awaiter||function(e,t,i,r){function n(a){return a instanceof i?a:new i(function(o){o(a)})}return new(i||(i=Promise))(function(a,o){function l(s){try{u(r.next(s))}catch(c){o(c)}}function d(s){try{u(r.throw(s))}catch(c){o(c)}}function u(s){s.done?a(s.value):n(s.value).then(l,d)}u((r=r.apply(e,t||[])).next())})};Object.defineProperty(G,"__esModule",{value:!0});G.ensureEndpointIdFormat=on;G.parseEndpointId=Kp;G.isValidUrl=Gp;G.throttle=Hp;G.isReact=Qp;G.isPlainObject=Wp;G.sleep=Yp;function on(e){if(e.split("/").length>1)return e;let[,i,r]=/^([0-9]+)-([a-zA-Z0-9-]+)$/.exec(e)||[];if(i&&r)return`${i}/${r}`;throw new Error(`Invalid app id: ${e}. Must be in the format <appOwner>/<appId>`)}var Vp=["workflows","comfy"];function Kp(e){let i=on(e).split("/");return Vp.includes(i[0])?{owner:i[1],alias:i[2],path:i.slice(3).join("/")||void 0,namespace:i[0]}:{owner:i[0],alias:i[1],path:i.slice(2).join("/")||void 0}}function Gp(e){try{let{host:t}=new URL(e);return/(fal\.(ai|run))$/.test(t)}catch{return!1}}function Hp(e,t,i=!1){let r,n;return(...a)=>{!n&&i?(e(...a),n=Date.now()):(r&&clearTimeout(r),r=setTimeout(()=>{Date.now()-n>=t&&(e(...a),n=Date.now())},t-(Date.now()-n)))}}var Si;function Qp(){if(Si===void 0){let e=new Error().stack;Si=!!e&&(e.includes("node_modules/react-dom/")||e.includes("node_modules/next/"))}return Si}function Wp(e){return!!e&&Object.getPrototypeOf(e)===Object.prototype}function Yp(e){return Lp(this,void 0,void 0,function*(){return new Promise(t=>setTimeout(t,e))})}});var ot=S(L=>{"use strict";var Zp=L&&L.__awaiter||function(e,t,i,r){function n(a){return a instanceof i?a:new i(function(o){o(a)})}return new(i||(i=Promise))(function(a,o){function l(s){try{u(r.next(s))}catch(c){o(c)}}function d(s){try{u(r.throw(s))}catch(c){o(c)}}function u(s){s.done?a(s.value):n(s.value).then(l,d)}u((r=r.apply(e,t||[])).next())})};Object.defineProperty(L,"__esModule",{value:!0});L.DEFAULT_RETRY_OPTIONS=L.DEFAULT_RETRYABLE_STATUS_CODES=void 0;L.isRetryableError=sn;L.calculateBackoffDelay=ln;L.executeWithRetry=eg;var Jp=se(),Xp=le();L.DEFAULT_RETRYABLE_STATUS_CODES=[429,502,503,504];L.DEFAULT_RETRY_OPTIONS={maxRetries:3,baseDelay:1e3,maxDelay:3e4,backoffMultiplier:2,retryableStatusCodes:L.DEFAULT_RETRYABLE_STATUS_CODES,enableJitter:!0};function sn(e,t){return!(e instanceof Jp.ApiError)||e.isUserTimeout?!1:t.includes(e.status)}function ln(e,t,i,r,n){let a=Math.min(t*Math.pow(r,e),i);if(n){let o=.25*a*(Math.random()*2-1);return Math.max(0,a+o)}return a}function eg(e,t,i){return Zp(this,void 0,void 0,function*(){let r={totalAttempts:0,totalDelay:0},n;for(let a=0;a<=t.maxRetries;a++){r.totalAttempts++;try{return{result:yield e(),metrics:r}}catch(o){if(n=o,r.lastError=o,a===t.maxRetries||!sn(o,t.retryableStatusCodes))throw o;let l=ln(a,t.baseDelay,t.maxDelay,t.backoffMultiplier,t.enableJitter);r.totalDelay+=l,i&&i(a+1,o,l),yield(0,Xp.sleep)(l)}}throw n})}});var un=S((oy,tg)=>{tg.exports={name:"@fal-ai/client",description:"The fal.ai client for JavaScript and TypeScript",version:"1.9.0",license:"MIT",repository:{type:"git",url:"https://github.com/fal-ai/fal-js.git",directory:"libs/client"},keywords:["fal","client","ai","ml","typescript"],exports:{".":"./src/index.js","./endpoints":"./src/types/endpoints.js"},typesVersions:{"*":{endpoints:["src/types/endpoints.d.ts"]}},main:"./src/index.js",types:"./src/index.d.ts",dependencies:{"@msgpack/msgpack":"^3.0.0-beta2","eventsource-parser":"^1.1.2",robot3:"^0.4.1"},engines:{node:">=18.0.0"},type:"commonjs"}});var Ct=S(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.isBrowser=ig;kt.getUserAgent=rg;function ig(){return typeof window<"u"&&typeof window.document<"u"}var At=null;function rg(){if(At!==null)return At;let e=un();return At=`${e.name}/${e.version}`,At}});var Pt=S(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.credentialsFromEnv=void 0;ue.resolveDefaultFetch=pn;ue.createConfig=ug;ue.getRestApiUrl=cg;var cn=xi(),ng=se(),dn=ot(),ag=Ct();function pn(){if(typeof fetch>"u")throw new Error("Your environment does not support fetch. Please provide your own fetch implementation.");return fetch}function og(){return typeof process<"u"&&process.env&&(typeof process.env.FAL_KEY<"u"||typeof process.env.FAL_KEY_ID<"u"&&typeof process.env.FAL_KEY_SECRET<"u")}var sg=()=>{if(og())return typeof process.env.FAL_KEY<"u"?process.env.FAL_KEY:process.env.FAL_KEY_ID?`${process.env.FAL_KEY_ID}:${process.env.FAL_KEY_SECRET}`:void 0};ue.credentialsFromEnv=sg;var lg={credentials:ue.credentialsFromEnv,suppressLocalCredentialsWarning:!1,requestMiddleware:e=>Promise.resolve(e),responseHandler:ng.defaultResponseHandler,retry:dn.DEFAULT_RETRY_OPTIONS};function ug(e){var t;let i=Object.assign(Object.assign(Object.assign({},lg),e),{fetch:(t=e.fetch)!==null&&t!==void 0?t:pn(),retry:Object.assign(Object.assign({},dn.DEFAULT_RETRY_OPTIONS),e.retry||{})});e.proxyUrl&&(i=Object.assign(Object.assign({},i),{requestMiddleware:(0,cn.withMiddleware)(i.requestMiddleware,(0,cn.withProxy)({targetUrl:e.proxyUrl}))}));let{credentials:r,suppressLocalCredentialsWarning:n}=i,a=typeof r=="function"?r():r;return(0,ag.isBrowser)()&&a&&!n&&console.warn("The fal credentials are exposed in the browser's environment. That's not recommended for production use cases."),i}function cg(){return"https://rest.alpha.fal.ai"}});var Re=S(ce=>{"use strict";var gn=ce&&ce.__awaiter||function(e,t,i,r){function n(a){return a instanceof i?a:new i(function(o){o(a)})}return new(i||(i=Promise))(function(a,o){function l(s){try{u(r.next(s))}catch(c){o(c)}}function d(s){try{u(r.throw(s))}catch(c){o(c)}}function u(s){s.done?a(s.value):n(s.value).then(l,d)}u((r=r.apply(e,t||[])).next())})},dg=ce&&ce.__rest||function(e,t){var i={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,r=Object.getOwnPropertySymbols(e);n<r.length;n++)t.indexOf(r[n])<0&&Object.prototype.propertyIsEnumerable.call(e,r[n])&&(i[r[n]]=e[r[n]]);return i};Object.defineProperty(ce,"__esModule",{value:!0});ce.dispatchRequest=gg;ce.buildUrl=mg;var mn=ot(),hn=Ct(),Ei=le(),pg=typeof navigator<"u"&&navigator?.userAgent==="Cloudflare-Workers";function gg(e){return gn(this,void 0,void 0,function*(){var t;let{targetUrl:i,input:r,config:n,options:a={}}=e,{credentials:o,requestMiddleware:l,responseHandler:d,fetch:u}=n,s=Object.assign(Object.assign({},n.retry),a.retry||{}),c=()=>gn(this,void 0,void 0,function*(){var g,h,f;let b=(0,hn.isBrowser)()?{}:{"User-Agent":(0,hn.getUserAgent)()},p=typeof o=="function"?o():o,{method:y,url:w,headers:_}=yield l({method:((h=(g=e.method)!==null&&g!==void 0?g:a.method)!==null&&h!==void 0?h:"post").toUpperCase(),url:i,headers:e.headers}),$=p?{Authorization:`Key ${p}`}:{},T=Object.assign(Object.assign(Object.assign(Object.assign({},$),{Accept:"application/json","Content-Type":"application/json"}),b),_??{}),{responseHandler:B,retry:P}=a,z=dg(a,["responseHandler","retry"]),M=yield u(w,Object.assign(Object.assign(Object.assign(Object.assign({},z),{method:y,headers:Object.assign(Object.assign({},T),(f=z.headers)!==null&&f!==void 0?f:{})}),!pg&&{mode:"cors"}),{signal:a.signal,body:y.toLowerCase()!=="get"&&r?JSON.stringify(r):void 0}));return yield(B??d)(M)}),m;for(let g=0;g<=s.maxRetries;g++)try{return yield c()}catch(h){if(m=h,g===s.maxRetries||!(0,mn.isRetryableError)(h,s.retryableStatusCodes)||((t=a.signal)===null||t===void 0?void 0:t.aborted))throw h;let b=(0,mn.calculateBackoffDelay)(g,s.baseDelay,s.maxDelay,s.backoffMultiplier,s.enableJitter);yield(0,Ei.sleep)(b)}throw m})}function mg(e,t={}){var i,r;let n=((i=t.method)!==null&&i!==void 0?i:"post").toLowerCase(),a=((r=t.path)!==null&&r!==void 0?r:"").replace(/^\//,"").replace(/\/{2,}/,"/"),o=t.input,l=Object.assign(Object.assign({},t.query||{}),n==="get"?o:{}),d=Object.keys(l).length>0?`?${new URLSearchParams(l).toString()}`:"";if((0,Ei.isValidUrl)(e))return`${e.endsWith("/")?e:`${e}/`}${a}${d}`;let u=(0,Ei.ensureEndpointIdFormat)(e);return`${`https://${t.subdomain?`${t.subdomain}.`:""}fal.run/${u}/${a}`.replace(/\/$/,"")}${d}`}});var Ai=S(J=>{"use strict";var we=J&&J.__awaiter||function(e,t,i,r){function n(a){return a instanceof i?a:new i(function(o){o(a)})}return new(i||(i=Promise))(function(a,o){function l(s){try{u(r.next(s))}catch(c){o(c)}}function d(s){try{u(r.throw(s))}catch(c){o(c)}}function u(s){s.done?a(s.value):n(s.value).then(l,d)}u((r=r.apply(e,t||[])).next())})};Object.defineProperty(J,"__esModule",{value:!0});J.OBJECT_LIFECYCYLE_PREFERENCE_HEADER=void 0;J.getExpirationDurationSeconds=Ti;J.buildObjectLifecycleHeaders=yg;J.createStorageClient=wg;var fn=Pt(),yn=Re(),hg=le();J.OBJECT_LIFECYCYLE_PREFERENCE_HEADER="x-fal-object-lifecycle-preference";var fg={never:31536e5,immediate:void 0,"1h":3600,"1d":86400,"7d":604800,"30d":2592e3,"1y":31536e3};function Ti(e){let{expiresIn:t}=e;return typeof t=="number"?t:fg[t]}function yg(e){if(!e)return{};let t=Ti(e);return t===void 0?{}:{[J.OBJECT_LIFECYCYLE_PREFERENCE_HEADER]:JSON.stringify({expiration_duration_seconds:t})}}function _n(e){var t;let[,i]=e.split("/");return(t=i.split(/[-;]/)[0])!==null&&t!==void 0?t:"bin"}function _g(e,t,i,r){return we(this,void 0,void 0,function*(){let n=e.name||`${Date.now()}.${_n(i)}`,a={};if(r){let o={expiration_duration_seconds:Ti(r),allow_io_storage:r.expiresIn!=="immediate"};a["X-Fal-Object-Lifecycle"]=JSON.stringify(o)}return yield(0,yn.dispatchRequest)({method:"POST",targetUrl:`${(0,fn.getRestApiUrl)()}/storage/upload/initiate?storage_type=fal-cdn-v3`,input:{content_type:i,file_name:n},config:t,headers:a})})}function bg(e,t,i,r){return we(this,void 0,void 0,function*(){let n=e.name||`${Date.now()}.${_n(i)}`,a={};return r&&(a["X-Fal-Object-Lifecycle"]=JSON.stringify(r)),yield(0,yn.dispatchRequest)({method:"POST",targetUrl:`${(0,fn.getRestApiUrl)()}/storage/upload/initiate-multipart?storage_type=fal-cdn-v3`,input:{content_type:i,file_name:n},config:t,headers:a})})}function bn(e,t,i){return we(this,arguments,void 0,function*(r,n,a,o=3){if(o===0)throw new Error("Part upload failed, retries exhausted");let{fetch:l,responseHandler:d}=a;try{let u=yield l(r,{method:"PUT",body:n});return yield d(u)}catch{return yield bn(r,n,a,o-1)}})}function vg(e,t,i){return we(this,void 0,void 0,function*(){let{fetch:r,responseHandler:n}=t,a=e.type||"application/octet-stream",{upload_url:o,file_url:l}=yield bg(e,t,a,i),d=10*1024*1024,u=Math.ceil(e.size/d),s=new URL(o),c=[];for(let h=0;h<u;h++){let f=h*d,b=Math.min(f+d,e.size),p=e.slice(f,b),y=h+1,w=`${s.origin}${s.pathname}/${y}${s.search}`;c.push(yield bn(w,p,t))}let m=`${s.origin}${s.pathname}/complete${s.search}`,g=yield r(m,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({parts:c.map(h=>({partNumber:h.partNumber,etag:h.etag}))})});return yield n(g),l})}function wg({config:e}){let t={upload:(i,r)=>we(this,void 0,void 0,function*(){let n=r?.lifecycle;if(i.size>94371840)return yield vg(i,e,n);let a=i.type||"application/octet-stream",{fetch:o,responseHandler:l}=e,{upload_url:d,file_url:u}=yield _g(i,e,a,n),s=yield o(d,{method:"PUT",body:i,headers:{"Content-Type":i.type||"application/octet-stream"}});return yield l(s),u}),transformInput:i=>we(this,void 0,void 0,function*(){if(Array.isArray(i))return Promise.all(i.map(r=>t.transformInput(r)));if(i instanceof Blob)return yield t.upload(i);if((0,hg.isPlainObject)(i)){let n=Object.entries(i).map(o=>we(this,[o],void 0,function*([l,d]){return[l,yield t.transformInput(d)]})),a=yield Promise.all(n);return Object.fromEntries(a)}return i})};return t}});var wn=S(ki=>{"use strict";Object.defineProperty(ki,"__esModule",{value:!0});function Ig(e){let t,i,r,n,a,o,l;return d(),{feed:u,reset:d};function d(){t=!0,i="",r=0,n=-1,a=void 0,o=void 0,l=""}function u(c){i=i?i+c:c,t&&xg(i)&&(i=i.slice(vn.length)),t=!1;let m=i.length,g=0,h=!1;for(;g<m;){h&&(i[g]===`
`&&++g,h=!1);let f=-1,b=n,p;for(let y=r;f<0&&y<m;++y)p=i[y],p===":"&&b<0?b=y-g:p==="\r"?(h=!0,f=y-g):p===`
`&&(f=y-g);if(f<0){r=m-g,n=b;break}else r=0,n=-1;s(i,g,b,f),g+=f+1}g===m?i="":g>0&&(i=i.slice(g))}function s(c,m,g,h){if(h===0){l.length>0&&(e({type:"event",id:a,event:o||void 0,data:l.slice(0,-1)}),l="",a=void 0),o=void 0;return}let f=g<0,b=c.slice(m,m+(f?h:g)),p=0;f?p=h:c[m+g+1]===" "?p=g+2:p=g+1;let y=m+p,w=h-p,_=c.slice(y,y+w).toString();if(b==="data")l+=_?"".concat(_,`
`):`
`;else if(b==="event")o=_;else if(b==="id"&&!_.includes("\0"))a=_;else if(b==="retry"){let $=parseInt(_,10);Number.isNaN($)||e({type:"reconnect-interval",value:$})}}}var vn=[239,187,191];function xg(e){return vn.every((t,i)=>e.charCodeAt(i)===t)}ki.createParser=Ig});var Ci=S(de=>{"use strict";var Sg=de&&de.__awaiter||function(e,t,i,r){function n(a){return a instanceof i?a:new i(function(o){o(a)})}return new(i||(i=Promise))(function(a,o){function l(s){try{u(r.next(s))}catch(c){o(c)}}function d(s){try{u(r.throw(s))}catch(c){o(c)}}function u(s){s.done?a(s.value):n(s.value).then(l,d)}u((r=r.apply(e,t||[])).next())})};Object.defineProperty(de,"__esModule",{value:!0});de.TOKEN_EXPIRATION_SECONDS=void 0;de.getTemporaryAuthToken=kg;var Eg=Pt(),Tg=Re(),Ag=le();de.TOKEN_EXPIRATION_SECONDS=120;function kg(e,t){return Sg(this,void 0,void 0,function*(){let i=(0,Ag.parseEndpointId)(e),r=yield(0,Tg.dispatchRequest)({method:"POST",targetUrl:`${(0,Eg.getRestApiUrl)()}/tokens/`,config:t,input:{allowed_apps:[i.alias],token_expiration:de.TOKEN_EXPIRATION_SECONDS}});return typeof r!="string"&&r.detail?r.detail:r})}});var $i=S(H=>{"use strict";var Be=H&&H.__awaiter||function(e,t,i,r){function n(a){return a instanceof i?a:new i(function(o){o(a)})}return new(i||(i=Promise))(function(a,o){function l(s){try{u(r.next(s))}catch(c){o(c)}}function d(s){try{u(r.throw(s))}catch(c){o(c)}}function u(s){s.done?a(s.value):n(s.value).then(l,d)}u((r=r.apply(e,t||[])).next())})},st=H&&H.__await||function(e){return this instanceof st?(this.v=e,this):new st(e)},Cg=H&&H.__asyncGenerator||function(e,t,i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=i.apply(e,t||[]),n,a=[];return n={},l("next"),l("throw"),l("return",o),n[Symbol.asyncIterator]=function(){return this},n;function o(g){return function(h){return Promise.resolve(h).then(g,c)}}function l(g,h){r[g]&&(n[g]=function(f){return new Promise(function(b,p){a.push([g,f,b,p])>1||d(g,f)})},h&&(n[g]=h(n[g])))}function d(g,h){try{u(r[g](h))}catch(f){m(a[0][3],f)}}function u(g){g.value instanceof st?Promise.resolve(g.value.v).then(s,c):m(a[0][2],g)}function s(g){d("next",g)}function c(g){d("throw",g)}function m(g,h){g(h),a.shift(),a.length&&d(a[0][0],a[0][1])}};Object.defineProperty(H,"__esModule",{value:!0});H.FalStream=void 0;H.createStreamingClient=Og;var Pg=wn(),$g=Ci(),In=Re(),Ne=se(),Pi="text/event-stream",qg=15*1e3,$t=class{constructor(t,i,r){var n;this.listeners=new Map,this.buffer=[],this.currentData=void 0,this.lastEventTimestamp=0,this.streamClosed=!1,this._requestId=null,this.abortController=new AbortController,this.start=()=>Be(this,void 0,void 0,function*(){var a,o;let{endpointId:l,options:d}=this,{input:u,method:s="post",connectionMode:c="server",tokenProvider:m}=d;try{if(c==="client"){let h=yield(m?()=>m(l):()=>(console.warn('[fal.stream] Using the default token provider is deprecated. Please provide a `tokenProvider` function when using `connectionMode: "client"`. See https://docs.fal.ai/fal-client/authentication for more information.'),(0,$g.getTemporaryAuthToken)(l,this.config)))(),{fetch:f}=this.config,b=new URL(this.url);b.searchParams.set("fal_jwt_token",h);let p=yield f(b.toString(),{method:s.toUpperCase(),headers:{accept:(a=d.accept)!==null&&a!==void 0?a:Pi,"content-type":"application/json"},body:u&&s!=="get"?JSON.stringify(u):void 0,signal:this.abortController.signal});return this._requestId=p.headers.get("x-fal-request-id"),yield this.handleResponse(p)}return yield(0,In.dispatchRequest)({method:s.toUpperCase(),targetUrl:this.url,input:u,config:this.config,options:{headers:{accept:(o=d.accept)!==null&&o!==void 0?o:Pi},responseHandler:g=>Be(this,void 0,void 0,function*(){return this._requestId=g.headers.get("x-fal-request-id"),yield this.handleResponse(g)}),signal:this.abortController.signal}})}catch(g){this.handleError(g)}}),this.handleResponse=a=>Be(this,void 0,void 0,function*(){var o,l;if(!a.ok){try{yield(0,Ne.defaultResponseHandler)(a)}catch(f){this.emit("error",f)}return}let d=a.body;if(!d){this.emit("error",new Ne.ApiError({message:"Response body is empty.",status:400,body:void 0,requestId:this._requestId||void 0}));return}if(!((o=a.headers.get("content-type"))!==null&&o!==void 0?o:"").startsWith(Pi)){let f=d.getReader(),b=()=>{f.read().then(({done:p,value:y})=>{if(p){this.emit("done",this.currentData);return}this.buffer.push(y),this.currentData=y,this.emit("data",y),b()})};b();return}let s=new TextDecoder("utf-8"),c=a.body.getReader(),m=(0,Pg.createParser)(f=>{if(f.type==="event"){let b=f.data;try{let p=JSON.parse(b);this.buffer.push(p),this.currentData=p,this.emit("data",p),this.emit("message",p)}catch(p){this.emit("error",p)}}}),g=(l=this.options.timeout)!==null&&l!==void 0?l:qg,h=()=>Be(this,void 0,void 0,function*(){let{value:f,done:b}=yield c.read();this.lastEventTimestamp=Date.now(),m.feed(s.decode(f)),Date.now()-this.lastEventTimestamp>g&&this.emit("error",new Ne.ApiError({message:`Event stream timed out after ${(g/1e3).toFixed(0)} seconds with no messages.`,status:408,requestId:this._requestId||void 0})),b?this.emit("done",this.currentData):h().catch(this.handleError)});h().catch(this.handleError)}),this.handleError=a=>{var o;if(a.name==="AbortError"||this.signal.aborted)return;let l=a instanceof Ne.ApiError?a:new Ne.ApiError({message:(o=a.message)!==null&&o!==void 0?o:"An unknown error occurred",status:500,requestId:this._requestId||void 0});this.emit("error",l)},this.on=(a,o)=>{var l;this.listeners.has(a)||this.listeners.set(a,[]),(l=this.listeners.get(a))===null||l===void 0||l.push(o)},this.emit=(a,o)=>{let l=this.listeners.get(a)||[];for(let d of l)d(o)},this.done=()=>Be(this,void 0,void 0,function*(){return this.donePromise}),this.abort=a=>{this.streamClosed||this.abortController.abort(a)},this.endpointId=t,this.config=i,this.url=(n=r.url)!==null&&n!==void 0?n:(0,In.buildUrl)(t,{path:"/stream",query:r.queryParams}),this.options=r,this.donePromise=new Promise((a,o)=>{this.streamClosed&&o(new Ne.ApiError({message:"Streaming connection is already closed.",status:400,body:void 0,requestId:this._requestId||void 0})),this.signal.addEventListener("abort",()=>{var l;a((l=this.currentData)!==null&&l!==void 0?l:{})}),this.on("done",l=>{this.streamClosed=!0,a(l)}),this.on("error",l=>{this.streamClosed=!0,o(l)})}),r.signal&&r.signal.addEventListener("abort",()=>{this.abortController.abort()}),this.start().catch(this.handleError)}[Symbol.asyncIterator](){return Cg(this,arguments,function*(){let i=!0,r=()=>i=!1;for(this.on("error",r),this.on("done",r);i||this.buffer.length>0;){let n=this.buffer.shift();n&&(yield yield st(n)),yield st(new Promise(a=>setTimeout(a,16)))}})}get signal(){return this.abortController.signal}get requestId(){return this._requestId}};H.FalStream=$t;function Og({config:e,storage:t}){return{stream(i,r){return Be(this,void 0,void 0,function*(){let n=r.input?yield t.transformInput(r.input):void 0;return new $t(i,e,Object.assign(Object.assign({},r),{input:n}))})}}}});var Tn=S(pe=>{"use strict";var Ie=pe&&pe.__awaiter||function(e,t,i,r){function n(a){return a instanceof i?a:new i(function(o){o(a)})}return new(i||(i=Promise))(function(a,o){function l(s){try{u(r.next(s))}catch(c){o(c)}}function d(s){try{u(r.throw(s))}catch(c){o(c)}}function u(s){s.done?a(s.value):n(s.value).then(l,d)}u((r=r.apply(e,t||[])).next())})},Dg=pe&&pe.__rest||function(e,t){var i={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,r=Object.getOwnPropertySymbols(e);n<r.length;n++)t.indexOf(r[n])<0&&Object.prototype.propertyIsEnumerable.call(e,r[n])&&(i[r[n]]=e[r[n]]);return i};Object.defineProperty(pe,"__esModule",{value:!0});pe.createQueueClient=void 0;var qi=Et(),re=Re(),jg=se(),En=ot(),Mg=Ai(),Fg=$i(),qt=le(),xn=500,Sn={maxRetries:3,baseDelay:1e3,maxDelay:6e4,retryableStatusCodes:En.DEFAULT_RETRYABLE_STATUS_CODES},Rg={maxRetries:5,baseDelay:1e3,maxDelay:3e4,retryableStatusCodes:[...En.DEFAULT_RETRYABLE_STATUS_CODES,500]},Ng=({config:e,storage:t})=>{let i={submit(r,n){return Ie(this,void 0,void 0,function*(){let{webhookUrl:a,priority:o,hint:l,startTimeout:d,headers:u,storageSettings:s}=n,c=Dg(n,["webhookUrl","priority","hint","startTimeout","headers","storageSettings"]),m=n.input?yield t.transformInput(n.input):void 0,g=Object.fromEntries(Object.entries(u??{}).map(([h,f])=>[h.toLowerCase(),f]));return(0,re.dispatchRequest)({method:n.method,targetUrl:(0,re.buildUrl)(r,Object.assign(Object.assign({},c),{subdomain:"queue",query:a?{fal_webhook:a}:void 0})),headers:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},g),(0,Mg.buildObjectLifecycleHeaders)(s)),{[qi.QUEUE_PRIORITY_HEADER]:o??"normal"}),l&&{[qi.RUNNER_HINT_HEADER]:l}),(0,qi.buildTimeoutHeaders)(d)),input:m,config:e,options:{signal:n.abortSignal,retry:Sn}})})},status(r,n){return Ie(this,arguments,void 0,function*(a,{requestId:o,logs:l=!1,abortSignal:d}){let u=(0,qt.parseEndpointId)(a),s=u.namespace?`${u.namespace}/`:"";return(0,re.dispatchRequest)({method:"get",targetUrl:(0,re.buildUrl)(`${s}${u.owner}/${u.alias}`,{subdomain:"queue",query:{logs:l?"1":"0"},path:`/requests/${o}/status`}),config:e,options:{signal:d,retry:Rg}})})},streamStatus(r,n){return Ie(this,arguments,void 0,function*(a,{requestId:o,logs:l=!1,connectionMode:d}){let u=(0,qt.parseEndpointId)(a),s=u.namespace?`${u.namespace}/`:"",c={logs:l?"1":"0"},m=(0,re.buildUrl)(`${s}${u.owner}/${u.alias}`,{subdomain:"queue",path:`/requests/${o}/status/stream`,query:c});return new Fg.FalStream(a,e,{url:m,method:"get",connectionMode:d,queryParams:c})})},subscribeToStatus(r,n){return Ie(this,void 0,void 0,function*(){let a=n.requestId,o=n.timeout,l,d=()=>{};if(n.mode==="streaming"){let u=yield i.streamStatus(r,{requestId:a,logs:n.logs,connectionMode:"connectionMode"in n?n.connectionMode:void 0}),s=[];o&&(l=setTimeout(()=>{throw u.abort(),i.cancel(r,{requestId:a}).catch(d),new Error(`Client timed out waiting for the request to complete after ${o}ms`)},o)),u.on("data",m=>{n.onQueueUpdate&&("logs"in m&&Array.isArray(m.logs)&&m.logs.length>0&&s.push(...m.logs),n.onQueueUpdate("logs"in m?Object.assign(Object.assign({},m),{logs:s}):m))});let c=yield u.done();return l&&clearTimeout(l),c}return new Promise((u,s)=>{var c;let m,g="pollInterval"in n&&typeof n.pollInterval=="number"&&(c=n.pollInterval)!==null&&c!==void 0?c:xn,h=()=>{l&&clearTimeout(l),m&&clearTimeout(m)};o&&(l=setTimeout(()=>{h(),i.cancel(r,{requestId:a}).catch(d),s(new Error(`Client timed out waiting for the request to complete after ${o}ms`))},o));let f=()=>Ie(this,void 0,void 0,function*(){var b;try{let p=yield i.status(r,{requestId:a,logs:(b=n.logs)!==null&&b!==void 0?b:!1,abortSignal:n.abortSignal});if(n.onQueueUpdate&&n.onQueueUpdate(p),p.status==="COMPLETED"){h(),u(p);return}m=setTimeout(f,g)}catch(p){h(),s(p)}});f().catch(s)})})},result(r,n){return Ie(this,arguments,void 0,function*(a,{requestId:o,abortSignal:l}){let d=(0,qt.parseEndpointId)(a),u=d.namespace?`${d.namespace}/`:"";return(0,re.dispatchRequest)({method:"get",targetUrl:(0,re.buildUrl)(`${u}${d.owner}/${d.alias}`,{subdomain:"queue",path:`/requests/${o}`}),config:Object.assign(Object.assign({},e),{responseHandler:jg.resultResponseHandler}),options:{signal:l,retry:Sn}})})},cancel(r,n){return Ie(this,arguments,void 0,function*(a,{requestId:o,abortSignal:l}){let d=(0,qt.parseEndpointId)(a),u=d.namespace?`${d.namespace}/`:"";yield(0,re.dispatchRequest)({method:"put",targetUrl:(0,re.buildUrl)(`${u}${d.owner}/${d.alias}`,{subdomain:"queue",path:`/requests/${o}/cancel`}),config:e,options:{signal:l}})})}};return i};pe.createQueueClient=Ng});var Ot=S(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.utf8Count=Bg;ne.utf8EncodeJs=An;ne.utf8EncodeTE=kn;ne.utf8Encode=Lg;ne.utf8DecodeJs=Cn;ne.utf8DecodeTD=Pn;ne.utf8Decode=Hg;function Bg(e){let t=e.length,i=0,r=0;for(;r<t;){let n=e.charCodeAt(r++);if(n&4294967168)if(!(n&4294965248))i+=2;else{if(n>=55296&&n<=56319&&r<t){let a=e.charCodeAt(r);(a&64512)===56320&&(++r,n=((n&1023)<<10)+(a&1023)+65536)}n&4294901760?i+=4:i+=3}else{i++;continue}}return i}function An(e,t,i){let r=e.length,n=i,a=0;for(;a<r;){let o=e.charCodeAt(a++);if(o&4294967168)if(!(o&4294965248))t[n++]=o>>6&31|192;else{if(o>=55296&&o<=56319&&a<r){let l=e.charCodeAt(a);(l&64512)===56320&&(++a,o=((o&1023)<<10)+(l&1023)+65536)}o&4294901760?(t[n++]=o>>18&7|240,t[n++]=o>>12&63|128,t[n++]=o>>6&63|128):(t[n++]=o>>12&15|224,t[n++]=o>>6&63|128)}else{t[n++]=o;continue}t[n++]=o&63|128}}var Ug=new TextEncoder,zg=50;function kn(e,t,i){Ug.encodeInto(e,t.subarray(i))}function Lg(e,t,i){e.length>zg?kn(e,t,i):An(e,t,i)}var Vg=4096;function Cn(e,t,i){let r=t,n=r+i,a=[],o="";for(;r<n;){let l=e[r++];if(!(l&128))a.push(l);else if((l&224)===192){let d=e[r++]&63;a.push((l&31)<<6|d)}else if((l&240)===224){let d=e[r++]&63,u=e[r++]&63;a.push((l&31)<<12|d<<6|u)}else if((l&248)===240){let d=e[r++]&63,u=e[r++]&63,s=e[r++]&63,c=(l&7)<<18|d<<12|u<<6|s;c>65535&&(c-=65536,a.push(c>>>10&1023|55296),c=56320|c&1023),a.push(c)}else a.push(l);a.length>=Vg&&(o+=String.fromCharCode(...a),a.length=0)}return a.length>0&&(o+=String.fromCharCode(...a)),o}var Kg=new TextDecoder,Gg=200;function Pn(e,t,i){let r=e.subarray(t,t+i);return Kg.decode(r)}function Hg(e,t,i){return i>Gg?Pn(e,t,i):Cn(e,t,i)}});var Di=S(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.ExtData=void 0;var Oi=class{type;data;constructor(t,i){this.type=t,this.data=i}};Dt.ExtData=Oi});var Mt=S(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.DecodeError=void 0;var ji=class e extends Error{constructor(t){super(t);let i=Object.create(e.prototype);Object.setPrototypeOf(this,i),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:e.name})}};jt.DecodeError=ji});var Ft=S(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.UINT32_MAX=void 0;ge.setUint64=Qg;ge.setInt64=Wg;ge.getInt64=Yg;ge.getUint64=Zg;ge.UINT32_MAX=4294967295;function Qg(e,t,i){let r=i/4294967296,n=i;e.setUint32(t,r),e.setUint32(t+4,n)}function Wg(e,t,i){let r=Math.floor(i/4294967296),n=i;e.setUint32(t,r),e.setUint32(t+4,n)}function Yg(e,t){let i=e.getInt32(t),r=e.getUint32(t+4);return i*4294967296+r}function Zg(e,t){let i=e.getUint32(t),r=e.getUint32(t+4);return i*4294967296+r}});var Mi=S(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.timestampExtension=V.EXT_TIMESTAMP=void 0;V.encodeTimeSpecToTimestamp=qn;V.encodeDateToTimeSpec=On;V.encodeTimestampExtension=Dn;V.decodeTimestampToTimeSpec=jn;V.decodeTimestampExtension=Mn;var Jg=Mt(),$n=Ft();V.EXT_TIMESTAMP=-1;var Xg=4294967296-1,em=17179869184-1;function qn({sec:e,nsec:t}){if(e>=0&&t>=0&&e<=em)if(t===0&&e<=Xg){let i=new Uint8Array(4);return new DataView(i.buffer).setUint32(0,e),i}else{let i=e/4294967296,r=e&4294967295,n=new Uint8Array(8),a=new DataView(n.buffer);return a.setUint32(0,t<<2|i&3),a.setUint32(4,r),n}else{let i=new Uint8Array(12),r=new DataView(i.buffer);return r.setUint32(0,t),(0,$n.setInt64)(r,4,e),i}}function On(e){let t=e.getTime(),i=Math.floor(t/1e3),r=(t-i*1e3)*1e6,n=Math.floor(r/1e9);return{sec:i+n,nsec:r-n*1e9}}function Dn(e){if(e instanceof Date){let t=On(e);return qn(t)}else return null}function jn(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:{let i=t.getUint32(0),r=t.getUint32(4),n=(i&3)*4294967296+r,a=i>>>2;return{sec:n,nsec:a}}case 12:{let i=(0,$n.getInt64)(t,4),r=t.getUint32(0);return{sec:i,nsec:r}}default:throw new Jg.DecodeError(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${e.length}`)}}function Mn(e){let t=jn(e);return new Date(t.sec*1e3+t.nsec/1e6)}V.timestampExtension={type:V.EXT_TIMESTAMP,encode:Dn,decode:Mn}});var Bt=S(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.ExtensionCodec=void 0;var Rt=Di(),tm=Mi(),Fi=class e{static defaultCodec=new e;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(tm.timestampExtension)}register({type:t,encode:i,decode:r}){if(t>=0)this.encoders[t]=i,this.decoders[t]=r;else{let n=-1-t;this.builtInEncoders[n]=i,this.builtInDecoders[n]=r}}tryToEncode(t,i){for(let r=0;r<this.builtInEncoders.length;r++){let n=this.builtInEncoders[r];if(n!=null){let a=n(t,i);if(a!=null){let o=-1-r;return new Rt.ExtData(o,a)}}}for(let r=0;r<this.encoders.length;r++){let n=this.encoders[r];if(n!=null){let a=n(t,i);if(a!=null){let o=r;return new Rt.ExtData(o,a)}}}return t instanceof Rt.ExtData?t:null}decode(t,i,r){let n=i<0?this.builtInDecoders[-1-i]:this.decoders[i];return n?n(t,i,r):new Rt.ExtData(i,t)}};Nt.ExtensionCodec=Fi});var Ni=S(Ri=>{"use strict";Object.defineProperty(Ri,"__esModule",{value:!0});Ri.ensureUint8Array=rm;function im(e){return e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer}function rm(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):im(e)?new Uint8Array(e):Uint8Array.from(e)}});var Ui=S(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.Encoder=X.DEFAULT_INITIAL_BUFFER_SIZE=X.DEFAULT_MAX_DEPTH=void 0;var Fn=Ot(),nm=Bt(),Rn=Ft(),am=Ni();X.DEFAULT_MAX_DEPTH=100;X.DEFAULT_INITIAL_BUFFER_SIZE=2048;var Bi=class e{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(t){this.extensionCodec=t?.extensionCodec??nm.ExtensionCodec.defaultCodec,this.context=t?.context,this.useBigInt64=t?.useBigInt64??!1,this.maxDepth=t?.maxDepth??X.DEFAULT_MAX_DEPTH,this.initialBufferSize=t?.initialBufferSize??X.DEFAULT_INITIAL_BUFFER_SIZE,this.sortKeys=t?.sortKeys??!1,this.forceFloat32=t?.forceFloat32??!1,this.ignoreUndefined=t?.ignoreUndefined??!1,this.forceIntegerToFloat=t?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new e({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(t){if(this.entered)return this.clone().encodeSharedRef(t);try{return this.entered=!0,this.reinitializeState(),this.doEncode(t,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(t){if(this.entered)return this.clone().encode(t);try{return this.entered=!0,this.reinitializeState(),this.doEncode(t,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(t,i){if(i>this.maxDepth)throw new Error(`Too deep objects in depth ${i}`);t==null?this.encodeNil():typeof t=="boolean"?this.encodeBoolean(t):typeof t=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(t):this.encodeNumber(t):typeof t=="string"?this.encodeString(t):this.useBigInt64&&typeof t=="bigint"?this.encodeBigInt64(t):this.encodeObject(t,i)}ensureBufferSizeToWrite(t){let i=this.pos+t;this.view.byteLength<i&&this.resizeBuffer(i*2)}resizeBuffer(t){let i=new ArrayBuffer(t),r=new Uint8Array(i),n=new DataView(i);r.set(this.bytes),this.view=n,this.bytes=r}encodeNil(){this.writeU8(192)}encodeBoolean(t){t===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(t){!this.forceIntegerToFloat&&Number.isSafeInteger(t)?t>=0?t<128?this.writeU8(t):t<256?(this.writeU8(204),this.writeU8(t)):t<65536?(this.writeU8(205),this.writeU16(t)):t<4294967296?(this.writeU8(206),this.writeU32(t)):this.useBigInt64?this.encodeNumberAsFloat(t):(this.writeU8(207),this.writeU64(t)):t>=-32?this.writeU8(224|t+32):t>=-128?(this.writeU8(208),this.writeI8(t)):t>=-32768?(this.writeU8(209),this.writeI16(t)):t>=-2147483648?(this.writeU8(210),this.writeI32(t)):this.useBigInt64?this.encodeNumberAsFloat(t):(this.writeU8(211),this.writeI64(t)):this.encodeNumberAsFloat(t)}encodeNumberAsFloat(t){this.forceFloat32?(this.writeU8(202),this.writeF32(t)):(this.writeU8(203),this.writeF64(t))}encodeBigInt64(t){t>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(t)):(this.writeU8(211),this.writeBigInt64(t))}writeStringHeader(t){if(t<32)this.writeU8(160+t);else if(t<256)this.writeU8(217),this.writeU8(t);else if(t<65536)this.writeU8(218),this.writeU16(t);else if(t<4294967296)this.writeU8(219),this.writeU32(t);else throw new Error(`Too long string: ${t} bytes in UTF-8`)}encodeString(t){let r=(0,Fn.utf8Count)(t);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),(0,Fn.utf8Encode)(t,this.bytes,this.pos),this.pos+=r}encodeObject(t,i){let r=this.extensionCodec.tryToEncode(t,this.context);if(r!=null)this.encodeExtension(r);else if(Array.isArray(t))this.encodeArray(t,i);else if(ArrayBuffer.isView(t))this.encodeBinary(t);else if(typeof t=="object")this.encodeMap(t,i);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(t)}`)}encodeBinary(t){let i=t.byteLength;if(i<256)this.writeU8(196),this.writeU8(i);else if(i<65536)this.writeU8(197),this.writeU16(i);else if(i<4294967296)this.writeU8(198),this.writeU32(i);else throw new Error(`Too large binary: ${i}`);let r=(0,am.ensureUint8Array)(t);this.writeU8a(r)}encodeArray(t,i){let r=t.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else if(r<4294967296)this.writeU8(221),this.writeU32(r);else throw new Error(`Too large array: ${r}`);for(let n of t)this.doEncode(n,i+1)}countWithoutUndefined(t,i){let r=0;for(let n of i)t[n]!==void 0&&r++;return r}encodeMap(t,i){let r=Object.keys(t);this.sortKeys&&r.sort();let n=this.ignoreUndefined?this.countWithoutUndefined(t,r):r.length;if(n<16)this.writeU8(128+n);else if(n<65536)this.writeU8(222),this.writeU16(n);else if(n<4294967296)this.writeU8(223),this.writeU32(n);else throw new Error(`Too large map object: ${n}`);for(let a of r){let o=t[a];this.ignoreUndefined&&o===void 0||(this.encodeString(a),this.doEncode(o,i+1))}}encodeExtension(t){if(typeof t.data=="function"){let r=t.data(this.pos+6),n=r.length;if(n>=4294967296)throw new Error(`Too large extension object: ${n}`);this.writeU8(201),this.writeU32(n),this.writeI8(t.type),this.writeU8a(r);return}let i=t.data.length;if(i===1)this.writeU8(212);else if(i===2)this.writeU8(213);else if(i===4)this.writeU8(214);else if(i===8)this.writeU8(215);else if(i===16)this.writeU8(216);else if(i<256)this.writeU8(199),this.writeU8(i);else if(i<65536)this.writeU8(200),this.writeU16(i);else if(i<4294967296)this.writeU8(201),this.writeU32(i);else throw new Error(`Too large extension object: ${i}`);this.writeI8(t.type),this.writeU8a(t.data)}writeU8(t){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,t),this.pos++}writeU8a(t){let i=t.length;this.ensureBufferSizeToWrite(i),this.bytes.set(t,this.pos),this.pos+=i}writeI8(t){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,t),this.pos++}writeU16(t){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,t),this.pos+=2}writeI16(t){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,t),this.pos+=2}writeU32(t){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,t),this.pos+=4}writeI32(t){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,t),this.pos+=4}writeF32(t){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,t),this.pos+=4}writeF64(t){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,t),this.pos+=8}writeU64(t){this.ensureBufferSizeToWrite(8),(0,Rn.setUint64)(this.view,this.pos,t),this.pos+=8}writeI64(t){this.ensureBufferSizeToWrite(8),(0,Rn.setInt64)(this.view,this.pos,t),this.pos+=8}writeBigUint64(t){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,t),this.pos+=8}writeBigInt64(t){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,t),this.pos+=8}};X.Encoder=Bi});var Nn=S(zi=>{"use strict";Object.defineProperty(zi,"__esModule",{value:!0});zi.encode=sm;var om=Ui();function sm(e,t){return new om.Encoder(t).encodeSharedRef(e)}});var Bn=S(Li=>{"use strict";Object.defineProperty(Li,"__esModule",{value:!0});Li.prettyByte=lm;function lm(e){return`${e<0?"-":""}0x${Math.abs(e).toString(16).padStart(2,"0")}`}});var Un=S(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.CachedKeyDecoder=void 0;var um=Ot(),cm=16,dm=16,Vi=class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(t=cm,i=dm){this.maxKeyLength=t,this.maxLengthPerKey=i,this.caches=[];for(let r=0;r<this.maxKeyLength;r++)this.caches.push([])}canBeCached(t){return t>0&&t<=this.maxKeyLength}find(t,i,r){let n=this.caches[r-1];e:for(let a of n){let o=a.bytes;for(let l=0;l<r;l++)if(o[l]!==t[i+l])continue e;return a.str}return null}store(t,i){let r=this.caches[t.length-1],n={bytes:t,str:i};r.length>=this.maxLengthPerKey?r[Math.random()*r.length|0]=n:r.push(n)}decode(t,i,r){let n=this.find(t,i,r);if(n!=null)return this.hit++,n;this.miss++;let a=(0,um.utf8DecodeJs)(t,i,r),o=Uint8Array.prototype.slice.call(t,i,i+r);return this.store(o,a),a}};Ut.CachedKeyDecoder=Vi});var Lt=S(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.Decoder=void 0;var Ki=Bn(),pm=Bt(),xe=Ft(),gm=Ot(),zn=Ni(),mm=Un(),ae=Mt(),Gi="array",ut="map_key",Vn="map_value",hm=e=>{if(typeof e=="string"||typeof e=="number")return e;throw new ae.DecodeError("The type of key must be string or number but "+typeof e)},Hi=class{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(t){let i=this.getUninitializedStateFromPool();i.type=Gi,i.position=0,i.size=t,i.array=new Array(t)}pushMapState(t){let i=this.getUninitializedStateFromPool();i.type=ut,i.readCount=0,i.size=t,i.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let t={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(t)}return this.stack[this.stackHeadPosition]}release(t){if(this.stack[this.stackHeadPosition]!==t)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(t.type===Gi){let r=t;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(t.type===ut||t.type===Vn){let r=t;r.size=0,r.map=void 0,r.readCount=0,r.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},lt=-1,Wi=new DataView(new ArrayBuffer(0)),fm=new Uint8Array(Wi.buffer);try{Wi.getInt8(0)}catch(e){if(!(e instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var Ln=new RangeError("Insufficient data"),ym=new mm.CachedKeyDecoder,Qi=class e{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=Wi;bytes=fm;headByte=lt;stack=new Hi;entered=!1;constructor(t){this.extensionCodec=t?.extensionCodec??pm.ExtensionCodec.defaultCodec,this.context=t?.context,this.useBigInt64=t?.useBigInt64??!1,this.rawStrings=t?.rawStrings??!1,this.maxStrLength=t?.maxStrLength??xe.UINT32_MAX,this.maxBinLength=t?.maxBinLength??xe.UINT32_MAX,this.maxArrayLength=t?.maxArrayLength??xe.UINT32_MAX,this.maxMapLength=t?.maxMapLength??xe.UINT32_MAX,this.maxExtLength=t?.maxExtLength??xe.UINT32_MAX,this.keyDecoder=t?.keyDecoder!==void 0?t.keyDecoder:ym,this.mapKeyConverter=t?.mapKeyConverter??hm}clone(){return new e({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=lt,this.stack.reset()}setBuffer(t){let i=(0,zn.ensureUint8Array)(t);this.bytes=i,this.view=new DataView(i.buffer,i.byteOffset,i.byteLength),this.pos=0}appendBuffer(t){if(this.headByte===lt&&!this.hasRemaining(1))this.setBuffer(t);else{let i=this.bytes.subarray(this.pos),r=(0,zn.ensureUint8Array)(t),n=new Uint8Array(i.length+r.length);n.set(i),n.set(r,i.length),this.setBuffer(n)}}hasRemaining(t){return this.view.byteLength-this.pos>=t}createExtraByteError(t){let{view:i,pos:r}=this;return new RangeError(`Extra ${i.byteLength-r} of ${i.byteLength} byte(s) found at buffer[${t}]`)}decode(t){if(this.entered)return this.clone().decode(t);try{this.entered=!0,this.reinitializeState(),this.setBuffer(t);let i=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return i}finally{this.entered=!1}}*decodeMulti(t){if(this.entered){yield*this.clone().decodeMulti(t);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(t);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(t){if(this.entered)return this.clone().decodeAsync(t);try{this.entered=!0;let i=!1,r;for await(let l of t){if(i)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(l);try{r=this.doDecodeSync(),i=!0}catch(d){if(!(d instanceof RangeError))throw d}this.totalPos+=this.pos}if(i){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return r}let{headByte:n,pos:a,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${(0,Ki.prettyByte)(n)} at ${o} (${a} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(t){return this.decodeMultiAsync(t,!0)}decodeStream(t){return this.decodeMultiAsync(t,!1)}async*decodeMultiAsync(t,i){if(this.entered){yield*this.clone().decodeMultiAsync(t,i);return}try{this.entered=!0;let r=i,n=-1;for await(let a of t){if(i&&n===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(a),r&&(n=this.readArraySize(),r=!1,this.complete());try{for(;yield this.doDecodeSync(),--n!==0;);}catch(o){if(!(o instanceof RangeError))throw o}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){let t=this.readHeadByte(),i;if(t>=224)i=t-256;else if(t<192)if(t<128)i=t;else if(t<144){let n=t-128;if(n!==0){this.pushMapState(n),this.complete();continue e}else i={}}else if(t<160){let n=t-144;if(n!==0){this.pushArrayState(n),this.complete();continue e}else i=[]}else{let n=t-160;i=this.decodeString(n,0)}else if(t===192)i=null;else if(t===194)i=!1;else if(t===195)i=!0;else if(t===202)i=this.readF32();else if(t===203)i=this.readF64();else if(t===204)i=this.readU8();else if(t===205)i=this.readU16();else if(t===206)i=this.readU32();else if(t===207)this.useBigInt64?i=this.readU64AsBigInt():i=this.readU64();else if(t===208)i=this.readI8();else if(t===209)i=this.readI16();else if(t===210)i=this.readI32();else if(t===211)this.useBigInt64?i=this.readI64AsBigInt():i=this.readI64();else if(t===217){let n=this.lookU8();i=this.decodeString(n,1)}else if(t===218){let n=this.lookU16();i=this.decodeString(n,2)}else if(t===219){let n=this.lookU32();i=this.decodeString(n,4)}else if(t===220){let n=this.readU16();if(n!==0){this.pushArrayState(n),this.complete();continue e}else i=[]}else if(t===221){let n=this.readU32();if(n!==0){this.pushArrayState(n),this.complete();continue e}else i=[]}else if(t===222){let n=this.readU16();if(n!==0){this.pushMapState(n),this.complete();continue e}else i={}}else if(t===223){let n=this.readU32();if(n!==0){this.pushMapState(n),this.complete();continue e}else i={}}else if(t===196){let n=this.lookU8();i=this.decodeBinary(n,1)}else if(t===197){let n=this.lookU16();i=this.decodeBinary(n,2)}else if(t===198){let n=this.lookU32();i=this.decodeBinary(n,4)}else if(t===212)i=this.decodeExtension(1,0);else if(t===213)i=this.decodeExtension(2,0);else if(t===214)i=this.decodeExtension(4,0);else if(t===215)i=this.decodeExtension(8,0);else if(t===216)i=this.decodeExtension(16,0);else if(t===199){let n=this.lookU8();i=this.decodeExtension(n,1)}else if(t===200){let n=this.lookU16();i=this.decodeExtension(n,2)}else if(t===201){let n=this.lookU32();i=this.decodeExtension(n,4)}else throw new ae.DecodeError(`Unrecognized type byte: ${(0,Ki.prettyByte)(t)}`);this.complete();let r=this.stack;for(;r.length>0;){let n=r.top();if(n.type===Gi)if(n.array[n.position]=i,n.position++,n.position===n.size)i=n.array,r.release(n);else continue e;else if(n.type===ut){if(i==="__proto__")throw new ae.DecodeError("The key __proto__ is not allowed");n.key=this.mapKeyConverter(i),n.type=Vn;continue e}else if(n.map[n.key]=i,n.readCount++,n.readCount===n.size)i=n.map,r.release(n);else{n.key=null,n.type=ut;continue e}}return i}}readHeadByte(){return this.headByte===lt&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=lt}readArraySize(){let t=this.readHeadByte();switch(t){case 220:return this.readU16();case 221:return this.readU32();default:{if(t<160)return t-144;throw new ae.DecodeError(`Unrecognized array type byte: ${(0,Ki.prettyByte)(t)}`)}}}pushMapState(t){if(t>this.maxMapLength)throw new ae.DecodeError(`Max length exceeded: map length (${t}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(t)}pushArrayState(t){if(t>this.maxArrayLength)throw new ae.DecodeError(`Max length exceeded: array length (${t}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(t)}decodeString(t,i){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(t,i):this.decodeBinary(t,i)}decodeUtf8Strin