@higgsfield/video-editor-mcp 1.1.1-dev.0 → 2.0.0

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 (59) hide show
  1. package/README.md +63 -26
  2. package/dist/cli.mjs +284 -112
  3. package/dist/guide.md +2 -3
  4. package/dist/index.html +1 -1
  5. package/dist/launcher.mjs +34 -14
  6. package/dist/server.mjs +209 -265
  7. package/node_modules/@higgsfield/higgsedit/dist/api.d.ts +481 -0
  8. package/node_modules/@higgsfield/higgsedit/dist/{chunk-PFQYUJQL.mjs → chunk-3XVMJSV2.mjs} +1 -1
  9. package/node_modules/@higgsfield/higgsedit/dist/{chunk-F4CMIG5G.mjs → chunk-4VE54E4U.mjs} +3 -1
  10. package/node_modules/@higgsfield/higgsedit/dist/{chunk-2JYLVSVV.mjs → chunk-55JARHLA.mjs} +205 -65
  11. package/node_modules/@higgsfield/higgsedit/dist/{chunk-YLVXQIPX.mjs → chunk-E4N76T2R.mjs} +1 -1
  12. package/node_modules/@higgsfield/higgsedit/dist/{chunk-OCIZ36XD.mjs → chunk-ECRSOIKI.mjs} +1 -1
  13. package/node_modules/@higgsfield/higgsedit/dist/{chunk-IEPPEDEU.mjs → chunk-ENALCTAD.mjs} +1 -1
  14. package/node_modules/@higgsfield/higgsedit/dist/chunk-HY2E7IWX.mjs +43 -0
  15. package/node_modules/@higgsfield/higgsedit/dist/{chunk-NARTAWRN.mjs → chunk-HYCUOCUQ.mjs} +9 -4
  16. package/node_modules/@higgsfield/higgsedit/dist/{chunk-C3GSB3XZ.mjs → chunk-NLEIBCAK.mjs} +1 -7
  17. package/node_modules/@higgsfield/higgsedit/dist/{chunk-2WKNH7OL.mjs → chunk-O3AVYZ6U.mjs} +1 -1
  18. package/node_modules/@higgsfield/higgsedit/dist/chunk-UXO22E3P.mjs +22 -0
  19. package/node_modules/@higgsfield/higgsedit/dist/{chunk-BH2QF635.mjs → chunk-V5XTCFYK.mjs} +4 -100
  20. package/node_modules/@higgsfield/higgsedit/dist/chunk-W2TANYEH.mjs +118 -0
  21. package/node_modules/@higgsfield/higgsedit/dist/{chunk-DVN4LUXV.mjs → chunk-XY5CCUOZ.mjs} +2 -6
  22. package/node_modules/@higgsfield/higgsedit/dist/{chunk-KIWGVAPJ.mjs → chunk-Y7SAX2P4.mjs} +8 -12
  23. package/node_modules/@higgsfield/higgsedit/dist/chunk-YNAIRXOP.mjs +22 -0
  24. package/node_modules/@higgsfield/higgsedit/dist/{chunk-WENFTPXQ.mjs → chunk-ZO3NDQD3.mjs} +1 -1
  25. package/node_modules/@higgsfield/higgsedit/dist/higgsedit.mjs +13 -13
  26. package/node_modules/@higgsfield/higgsedit/package.json +4 -1
  27. package/package.json +4 -4
  28. package/plugin/.codex-plugin/plugin.json +1 -1
  29. package/plugin/skills/video-editing/SKILL.md +109 -95
  30. package/plugin/mcp.json +0 -10
  31. package/plugin/plugin.json +0 -41
  32. package/plugin/skills/motion-craft/SKILL.md +0 -87
  33. package/plugin/skills/motion-craft/agents/openai.yaml +0 -6
  34. package/plugin/skills/motion-craft/references/causality.md +0 -25
  35. package/plugin/skills/motion-craft/references/composition.md +0 -20
  36. package/plugin/skills/motion-craft/references/easing.md +0 -19
  37. package/plugin/skills/motion-craft/references/qc.md +0 -33
  38. package/plugin/skills/motion-craft/references/recipes.md +0 -31
  39. package/plugin/skills/motion-craft/references/stepped.md +0 -43
  40. package/plugin/skills/motion-craft/references/timing.md +0 -60
  41. package/plugin/skills/motion-craft/references/tsx.md +0 -60
  42. package/plugin/skills/motion-craft/references/typography.md +0 -22
  43. package/plugin/skills/video-editing/agents/openai.yaml +0 -6
  44. package/plugin/skills/video-editing/references/animation-contract.md +0 -45
  45. package/plugin/skills/video-editing/references/assembly.md +0 -58
  46. package/plugin/skills/video-editing/references/caption-systems.md +0 -29
  47. package/plugin/skills/video-editing/references/caption-titling.md +0 -41
  48. package/plugin/skills/video-editing/references/clip-geometry.md +0 -37
  49. package/plugin/skills/video-editing/references/compose.md +0 -283
  50. package/plugin/skills/video-editing/references/editor-measured.md +0 -37
  51. package/plugin/skills/video-editing/references/failure-modes.md +0 -37
  52. package/plugin/skills/video-editing/references/local-setup.md +0 -25
  53. package/plugin/skills/video-editing/references/motion-language.md +0 -27
  54. package/plugin/skills/video-editing/references/provenance.md +0 -7
  55. package/plugin/skills/video-editing/references/sandbox.md +0 -31
  56. package/plugin/skills/video-editing/references/shot-blueprints.md +0 -24
  57. package/plugin/skills/video-editing/references/title-animation.md +0 -29
  58. package/plugin/skills/video-editing/references/tsx-projects.md +0 -187
  59. package/plugin/skills/video-editing/references/workflows.md +0 -41
package/dist/index.html CHANGED
@@ -276,7 +276,7 @@ fn sampleTo(uv: vec2f) -> vec4f {
276
276
  `).map(e=>e.trim()).filter(e=>e.length>0&&!n?.ignore?.(e))})),tx,nx,rx,OAe,ix,ax,ox,kAe,sx=o((()=>{jy(),ny(),$v(),ex(),(function(e){e[e.Unsynchronisation=128]=`Unsynchronisation`,e[e.ExtendedHeader=64]=`ExtendedHeader`,e[e.ExperimentalIndicator=32]=`ExperimentalIndicator`,e[e.Footer=16]=`Footer`})(tx||={}),(function(e){e[e.ISO_8859_1=0]=`ISO_8859_1`,e[e.UTF_16_WITH_BOM=1]=`UTF_16_WITH_BOM`,e[e.UTF_16_BE_NO_BOM=2]=`UTF_16_BE_NO_BOM`,e[e.UTF_8=3]=`UTF_8`})(nx||={}),rx=`Blues.Classic rock.Country.Dance.Disco.Funk.Grunge.Hip-hop.Jazz.Metal.New age.Oldies.Other.Pop.Rhythm and blues.Rap.Reggae.Rock.Techno.Industrial.Alternative.Ska.Death metal.Pranks.Soundtrack.Euro-techno.Ambient.Trip-hop.Vocal.Jazz & funk.Fusion.Trance.Classical.Instrumental.Acid.House.Game.Sound clip.Gospel.Noise.Alternative rock.Bass.Soul.Punk.Space.Meditative.Instrumental pop.Instrumental rock.Ethnic.Gothic.Darkwave.Techno-industrial.Electronic.Pop-folk.Eurodance.Dream.Southern rock.Comedy.Cult.Gangsta.Top 40.Christian rap.Pop/funk.Jungle music.Native US.Cabaret.New wave.Psychedelic.Rave.Showtunes.Trailer.Lo-fi.Tribal.Acid punk.Acid jazz.Polka.Retro.Musical.Rock 'n' roll.Hard rock.Folk.Folk rock.National folk.Swing.Fast fusion.Bebop.Latin.Revival.Celtic.Bluegrass.Avantgarde.Gothic rock.Progressive rock.Psychedelic rock.Symphonic rock.Slow rock.Big band.Chorus.Easy listening.Acoustic.Humour.Speech.Chanson.Opera.Chamber music.Sonata.Symphony.Booty bass.Primus.Porn groove.Satire.Slow jam.Club.Tango.Samba.Folklore.Ballad.Power ballad.Rhythmic Soul.Freestyle.Duet.Punk rock.Drum solo.A cappella.Euro-house.Dance hall.Goa music.Drum & bass.Club-house.Hardcore techno.Terror.Indie.Britpop.Negerpunk.Polsk punk.Beat.Christian gangsta rap.Heavy metal.Black metal.Crossover.Contemporary Christian.Christian rock.Merengue.Salsa.Thrash metal.Anime.Jpop.Synthpop.Christmas.Art rock.Baroque.Bhangra.Big beat.Breakbeat.Chillout.Downtempo.Dub.EBM.Eclectic.Electro.Electroclash.Emo.Experimental.Garage.Global.IDM.Illbient.Industro-Goth.Jam Band.Krautrock.Leftfield.Lounge.Math rock.New romantic.Nu-breakz.Post-punk.Post-rock.Psytrance.Shoegaze.Space rock.Trop rock.World music.Neoclassical.Audiobook.Audio theatre.Neue Deutsche Welle.Podcast.Indie rock.G-Funk.Dubstep.Garage rock.Psybient`.split(`.`),OAe=(e,t)=>{let n=e.filePos;t.raw??={},t.raw.TAG??=Hb(e,125),e.filePos=n;let r=ix(e,30);r&&(t.title??=r);let i=ix(e,30);i&&(t.artist??=i);let a=ix(e,30);a&&(t.album??=a);let o=ix(e,4),s=Number.parseInt(o,10);Number.isInteger(s)&&s>0&&(t.date??=new Date(String(s)));let c=Hb(e,30),l;if(c[28]===0&&c[29]!==0){let n=c[29];n>0&&(t.trackNumber??=n),e.skip(-30),l=ix(e,28),e.skip(2)}else e.skip(-30),l=ix(e,30);l&&(t.comment??=l);let u=Ub(e);u<rx.length&&(t.genre??=rx[u])},ix=(e,t)=>{let n=Hb(e,t),r=qv(n.indexOf(0),n.length),i=n.subarray(0,r),a=``;for(let e=0;e<i.length;e++)a+=String.fromCharCode(i[e]);return a.trimEnd()},ax=e=>{let t=e.filePos,n=$b(e,3),r=Ub(e),i=Ub(e),a=Ub(e),o=Yb(e);if(n!==`ID3`||r===255||i===255||o&2155905152)return e.filePos=t,null;let s=ZTe(o);return a&tx.Footer&&(s+=10),{majorVersion:r,revision:i,flags:a,size:s}},ox=(e,t,n)=>{if(![2,3,4].includes(t.majorVersion)){ty._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);return}let r=t.flags&tx.Footer?t.size-10:t.size,i=Hb(e,r),a=new kAe(t,i);if(t.flags&tx.Unsynchronisation&&t.majorVersion===3&&a.ununsynchronizeAll(),t.flags&tx.ExtendedHeader){let e=a.readU32();t.majorVersion===3?a.pos+=e:a.pos+=e-4}for(;a.pos<=a.bytes.length-a.frameHeaderSize();){let e=a.readId3V2Frame();if(!e)break;let r=a.pos,i=a.pos+e.size,o=!1,s=!1,c=!1;if(t.majorVersion===3?(o=!!(e.flags&64),s=!!(e.flags&128)):t.majorVersion===4&&(o=!!(e.flags&4),s=!!(e.flags&8),c=!!(e.flags&2)||!!(t.flags&tx.Unsynchronisation)),o){ty._warn(`Skipping encrypted ID3v2 frame ${e.id}`),a.pos=i;continue}if(s){ty._warn(`Skipping compressed ID3v2 frame ${e.id}`),a.pos=i;continue}if(c&&a.ununsynchronizeRegion(a.pos,i),n.raw??={},e.id===`TXXX`){let e=n.raw.TXXX??={},t=a.readId3V2TextEncoding(),r=a.readId3V2Text(t,i),o=a.readId3V2Text(t,i);e[r]??=o}else e.id[0]===`T`?n.raw[e.id]??=a.readId3V2EncodingAndText(i):n.raw[e.id]??=a.readBytes(e.size);switch(a.pos=r,e.id){case`TIT2`:case`TT2`:n.title??=a.readId3V2EncodingAndText(i);break;case`TIT3`:case`TT3`:n.description??=a.readId3V2EncodingAndText(i);break;case`TPE1`:case`TP1`:n.artist??=a.readId3V2EncodingAndText(i);break;case`TALB`:case`TAL`:n.album??=a.readId3V2EncodingAndText(i);break;case`TPE2`:case`TP2`:n.albumArtist??=a.readId3V2EncodingAndText(i);break;case`TRCK`:case`TRK`:{let e=a.readId3V2EncodingAndText(i).split(`/`),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(n.trackNumber??=t),r&&Number.isInteger(r)&&r>0&&(n.tracksTotal??=r)}break;case`TPOS`:case`TPA`:{let e=a.readId3V2EncodingAndText(i).split(`/`),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(n.discNumber??=t),r&&Number.isInteger(r)&&r>0&&(n.discsTotal??=r)}break;case`TCON`:case`TCO`:{let e=a.readId3V2EncodingAndText(i),t=/^\((\d+)\)/.exec(e);if(t){let e=Number.parseInt(t[1]);if(rx[e]!==void 0){n.genre??=rx[e];break}}if(t=/^\d+$/.exec(e),t){let e=Number.parseInt(t[0]);if(rx[e]!==void 0){n.genre??=rx[e];break}}n.genre??=e}break;case`TDRC`:case`TDAT`:{let e=a.readId3V2EncodingAndText(i),t=new Date(e);Number.isNaN(t.getTime())||(n.date??=t)}break;case`TYER`:case`TYE`:{let e=a.readId3V2EncodingAndText(i),t=Number.parseInt(e,10);Number.isInteger(t)&&(n.date??=new Date(String(t)))}break;case`TBPM`:case`TBP`:{let e=a.readId3V2EncodingAndText(i),t=Number.parseInt(e,10);Number.isInteger(t)&&(n.beatsPerMinute??=t)}break;case`USLT`:case`ULT`:{let e=a.readU8();a.pos+=3,a.readId3V2Text(e,i),n.lyrics??=a.readId3V2Text(e,i)}break;case`COMM`:case`COM`:{let e=a.readU8();a.pos+=3,a.readId3V2Text(e,i),n.comment??=a.readId3V2Text(e,i)}break;case`APIC`:case`PIC`:{let e=a.readId3V2TextEncoding(),r;if(t.majorVersion===2){let e=a.readAscii(3);r=e===`PNG`?`image/png`:e===`JPG`?`image/jpeg`:`image/*`}else r=a.readId3V2Text(e,i);let o=a.readU8(),s=a.readId3V2Text(e,i).trimEnd(),c=i-a.pos;if(c>=0){let e=a.readBytes(c);n.images||=[],n.images.push({data:e,mimeType:r,kind:o===3?`coverFront`:o===4?`coverBack`:`unknown`,description:s})}}break;default:a.pos+=e.size}a.pos=i}},kAe=class{constructor(e,t){this.header=e,this.bytes=t,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){let e=[];for(let t=0;t<this.bytes.length;t++){let n=this.bytes[t];e.push(n),n===255&&t!==this.bytes.length-1&&this.bytes[t]===0&&t++}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,t){let n=[];for(let r=e;r<t;r++){let e=this.bytes[r];n.push(e),e===255&&r!==t-1&&this.bytes[r+1]===0&&r++}let r=this.bytes.subarray(0,e),i=this.bytes.subarray(t);this.bytes=new Uint8Array(r.length+n.length+i.length),this.bytes.set(r,0),this.bytes.set(n,r.length),this.bytes.set(i,r.length+n.length),this.view=new DataView(this.bytes.buffer)}readBytes(e){let t=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,t}readU8(){let e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){let e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){let e=this.view.getUint16(this.pos,!1),t=this.view.getUint8(this.pos+2);return this.pos+=3,e*256+t}readU32(){let e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let t=``;for(let n=0;n<e;n++)t+=String.fromCharCode(this.view.getUint8(this.pos+n));return this.pos+=e,t}readId3V2Frame(){if(this.header.majorVersion===2){let e=this.readAscii(3);return e===`\0\0\0`?null:{id:e,size:this.readU24(),flags:0}}{let e=this.readAscii(4);if(e===`\0\0\0\0`)return null;let t=this.readU32(),n=this.header.majorVersion===4?ZTe(t):t,r=this.readU16(),i=this.pos,a=e=>{let t=this.pos+e;if(t>this.bytes.length)return!1;if(t<=this.bytes.length-this.frameHeaderSize()){this.pos+=e;let t=this.readAscii(4);if(t!==`\0\0\0\0`&&!/[0-9A-Z]{4}/.test(t))return!1}return!0};if(!a(n)){let e=this.header.majorVersion===4?t:ZTe(t);a(e)&&(n=e)}return this.pos=i,{id:e,size:n,flags:r}}}readId3V2TextEncoding(){let e=this.readU8();if(e>3)throw Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){let n=this.pos,r=this.readBytes(t-this.pos);switch(e){case nx.ISO_8859_1:{let e=``;for(let t=0;t<r.length;t++){let i=r[t];if(i===0){this.pos=n+t+1;break}e+=String.fromCharCode(i)}return e}case nx.UTF_16_WITH_BOM:if(r[0]===255&&r[1]===254){let e=new Av(`utf-16le`),t=qv(r.findIndex((e,t)=>e===0&&r[t+1]===0&&t%2==0),r.length);return this.pos=n+Math.min(t+2,r.length),e.decode(r.subarray(2,t))}if(r[0]===254&&r[1]===255){let e=new Av(`utf-16be`),t=qv(r.findIndex((e,t)=>e===0&&r[t+1]===0&&t%2==0),r.length);return this.pos=n+Math.min(t+2,r.length),e.decode(r.subarray(2,t))}{let e=qv(r.findIndex(e=>e===0),r.length);return this.pos=n+Math.min(e+1,r.length),jv.decode(r.subarray(0,e))}case nx.UTF_16_BE_NO_BOM:{let e=new Av(`utf-16be`),t=qv(r.findIndex((e,t)=>e===0&&r[t+1]===0&&t%2==0),r.length);return this.pos=n+Math.min(t+2,r.length),e.decode(r.subarray(0,t))}case nx.UTF_8:{let e=qv(r.findIndex(e=>e===0),r.length);return this.pos=n+Math.min(e+1,r.length),jv.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return``;let t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}})),AAe=o((()=>{$v(),ay(),ly(),ky(),sx(),Cy(),ex(),kDe(),sy(),yDe(),nEe(),oEe(),zEe(),VEe(),ny(),jy(),sDe(),uDe(),FDe(),vDe(),Gke(),Hke(),Jke(),Iy(),fOe(),gb(),_ke(),Rb(),vAe(),lAe()})),jAe,MAe,NAe=o((()=>{AAe(),jAe=class extends Error{constructor(e){super(`${e}: no audio track`),this.name=`NoAudioTrackError`}},MAe=class{src;ready;facts;input;sink;disposed=!1;constructor(e,t){this.src=e,this.ready=this.open(t),this.ready.catch(()=>{})}async open(e){let t=new yAe({source:new EOe(e,{maxCacheSize:33554432}),formats:hke});this.input=t;let n=await t.getPrimaryAudioTrack();if(this.disposed)throw new DOMException(`Audio source disposed`,`AbortError`);if(!n)throw new jAe(this.src);let r=await n.computeDuration();if(this.disposed)throw new DOMException(`Audio source disposed`,`AbortError`);return this.sink=new cAe(n),this.facts={duration:r,sampleRate:n.sampleRate,channels:n.numberOfChannels},this.facts}chunks(e,t){let n=!1,r,i=async()=>(n||(n=!0,await r?.return()),{done:!0,value:void 0});return{next:async()=>{if(n||this.disposed||(await this.ready,n||this.disposed||!this.sink||t<=e))return{done:!0,value:void 0};r??=this.sink.buffers(e,t);let i=await r.next();return n||this.disposed||i.done?{done:!0,value:void 0}:{done:!1,value:{buffer:i.value.buffer,timestamp:i.value.timestamp}}},return:i,throw:async e=>{throw await i(),e},[Symbol.asyncIterator](){return this}}}dispose(){this.disposed||(this.disposed=!0,this.input?.dispose?.(),this.sink=void 0)}}}));function PAe(e){let t=new Map,n=e.getUint16(4),r=e.getUint16(8),i=e.getUint16(10);for(let a=0;a<r;a++){let r=n+a*i;if(r+16>e.byteLength)break;t.set(cx(e,r),[e.getInt32(r+4)/65536,e.getInt32(r+12)/65536])}return t}function FAe(e){return{weight:e.weights?`${e.weights[0]} ${e.weights[1]}`:String(e.weight),style:e.style,...e.stretches?{stretch:`${e.stretches[0]}% ${e.stretches[1]}%`}:{}}}function IAe(e,t,n){let r=``;for(let i=0;i<n;i+=2)r+=String.fromCharCode(e.getUint16(t+i));return r}function LAe(e){let t=e.getUint16(2),n=e.getUint16(4),r;for(let i=0;i<t;i++){let t=6+i*12,a=e.getUint16(t),o=e.getUint16(t+4),s=e.getUint16(t+6);if(s!==1&&s!==16)continue;let c=e.getUint16(t+8),l=n+e.getUint16(t+10),u=a===1?WAe(e,l,c):IAe(e,l,c),d=(s===16?0:4)+(a===3&&o===1033?0:a===3||a===0?1:2);(!r||d<r.rank)&&(r={rank:d,value:u})}return r?.value.trim()||void 0}function RAe(e){let t=e.get(`name`),n=t&&LAe(t);if(!n)return null;let r=e.get(`OS/2`),i=r?r.getUint16(4):400,a=r?(r.getUint16(62)&1)==1:!1,o=e.get(`fvar`)?PAe(e.get(`fvar`)):void 0,s=o?.get(`wght`),c=o?.get(`wdth`);return{family:n,weight:i>=1&&i<=1e3?i:400,style:a?`italic`:`normal`,...s&&s[0]>=1&&s[1]<=1e3&&s[0]<s[1]?{weights:s}:{},...c&&c[0]>0&&c[0]<c[1]?{stretches:c}:{}}}async function zAe(e){let t=new Blob([e]).stream().pipeThrough(new DecompressionStream(`deflate`));return new Uint8Array(await new Response(t).arrayBuffer())}async function BAe(e){let t=new DataView(e);if(t.byteLength<12)return null;let n=cx(t,0),r=new Set([`name`,`OS/2`,`fvar`]),i=new Map;if(n===`\0\0\0`||n===`OTTO`||n===`true`){let n=t.getUint16(4);for(let a=0;a<n;a++){let n=12+a*16,o=cx(t,n);r.has(o)&&i.set(o,new DataView(e,t.getUint32(n+8),t.getUint32(n+12)))}return RAe(i)}if(n===`wOFF`){let n=t.getUint16(12);for(let a=0;a<n;a++){let n=44+a*20,o=cx(t,n);if(!r.has(o))continue;let s=t.getUint32(n+4),c=t.getUint32(n+8),l=t.getUint32(n+12),u=new Uint8Array(e,s,c),d=c<l?await zAe(u):u.slice();i.set(o,new DataView(d.buffer,d.byteOffset,d.byteLength))}return RAe(i)}return null}async function VAe(e,t){return await BAe(t)??qAe(e)}function HAe(e,t){let n=t.indexOf(UAe);return e.startsWith(`/`)&&n>0?`${t.slice(0,n)}${e}`:new URL(e,t).href}var UAe,cx,WAe,GAe,KAe,qAe,JAe,YAe,XAe,ZAe=o((()=>{F_(),UAe=`/__higgsedit/fonts/google`,cx=(e,t)=>String.fromCharCode(e.getUint8(t),e.getUint8(t+1),e.getUint8(t+2),e.getUint8(t+3)),WAe=(e,t,n)=>String.fromCharCode(...new Uint8Array(e.buffer,e.byteOffset+t,n)),GAe=/\.(ttf|otf|woff2?)$/i,KAe=e=>GAe.test(e),qAe=e=>({family:e.split(`/`).at(-1).replace(GAe,``),weight:400,style:`normal`}),JAe=class{faces=new Map;misses=new Map;load(e,t){let n=XAe();return Promise.all(e.filter(KAe).map(e=>{let r=t(e),i=this.faces.get(r);if(!i){let t;i=(async()=>{let i=await(await fetch(r)).arrayBuffer();t=await VAe(e,i);let a=new FontFace(t.family,i,FAe(t));return await a.load(),n?.add(a),a})().catch(n=>{let{family:i,weight:a,style:o}=t??qAe(e);return this.misses.set(r,{family:i,weight:a,style:o,reason:`${e}: ${n.message}`}),console.warn(`[higgsedit] font ${e}: ${n.message}`),null}),this.faces.set(r,i)}return i}))}},YAe=class{endpoint;asked=new Map;faces=new Map;misses=new Map;constructor(e){this.endpoint=e}retryFailed(){for(let e of this.misses.keys())this.asked.delete(e);this.misses.clear()}load(e,t){let n=XAe();return n?Promise.all(e.filter(e=>!t.has(e.family.toLowerCase())).map(e=>{let t=`${e.family}|${e.weight}|${e.style}`,r=this.asked.get(t);return r||(r=this.resolve(e,n).catch(n=>{this.misses.set(t,{...e,reason:n.message}),console.warn(`[higgsedit] Google font ${e.family} ${e.weight} ${e.style}: ${n.message}`)}),this.asked.set(t,r)),r})).then(()=>void 0):Promise.resolve()}async resolve(e,t){let n=new URLSearchParams({family:e.family,weight:String(e.weight),style:e.style}),r=await fetch(`${this.endpoint}?${n}`);if(r.status===404)return;let i=await r.json();if(!i)return;if(`unavailable`in i){console.warn(`[higgsedit] Google font ${e.family} ${e.weight} ${e.style}: ${i.unavailable}; it draws in a system font`);return}if(`error`in i)throw Error(i.error);let a=HAe(i.url,this.endpoint),o=`${e.family}|${i.weight}|${i.style}`,s=this.faces.get(o);s||(s=(async()=>{let n=await fetch(a);if(!n.ok)throw Error(`${n.status} from ${a}`);let r=new FontFace(e.family,await n.arrayBuffer(),{weight:String(i.weight),style:i.style});await r.load(),t.add(r),Rye()})(),s.catch(()=>this.faces.delete(o)),this.faces.set(o,s)),await s}},XAe=()=>globalThis.document?.fonts??globalThis.fonts}));function QAe(e){let t=/<svg\b[^>]*\bviewBox\s*=\s*["']\s*[-\d.e]+[\s,]+[-\d.e]+[\s,]+([\d.e]+)[\s,]+([\d.e]+)/i.exec(e),n=Number(t?.[1]),r=Number(t?.[2]);return n>0&&r>0?{width:n,height:r}:void 0}async function $Ae(e){let t=await e.text(),n=URL.createObjectURL(new Blob([t],{type:`image/svg+xml`})),r=new Image;r.src=n;try{await r.decode()}catch(e){throw URL.revokeObjectURL(n),e}let i=r.naturalWidth>0&&r.naturalHeight>0?{width:r.naturalWidth,height:r.naturalHeight}:QAe(t);if(!i)throw Error(`SVG has no width/height or viewBox to size it by`);return r.width=i.width,r.height=i.height,{picture:r,...i}}var eje,tje,nje=o((()=>{Dxe(),eje=(e,t)=>/^image\/svg\+xml\b/i.test(t??``)||/\.svg(?:[?#]|$)/i.test(e),tje=class{src;ready;bitmap;width=0;height=0;constructor(e,t){this.src=e,this.ready=(async()=>{let n=await fetch(t);if(!n.ok)throw Error(`${e}: HTTP ${n.status}`);let r=await n.blob();try{if(eje(e,n.headers.get(`content-type`))){let{picture:e,width:t,height:n}=await $Ae(r);this.bitmap=e,this.width=t,this.height=n;return}let t=await createImageBitmap(r);this.bitmap=t,this.width=t.width,this.height=t.height}catch(t){throw Cxe(t,e)}})(),this.ready.catch(()=>{})}}}));function rje(e,t,n=0,r=e.length){t.fill(0);let i=n,a=0,o=0;for(;i<r;){let[n,r]=ije(e,i);i=r,o&&t.fill(1,a,Math.min(t.length,a+n)),a+=n,o^=1}return a}function ije(e,t){let n=0,r=0,i=t;for(;;){let t=e[i++];if(t===void 0)throw Error(`mask file is cut short`);if(n+=(t&127)*2**r,t<128)return[n,i];r+=7}}var aje,oje,sje=o((()=>{m_(),aje=`RMSK`,oje=class e{header;bytes;starts;ends;times;constructor(e,t,n,r){this.bytes=e,this.header=t,this.starts=n,this.ends=r}static parse(t){if(t.length<8||new TextDecoder().decode(t.subarray(0,4))!==aje)throw Error(`not a higgsedit mask file`);let n=new DataView(t.buffer,t.byteOffset,t.byteLength).getUint32(4,!0),r=JSON.parse(new TextDecoder().decode(t.subarray(8,8+n)));if(r.version!==1)throw Error(`mask file version ${String(r.version)} is newer than this higgsedit`);let i=new Uint32Array(r.frames),a=new Uint32Array(r.frames),o=8+n;for(let e=0;e<r.frames;e++){let[n,r]=ije(t,o);if(i[e]=r,o=a[e]=r+n,o>t.length)throw Error(`mask file is cut short at frame ${e}`)}return new e(t,r,i,a)}get frameCount(){return this.header.frames}frame(e,t){let n=this.starts[e],r=this.ends[e];return rje(this.bytes,t,n,r),n<r}indexAt(e){let{frames:t,frameRate:n,start:r}=this.header;return t===0?-1:(this.times??=Float64Array.from({length:t},(e,t)=>r+t/n),p_(this.times,e,n))}}})),cje,lje=o((()=>{sje(),cje=class{src;ready;file;canvas;cells;drawn=-1;constructor(e,t){this.src=e,this.ready=(async()=>{let n=await fetch(t);if(!n.ok)throw Error(`${e}: HTTP ${n.status}`);this.file=oje.parse(new Uint8Array(await n.arrayBuffer()))})(),this.ready.catch(()=>{})}frame(e){let t=this.file;if(!t||t.frameCount===0)return;let[n,r]=t.header.grid;this.canvas||(this.canvas=new OffscreenCanvas(n,r),this.cells=new Uint8Array(n*r));let i=Math.min(Math.max(e,0),t.frameCount-1);if(i===this.drawn)return this.canvas;let a=this.cells;t.frame(i,a);let o=new ImageData(n,r);for(let e=0;e<a.length;e++)a[e]&&(o.data[e*4]=255,o.data[e*4+1]=255,o.data[e*4+2]=255,o.data[e*4+3]=255);return this.canvas.getContext(`2d`).putImageData(o,0,0),this.drawn=i,this.canvas}}})),uje,dje=o((()=>{tye(),uje=class{src;ready;transcript;constructor(e,t){this.src=e,this.ready=(async()=>{let n=await fetch(t);if(!n.ok)throw Error(`${e}: HTTP ${n.status}`);return this.transcript=Zve(await n.text(),e),this.transcript})(),this.ready.catch(()=>{})}}}));async function fje(e,t){let n=new yAe({source:new EOe(t,{maxCacheSize:134217728}),formats:hke});try{let t=await n.getPrimaryVideoTrack();if(!t)throw Error(`${e}: no video track`);if(!await t.canDecode())throw Error(`${e}: this browser cannot decode ${await t.getCodecParameterString()}`);let r=new jb(t),i=[],a=[];for await(let e of r.packets(void 0,void 0,{metadataOnly:!0}))i.push(e.timestamp),e.type===`key`&&a.push(e.timestamp);i.sort((e,t)=>e-t);let o=Float64Array.from(i),s=rye(o),c=Int32Array.from(new Set(a.map(e=>pje(o,e)))).toSorted();return{input:n,sink:new iAe(t),facts:{width:t.displayWidth,height:t.displayHeight,fps:s,timestamps:o,duration:o.length?o[o.length-1]-Math.max(0,o[0])+1/s:0},keys:c}}catch(e){try{n.dispose()}catch{}throw e}}function pje(e,t){let n=0,r=e.length-1;for(;n<r;){let i=n+r>>1;e[i]<t-1e-7?n=i+1:r=i}return n}function mje(e){e.frame.close(),e.sample.close()}var hje,gje,_je,vje,yje=o((()=>{AAe(),m_(),hje=36,gje=4,_je=4,vje=class{src;ready;facts;input;sink;cache=new Map;waiters=new Map;wanted=-1;lookahead=0;cursor=-1;iterator;wake;pumping=!1;disposed=!1;lastShown;requested=[];failure;constructor(e,t){this.src=e,this.ready=this.open(t),this.ready.catch(()=>{})}async open(e){try{let t=await fje(this.src,e);return this.input=t.input,this.sink=t.sink,this.facts=t.facts,this.facts}catch(e){throw this.failure=e,e}}request(e,t=0){if(this.failure)return Promise.reject(this.failure);if(this.wanted=e,this.lookahead=t,this.requested.includes(e)||(this.requested.push(e),this.requested.length>_je&&this.requested.shift()),this.cache.has(e))return this.kick(),Promise.resolve();let n=new Promise(t=>{let n=this.waiters.get(e)??[];n.push(t),this.waiters.set(e,n)});return this.kick(),n}exact(e){let t=this.cache.get(e);if(t)return this.lastShown=e,t.frame}peek(e){this.wanted!==e&&this.request(e,this.lookahead).catch(()=>{});let t=this.exact(e);if(t)return t;let n;for(let t of this.cache.keys()){let r=Math.abs(t-e);r<=gje&&(n===void 0||r<Math.abs(n-e)||r===Math.abs(n-e)&&t<n)&&(n=t)}let r=n??(this.lastShown!==void 0&&this.cache.has(this.lastShown)?this.lastShown:void 0);return r===void 0?void 0:this.cache.get(r)?.frame}setLookahead(e){this.lookahead=e}kick(){if(this.wake){let e=this.wake;this.wake=void 0,e()}this.pumping||this.pump()}satisfied(){if(this.wanted<0)return!0;let e=Math.min(this.wanted+this.lookahead,(this.facts?.timestamps.length??1)-1);for(let t=this.wanted;t<=e;t++)if(!this.cache.has(t))return!1;return!0}async pump(){this.pumping=!0;try{let e=await this.ready,t=this.sink;for(;!this.disposed;){if(this.satisfied()){let e=[...this.waiters.keys()].find(e=>!this.cache.has(e));if(e!==void 0){this.wanted=e,this.lookahead=0;continue}this.evict(),await new Promise(e=>this.wake=e);continue}let n=this.wanted;if(!this.iterator||n<this.cursor-0||n>this.cursor+hje){await this.iterator?.return();let r=e.timestamps[Math.max(0,n)]??0;this.iterator=t.samples(r),this.cursor=n-1}let{value:r,done:i}=await this.iterator.next();if(i||!r){this.iterator=void 0,this.cursor=e.timestamps.length;for(let[t,n]of this.waiters)(t>=e.timestamps.length-1||!this.cache.has(t))&&n.forEach(e=>e());this.waiters.clear(),await new Promise(e=>this.wake=e);continue}let a=pje(e.timestamps,r.timestamp);this.cursor=a,this.cache.has(a)?r.close():this.cache.set(a,{sample:r,frame:r.toVideoFrame()});let o=this.waiters.get(a);o&&(this.waiters.delete(a),o.forEach(e=>e())),this.evict()}}catch(e){this.failure=e;for(let e of this.waiters.values())e.forEach(e=>e());this.waiters.clear()}finally{this.pumping=!1}}evict(){let e=this.wanted-2,t=this.wanted+this.lookahead+2;for(let[n,r]of this.cache)(n<e||n>t)&&n!==this.lastShown&&!this.waiters.has(n)&&!this.requested.includes(n)&&(mje(r),this.cache.delete(n))}dispose(){this.disposed=!0,this.kick(),this.iterator?.return();for(let e of this.cache.values())mje(e);this.cache.clear(),this.input?.dispose()}}})),bje,xje=o((()=>{NAe(),nje(),lje(),dje(),yje(),bje=class{videos=new Map;images=new Map;audios=new Map;mattes=new Map;transcripts=new Map;readyListeners=new Set;resolve;makeVideo;resolveVideo;constructor(e,t,n){this.resolve=e,this.makeVideo=t??((e,t)=>new vje(e,t)),this.resolveVideo=n??e}onReady(e){return this.readyListeners.add(e),()=>this.readyListeners.delete(e)}watchReady(e,t){let n=()=>{for(let t of this.readyListeners)t(e)};t.then(n,n)}forget(e){let t=this.resolveVideo(e);this.videos.get(t)?.dispose(),this.videos.delete(t),this.mattes.delete(this.resolve(e)),this.transcripts.delete(this.resolve(e))}transcript(e){let t=this.resolve(e),n=this.transcripts.get(t);return n||(n=new uje(e,t),this.transcripts.set(t,n),this.watchReady(e,n.ready)),n}video(e){let t=this.resolveVideo(e),n=this.videos.get(t);return n||(n=this.makeVideo(e,t),this.videos.set(t,n),this.watchReady(e,n.ready)),n}image(e){let t=this.resolve(e),n=this.images.get(t);return n||(n=new tje(e,t),this.images.set(t,n),this.watchReady(e,n.ready)),n}audio(e){let t=this.resolve(e),n=this.audios.get(t);return n||(n=new MAe(e,t),this.audios.set(t,n)),n}matte(e){let t=this.resolve(e),n=this.mattes.get(t);return n||(n=new cje(e,t),this.mattes.set(t,n),this.watchReady(e,n.ready)),n}forgetAll(){for(let e of this.audios.values())e.dispose();this.audios.clear();for(let e of this.videos.values())e.dispose();this.videos.clear(),this.images.clear(),this.mattes.clear(),this.transcripts.clear()}dispose(){this.readyListeners.clear(),this.forgetAll()}}})),Sje=o((()=>{}));function Cje(e){return dx.add(e),()=>dx.delete(e)}async function wje(e,t,n){let r=!1,i=[],a=()=>{r=!0;for(let e of i.splice(0))e.close()},o=async e=>{let t=await e();if(t){if(r){t.close();return}return i.push(t),t}},s,c=new Promise(e=>{s=()=>{a(),e([void 0,void 0])},n.addEventListener(`abort`,s,{once:!0}),n.aborted&&s()});try{let n=await Promise.race([Promise.all([o(e),o(t)]),c]);return r?[void 0,void 0]:n}catch(e){throw a(),e}finally{n.removeEventListener(`abort`,s)}}async function Tje(e,t){let n=e.displayWidth,r=e.displayHeight,i=await createImageBitmap(e),a;try{let e=new OffscreenCanvas(n,r).getContext(`2d`,{willReadFrequently:!0});e.drawImage(i,0,0,n,r),a=e.getImageData(0,0,n,r).data}finally{i.close()}let o=t.toVideoFrame();try{let e=new Uint8Array(o.allocationSize()),[t]=await o.copyTo(e),{offset:i,stride:s}=t;for(let t=0;t<r;t++){let r=i+t*s,o=t*n*4+3;for(let t=0;t<n;t++,o+=4)a[o]=e[r+t]}}finally{o.close()}return new ImageData(a,n,r)}var Eje,Dje,Oje,lx,kje,Aje,jje,Mje,Nje,ux,Pje,Fje,Ije,Lje,Rje,zje,Bje,Vje,dx,Hje,Uje=o((()=>{yje(),Eje=24,Dje=6,Oje=128<<20,lx=4,kje=6,Aje=4,jje=[360,540,720,1080,1440,2160],Mje=720,Nje=500,ux=70,Pje=3,Fje=300,Ije=32,Lje=24,Rje=1e4,zje=8,Bje=36,Vje=250,dx=new Set,Hje=class{src;ready;facts;url;matteUrl;opened;matte;matteIterator;failure;cache=new Map;keys=new Map;target=-1;warmTarget=-1;lastPeekAt=-1/0;lastJumpAt=-1/0;dragging=!1;playingUntil=0;reverseUntil=0;shown;stale;missed=!1;iterator;cursor=-1;wake;pumping=!1;disposed=!1;decodeLifetime=new AbortController;open=!1;lastUsedAt=0;idleTimer;height=Mje;fitPx=0;fitAt=-1/0;waiters=new Map;peeks=0;misses=0;constructor(e,t,n){this.src=e,this.url=t,this.matteUrl=n,this.ready=this.load(),this.ready.catch(()=>{})}async load(){let e=!1,t=async t=>{let n=await fje(t?`${this.src} (matte)`:this.src,t?this.matteUrl:this.url);if(this.disposed||e)throw n.input.dispose(),new DOMException(`Preview video disposed`,`AbortError`);return t?this.matte=n:this.opened=n,n};try{let[e,n]=await Promise.all([t(!1),this.matteUrl?t(!0):void 0]);if(this.disposed)throw new DOMException(`Preview video disposed`,`AbortError`);if(n&&n.facts.timestamps.length!==e.facts.timestamps.length)throw Error(`${this.src}: the matte has ${n.facts.timestamps.length} frames, the video ${e.facts.timestamps.length}`);return this.facts=e.facts,this.open=!0,this.facts}catch(t){throw e=!0,this.closeInputs(),this.failure=t,t}}stats(){let e=-1;for(let[t,n]of this.cache)n===this.shown&&(e=t);return{cached:[...this.cache.keys()].toSorted((e,t)=>e-t),open:this.open,shown:e,height:this.shown?.height??0,target:Math.min(this.height,this.facts?.height??this.height),peeks:this.peeks,misses:this.misses}}request(e){return this.disposed?Promise.resolve():this.failure?Promise.reject(this.failure):(this.want(e,performance.now()),this.cache.has(e)?Promise.resolve():new Promise(t=>{let n=this.waiters.get(e)??[];n.push(t),this.waiters.set(e,n)}))}exact(e){return this.cache.get(e)}peek(e){if(this.disposed)return;let t=performance.now();this.want(e,t),this.lastPeekAt=t,this.peeks++;let n=this.cache.get(e);if(n)return this.show(n),this.missed=!1,n;this.missed=!0,this.misses++;let r=this.nearest(e,t)??this.shown;return r&&this.show(r),r}fit(e){if(this.disposed)return;let t=this.facts?.height;if(!t||!(e>0))return;let n=performance.now();if(e<this.fitPx&&n-this.fitAt<Nje)return;this.fitPx=e,this.fitAt=n;let r=Math.min(t,jje.find(t=>t>=e)??jje.at(-1));if(r===this.height)return;let i=r>this.height;if(this.height=r,i){for(let[e,t]of this.cache)t.height>=r||this.waiters.has(e)||(this.cache.delete(e),t===this.shown?this.stale=t:t.close());this.missed=!0,this.kick()}}warm(e){this.disposed||e<0||performance.now()-this.lastPeekAt<Vje||this.cache.has(e)||(this.warmTarget=e,this.touch(performance.now()),this.kick())}dispose(){this.disposed||(this.disposed=!0,this.idleTimer&&clearInterval(this.idleTimer),this.idleTimer=void 0,this.kick(),this.release(),this.closeInputs())}closeInputs(){this.opened?.input.dispose(),this.matte?.input.dispose(),this.opened=void 0,this.matte=void 0}want(e,t){if(this.touch(t),e===this.target)return;let n=e-this.target;this.target>=0&&n>0&&n<=Pje?this.playingUntil=t+Fje:this.target>=0&&n<0&&n>=-3?this.reverseUntil=t+Fje:this.target>=0&&(this.dragging=t-this.lastJumpAt<ux,this.lastJumpAt=t,this.playingUntil=0),this.target=e,this.warmTarget=-1,this.kick()}nearest(e,t){if(t<this.playingUntil||t<this.reverseUntil){let t;for(let n of this.cache.keys()){let r=Math.abs(n-e);r<=Aje&&(t===void 0||r<Math.abs(t-e))&&(t=n)}if(t!==void 0)return this.cache.get(t)}let n=this.keyAtOrBefore(e);return this.cache.get(n)??this.keys.get(n)}show(e){this.stale&&this.stale!==e&&(this.stale.close(),this.stale=void 0),this.shown=e}keyAtOrBefore(e){let t=this.opened?.keys;if(!t?.length)return 0;let n=0,r=t.length-1;for(;n<r;){let i=n+r+1>>1;t[i]<=e?n=i:r=i-1}return t[n]<=e?t[n]:0}touch(e){this.lastUsedAt=e,this.idleTimer??=setInterval(()=>{performance.now()-this.lastUsedAt<Rje||(clearInterval(this.idleTimer),this.idleTimer=void 0,this.release())},Rje/10)}release(){this.decodeLifetime.abort(),this.decodeLifetime=new AbortController,this.iterator?.return().catch(()=>{}),this.iterator=void 0,this.matteIterator?.return().catch(()=>{}),this.matteIterator=void 0,this.cursor=-1;for(let e of this.cache.values())e.close();for(let e of this.keys.values())e.close();this.cache.clear(),this.keys.clear(),this.stale?.close(),this.stale=void 0,this.shown=void 0,this.target=-1,this.warmTarget=-1,this.open=!1;for(let e of this.waiters.values())e.forEach(e=>e());this.waiters.clear()}kick(){let e=this.wake;this.wake=void 0,e?.(),!this.pumping&&!this.disposed&&!this.failure&&this.pump()}next(e){let t=(this.facts?.timestamps.length??0)-1,n=this.warmTarget>=0&&e-this.lastPeekAt>=Vje,r=n?this.warmTarget:this.target;if(r<0||t<0)return null;let i=[...this.waiters.keys()].find(e=>!this.cache.has(e));if(i!==void 0)return{kind:`frame`,index:i};if(!n&&e<this.reverseUntil)return this.reverseJob(r);if(!this.cache.has(r)){if(!n&&this.dragging&&e-this.lastJumpAt<ux){let t=this.keyAtOrBefore(r);return t!==r&&!this.cache.has(t)&&!this.keys.has(t)?{kind:`key`,index:t}:{kind:`wait`,ms:this.lastJumpAt+ux-e}}return{kind:`frame`,index:Math.min(r,t)}}let a=n?kje:e<this.playingUntil?this.ahead():0;for(let e=r+1;e<=Math.min(r+a,t);e++)if(!this.cache.has(e))return{kind:`frame`,index:e};return null}reverseJob(e){let t=e=>Math.max(this.keyAtOrBefore(e),Math.floor(e/Ije)*Ije),n=t(e);for(let t=n;t<=e;t++)if(!this.cache.has(t))return{kind:`frame`,index:t};if(n===0||e-n>=Lje)return null;for(let e=t(n-1);e<n;e++)if(!this.cache.has(e))return{kind:`frame`,index:e};return null}async pump(){this.pumping=!0;try{for(await this.ready;!this.disposed;){let e=this.next(performance.now());if(!e){this.evict(),await new Promise(e=>this.wake=e);continue}if(e.kind===`wait`){await new Promise(t=>{let n=setTimeout(t,Math.max(1,e.ms));this.wake=()=>{clearTimeout(n),t()}});continue}this.open=!0,e.kind===`key`?await this.decodeKey(e.index):await this.decodeFrame(e.index),this.evict()}}catch(e){this.failure=e}finally{this.pumping=!1;for(let e of this.waiters.values())e.forEach(e=>e());this.waiters.clear()}}async decodeKey(e){let t=this.decodeLifetime.signal,n=this.facts.timestamps[e],r=this.opened,i=this.matte,[a,o]=await wje(()=>r.sink.getSample(n),()=>i?.sink.getSample(i.facts.timestamps[e]),t);if(!a){o?.close();return}try{if(!this.current(t))return;let n=await this.bitmap(a,o??void 0);if(!this.current(t)){n.close();return}for(this.keys.set(e,n);this.keys.size>zje;){let[e,t]=this.keys.entries().next().value;if(t===this.shown)break;t.close(),this.keys.delete(e)}this.missed&&this.keyAtOrBefore(this.target)===e&&this.notify()}finally{a.close(),o?.close()}}async decodeFrame(e){let t=this.decodeLifetime.signal,n=this.facts;if(!this.iterator||e<=this.cursor||e>this.cursor+Bje){let r=this.iterator,i=this.matteIterator;if(this.iterator=void 0,this.matteIterator=void 0,await r?.return(),await i?.return(),!this.current(t))return;this.iterator=this.opened.sink.samples(n.timestamps[e]),this.matteIterator=this.matte?.sink.samples(this.matte.facts.timestamps[e]),this.cursor=e-1}let r=this.iterator,i=this.matteIterator,[a,o]=await wje(async()=>{let e=await r.next();return e.done?void 0:e.value},async()=>{let e=await i?.next();return e?.done?void 0:e?.value},t);if(!a){if(o?.close(),!this.current(t))return;i?.return().catch(()=>{}),this.iterator=void 0,this.matteIterator=void 0;for(let[t,n]of this.waiters)t<e||(n.forEach(e=>e()),this.waiters.delete(t));this.cursor=n.timestamps.length,this.target>=n.timestamps.length&&(this.target=n.timestamps.length-1);return}try{if(!this.current(t))return;let r=pje(n.timestamps,a.timestamp);if(this.cursor=r,r>=Math.min(this.warmTarget>=0?this.warmTarget:this.target,e)-lx&&!this.cache.has(r)){let e=await this.bitmap(a,o);if(!this.current(t)){e.close();return}this.cache.set(r,e);let n=this.waiters.get(r);n&&(this.waiters.delete(r),n.forEach(e=>e())),this.missed&&r===this.target&&this.notify()}}finally{a.close(),o?.close()}}current(e){return!this.disposed&&!e.aborted}async bitmap(e,t){let n=e.toVideoFrame();try{let e=Math.min(1,this.height/n.displayHeight),r=Math.max(1,Math.round(n.displayWidth*e)),i=Math.max(1,Math.round(n.displayHeight*e)),a=t?await Tje(n,t):n;return await createImageBitmap(a,{resizeWidth:r,resizeHeight:i,resizeQuality:`medium`})}finally{n.close()}}ahead(){let e=this.facts;if(!e?.height)return Eje;let t=Math.min(this.height,e.height),n=Math.round(e.width*t/e.height)*t*4;return Math.max(Dje,Math.min(Eje,Math.floor(Oje/n)))}notify(){this.missed=!1;for(let e of dx)e(this.src)}evict(){let e=this.warmTarget>=0?this.warmTarget:this.target,t=performance.now()<this.reverseUntil,n=e-(t?64:lx),r=e+(t?lx:Math.max(this.ahead(),kje));for(let[e,t]of this.cache)(e<n||e>r)&&t!==this.shown&&!this.waiters.has(e)&&(t.close(),this.cache.delete(e))}}})),Wje=o((()=>{})),Gje=o((()=>{NAe(),ZAe(),Ive(),m_(),xje(),nje(),lye(),sje(),lje(),dje(),Sje(),yje(),Uje(),Wje()}));function Kje(e,t){let n=Math.max(2,Math.round(t/2)*2),r=eMe.find(t=>t>=e)??eMe.at(-1);return Math.min(r,n)}function qje(e){if(px(e)===!1)return!1;if(nMe.has(fx(e)))return!0;let t=e.get(Eh);if(typeof t?.blur==`number`&&t.blur>0||t?.effects?.some(e=>e.type===`blur`&&!e.hidden)||e.get(Mh)?.animate?.blur)return!0;let n=e.get(Nh);return[...S_(n?.enter),...S_(n?.exit)].some(e=>e.preset===`blur`)}function Jje(e){let t=rMe(e),n=u_(e);return!!t&&!!n&&t!==rMe(n)}function Yje(e){let t=[];for(let n=e;n&&fx(n)!==`scene`&&fx(n)!==`stage`;n=u_(n))t.unshift(n);if(!t.some(e=>px(e)===!1))return px(e)===!0&&mx(u_(e))?e:t.find(e=>Jje(e)&&mx(u_(e)))??t[0]}function Xje(e,t){return t(e)||l_(e).some(e=>Xje(e,t))}function Zje(e){let t=u_(e);if(!mx(t)||e.get(mh).key.startsWith(`~`)||e.get(xh)?.hidden)return!1;let n=l_(t),r=n[n.indexOf(e)+1],i=e=>fx(e)===`adjustmentLayer`;return r&&(i(r)||fx(r)===`sequence`&&Xje(r,i))?!1:!Xje(e,i)}function Qje(e){let t=new Set;for(let n of e.query(mh)){if(!qje(n)&&px(n)!==!0)continue;let e=Yje(n);e&&Zje(e)&&t.add(e)}let n=e=>{for(let n=u_(e);n;n=u_(n))if(t.has(n))return!0;return!1};return[...t].filter(e=>!n(e))}function $je(e,t){let n=u_(t);if(!n)return;let r=H_(e).fps,i=-gbe(e,t,0),a=Math.ceil(i*r-tMe);G_(e,a/r);let o=t.get(zh),s=n.get(zh);if(!o.active||!(o.length>0))return;let c=B_(e,t,o.fps),l=Math.min(Number.isFinite(c.end)?c.end-c.start:o.length,120),u=Math.ceil((i+l)*r-tMe);return{key:t.get(mh).key,width:s.width,height:s.height,fps:r,firstFrame:a,frames:u-a,offset:a/r-i,rootStart:i}}var eMe,tMe,nMe,fx,px,mx,rMe,iMe=o((()=>{C_(),Wh(),Y_(),d_(),eMe=[360,540,720,1080,1440,2160],tMe=1e-6,nMe=new Set([`html`,`surface`,`shaderPaint`]),fx=e=>e.get(mh).tag,px=e=>e.get(xh)?.prerender,mx=e=>!!e&&(fx(e)===`scene`||fx(e)===`group`&&e.get(Eh)?.clip===!0),rMe=e=>{let t=e.get(mh).key;return t.startsWith(`~`)?void 0:t.split(`/`).slice(0,-1).join(`/`)}})),hx=o((()=>{nye(),hCe(),gCe(),Sxe(),v_(),Gje(),C_(),Fbe(),Dxe(),O_(),iMe(),r_(),dbe(),Wxe(),lSe(),hSe(),Y_(),wye(),Wh(),d_()}));function aMe(e=new Map){let t=[];return{entries:t,module:{inspected(n,r){let i=e.get(gx(n.file,n.name)),a=i!==void 0&&Fge(n,i)===void 0?i:r;return t.push({...n,...Lge(n.name,n),initial:r,value:a}),a}}}}var oMe,gx,sMe,cMe=o((()=>{e_(),oMe=`@higgsfield/higgsedit/jsx/inspect`,gx=(e,t)=>`${e}#${t}`,sMe={inspected:(e,t)=>t}}));function lMe(e){let t=[];for(let n of e.split(`/`))n!==``&&n!==`.`&&(n===`..`?t.pop():t.push(n));return t.join(`/`)}function uMe(e){let t=new Set(e);return pMe.find(e=>t.has(e))}function dMe(e,t){if(!e)return{};let n={exports:{}};return Function(`require`,`module`,`exports`,`${e}\n//# sourceURL=higgsedit-project/node_modules.js`)(e=>{if(e in t)return t[e];throw Error(`a package imports "${e}", which the host does not provide (available: ${Object.keys(t).join(`, `)})`)},n,n.exports),n.exports}function fMe(e,t,n=uMe(Object.keys(e)),r={}){if(!n||!(n in e))throw Error(`project has no entry file (expected one of ${pMe.join(`, `)})`);let i=new Map,a=n=>{let o=i.get(n);if(o)return o.exports;let s={exports:{}};return i.set(n,s),(0,eval)(`(function (require, module, exports) {${e[n]}\n})\n//# sourceURL=higgsedit-project/${n}`)(i=>{let o=r.perFile?.[i];if(o)return o(n);if(i in t)return t[i];if(!i.startsWith(`.`))throw gMe(i)?Error(`${n}: cannot import "${i}" (available: ${Object.keys(t).join(`, `)}, or relative files)`):Error(`${n}: cannot import "${i}": it is not installed in the project (npm install ${_Me(i)})`);let s=lMe(`${hMe(n)}/${i}`),c=mMe.map(e=>s+e).find(t=>t in e);if(!c)throw Error(`${n}: cannot resolve "${i}"`);if(r.imports){let e=r.imports.get(n)??new Set;e.add(c),r.imports.set(n,e)}return a(c)},s,s.exports),s.exports},o=a(n).default;if(typeof o!=`function`)throw Error(`${n} must export a component as default`);return o}var pMe,mMe,hMe,gMe,_Me,vMe=o((()=>{pMe=[`index.tsx`,`index.jsx`,`index.ts`,`project.tsx`],mMe=[``,`.tsx`,`.ts`,`.jsx`,`.js`,`/index.tsx`,`/index.ts`,`/index.jsx`,`/index.js`],hMe=e=>e.split(`/`).slice(0,-1).join(`/`),gMe=e=>/^(solid-js|@higgsfield\/higgsedit\/jsx)(\/|$)/.test(e),_Me=e=>e.split(`/`).slice(0,e.startsWith(`@`)?2:1).join(`/`)})),yMe=c({$RAW:()=>wx,DEV:()=>void 0,createMutable:()=>AMe,createStore:()=>DMe,modifyMutable:()=>jMe,produce:()=>PMe,reconcile:()=>NMe,unwrap:()=>vx});function bMe(e){let t=e[Og];if(!t&&(Object.defineProperty(e,Og,{value:t=new Proxy(e,IMe)}),!Array.isArray(e))){let n=Object.keys(e),r=Object.getOwnPropertyDescriptors(e),i=Object.getPrototypeOf(e),a=i!==null&&typeof e==`object`&&!!e&&!Array.isArray(e)&&i!==Object.prototype;if(a){let e=Object.getOwnPropertyDescriptors(i);n.push(...Object.keys(e)),Object.assign(r,e)}for(let i=0,o=n.length;i<o;i++){let o=n[i];a&&o===`constructor`||r[o].get&&Object.defineProperty(e,o,{configurable:!0,enumerable:r[o].enumerable,get:r[o].get.bind(t)})}}return t}function _x(e){let t;return typeof e==`object`&&!!e&&(e[Og]||!(t=Object.getPrototypeOf(e))||t===Object.prototype||Array.isArray(e))}function vx(e,t=new Set){let n,r,i,a;if(n=e!=null&&e[wx])return n;if(!_x(e)||t.has(e))return e;if(Array.isArray(e)){Object.isFrozen(e)?e=e.slice(0):t.add(e);for(let n=0,a=e.length;n<a;n++)i=e[n],(r=vx(i,t))!==i&&(e[n]=r)}else{Object.isFrozen(e)?e=Object.assign({},e):t.add(e);let n=Object.keys(e),o=Object.getOwnPropertyDescriptors(e);for(let s=0,c=n.length;s<c;s++)a=n[s],!o[a].get&&(i=e[a],(r=vx(i,t))!==i&&(e[a]=r))}return e}function yx(e,t){let n=e[t];return n||Object.defineProperty(e,t,{value:n=Object.create(null)}),n}function bx(e,t,n){if(e[t])return e[t];let[r,i]=Xh(n,{equals:!1,internal:!0});return r.$=i,e[t]=r}function xMe(e,t){let n=Reflect.getOwnPropertyDescriptor(e,t);return!n||n.get||!n.configurable||t===Og||t===Tx?n:(delete n.value,delete n.writable,n.get=()=>e[Og][t],n)}function SMe(e){ng()&&bx(yx(e,Tx),FMe)()}function CMe(e){return SMe(e),Reflect.ownKeys(e)}function xx(e,t,n,r=!1){if(t===`__proto__`||!r&&e[t]===n)return;let i=e[t],a=e.length;n===void 0?(delete e[t],e[Ex]&&e[Ex][t]&&i!==void 0&&e[Ex][t].$()):(e[t]=n,e[Ex]&&e[Ex][t]&&i===void 0&&e[Ex][t].$());let o=yx(e,Tx),s;if((s=bx(o,t,i))&&s.$(()=>n),Array.isArray(e)&&e.length!==a){for(let t=e.length;t<a;t++)(s=o[t])&&s.$();(s=bx(o,`length`,a))&&s.$(e.length)}(s=o[FMe])&&s.$()}function wMe(e,t){let n=Object.keys(t);for(let r=0;r<n.length;r+=1){let i=n[r];TMe(i)||xx(e,i,t[i])}}function TMe(e){return e===`__proto__`||e===`constructor`||e===`prototype`}function EMe(e,t){if(typeof t==`function`&&(t=t(e)),t=vx(t),Array.isArray(t)){if(e===t)return;let n=0,r=t.length;for(;n<r;n++){let r=t[n];e[n]!==r&&xx(e,n,r)}xx(e,`length`,r)}else wMe(e,t)}function Sx(e,t,n=[]){let r,i=e;if(t.length>1){r=t.shift();let a=typeof r,o=Array.isArray(e);if(a===`string`&&(r===`__proto__`||t.length>1&&TMe(r)))return;if(Array.isArray(r)){for(let i=0;i<r.length;i++)Sx(e,[r[i]].concat(t),n);return}if(o&&a===`function`){for(let i=0;i<e.length;i++)r(e[i],i)&&Sx(e,[i].concat(t),n);return}if(o&&a===`object`){let{from:i=0,to:a=e.length-1,by:o=1}=r;for(let r=i;r<=a;r+=o)Sx(e,[r].concat(t),n);return}if(t.length>1){Sx(e[r],t,[r].concat(n));return}i=e[r],n=[r].concat(n)}let a=t[0];typeof a==`function`&&(a=a(i,n),a===i)||(r!==void 0||a!=null)&&(a=vx(a),r===void 0||_x(i)&&_x(a)&&!Array.isArray(a)?wMe(i,a):xx(e,r,a))}function DMe(...[e,t]){let n=vx(e||{}),r=Array.isArray(n),i=bMe(n);function a(...e){$h(()=>{r&&e.length===1?EMe(n,e[0]):Sx(n,e)})}return[i,a]}function OMe(e,t){let n=Reflect.getOwnPropertyDescriptor(e,t);return!n||n.get||n.set||!n.configurable||t===Og||t===Tx?n:(delete n.value,delete n.writable,n.get=()=>e[Og][t],n.set=n=>e[Og][t]=n,n)}function kMe(e){let t=e[Og];if(!t){Object.defineProperty(e,Og,{value:t=new Proxy(e,LMe)});let n=Object.keys(e),r=Object.getOwnPropertyDescriptors(e),i=Object.getPrototypeOf(e),a=i!==null&&typeof e==`object`&&!!e&&!Array.isArray(e)&&i!==Object.prototype;if(a){let e=i;for(;e!=null;){let t=Object.getOwnPropertyDescriptors(e);n.push(...Object.keys(t)),Object.assign(r,t),e=Object.getPrototypeOf(e)}}for(let i=0,o=n.length;i<o;i++){let o=n[i];if(!(a&&o===`constructor`)){if(r[o].get){let n=r[o].get.bind(t);Object.defineProperty(e,o,{get:n,configurable:!0})}if(r[o].set){let n=r[o].set;Object.defineProperty(e,o,{set:e=>$h(()=>n.call(t,e)),configurable:!0})}}}}return t}function AMe(e,t){return kMe(vx(e||{}))}function jMe(e,t){$h(()=>t(vx(e)))}function MMe(e){return e===`__proto__`||e===`constructor`||e===`prototype`}function Cx(e,t,n,r,i){if(MMe(n))return;let a=t[n];if(e===a)return;let o=Array.isArray(e);if(n!==Dx&&(!_x(e)||!_x(a)||o!==Array.isArray(a)||i&&e[i]!==a[i])){xx(t,n,e);return}if(o){if(e.length&&a.length&&(!r||i&&e[0]&&e[0][i]!=null)){let t,n,o,s,c,l,u,d;for(o=0,s=Math.min(a.length,e.length);o<s&&(a[o]===e[o]||i&&a[o]&&e[o]&&a[o][i]&&a[o][i]===e[o][i]);o++)Cx(e[o],a,o,r,i);let f=Array(e.length),p=new Map;for(s=a.length-1,c=e.length-1;s>=o&&c>=o&&(a[s]===e[c]||i&&a[s]&&e[c]&&a[s][i]&&a[s][i]===e[c][i]);s--,c--)f[c]=a[s];if(o>c||o>s){for(n=o;n<=c;n++)xx(a,n,e[n]);for(;n<e.length;n++)xx(a,n,f[n]),Cx(e[n],a,n,r,i);a.length>e.length&&xx(a,`length`,e.length);return}for(u=Array(c+1),n=c;n>=o;n--)l=e[n],d=i&&l?l[i]:l,t=p.get(d),u[n]=t===void 0?-1:t,p.set(d,n);for(t=o;t<=s;t++)l=a[t],d=i&&l?l[i]:l,n=p.get(d),n!==void 0&&n!==-1&&(f[n]=a[t],n=u[n],p.set(d,n));for(n=o;n<e.length;n++)n in f?(xx(a,n,f[n]),Cx(e[n],a,n,r,i)):xx(a,n,e[n])}else for(let t=0,n=e.length;t<n;t++)Cx(e[t],a,t,r,i);a.length>e.length&&xx(a,`length`,e.length);return}let s=Object.keys(e);for(let t=0,n=s.length;t<n;t++)MMe(s[t])||Cx(e[s[t]],a,s[t],r,i);let c=Object.keys(a);for(let t=0,n=c.length;t<n;t++)e[c[t]]===void 0&&xx(a,c[t],void 0)}function NMe(e,t={}){let{merge:n,key:r=`id`}=t,i=vx(e);return e=>{if(!_x(e)||!_x(i))return i;let t=Cx(i,{[Dx]:e},Dx,n,r);return t===void 0?e:t}}function PMe(e){return t=>{if(_x(t)){let n;(n=Ox.get(t))||Ox.set(t,n=new Proxy(t,RMe)),e(n)}return t}}var wx,Tx,Ex,FMe,IMe,LMe,Dx,Ox,RMe,zMe=o((()=>{Jg(),wx=Symbol(`store-raw`),Tx=Symbol(`store-node`),Ex=Symbol(`store-has`),FMe=Symbol(`store-self`),IMe={get(e,t,n){if(t===wx)return e;if(t===Og)return n;if(t===kg)return SMe(e),n;let r=yx(e,Tx),i=r[t],a=i?i():e[t];if(t===Tx||t===Ex||t===`__proto__`)return a;if(!i){let n=Object.getOwnPropertyDescriptor(e,t);ng()&&(typeof a!=`function`||Object.prototype.hasOwnProperty.call(e,t))&&!(n&&n.get)&&(a=bx(r,t,a)())}return _x(a)?bMe(a):a},has(e,t){return t===wx||t===Og||t===kg||t===Tx||t===Ex||t===`__proto__`||(ng()&&bx(yx(e,Ex),t)(),t in e)},set(){return!0},deleteProperty(){return!0},ownKeys:CMe,getOwnPropertyDescriptor:xMe},LMe={get(e,t,n){if(t===wx)return e;if(t===Og)return n;if(t===kg)return SMe(e),n;let r=yx(e,Tx),i=r[t],a=i?i():e[t];if(t===Tx||t===Ex||t===`__proto__`)return a;if(!i){let i=Object.getOwnPropertyDescriptor(e,t),o=typeof a==`function`;if(ng()&&(!o||Object.prototype.hasOwnProperty.call(e,t))&&!(i&&i.get))a=bx(r,t,a)();else if(a!=null&&o&&a===Array.prototype[t])return(...e)=>$h(()=>Array.prototype[t].apply(n,e))}return _x(a)?kMe(a):a},has(e,t){return t===wx||t===Og||t===kg||t===Tx||t===Ex||t===`__proto__`||(ng()&&bx(yx(e,Ex),t)(),t in e)},set(e,t,n){return $h(()=>xx(e,t,vx(n))),!0},deleteProperty(e,t){return $h(()=>xx(e,t,void 0,!0)),!0},ownKeys:CMe,getOwnPropertyDescriptor:OMe},Dx=Symbol(`store-root`),Ox=new WeakMap,RMe={get(e,t){if(t===wx)return e;let n=e[t];if(t===Og||t===kg||t===Tx||t===Ex||t===`__proto__`)return n;let r;return _x(n)?Ox.get(n)||(Ox.set(n,r=new Proxy(n,RMe)),r):n},set(e,t,n){return xx(e,t,vx(n)),!0},deleteProperty(e,t){return xx(e,t,void 0,!0),!0}}}));function BMe(e,t){let n=UMe[e.toLowerCase()];if(n)throw Error(n);let r=Yg(e),i=e.startsWith(`svg:`)?e.slice(pve.length):e,a;if(typeof document>`u`)a={tagName:r?i:i.toUpperCase(),style:{}};else if(r)a=document.createElementNS(HMe,i);else{let n=document.createElement(e);if(n instanceof HTMLUnknownElement&&!e.includes(`-`))throw t();a=n}return WMe.add(a),a}function VMe(e,t,n,r,i){if(!kx(e)||/^on[A-Z:]/.test(t)||t.startsWith(`on:`))return;let a=e.style;switch(t){case`style`:{if(typeof n==`string`||n==null){a.cssText=n??``;return}let e=n;if(r&&typeof r==`object`)for(let t of Object.keys(r))t in e||a.removeProperty(jx(t));for(let[t,n]of Object.entries(e))n==null||n===!1?a.removeProperty(jx(t)):a.setProperty(jx(t),String(n));return}case`class`:case`className`:n==null?e.removeAttribute(`class`):e.setAttribute(`class`,String(n));return;case`innerText`:case`textContent`:case`innerHTML`:{let r=n==null?``:String(n);t===`innerHTML`?e.innerHTML=r:t===`innerText`&&e instanceof HTMLElement?e.innerText=r:e.textContent=r;return}default:n==null||n===!1?e.removeAttribute(t):(t===`src`||t===`href`&&e.localName===`image`)&&typeof n==`string`&&!KMe(n)?e.setAttribute(t,i(n)):e.setAttribute(t,n===!0?``:String(n))}}var HMe,kx,UMe,WMe,Ax,GMe,jx,KMe,qMe=o((()=>{e_(),HMe=`http://www.w3.org/2000/svg`,kx=e=>typeof Element<`u`&&e instanceof Element,UMe={canvas:`<canvas> cannot go inside <html>: html-in-canvas draws it blank; draw into a <surface> instead`},WMe=new WeakSet,Ax=e=>typeof e==`object`&&!!e&&WMe.has(e),GMe=e=>kx(e)&&e.namespaceURI===HMe?e.tagName:e.tagName.toLowerCase(),jx=e=>e.startsWith(`--`)||!/[A-Z]/.test(e)?e:e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`),KMe=e=>/^([a-z][a-z\d+.-]*:|\/)/i.test(e)}));function JMe(e){let t=$Me.get(e);return t||$Me.set(e,t={parent:null,children:[]}),t}function YMe(e,t){Ax(e)?JMe(e).parent=t:e.parent=t}function XMe(e){return typeof HTMLElement>`u`?null:Ax(e)?kx(e)?e:null:e.kind===`element`&&e.tag===`html`&&e.element instanceof HTMLElement?e.element:null}function ZMe(e){return Ax(e)?kx(e)?e:null:e.kind!==`text`||typeof document>`u`?null:e.dom??=document.createTextNode(e.value)}function QMe(e,t,n){if(!e||!(`getContext`in e)||typeof n!=`number`||!Number.isFinite(n))return;let r=Math.max(1,Math.round(n));e[t]!==r&&(e[t]=r)}var $Me,Mx,Nx,Px,eNe,tNe,nNe,rNe=o((()=>{Jg(),e_(),hx(),qMe(),$Me=new WeakMap,Mx=e=>!Ax(e)&&e.kind===`text`,Nx=e=>Ax(e)?JMe(e).parent:e.parent,Px=e=>Ax(e)?JMe(e).children:e.children,eNe=e=>Ax(e)||e.kind===`element`&&e.tag===`html`,tNe=new Set([`children`,`ref`]),nNe=class{root={kind:`root`,parent:null,children:[]};mode;tick;setTick;holds=new Set;nodes=new Map;keyCounts=new Map;world;frozen;setFrozenScopes;scopes=new Map;scopeOf=()=>[];resolveUrl;constructor(e,t=`live`,n=e=>e){this.world=e,this.mode=t,this.resolveUrl=n;let[r,i]=Xh({time:0,frame:0,delta:0,playing:!1},{equals:(e,t)=>e.time===t.time&&e.frame===t.frame&&e.delta===t.delta&&e.playing===t.playing});this.tick=r,this.setTick=i;let[a,o]=Xh(new Set,{equals:(e,t)=>e.size===t.size&&[...e].every(e=>t.has(e))});this.frozen=a,this.setFrozenScopes=o}setFrozen(e){this.mode!==`capture`&&this.setFrozenScopes(new Set(e))}hold(e){this.mode===`capture`&&(this.holds.add(e),e.then(()=>this.holds.delete(e),()=>this.holds.delete(e)))}notProject(e){return Error(`<${e}> is not a higgsedit element; use ${Xg.join(`, `)} (HTML tags go inside <html>)`)}createElement(e){if(!gve(e))return BMe(e,()=>this.notProject(e));let t=Tve(this.world,e),n=null;if(e===`surface`){let e=Ibe();t.set(Lh,{canvas:e,root:null}),n=e}else if(e===`html`){let e=Lbe();t.set(Lh,{canvas:e?.canvas??null,root:e?.root??null}),n=e?.root??null}let r={kind:`element`,entity:t,tag:e,parent:null,children:[],scope:this.scopeOf(),accessors:new Map,disposed:!1,element:n};return this.nodes.set(t,r),this.assignKey(r,void 0),rg()&&tg(()=>this.disposeElement(r)),r}noteFile(e,t){e.entity.get(mh).file=t}createTextNode(e){return{kind:`text`,value:e,parent:null}}replaceText(e,t){Mx(e)&&(e.value=t,e.dom&&(e.dom.data=t),this.syncText(e.parent))}isTextNode(e){return Mx(e)}setProperty(e,t,n,r){if(tNe.has(t))return;if(Ax(e)){VMe(e,t,n,r,this.resolveUrl);return}if(e.kind!==`element`)return;e.accessors.get(t)?.(),e.accessors.delete(t);let i=e.entity.get(mh).accessors;if(typeof n==`function`&&t!==`animate`){i.add(t);let r=n,a=Yh(n=>(Zh(()=>this.applyProp(e,t,r())),n));e.accessors.set(t,a);return}i.delete(t),this.applyProp(e,t,n)}applyProp(e,t,n){if(e.disposed)return;let{entity:r}=e;if(e.tag===`surface`&&(t===`width`||t===`height`)&&QMe(e.element,t,n),t===`id`){this.assignKey(e,typeof n==`string`?n:void 0);return}if(t===`name`){r.set(mh,{...r.get(mh),name:typeof n==`string`?n:void 0});return}let i=Sge(e.tag,t);if(i){let e=r.get(i);if(e[t]===n)return;r.set(i,{...e,[t]:n});return}r.has(Rh)||r.add(Rh),r.set(Rh,{props:{...r.get(Rh).props,[t]:n}})}assignKey(e,t){let n=e.entity.get(mh);n.key&&this.releaseKey(n.key);let r=t===void 0?`~${e.tag}${e.entity.id()}`:[...e.scope,t].join(`/`),i=this.keyCounts.get(r)??0;this.keyCounts.set(r,i+1);let a=i===0?r:`${r}#${i}`;e.entity.set(mh,{...n,id:t,key:a})}releaseKey(e){let t=e.replace(/#\d+$/,``),n=this.keyCounts.get(t)??0;n<=1?this.keyCounts.delete(t):this.keyCounts.set(t,n-1)}insertNode(e,t,n){if(Mx(e))return;if(eNe(e)){if(!Ax(t)&&t.kind===`element`)throw Error(`<${t.tag}> cannot go inside <html>: its content is HTML tags and text, not higgsedit elements`)}else if(Ax(t))throw this.notProject(GMe(t));let r=Nx(t);r&&this.removeChild(r,t);let i=Px(e),a=n?i.indexOf(n):-1;a>=0?i.splice(a,0,t):i.push(t),YMe(t,e);let o=XMe(e),s=o&&ZMe(t);if(o&&s&&o.insertBefore(s,a>=0?ZMe(n):null),!(Ax(t)||Ax(e))){if(t.kind===`text`){this.syncText(e);return}t.kind===`element`&&e.kind===`element`&&t.entity.isAlive()&&e.entity.isAlive()&&Eve(e.entity,t.entity,this.nextEntity(e,t))}}nextEntity(e,t){let n=e.children;for(let e=n.indexOf(t)+1;e<n.length;e++){let t=n[e];if(!Ax(t)&&t.kind===`element`)return t.entity}return null}removeNode(e,t){this.removeChild(e,t)}removeChild(e,t){if(Mx(e))return;let n=Px(e),r=n.indexOf(t);if(r>=0&&n.splice(r,1),YMe(t,null),Ax(t)){kx(t)&&t.remove();return}t.kind===`text`&&(t.dom?.remove(),this.syncText(e)),t.kind===`element`&&t.entity.isAlive()&&i_(t.entity)}getParentNode(e){return Nx(e)??void 0}getFirstChild(e){return Mx(e)?void 0:Px(e)[0]}getNextSibling(e){let t=Nx(e);if(!t)return;let n=Px(t);return n[n.indexOf(e)+1]}syncText(e){if(!e||Ax(e)||e.kind!==`element`||e.tag!==`text`||e.disposed)return;let t=e.children.map(e=>Mx(e)?e.value:``).join(``);e.entity.get(Oh)?.text!==t&&e.entity.set(Oh,{text:t})}disposeElement(e){if(e.disposed)return;e.disposed=!0;for(let t of e.accessors.values())t();e.accessors.clear(),this.nodes.delete(e.entity);let{entity:t}=e;if(!t.isAlive())return;let n=e.tag===`html`?t.get(Lh)?.canvas:null;typeof HTMLCanvasElement<`u`&&n instanceof HTMLCanvasElement&&n.remove(),this.releaseKey(t.get(mh).key);for(let e of t.get(hh)?.children??[])i_(e);i_(t),t.destroy()}dispose(){for(let e of this.nodes.values())this.disposeElement(e);this.root.children.length=0,this.holds.clear()}}}));function iNe({createElement:e,createTextNode:t,isTextNode:n,replaceText:r,insertNode:i,removeNode:a,setProperty:o,getParentNode:s,getFirstChild:c,getNextSibling:l}){function u(e,t,n,r){if(n!==void 0&&!r&&(r=[]),typeof t!=`function`)return d(e,t,r,n);Zh(r=>d(e,t(),r,n),r)}function d(e,a,o,s,l){for(;typeof o==`function`;)o=o();if(a===o)return o;let u=typeof a,_=s!==void 0;if(u===`string`||u===`number`){if(u===`number`&&(a=a.toString()),_){let i=o[0];i&&n(i)?r(i,a):i=t(a),o=m(e,o,s,i)}else o!==``&&typeof o==`string`?r(c(e),o=a):(m(e,o,s,t(a)),o=a)}else if(a==null||u===`boolean`)o=m(e,o,s);else if(u===`function`)return Zh(()=>{let t=a();for(;typeof t==`function`;)t=t();o=d(e,t,o,s)}),()=>o;else if(Array.isArray(a)){let t=[];if(f(t,a,l))return Zh(()=>o=d(e,t,o,s,!0)),()=>o;if(t.length===0){let t=m(e,o,s);if(_)return o=t}else Array.isArray(o)?o.length===0?h(e,t,s):p(e,o,t):o==null||!c(e)?h(e,t):p(e,_&&o||[c(e)],t);o=t}else{if(Array.isArray(o)){if(_)return o=m(e,o,s,a);m(e,o,null,a)}else o==null||!c(e)?i(e,a):g(e,a,c(e));o=a}return o}function f(e,n,r){let i=!1;for(let a=0,o=n.length;a<o;a++){let o=n[a],s;if(o!=null&&o!==!0&&o!==!1){if(Array.isArray(o))i=f(e,o)||i;else if((s=typeof o)==`string`||s===`number`)e.push(t(o));else if(s===`function`){if(r){for(;typeof o==`function`;)o=o();i=f(e,Array.isArray(o)?o:[o])||i}else e.push(o),i=!0}else e.push(o)}}return i}function p(e,t,n){let r=n.length,o=t.length,s=r,c=0,u=0,d=l(t[o-1]),f=null;for(;c<o||u<s;){if(t[c]===n[u]){c++,u++;continue}for(;t[o-1]===n[s-1];)o--,s--;if(o===c){let t=s<r?u?l(n[u-1]):n[s-u]:d;for(;u<s;)i(e,n[u++],t)}else if(s===u)for(;c<o;)(!f||!f.has(t[c]))&&a(e,t[c]),c++;else if(t[c]===n[s-1]&&n[u]===t[o-1]){let r=l(t[--o]);i(e,n[u++],l(t[c++])),i(e,n[--s],r),t[o]=n[s]}else{if(!f){f=new Map;let e=u;for(;e<s;)f.set(n[e],e++)}let r=f.get(t[c]);if(r!=null){if(u<r&&r<s){let a=c,l=1,d;for(;++a<o&&a<s&&(d=f.get(t[a]))!=null&&d===r+l;)l++;if(l>r-u){let a=t[c];for(;u<r;)i(e,n[u++],a)}else g(e,n[u++],t[c++])}else c++}else a(e,t[c++])}}}function m(e,n,r,o){if(r===void 0){let t;for(;t=c(e);)a(e,t);return o&&i(e,o),``}let l=o||t(``);if(n.length){let t=!1;for(let o=n.length-1;o>=0;o--){let c=n[o];if(l!==c){let n=s(c)===e;!t&&!o?n?g(e,l,c):i(e,l,r):n&&a(e,c)}else t=!0}}else i(e,l,r);return[l]}function h(e,t,n){for(let r=0,a=t.length;r<a;r++)i(e,t[r],n)}function g(e,t,n){i(e,t,n),a(e,n)}function _(e,t,n={},r){return t||={},r||Zh(()=>n.children=d(e,t.children,n.children)),Zh(()=>t.ref&&t.ref(e)),Zh(()=>{for(let r in t){if(r===`children`||r===`ref`)continue;let i=t[r];i!==n[r]&&(o(e,r,i,n[r]),n[r]=i)}}),n}return{render(e,t){let n;return Yh(r=>{n=r,u(t,e())}),n},insert:u,spread(e,t,n){typeof t==`function`?Zh(r=>_(e,t(),r,n)):_(e,t,void 0,n)},createElement:e,createTextNode:t,insertNode:i,setProp(e,t,n,r){return o(e,t,n,r),n},mergeProps:F_e,effect:Zh,memo:oNe,createComponent:gg,use(e,t,n){return eg(()=>e(t,n))}}}function aNe(e){let t=iNe(e);return t.mergeProps=F_e,t}var oNe,sNe=o((()=>{Jg(),oNe=e=>Qh(()=>e())})),cNe=c({createComponent:()=>dNe,createElement:()=>CNe,createElementIn:()=>lNe,createTextNode:()=>wNe,currentScope:()=>fNe,effect:()=>xNe,insert:()=>ENe,insertNode:()=>TNe,memo:()=>SNe,mergeProps:()=>kNe,registerBuiltins:()=>uNe,render:()=>bNe,renderProject:()=>_Ne,setProp:()=>ONe,spread:()=>DNe,use:()=>ANe,useLocalTime:()=>hNe,useResolution:()=>gNe,useTicker:()=>mNe});function Fx(){let e=ag(vNe)??Rx;if(!e)throw Error(`higgsedit elements can only be created while a project mounts`);return e}function lNe(e,t){let n=CNe(t);return`entity`in n&&Fx().noteFile(n,e),n}function uNe(e){for(let t of e)jNe.add(t)}function dNe(e,t){let n=jNe.has(e)?void 0:eg(()=>t.id);if(typeof n!=`string`)return gg(e,t);let r=ag(Lx);return Fx().scopes.set([...r,n].join(`/`),t),gg(Lx.Provider,{value:[...r,n],get children(){return gg(e,t)}})}function fNe(){return ag(Lx)}function pNe(e){let t=ag(Lx).join(`/`);return t?Qh(()=>{for(let n of e.frozen())if(t===n||t.startsWith(`${n}/`))return!0;return!1}):()=>!1}function Ix(e,t,n){return Qh(r=>r!==void 0&&t()?r:n(e.tick()),void 0)}function mNe(){let e=Fx(),t=pNe(e);return{time:Ix(e,t,e=>e.time),frame:Ix(e,t,e=>e.frame),delta:Ix(e,t,e=>e.delta),playing:Ix(e,t,e=>e.playing),hold:t=>e.hold(t)}}function hNe(e){let t=Fx(),{world:n,tick:r}=t,i=pNe(t);return Qh(t=>{if(t!==void 0&&i())return t;let a=r().time,o=s_(n,e)??n.query(mh).find(t=>t.get(mh).id===e);if(!o)throw Error(`useLocalTime("${e}"): no element has id "${e}"`);return gbe(n,o,a)})}function gNe(){let e=Fx();return()=>{let t=H_(e.world);return{width:t.width,height:t.height,fps:t.fps}}}function _Ne(e,t){let n=Rx;Rx=t,t.scopeOf=fNe;try{return bNe(()=>gg(vNe.Provider,{value:t,get children(){return gg(e,{})}}),t.root)}finally{Rx=n}}var vNe,Lx,Rx,yNe,bNe,xNe,SNe,CNe,wNe,TNe,ENe,DNe,ONe,kNe,ANe,jNe,MNe=o((()=>{Jg(),sNe(),hx(),rNe(),vNe=ig(null),Lx=ig([]),Rx=null,yNe=aNe({createElement:e=>Fx().createElement(e),createTextNode:e=>Fx().createTextNode(String(e)),replaceText:(e,t)=>Fx().replaceText(e,String(t)),isTextNode:e=>Mx(e),setProperty:(e,t,n,r)=>Fx().setProperty(e,t,n,r),insertNode:(e,t,n)=>Fx().insertNode(e,t,n),removeNode:(e,t)=>Fx().removeNode(e,t),getParentNode:e=>Nx(e)??void 0,getFirstChild:e=>Mx(e)?void 0:Px(e)[0],getNextSibling:e=>Fx().getNextSibling(e)}),{render:bNe,effect:xNe,memo:SNe,createElement:CNe,createTextNode:wNe,insertNode:TNe,insert:ENe,spread:DNe,setProp:ONe,mergeProps:kNe,use:ANe}=yNe,jNe=new Set}));function NNe(e,t,n=`live`,r={}){let i=new nNe(t,n,r.resolveUrl),a;try{a=_Ne(e,i)}catch(e){throw i.dispose(),e}return{document:i,world:t,tick:e=>$h(()=>i.setTick(e)),dispose(){a(),i.dispose()}}}var PNe,FNe,INe,LNe=o((()=>{Jg(),zMe(),e_(),rNe(),cMe(),MNe(),uNe([z_e,B_e,V_e,H_e,U_e,G_e,q_e,K_e]),PNe={...hve,useTicker:mNe,useResolution:gNe,useLocalTime:hNe},FNe={"solid-js":Hge,"solid-js/store":yMe,"@higgsfield/higgsedit/jsx":PNe,"@higgsfield/higgsedit/jsx/renderer":cNe,[oMe]:sMe},INe={"@higgsfield/higgsedit/jsx/renderer":e=>({...cNe,createElement:t=>lNe(e,t)})}}));function zx(e,t){if(e===void 0)return`u`;if(e===null||typeof e==`number`||typeof e==`boolean`||typeof e==`string`)return JSON.stringify(e);if(typeof e==`function`)return`f${JSON.stringify(String(e))}`;if(typeof e!=`object`)return JSON.stringify(String(e));if(t.has(e))return`"[cycle]"`;if(t.add(e),Array.isArray(e))return`[${e.map(e=>zx(e,t)).join(`,`)}]`;if(e instanceof Set)return`s[${[...e].map(e=>zx(e,t)).toSorted().join(`,`)}]`;if(e instanceof Map)return`m{${[...e].map(([e,n])=>`${zx(e,t)}:${zx(n,t)}`).toSorted().join(`,`)}}`;let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null||UNe(e))return JSON.stringify(`[${UNe(e)?`node`:n?.constructor?.name??`object`}]`);let r=e;return`{${Object.keys(r).filter(e=>!zNe.has(e)).toSorted().map(e=>`${JSON.stringify(e)}:${zx(r[e],t)}`).join(`,`)}}`}function RNe(e,t,n){let r=[`E ${t.get(mh).key}`],i=new Set,a=new Set,o=u_(t),s=(o&&e.nodes.get(o)?.scope.length)??0,c=!1,l=(t,n)=>{let o=t.get(mh),u=o_(t);for(let e of o.accessors)delete u[e];r.push(`N ${n} ${o.tag} ${o.id??``} ${[...o.accessors].toSorted().join(`,`)} ${eg(()=>zx(u,new WeakSet))}`),o.file&&i.add(o.file);let d=e.nodes.get(t)?.scope??[];for(let e=s+1;e<=d.length;e++)a.add(d.slice(0,e).join(`/`));let f=t.get(Dh)?.blend;f&&f!==`normal`&&(c=!0),l_(t).forEach((e,t)=>l(e,`${n}/${t}`))};l(t,``);for(let t of[...a].toSorted())r.push(`S ${t} ${eg(()=>zx(e.scopes.get(t),new WeakSet))}`);let u=[...i];for(let e of u)for(let t of n.imports.get(e)??[])i.has(t)||(i.add(t),u.push(t));let d=[...i].toSorted();for(let e of d)r.push(`M ${e}\n${HNe(n,e)}`);n.packages&&r.push(`P ${n.packages}`);let f=r.join(`
277
277
  `),p=new Set;for(let e of f.matchAll(BNe))p.add(e[1].replace(/^\.\//,``).replace(/\$\{[^}]*\}/g,`*`));return{text:f,ticker:d.some(e=>/\buseTicker\b/.test(HNe(n,e))),blend:c,media:[...p].toSorted()}}var zNe,BNe,VNe,HNe,UNe,WNe=o((()=>{Jg(),hx(),zNe=new Set([`children`,`ref`]),BNe=/["'`]((?:\.\/)?(?:\$\{[^}]*\}|[^"'`\s<>])+?\.(?:mp4|mov|m4v|webm|mkv|png|jpe?g|webp|gif|avif|svg|mp3|wav|m4a|aac|ogg|flac|mask|json|ttf|otf|woff2?))["'`]/gi,VNe=/\n?\/\/# sourceMappingURL=\S*\s*$/,HNe=(e,t)=>(e.modules[t]??``).replace(VNe,``),UNe=e=>`kind`in e&&`entity`in e}));function GNe(e){let t=2166136261,n=16777619^e.length;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);t=Math.imul(t^i,16777619),n=Math.imul(n^i,16777629)}return`${(t>>>0).toString(16)}${(n>>>0).toString(16)}:${e.length}`}async function KNe(e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return[...new Uint8Array(t)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}var qNe,JNe,YNe,XNe,ZNe=o((()=>{Jg(),cMe(),vMe(),LNe(),WNe(),hx(),qNe=3e4,JNe=e=>e.replace(/^\.\//,``),YNe=(e,t)=>[...jve(e,t),...Mve(e,t)],XNe=class{world=wve();mount;media;fonts=new JAe;googleFonts;projectFamilies=new Set;mediaUrl;server;options;comp;captureScene;captureIncludes=e=>{if(!this.captureScene)return!0;for(let t=e;t;t=u_(t))if(t===this.captureScene)return!0;return!1};inspect=[];prerender=new Map;constructor(e){this.options=e;let t=e.mediaBase.replace(/\/$/,``);this.mediaUrl=e=>`${t}/${JNe(e)}`;let n=(e.videoBase??t).replace(/\/$/,``);this.media=new bje(this.mediaUrl,e.makeVideo,e=>`${n}/${JNe(e)}`),this.server=e.origin??new URL(t,globalThis.location?.href).origin,this.googleFonts=new YAe(new URL(`${this.server}/__higgsedit/fonts/google`,globalThis.location?.href).href)}bundled;packages(e,t){return e?(this.bundled?.code!==e&&(this.bundled={code:e,modules:dMe(e,t)}),this.bundled.modules):{}}async load(e,t=[],n,r){let i=this.fonts.load(t,this.mediaUrl),a=performance.now(),o=aMe(n),s={...FNe,[oMe]:o.module},c=new Map,l=fMe(e,{...s,...this.packages(r,s)},void 0,{perFile:INe,imports:c}),u=performance.now(),d=wve();this.options.captureSceneId!==void 0&&pbe(d,this.options.captureSceneId);let f=NNe(l,d,this.options.mode===`capture`?`capture`:`live`,{resolveUrl:this.mediaUrl}),p=this.options.captureSceneId===void 0?void 0:z_(d)[0];if(this.options.captureSceneId!==void 0&&!p)throw f.dispose(),d.destroy(),Error(`unknown scene: ${this.options.captureSceneId}`);let m=performance.now(),h={modules:e,imports:c,...r?{packages:GNe(r)}:{}},g=new Map(Qje(d).map(e=>[e.get(mh).key,RNe(f.document,e,h)]));this.mount?.dispose(),this.world.destroy(),this.world=d,this.mount=f,this.captureScene=p,this.inspect=o.entries,this.prerender=g;let _=await i;return this.projectFamilies=new Set(_.flatMap(e=>e?[e.family.replace(/^["']|["']$/g,``).toLowerCase()]:[])),this.googleFonts.retryFailed(),await this.googleFonts.load(YNe(d,this.captureIncludes),this.projectFamilies),await this.resolveMedia(this.options.mode===`capture`),this.comp=G_(d,0),{composition:{width:this.comp.width,height:this.comp.height,fps:this.comp.fps,duration:this.comp.duration,frames:this.comp.frames},clips:Ebe(d),entities:d.query(mh).length,compileMs:u-a,mountMs:m-u}}async resolveMedia(e){let t=this.world.get(c_).durations,n=new Set(this.world.query(kh).filter(this.captureIncludes)),r=new Map(obe(this.world).filter(e=>!e.problem&&e.target).map(e=>[e.entity,e.target]));for(let e of n){let t=r.get(e);t&&n.add(t)}let i=[...n].filter(e=>(e.get(mh).tag===`video`||e.get(mh).tag===`audio`)&&e.get(kh).src).map(e=>{let n=e.get(kh).src;return(e.get(mh).tag===`audio`?this.media.audio(n):this.media.video(n)).ready.then(e=>{t.set(n,e.duration)})});for(let e of this.world.query(Ah)){if(!this.captureIncludes(e))continue;let n=e.get(Ah).src;n&&i.push(this.media.transcript(n).ready.then(e=>void t.set(n,Qve(e))))}i.push(this.resolveSyncs(n)),e?await Promise.all(i):await Promise.race([Promise.allSettled(i),new Promise(e=>setTimeout(e,0))])}async resolveSyncs(e){let t=this.world,n=t.get(c_).offsets,r=this.options.syncUrl??`${this.server}/__higgsedit/sync`;await Promise.all(obe(t).filter(t=>e.has(t.entity)).map(async e=>{if(e.problem||!e.src||!e.targetSrc){console.warn(`syncTo on ${e.key}: ${e.problem??`nothing to align`}; it keeps its default placement`);return}let t=ube(e.src,e.targetSrc);if(n.has(t))return;let i;try{let a=await fetch(`${r}?${new URLSearchParams({src:e.src,target:e.targetSrc})}`),o=await a.json();if(a.ok&&typeof o.offset==`number`){n.set(t,o.offset);return}i=o.error??`HTTP ${a.status}`}catch(e){i=e instanceof Error?e.message:String(e)}console.warn(`syncTo on ${e.key}: ${i}; it keeps its default placement`)}))}fontMisses(){return[...this.fonts.misses.values(),...this.googleFonts.misses.values()]}durationsReady(){return this.resolveMedia(!0)}tick(e,t={}){let n=R_(this.world),r=t.time??e/n,i=()=>{$h(()=>this.mount?.tick({time:r,frame:e,delta:t.delta??1/n,playing:t.playing??!0})),this.comp=G_(this.world,r)};return this.options.mode===`live`?Wbe(this.world,i):i(),this.comp}async settle(e,t=e/R_(this.world)){let n=this.mount?.document;for(let r=0;r<50;r++){let r=n?[...n.holds]:[],i=Promise.all([...r,xSe(this.world,this.media),this.googleFonts.load(YNe(this.world,this.captureIncludes),this.projectFamilies),globalThis.document?.fonts?.ready]),a,o=new Promise((t,n)=>{a=setTimeout(()=>n(Error(`frame ${e}: hold() did not settle within ${qNe/1e3} s`)),qNe)});try{await Promise.race([i,o])}finally{clearTimeout(a)}if(this.comp=G_(this.world,t),!n||n.holds.size===0){await xSe(this.world,this.media);return}}throw Error(`frame ${e}: hold() kept registering new work`)}async renderFrame(e,t,n=1,r={}){try{this.tick(t,{time:r.time}),await this.settle(t,r.time),QSe(e,this.world,this.comp,this.media,{mode:`capture`,scale:n,origin:r.origin})}catch(e){throw Txe(e,t,R_(this.world))}}async prerenderInputs(){let e=[];for(let[t,n]of this.prerender){let r=this.prerenderPlan(t);if(!r)continue;let i=`G ${r.width}x${r.height} ${r.fps} ${r.frames} ${Math.round(r.offset*1e6)}${n.ticker?` ${r.rootStart}`:``}`;e.push({...r,digest:await KNe(`${n.text}\n${i}`),media:n.media,blend:n.blend})}return this.comp&&=G_(this.world,0),e}prerenderPlan(e){let t=s_(this.world,e);return t?$je(this.world,t):void 0}async renderIsolated(e,t,n,r){try{this.tick(n),await this.settle(n);let i=s_(this.world,t);if(!i)throw Error(`no element ${t}`);Tbe(i),$Se(e,i,this.media,{mode:`capture`,scale:r})}catch(e){throw Txe(e,n,R_(this.world))}}drawLive(e,t=1,n,r,i){let a=new Set,o=!1,s=new Set;return this.comp&&QSe(e,this.world,this.comp,this.media,{mode:`live`,scale:t,...n?{origin:n}:{},...r?{visible:r}:{},...i?{prerendered:i}:{},onPendingMedia:e=>{a.add(e)},onHtml:(e,t)=>{s.add(e),t||(o=!0)}}),{pendingMedia:[...a],pendingHtml:o,htmlKeys:[...s]}}entity(e){return s_(this.world,e)}}}));function QNe(e,t,n){let r=e;for(let e of t){let i=r[e];if(typeof i!=`object`||!i)throw new Bx(`${n.op}: ${Vx(t)} does not exist`,n);let a=Array.isArray(i)?[...i]:{...i};r[e]=a,r=a}return r}function $Ne(e,t){let n={...e},r=[];for(let e of t){let t={root:n};if(e.op===`set`){if(e.path.length===0)throw new Bx(`set: the root cannot be replaced`,e);let n=QNe(t,[`root`,...e.path.slice(0,-1)],e),i=e.path.at(-1);if(!(i in n))throw new Bx(`set: ${Vx(e.path)} does not exist`,e);r.unshift({op:`set`,path:e.path,value:Hx(n[i])}),n[i]=Hx(e.value)}else{let n=QNe(t,[`root`,...e.path.slice(0,-1)],e),i=e.path.length?e.path.at(-1):`root`,a=n[i];if(!Array.isArray(a))throw new Bx(`${e.op}: ${Vx(e.path)} is not an array`,e);let o=[...a];if(n[i]=o,e.op===`insert`){if(e.index<0||e.index>o.length)throw new Bx(`insert: index ${e.index} out of range at ${Vx(e.path)}`,e);o.splice(e.index,0,Hx(e.value)),r.unshift({op:`remove`,path:e.path,index:e.index})}else if(e.op===`remove`){if(e.index<0||e.index>=o.length)throw new Bx(`remove: index ${e.index} out of range at ${Vx(e.path)}`,e);let[t]=o.splice(e.index,1);r.unshift({op:`insert`,path:e.path,index:e.index,value:t})}else{if(e.from<0||e.from>=o.length||e.to<0||e.to>=o.length)throw new Bx(`move: ${e.from}→${e.to} out of range at ${Vx(e.path)}`,e);o.splice(e.to,0,...o.splice(e.from,1)),r.unshift({op:`move`,path:e.path,from:e.to,to:e.from})}}n=t.root}return{document:n,inverse:r}}var Bx,Vx,Hx,Ux,ePe=o((()=>{Bx=class extends Error{op;constructor(e,t){super(e),this.op=t,this.name=`DocumentOpError`}},Vx=e=>e.map(String).join(`.`)||`<root>`,Hx=e=>structuredClone(e),Ux=(e,t)=>$Ne(e,t).document}));function tPe(e=`id`){return`${e}-${globalThis.crypto?.randomUUID?.().slice(0,8)??Math.random().toString(36).slice(2,10)}-${(lPe++).toString(36)}`}function Wx(e,t){return{id:t.id??tPe(e),name:t.name??e,transform:uPe(t.transform),size:t.size??{width:100,height:100},opacity:t.opacity??1,blendMode:t.blendMode??`normal`,effects:t.effects??[],timeRange:t.timeRange??{start:0,duration:5},animations:t.animations??[],presetAnimations:t.presetAnimations??[],mask:t.mask??null,locked:t.locked??!1,hidden:t.hidden??!1,...t.constrainX?{constrainX:t.constrainX}:{},...t.constrainY?{constrainY:t.constrainY}:{}}}function nPe(e={}){return{...Wx(`rect`,e),kind:`rect`,fill:e.fill??{type:`solid`,color:`#ffffff`},stroke:e.stroke??{color:`#000000`,width:0},cornerRadius:e.cornerRadius??qx(0)}}function Gx(e={}){return{...Wx(`text`,e),kind:`text`,text:e.text??`Text`,fontFamily:e.fontFamily??`sans-serif`,fontSize:e.fontSize??48,fontWeight:e.fontWeight??400,italic:e.italic??!1,letterSpacing:e.letterSpacing??0,lineHeight:e.lineHeight??1.2,align:e.align??`left`,fill:e.fill??{type:`solid`,color:`#ffffff`},stroke:e.stroke??{color:`#000000`,width:0},motion:e.motion??null}}function rPe(e){let t=e.timeRange??{start:0,duration:5};return{...Wx(`media`,{...e,timeRange:t}),kind:`media`,assetId:e.assetId,trim:e.trim??{start:0,end:t.duration},volume:e.volume??1,muted:e.muted??!1,speed:e.speed??1,preservePitch:e.preservePitch??!0,cornerRadius:e.cornerRadius??qx(0)}}function iPe(e){let t=e.timeRange??{start:0,duration:5};return{...Wx(`audio`,{...e,timeRange:t}),kind:`audio`,assetId:e.assetId,trim:e.trim??{start:0,end:t.duration},volume:e.volume??1,muted:e.muted??!1,speed:e.speed??1,preservePitch:e.preservePitch??!0}}function aPe(e={}){return{...Wx(`adjustment`,e),kind:`adjustment`}}function oPe(e={}){return{...Wx(`group`,e),kind:`group`,children:e.children??[]}}function Kx(e={}){return{id:e.id??tPe(`track`),name:e.name??`Track`,mode:e.mode??`default`,clips:e.clips??[],locked:e.locked??!1,hidden:e.hidden??!1,muted:e.muted??!1,solo:e.solo??!1,volume:e.volume??1}}function sPe(e){let t=0;for(let n of e.tracks)for(let e of n.clips)t=Math.max(t,e.timeRange.start+e.timeRange.duration);return t}function cPe(e={}){let t=e.tracks??[];return{id:e.id??tPe(`scene`),name:e.name??`Scene`,x:e.x??0,y:e.y??0,width:e.width??1920,height:e.height??1080,background:e.background??{type:`solid`,color:`#000000`},fps:e.fps??30,duration:sPe({tracks:t}),tracks:t,markers:e.markers??[]}}var lPe,uPe,qx,dPe=o((()=>{Tm(),lPe=0,uPe=(e={})=>({x:0,y:0,scaleX:1,scaleY:1,rotation:0,skewX:0,skewY:0,anchorX:0,anchorY:0,flipX:!1,flipY:!1,...e}),qx=(e=0)=>({mixed:!1,uniform:e,tl:e,tr:e,br:e,bl:e})}));function Jx(e){let t=!1,n=e.scenes.map(e=>{let n=sPe(e);return n===e.duration?e:(t=!0,{...e,duration:n})});return t?{...e,scenes:n}:e}var fPe,pPe,mPe=o((()=>{jm(),ePe(),dPe(),fPe={sceneId:null,clipIds:[],trackIds:[],markerIds:[],keyframes:[],time:0},pPe=class{doc=null;sel=fPe;undoStack=[];redoStack=[];listeners=new Set;snapshot(){return this.doc}selection(){return this.sel}setSelection(e){this.sel={...this.sel,...e}}undoState(){return{canUndo:this.undoStack.length>0,canRedo:this.redoStack.length>0,undoName:this.undoStack.at(-1)?.name??null,redoName:this.redoStack.at(-1)?.name??null}}onEvent(e){return this.listeners.add(e),km(()=>this.listeners.delete(e))}emit(e){for(let t of Array.from(this.listeners))t(e)}open(e){this.doc=Jx(e),this.undoStack=[],this.redoStack=[],this.sel={...fPe,sceneId:this.doc.activeSceneId},this.emit({type:`opened`,document:this.doc}),this.emitHistory()}replace(e,t=`load`){this.doc=Jx(e),this.emit({type:`changed`,commandId:`replace-${Date.now()}`,name:`Reload`,ops:[],inverse:null,supersedes:null,origin:t})}close(){if(!this.doc)return;let e=this.doc.id;this.doc=null,this.undoStack=[],this.redoStack=[],this.emit({type:`closed`,documentId:e})}execute(e,t=`local`){if(!this.doc)throw Error(`no document is open`);let{document:n,inverse:r}=$Ne(this.doc,e.ops);this.doc=Jx(n);let i=this.undoStack.at(-1),a=null;t===`local`&&(e.coalesceKey!==null&&i?.coalesceKey===e.coalesceKey?(a=i.commandId,i.commandId=e.id,i.ops=[...i.ops,...e.ops],i.inverse=[...r,...i.inverse]):this.undoStack.push({commandId:e.id,name:e.name,coalesceKey:e.coalesceKey,ops:[...e.ops],inverse:r}),this.redoStack=[]),this.emit({type:`changed`,commandId:e.id,name:e.name,ops:e.ops,inverse:r,supersedes:a,origin:t}),t===`local`&&this.emitHistory()}undo(){return this.step(this.undoStack,this.redoStack,`undo`)}redo(){return this.step(this.redoStack,this.undoStack,`redo`)}step(e,t,n){let r=e.pop();if(!r||!this.doc)return!1;let i=n===`undo`?r.inverse:r.ops,{document:a,inverse:o}=$Ne(this.doc,i);return this.doc=Jx(a),t.push(r),this.emit({type:`changed`,commandId:r.commandId,name:r.name,ops:i,inverse:o,supersedes:null,origin:n}),this.emitHistory(),!0}emitHistory(){this.emit({type:`history`,state:this.undoState()})}}})),Yx=o((()=>{ePe(),dPe(),mPe()}));function hPe(e,t,n,r,i,a){let o=a-i;if(!e||o===0)return[t,n];switch(e){case`right`:case`bottom`:return[t+o,n];case`center`:return[t+o/2,n];case`stretch`:return[t,r?n+o:n];case`scale`:{if(i<=0)return[t,n];let e=a/i;return[t*e,r?n*e:n]}default:return[t,n]}}function gPe(e,t,n){let r=new Map,i=e=>{for(let t of e)r.set(t.id,t),t.kind===`group`&&i(t.children)};for(let t of e.scenes)for(let e of t.tracks)i(e.clips);let a=[],o=(e,t,i,s,c)=>{i.forEach((i,l)=>{let u=[...s,l],d=r.get(i.id);if(d&&(d.size.width!==i.size.width||d.size.height!==i.size.height||d.transform.x!==i.transform.x||d.transform.y!==i.transform.y))return;let f=n.get(i.id),p=f?.boxOffset??{x:0,y:0},m={...i.size},h={x:i.transform.x,y:i.transform.y};for(let n of _Pe){let r=n.pos===`x`?c.x:c.y,a=i[n.mode];if(!a||!r||i.animations.some(e=>n.animated.includes(e.property)))continue;let o=n.pos===`x`?e.width:e.height,s=n.pos===`x`?t.width:t.height,l=i.transform[n.anchor],[u,d]=hPe(a,i.transform[n.pos]-l*i.size[n.size]-p[n.pos],i.size[n.size],typeof f?.authored[n.size]==`number`,o,s);m[n.size]=d,h[n.pos]=u+l*d+p[n.pos]}h.x!==i.transform.x&&a.push({op:`set`,path:[...u,`transform`,`x`],value:h.x}),h.y!==i.transform.y&&a.push({op:`set`,path:[...u,`transform`,`y`],value:h.y}),m.width!==i.size.width&&a.push({op:`set`,path:[...u,`size`,`width`],value:m.width}),m.height!==i.size.height&&a.push({op:`set`,path:[...u,`size`,`height`],value:m.height}),i.kind===`group`&&(m.width!==i.size.width||m.height!==i.size.height)&&o(i.size,m,i.children,[...u,`children`],{x:!0,y:!0})})},s=(e,t)=>{e.forEach((e,i)=>{if(e.kind!==`group`)return;let a=[...t,i],c=r.get(e.id),l=n.get(e.id)?.authored??{};c&&(c.size.width!==e.size.width||c.size.height!==e.size.height)&&o(c.size,e.size,e.children,[...a,`children`],{x:typeof l.width==`number`,y:typeof l.height==`number`}),s(e.children,[...a,`children`])})};return t.scenes.forEach((t,n)=>{let r=e.scenes.find(e=>e.id===t.id);t.tracks.forEach((e,i)=>{let a=[`scenes`,n,`tracks`,i,`clips`];r&&(r.width!==t.width||r.height!==t.height)&&o(r,t,e.clips,a,{x:!0,y:!0}),s(e.clips,a)})}),a}var _Pe,vPe=o((()=>{_Pe=[{pos:`x`,size:`width`,anchor:`anchorX`,mode:`constrainX`,animated:[`positionX`,`width`,`scale`,`scaleX`]},{pos:`y`,size:`height`,anchor:`anchorY`,mode:`constrainY`,animated:[`positionY`,`height`,`scale`,`scaleY`]}]}));function yPe(e,t,n){let r=s_(e,t);if(!r)return!1;let i=r.get(mh),a=(e,t)=>{if(i.accessors.has(e))return!1;let n=Sge(i.tag,e);return n?(r.set(n,{...r.get(n),[e]:t}),!0):!1};switch(n.op){case`set-prop`:{let[e,...t]=n.name.split(`.`);if(!t.length)return a(e,n.value);let o=Sge(i.tag,e),s=o?r.get(o)[e]:void 0;if(typeof s!=`object`||!s)return!1;let c=structuredClone(s),l=c;for(let e of t.slice(0,-1)){let t=l[e];if(typeof t!=`object`||!t)return!1;l=t}let u=t.at(-1);return u in l&&(l[u]=n.value,a(e,c))}case`retime`:{let e=!0;return n.start!==void 0&&(e=a(`start`,n.start)&&e),n.end!==void 0&&(e=a(`end`,n.end)&&e),e}case`set-text`:return r.has(Oh)?(r.set(Oh,{text:n.text}),!0):!1;default:return!1}}var bPe=o((()=>{hx()}));function xPe(e,t){let n=u_(e);if(!n||n.get(mh).tag===`scene`)return{width:t.width,height:t.height};let r=o_(n);return{width:Zx(r.width,t.width),height:Zx(r.height,t.height)}}function SPe(e,t,n,r,i){let a=t.get(Ah),o=Im(a.preset),s=Zx(n.width,o.width),c=Zx(n.height,o.height),l=zme(o,a,{width:s,height:c},xPe(t,r),n.x,n.y),u=Gh(a.sourceOut,i)??(a.src?e.get(c_)?.durations.get(a.src):void 0),d={src:a.src??``,preset:Zg.includes(a.preset??``)?a.preset:`classic`,colors:[...a.colors??[]],verticalAlign:a.verticalAlign??o.align,offsetX:Zx(a.offsetX,0),offsetY:Zx(a.offsetY,0)};return{box:{x:l.x,y:l.y,width:s,height:c},stop:u,clip:e=>({...Gx({...e,text:``,fontSize:Zx(n.fontSize,o.font.size),fontFamily:typeof n.fontFamily==`string`?n.fontFamily:o.font.family,fontWeight:n.fontWeight===`bold`?700:n.fontWeight===`normal`?400:Zx(n.fontWeight,o.font.weight),italic:n.fontStyle===void 0?o.font.italic:n.fontStyle===`italic`,lineHeight:Zx(n.lineHeight,o.font.lineHeight),align:n.align??o.font.align,fill:{type:`solid`,color:typeof n.fill==`string`?n.fill:`#ffffff`}}),captions:d})}}function CPe(e,t){let n=[],r=(e,t)=>n.push({op:`set-prop`,name:e,value:t});for(let n of new Set([...Object.keys(e),...Object.keys(t)])){let[i,a]=[e[n],t[n]];if(JSON.stringify(i)!==JSON.stringify(a))switch(n){case`src`:if(typeof a!=`string`||!a)throw new Qx(`captions need a transcript src`,`captions.src`);r(`src`,a);break;case`preset`:if(!Zg.includes(a))throw new Qx(`caption preset ${JSON.stringify(a)} is not one of ${Zg.join(`, `)}`,`captions.preset`);r(`preset`,a===`classic`?null:a);break;case`verticalAlign`:if(!Qg.includes(a))throw new Qx(`caption verticalAlign ${JSON.stringify(a)} is not one of ${Qg.join(`, `)}`,`captions.verticalAlign`);r(`verticalAlign`,a);break;case`colors`:if(!Array.isArray(a)||a.some(e=>typeof e!=`string`))throw new Qx(`caption colors must be a list of CSS colours`,`captions.colors`);r(`colors`,a.length?[...a]:null);break;case`offsetX`:case`offsetY`:if(typeof a!=`number`||!Number.isFinite(a))throw new Qx(`caption ${n} must be a number`,`captions.${n}`);r(n,a===0?null:wPe(a));break;default:throw new Qx(`caption field ${String(n)} is not in higgsedit's vocabulary`,`captions.${String(n)}`)}}return n}var Xx,Zx,Qx,wPe,TPe=o((()=>{e_(),Yx(),hx(),Xx=e=>e.kind===`text`&&`captions`in e,Zx=(e,t)=>typeof e==`number`&&Number.isFinite(e)?e:t,Qx=class extends Error{reason;field;constructor(e,t){super(e),this.reason=e,this.field=t}},wPe=e=>Math.round(e*1e3)/1e3}));function EPe(e,t){let n=[];for(let t of e){let e=n.at(-1);`kind`in t?e&&!tS(e)&&rS(e.clips,t)?e.clips.push(t):n.push(Kx({id:`track:${t.id}`,name:t.name,clips:[t]})):n.push(t)}return n.map(e=>{let n=t=>e.clips.length>0&&e.clips.every(t),r=e.clips.filter(t);return{...e,hidden:n(e=>e.hidden),locked:n(e=>e.locked),muted:r.length>0&&r.every(e=>`muted`in e&&e.muted)}})}function DPe(e,t){let n=e.clips.at(-1),r=eS(t);return!!n&&!!r&&!tS(e)&&NPe(n)===NPe(r)}function OPe(e,t,n,r){let i=e[t];if(!i||i.locked||i.mode===`sequential`||tS(i)||i.clips.some(e=>nS(e)!==nS(n[0]))||!n.every(e=>r(i,e.timeRange)))return!1;let a=e.slice(t+1).find(e=>e.clips.length>0);return!a||!DPe(i,a)}function kPe(e,t,n,r=jPe){if(n.length===0)return-1;if(OPe(e,t,n,r))return t;let i=nS(n[0]);for(let a=1;a<e.length;a++)for(let o of i?[t+a,t-a]:[t+a])if(OPe(e,o,n,r))return o;return-1}var APe,$x,jPe,eS,tS,MPe,nS,rS,NPe,iS=o((()=>{Yx(),APe=1e-6,$x=(e,t)=>e.start<t.start+t.duration-APe&&t.start<e.start+e.duration-APe,jPe=(e,t,n=[])=>e.clips.every(e=>n.includes(e.id)||!$x(e.timeRange,t)),eS=e=>e.clips.find(t=>e.id===`track:${t.id}`),tS=e=>e.id.startsWith(`track:`)&&!eS(e),MPe=new Set([`video`,`audio`]),nS=e=>e.kind===`audio`,rS=(e,t)=>e.length>0&&nS(e[0])===nS(t)&&e.every(e=>!$x(e.timeRange,t.timeRange)),NPe=e=>e.id.replace(/#\d+$/,``)}));function PPe(e){if(e===void 0||e===`linear`)return{kind:`linear`};if(e===`step`)return{kind:`hold`};let t=IPe[e];if(t)return{kind:`cubic-bezier`,x1:t[0],y1:t[1],x2:t[2],y2:t[3]};let n=/^cubicBezier\(([^)]*)\)$/.exec(e)?.[1].split(`,`).map(e=>Number(e.trim()))??[];return{kind:`cubic-bezier`,x1:n[0]??0,y1:n[1]??0,x2:n[2]??1,y2:n[3]??1}}function FPe(e){if(e.kind===`linear`)return`linear`;if(e.kind===`hold`)return`step`;if(e.kind===`cubic-bezier`){for(let[t,n]of Object.entries(IPe))if(n[0]===e.x1&&n[1]===e.y1&&n[2]===e.x2&&n[3]===e.y2)return t;return`cubicBezier(${e.x1}, ${e.y1}, ${e.x2}, ${e.y2})`}return{refused:`${e.kind} easing`}}var IPe,aS=o((()=>{IPe={easeIn:[.42,0,1,1],easeOut:[0,0,.58,1],easeInOut:[.42,0,.58,1]}}));function LPe(e,t,n){let r=[],i=[];return Array.isArray(t)&&t.forEach((t,a)=>{let o=WPe(e,a),s=t.mask?{value:t.value,mask:t.mask}:{value:t.value};r.push({id:o,kind:oS[t.type]??String(t.type),enabled:t.hidden!==!0,params:s});let c=t.animate?.value;Array.isArray(c)&&c.length!==0&&i.push({id:`${o}:value`,property:`effectParam`,effectId:o,effectParam:`value`,gradientStopIndex:null,keyframes:c.map((e,t)=>({id:`${o}:value:${t}`,time:Gh(e[0],n)??0,value:e[1],easing:PPe(e[2])}))})}),{effects:r,tracks:i}}function RPe(e,t){return e.keyframes.map(e=>{let n=FPe(e.easing);if(typeof n==`object`)return t(n.refused);let r=typeof e.value==`number`?sS(e.value):e.value;return n===`linear`?[sS(e.time),r]:[sS(e.time),r,n]})}function zPe(e,t){return e.effects.length===0?null:e.effects.map(n=>{let r=UPe[n.kind.replace(/^fable\./,``)];if(!r)return t(`${n.kind} effect`);let i=n.params.value;if(typeof i!=`number`||!Number.isFinite(i))return t(`${n.kind} effect without a value`);let a={type:r,value:sS(i)},o=e.animations.find(e=>e.property===`effectParam`&&e.effectId===n.id);return o&&(o.effectParam!==`value`&&t(`${o.effectParam} of an effect`),o.keyframes.length&&(a.animate={value:RPe(o,t)})),n.params.mask&&(a.mask=n.params.mask),n.enabled||(a.hidden=!0),a})}function BPe(e,t,n){let r=zPe(e,n),i=zPe(t,n);return JSON.stringify(r)===JSON.stringify(i)?[]:r&&i&&r.length===i.length&&r.every((e,t)=>JSON.stringify({...e,value:0})===JSON.stringify({...i[t],value:0}))?i.flatMap((e,t)=>e.value===r[t].value?[]:[{op:`set-prop`,name:`effects.${t}.value`,value:e.value}]):[{op:`set-prop`,name:`effects`,value:i}]}function VPe(e,t){return D_(e)?{type:`gradient`,gradientKind:e.type,angle:typeof e.rotation==`number`?e.rotation:0,stops:e.stops.map(e=>({offset:e.offset,color:e.color,opacity:typeof e.opacity==`number`?e.opacity:1}))}:{type:`solid`,color:typeof e==`string`?e:t}}function HPe(e,t){if(e.type===`solid`)return e.color;if(e.type!==`gradient`)return t(`${e.type} fill`);let n={type:e.gradientKind};return e.gradientKind===`linear`&&e.angle&&(n.rotation=sS(e.angle)),n.stops=e.stops.map(e=>({offset:sS(e.offset),color:e.color,...e.opacity===1?{}:{opacity:sS(e.opacity)}})),n}var oS,UPe,WPe,sS,cS,GPe=o((()=>{e_(),hx(),aS(),oS={blur:`layer-blur`,hueRotate:`hue-rotate`,brightness:`brightness`,contrast:`contrast`,grayscale:`grayscale`,invert:`invert`,saturate:`saturate`,sepia:`sepia`,opacity:`opacity`},UPe=Object.fromEntries(Object.entries(oS).map(([e,t])=>[t,e])),new Set(Object.values(oS)),WPe=(e,t)=>`${e}:fx:${t}`,sS=e=>Math.round(e*1e3)/1e3,cS=e=>e.animations.filter(e=>e.effectId===null)}));function KPe(e,t,n){let r=[],i=(t,i)=>t.forEach((t,a)=>{let o=Gh(t.at,n);r.push({id:`${e}:${i}:${a}`,preset:t.preset,direction:i,duration:Gh(t.duration,n)??.5,easing:PPe(t.easing),params:{...t.params},...o===void 0?{}:{at:o}})});i(S_(t.enter),`in`),i(S_(t.exit),`out`);for(let[n,i]of[[`in`,t.fadeIn],[`out`,t.fadeOut]])typeof i==`number`&&i>0&&r.push({id:`${e}:fade-${n}`,preset:`volume`,direction:n,duration:i,easing:JPe,params:{}});return r}function qPe(e,t,n,r=!1){let i={in:[],out:[]},a={in:0,out:0};for(let o of e){if(o.anchor&&n(`${o.preset} pinned to a word`),o.preset===`volume`){t||n(`volume preset on an element without sound`),o.at!==void 0&&o.at!==null&&n(`offset sound fade`),a[o.direction]=Math.max(a[o.direction],o.duration);continue}o.preset in Oye||n(`${o.preset} preset`),bye(o.preset)&&!r&&n(`${o.preset} preset on an element that is not text`);let e=FPe(o.easing);typeof e==`object`&&n(e.refused);let s={preset:o.preset,duration:lS(o.duration)};e!==`linear`&&(s.easing=e),o.at!==void 0&&o.at!==null&&(s.at=lS(o.at)),Object.keys(o.params).length&&(s.params=o.params),i[o.direction].push(s)}return{enter:YPe(i.in),exit:YPe(i.out),fadeIn:a.in>0?lS(a.in):null,fadeOut:a.out>0?lS(a.out):null}}var JPe,lS,YPe,XPe=o((()=>{e_(),hx(),aS(),JPe={kind:`linear`},lS=e=>Math.round(e*1e4)/1e4,YPe=e=>e.length===0?null:e.length===1?e[0]:e}));function ZPe(e,t){return{italic:t.fontStyle===`italic`,letterSpacing:uS(t.letterSpacing)??0,textCase:t.textCase===`upper`||t.textCase===`lower`?t.textCase:`original`,textBaseline:t.textBaseline===`middle`||t.textBaseline===`bottom`||t.textBaseline===`alphabetic`?t.textBaseline:`top`,ranges:l_(e).filter(e=>e.get(mh).tag===`textRange`).map(e=>QPe(e.get(mh).key,o_(e)))}}function QPe(e,t){let n={id:e,start:uS(t.start)??0,end:uS(t.end)??null};return typeof t.fill==`string`&&(n.fill=t.fill),typeof t.fontFamily==`string`&&(n.fontFamily=t.fontFamily),uS(t.fontSize)!==void 0&&(n.fontSize=uS(t.fontSize)),nFe(t.fontWeight)!==void 0&&(n.fontWeight=nFe(t.fontWeight)),t.fontStyle!==void 0&&(n.italic=t.fontStyle===`italic`),uS(t.letterSpacing)!==void 0&&(n.letterSpacing=uS(t.letterSpacing)),(t.textCase===`original`||t.textCase===`upper`||t.textCase===`lower`)&&(n.textCase=t.textCase),n}function $Pe(e){return{start:e.start,end:e.end??null,fill:e.fill??null,fontFamily:e.fontFamily??null,fontSize:e.fontSize??null,fontWeight:e.fontWeight??null,fontStyle:e.italic===void 0?null:e.italic?`italic`:`normal`,letterSpacing:e.letterSpacing??null,textCase:e.textCase??null}}function eFe(e,t){switch(e){case`italic`:return dS(`fontStyle`,t.italic?`italic`:null);case`letterSpacing`:return dS(`letterSpacing`,t.letterSpacing?Math.round(t.letterSpacing*1e3)/1e3:null);case`textCase`:return dS(`textCase`,t.textCase&&t.textCase!==`original`?t.textCase:null);case`textBaseline`:return dS(`textBaseline`,t.textBaseline&&t.textBaseline!==`top`?t.textBaseline:null);case`ranges`:return[];default:return}}function tFe(e,t=[],n=[],r){let i=[],a=new Map(t.flatMap(e=>e.id?[[e.id,e]]:[])),o=n.flatMap(e=>e.id&&a.has(e.id)?[e.id]:[]);o.join(`
278
278
  `)!==t.flatMap(e=>e.id&&o.includes(e.id)?[e.id]:[]).join(`
279
- `)&&r(`reordering text ranges`);for(let e of t)e.id&&!o.includes(e.id)&&i.push({key:e.id,edit:{op:`remove`}});return n.forEach((t,o)=>{let s=t.end??null;s!==null&&!(s>t.start)&&r(`a text range that ends before it starts`);let c=t.id?a.get(t.id):void 0;if(!c){let r=n.slice(o+1).find(e=>e.id&&a.has(e.id))?.id;i.push({key:e,edit:{op:`insert`,tag:`textRange`,props:rFe($Pe(t)),...r?{before:r}:{}}});return}let[l,u]=[$Pe(c),$Pe(t)];for(let e of Object.keys(u))l[e]!==u[e]&&i.push({key:t.id,edit:{op:`set-prop`,name:e,value:u[e]}})}),i}var uS,nFe,rFe,dS,iFe=o((()=>{hx(),uS=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,nFe=e=>e===`bold`?700:e===`normal`?400:uS(e),rFe=e=>Object.fromEntries(Object.entries(e).filter(([,e])=>e!==null)),dS=(e,t)=>[{op:`set-prop`,name:e,value:t}]}));function aFe(e,t,n){e.forEach((r,i)=>{let a=vve(t(r.id),n);if(!a)return;let o=e[i+1],s=o&&Cve(r.timeRange.start+r.timeRange.duration,o.timeRange.start,n)?o:void 0,c=`${r.id}:transition`,l=a.duration/2;r.presetAnimations.push({id:`${c}:out`,preset:a.type,direction:`out`,duration:l,easing:uFe,params:{transitionId:c,transitionPeerId:s?.id??``}}),s?.presetAnimations.push({id:`${c}:in`,preset:a.type,direction:`in`,duration:l,easing:uFe,params:{transitionId:c,transitionPeerId:r.id}})})}function oFe(e,t){for(let n of e)t(n),n.kind===`group`&&oFe(n.children,t)}function sFe(e){let t=new Map,n=[];for(let r of e.scenes)for(let e of r.tracks)oFe(e.clips,e=>{for(let r of e.presetAnimations)lFe(r)&&(r.direction===`in`?t.set(r.params.transitionId,r.duration):n.push([e.id,r]))});return new Map(n.map(([e,n])=>[e,{type:n.preset,duration:n.duration+(t.get(n.params.transitionId)??n.duration)}]))}function cFe(e,t,n,r,i){if(!t)return null;if($g.includes(t.type)||i(`${t.type} transition`),typeof e!=`object`||!e||Array.isArray(e))return{type:t.type,duration:r(t.duration,void 0)};let a={...e},o=a.duration;return t.type!==(a.type??t_.type)&&(a.type=t.type),Math.abs(t.duration-(Gh(o,n)??xve(t.type)))>dFe&&(a.duration=r(t.duration,o)),a}var lFe,uFe,dFe,fFe,pFe=o((()=>{e_(),hx(),lFe=e=>typeof e.params.transitionId==`string`,uFe={kind:`linear`},dFe=1e-6,fFe=(e,t)=>e===t||!!e&&!!t&&e.type===t.type&&Math.abs(e.duration-t.duration)<dFe}));function mFe(e,t,n){return e===`x`?t.x:e===`y`?t.y:e===`maskX`?-n.x:e===`maskY`?-n.y:0}function hFe(e,t,n){return e?{enabled:!0,shape:e.shape??`rectangle`,x:fS(e.x,n.x+t.width/2)-n.x,y:fS(e.y,n.y+t.height/2)-n.y,width:fS(e.width,t.width),height:fS(e.height,t.height),rotation:fS(e.rotation,0),cornerRadius:fS(e.cornerRadius,0),feather:fS(e.feather,0),invert:e.invert===!0,d:e.shape===`path`?e.d??``:null,...e.src?{src:e.src}:{}}:null}function gFe(e,t,n,r,i){let a=[],o={};for(let[s,c]of Object.entries(t??{})){let t=bFe[s];if(!t){o[s]=c;continue}let l=mFe(s,r,i);a.push({id:`${e}:${t}`,property:t,effectId:null,effectParam:null,gradientStopIndex:null,keyframes:c.map((r,i)=>({id:`${e}:${t}:${i}`,time:Gh(r[0],n)??0,value:typeof r[1]==`number`?r[1]+l:r[1],easing:PPe(r[2])}))})}return{tracks:a,unmapped:o}}function _Fe(e,t,n,r,i,a,o,s){let c=t.get(mh),l=c.tag;if(l===`stage`||l===`scene`)return null;let u=o_(t),d=t.get(gh)??{},f=B_(e,t,r),p=!Number.isFinite(f.end),m=p?Math.max(f.start,i):f.end,[h,g,_,v]=t.get(zh)?.bounds??[0,0,0,0],y=l===`captions`?SPe(e,t,u,n,r):void 0,b=u.width===void 0&&_>h&&!y,x=l===`adjustmentLayer`,S=y?y.box.width:fS(u.width,x?n.width:b?_-h:l===`text`?0:100),C=y?y.box.height:fS(u.height,x?n.height:u.height===void 0&&v>g?v-g:l===`text`?0:100),w={x:b?h:0,y:u.height===void 0&&v>g?g:0},T=fS(u.anchorX,x?.5:0),E=fS(u.anchorY,x?.5:0),D={x:T*S+w.x,y:E*C+w.y},O=c.key,k=gFe(O,t.get(Mh)?.animate,r,D,w),A=LPe(O,u.effects,r),j=typeof u.scale==`number`?u.scale:void 0,M={id:O,name:c.name??c.id??l,transform:uPe({x:(y?y.box.x:fS(u.x,0))+D.x,y:(y?y.box.y:fS(u.y,0))+D.y,scaleX:fS(u.scaleX,j??1),scaleY:fS(u.scaleY,j??1),rotation:fS(u.rotation,0),anchorX:T,anchorY:E}),size:{width:S,height:C},opacity:fS(u.opacity,1),timeRange:{start:f.start,duration:Math.max(0,m-f.start)},animations:[...k.tracks,...A.tracks],effects:A.effects,presetAnimations:KPe(O,u,r),blendMode:u.blend??`normal`,mask:hFe(u.mask,{width:S,height:C},w),hidden:u.hidden===!0,locked:u.locked===!0,...typeof u.constrainX==`string`&&u.constrainX!==`left`?{constrainX:u.constrainX}:{},...typeof u.constrainY==`string`&&u.constrainY!==`top`?{constrainY:u.constrainY}:{}},N=l===`video`||l===`audio`?e.get(c_)?.durations.get(String(u.src)):void 0;a.set(O,{key:O,tag:l,sceneId:n.id,fps:r,timing:{...d.start===void 0?{}:{start:d.start},...d.end===void 0?{}:{end:d.end},...d.sourceIn===void 0?{}:{sourceIn:d.sourceIn}},openEnded:p,boxOffset:w,...N===void 0?{}:{mediaDuration:N},...y?.stop===void 0?{}:{captionStop:y.stop},accessors:new Set(c.accessors),unmappedAnimate:k.unmapped,authored:u});let P=u.fill;switch(l){case`rect`:return nPe({...M,fill:VPe(P,`#ffffff`),cornerRadius:qx(fS(u.cornerRadius,0))});case`surface`:case`html`:return{...nPe({...M,fill:{type:`solid`,color:`#00000000`},cornerRadius:qx(fS(u.cornerRadius,0))}),drawnBy:l};case`text`:return{...Gx({...M,text:String(u.text??``),fontSize:fS(u.fontSize,48),fontFamily:typeof u.fontFamily==`string`?u.fontFamily:`sans-serif`,fontWeight:u.fontWeight===`bold`?700:fS(u.fontWeight,400),lineHeight:fS(u.lineHeight,1.2),align:u.align??`left`,fill:VPe(P,`#ffffff`)}),...ZPe(t,u)};case`video`:case`image`:case`audio`:{let n=String(t.get(kh)?.src??``);if(!o.has(n)||l===`video`&&o.get(n)?.kind===`audio`){let t=n.split(`.`).at(-1)?.toLowerCase()??``;o.set(n,{id:n,name:n.split(`/`).at(-1)??n,kind:SFe(l),mimeType:CFe[t]??`application/octet-stream`,byteSize:0,duration:e.get(c_)?.durations.get(n)??null,width:null,height:null,uri:s.mediaUrl(n),hash:null})}let i=hbe(e,t,r),a=V_(t),c={start:i,end:i+(M.timeRange?.duration??0)*a},d={...M,assetId:n,trim:c,volume:fS(u.volume,1),muted:u.muted===!0,speed:a,preservePitch:u.preservePitch!==!1};if(l===`audio`)return iPe({...d,size:{width:0,height:0}});let f=rPe({...d,cornerRadius:qx(fS(u.cornerRadius,0))});return u.fit===`cover`||u.fit===`contain`||u.fit===`fill`?{...f,layoutFit:u.fit}:f}case`captions`:return y.clip(M);case`adjustmentLayer`:return aPe(M);case`group`:{let c=l_(t).map(t=>_Fe(e,t,n,r,i,a,o,s)).filter(e=>e!==null);return oPe({...M,children:c})}case`sequence`:{let l=vFe(e,t,n,r,i,a,o,s);return oPe({...M,name:c.name??c.id??`Sequence`,children:l})}default:return null}}function vFe(e,t,n,r,i,a,o,s){let c=l_(t).map(t=>_Fe(e,t,n,r,i,a,o,s)).filter(e=>e!==null);return aFe(c,e=>a.get(e)?.authored.transition,r),c}function yFe(e,t){let n=new Map,r=new Map,i=new Map,a=[];for(let o of z_(e)){let s=o.get(mh),c=o.get(jh)??{},l=K_(o),u=o_(o),d=B_(e,o,l),f=d.end-d.start,p=cPe({id:s.key,name:s.name??s.id??`Scene`,width:fS(c.width,1920),height:fS(c.height,1080),fps:l,background:{type:`solid`,color:typeof u.fill==`string`?u.fill:`#000000`}});p.tracks=EPe(l_(o).flatMap(a=>{let o=a.get(mh);if(o.tag===`sequence`){let s=`track:${o.key}`;return i.set(s,o.key),[Kx({id:s,name:o.name??o.id??`Sequence`,clips:vFe(e,a,p,l,f,n,r,t)})]}let s=_Fe(e,a,p,l,f,n,r,t);return s?[s]:[]}),e=>MPe.has(n.get(e.id)?.tag??``)),p.duration=f,a.push(p)}return{document:{id:`higgsedit:${t.name}`,name:t.name,schemaVersion:2,scenes:a,activeSceneId:a[0]?.id??``,assets:[...r.values()],createdAt:0,modifiedAt:0},meta:n,sequences:i}}var bFe,xFe,fS,SFe,CFe,wFe=o((()=>{e_(),Tm(),Yx(),aS(),iS(),GPe(),XPe(),TPe(),iFe(),pFe(),hx(),bFe={x:`positionX`,y:`positionY`,width:`width`,height:`height`,rotation:`rotation`,scale:`scale`,scaleX:`scaleX`,scaleY:`scaleY`,opacity:`opacity`,cornerRadius:`radius`,fill:`color`,maskX:`maskX`,maskY:`maskY`,maskWidth:`maskWidth`,maskHeight:`maskHeight`},xFe=Object.fromEntries(Object.entries(bFe).map(([e,t])=>[t,e])),fS=(e,t)=>typeof e==`number`&&Number.isFinite(e)?e:t,SFe=e=>e===`image`?`image`:e===`audio`?`audio`:`video`,CFe={mp4:`video/mp4`,mov:`video/quicktime`,webm:`video/webm`,png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,webp:`image/webp`,gif:`image/gif`,mp3:`audio/mpeg`,wav:`audio/wav`,m4a:`audio/mp4`,aac:`audio/aac`}}));function pS(e,t,n){if(typeof t==`string`&&/f$/i.test(t.trim()))return`${Math.round(e*n)}f`;if(typeof t==`string`&&t.includes(`:`)){let n=t.split(`:`).length===3,r=Math.max(0,e),i=Math.floor(r/3600),a=Math.floor(r%3600/60),o=gS(r%60),s=(o<10?`0`:``)+String(o),c=String(a).padStart(2,`0`);return n||i>0?`${String(i).padStart(2,`0`)}:${c}:${s}`:`${c}:${s}`}return gS(e)}function TFe(e){let t=eS(e);return t?[t,...e.clips.filter(e=>e!==t)]:[...e.clips]}function EFe(e,t,n,r){let i=[...e.clips.filter(n=>t.placed.get(n.id)?.track===e.id).toSorted((e,t)=>n.get(e.id)-n.get(t.id)),...VFe(e.clips.filter(n=>t.placed.get(n.id)?.track!==e.id))];if(r&&rS(r,i[0])){let e=i.findIndex(e=>!rS(r,e));e>0&&i.unshift(...i.splice(e,1))}return i}function DFe(e,t,n){let r=new Map,i=new Map,a=new Map,o=new Map,s=(e,t,n,a)=>{for(let o of e)r.set(o.id,{clip:o,parent:t,scene:n,track:a}),o.kind===`group`&&(i.set(o.id,o.children.map(e=>e.id)),s(o.children,o.id,n,a))};for(let r of e.scenes){let e=[],c=new Map(n?.order.get(r.id)?.map((e,t)=>[e,t])),l=null;for(let u of r.tracks){a.set(u.id,u);let d=t.get(u.id);if(d){let t=VFe(u.clips);o.set(d,r.id),e.push(d),i.set(d,t.map(e=>e.id)),s(t,d,r.id,u.id),l=null}else if(u.clips.length>0){let t=n?EFe(u,n,c,l):TFe(u);e.push(...t.map(e=>e.id)),s(t,r.id,r.id,u.id),l=t}}i.set(r.id,e)}return{placed:r,order:i,tracks:a,sequences:o}}function OFe(e,t){let n=t.split(`/`).length,r=[];for(let t of e){let e=t.split(`/`),i=e.length>n?e.slice(0,n).join(`/`):t,a=r.at(-1);if(a?.key===i)a.members.push(t);else if(r.some(e=>e.key===i))throw new mS(`"${yS(i)}" is one component; its layers move together`,t);else r.push({key:i,members:[t]})}return r}function kFe(e){let t=[],n=Array.from({length:e.length},()=>-1);for(let r=0;r<e.length;r++){let i=0,a=t.length;for(;i<a;){let n=i+a>>1;e[t[n]]<e[r]?i=n+1:a=n}i>0&&(n[r]=t[i-1]),t[i]=r}let r=new Set;for(let e=t.at(-1)??-1;e>=0;e=n[e])r.add(e);return r}function AFe(e,t){let n={...t.unmappedAnimate},r=e.transform.anchorX*e.size.width+t.boxOffset.x,i=e.transform.anchorY*e.size.height+t.boxOffset.y;for(let a of cS(e)){let o=xFe[a.property];if((!o||a.effectId!==null||a.gradientStopIndex!==null)&&vS(`${a.property} animation`,e.id),t.tag===`adjustmentLayer`&&!JFe.has(o)&&vS(`${a.property} animation on an adjustment layer`,e.id),o===`fill`&&(t.tag===`surface`||t.tag===`html`))throw new mS(YFe(t.tag),e.id,`animations`);n[o]=a.keyframes.map(n=>{let a=FPe(n.easing);typeof a==`object`&&vS(a.refused,e.id);let s=mFe(o,{x:r,y:i},t.boxOffset),c=typeof n.value==`number`?gS(n.value-s):n.value;return a===`linear`?[gS(n.time),c]:[gS(n.time),c,a]})}return n}function jFe(e,t,n,r,i){let a=n.boxOffset[r];return UFe(n,i)?WFe(e,t)?e.size[i]?a*t.size[i]/e.size[i]:a:e.size[i]===t.size[i]?a:0:a}function MFe(e,t,n){let r=[],i=(e,t)=>r.push({op:`set-prop`,name:e,value:t}),a=t.id,o=e,s=t,c=e=>vS(e,a),l=!1;for(let u of new Set([...Object.keys(o),...Object.keys(s)]))if(!(KFe.has(u)||_S(o[u],s[u]))){if(n.tag===`sequence`&&u!==`name`&&vS(`${u} of a <sequence>`,a),n.tag===`adjustmentLayer`&&qFe.has(u)&&vS(`${u} on an adjustment layer`,a),(n.tag===`surface`||n.tag===`html`)&&XFe.has(u))throw new mS(YFe(n.tag),a,u);switch(u){case`name`:i(`name`,t.name);break;case`transform`:case`size`:{if(u===`size`&&!_S(o.transform,s.transform))break;let r=t.transform,c=e.transform;for(let e of[`skewX`,`skewY`,`flipX`,`flipY`])r[e]!==c[e]&&vS(e,a);let[l,d]=[HFe(e,n.boxOffset),HFe(t,n.boxOffset)];if(Xx(e)&&Xx(t))for(let[e,r]of[[`x`,`offsetX`],[`y`,`offsetY`]]){let a=d[e]-l[e];if(!(Math.abs(a)<=hS)){if(n.authored[e]!==void 0)i(e,gS(d[e]));else{let e=gS(t.captions[r]+a);i(r,e===0?null:e)}}}else for(let[r,a]of[[`x`,`width`],[`y`,`height`]]){let o=d[r]+n.boxOffset[r]-jFe(e,t,n,r,a);Math.abs(l[r]-o)>hS&&i(r,gS(o))}r.rotation!==c.rotation&&i(`rotation`,gS(r.rotation)),r.anchorX!==c.anchorX&&i(`anchorX`,gS(r.anchorX)),r.anchorY!==c.anchorY&&i(`anchorY`,gS(r.anchorY)),(r.scaleX!==c.scaleX||r.scaleY!==c.scaleY)&&(n.authored.scale!==void 0&&n.authored.scaleX===void 0&&n.authored.scaleY===void 0&&r.scaleX===r.scaleY?i(`scale`,gS(r.scaleX)):(r.scaleX!==c.scaleX&&i(`scaleX`,gS(r.scaleX)),r.scaleY!==c.scaleY&&i(`scaleY`,gS(r.scaleY))));for(let r of[`width`,`height`])e.size[r]!==t.size[r]&&!(UFe(n,r)&&WFe(e,t))&&i(r,gS(t.size[r]));break}case`opacity`:i(`opacity`,gS(t.opacity));break;case`locked`:i(`locked`,t.locked?!0:null);break;case`constrainX`:i(`constrainX`,t.constrainX&&t.constrainX!==`left`?t.constrainX:null);break;case`constrainY`:i(`constrainY`,t.constrainY&&t.constrainY!==`top`?t.constrainY:null);break;case`hidden`:i(`hidden`,t.hidden?!0:null);break;case`timeRange`:{if(n.tag===`captions`){r.push(...NFe(e,t,n));break}let i=t.timeRange.start,o=i+t.timeRange.duration,s=i-e.timeRange.start,c={op:`retime`},l=e.timeRange.start+e.timeRange.duration;if(typeof n.authored.syncTo==`string`){let i=(t.kind===`media`||t.kind===`audio`)&&e.kind===t.kind?(t.trim.start-e.trim.start)/t.speed:0;if(Math.abs(s-i)>hS)throw new mS(`${a} is placed by syncTo="${n.authored.syncTo}"; remove syncTo to move it by hand`,a,`timeRange`);Math.abs(o-l)>hS&&r.push({op:`retime`,end:pS(o,n.timing.end??n.timing.start,n.fps)});break}Math.abs(s)>hS&&(c.start=pS(i,n.timing.start??n.timing.end,n.fps));let u;if(n.timing.end!==void 0)u=Math.abs(o-l)>hS;else if(n.openEnded)u=Math.abs(t.timeRange.duration-e.timeRange.duration)>hS;else if(n.tag===`group`)u=Math.abs(t.timeRange.duration-e.timeRange.duration)>hS;else if(n.mediaDuration!==void 0){let[e,r]=t.kind===`media`||t.kind===`audio`?[t.trim.start,t.speed]:[0,1];u=Math.abs(o-(i+(n.mediaDuration-e)/r))>hS}else u=Math.abs(o-l)>hS;u&&(c.end=pS(o,n.timing.end??n.timing.start,n.fps)),(c.start!==void 0||c.end!==void 0)&&r.push(c);break}case`trim`:if(t.kind!==`media`&&t.kind!==`audio`||e.kind!==t.kind)break;Math.abs(t.trim.start-e.trim.start)>hS&&i(`sourceIn`,pS(t.trim.start,n.timing.sourceIn??n.timing.start,n.fps));break;case`animations`:_S(cS(e),cS(t))||i(`animate`,AFe(t,n)),l=!0;break;case`effects`:l=!0;break;case`blendMode`:i(`blend`,t.blendMode===`normal`?null:t.blendMode);break;case`mask`:i(`mask`,PFe(t.mask,n.boxOffset,a));break;case`presetAnimations`:{let r=n.tag===`video`||n.tag===`audio`,o=e=>vS(e,a),s=n.tag===`text`,[c,l]=[qPe(GFe(e),r,o,s),qPe(GFe(t),r,o,s)];for(let e of[`enter`,`exit`,`fadeIn`,`fadeOut`])_S(c[e],l[e])||i(e,l[e]);break}case`text`:if(n.tag===`captions`)throw new mS(`caption text comes from its transcript: edit the transcript file or point src at another`,a,`text`);r.push({op:`set-text`,text:String(s.text)});break;case`captions`:if(!Xx(e)||!Xx(t))return vS(u,a);try{r.push(...CPe(e.captions,t.captions))}catch(e){throw e instanceof Qx?new mS(e.reason,a,e.field):e}break;case`fontSize`:case`fontFamily`:case`lineHeight`:case`align`:case`fontWeight`:case`volume`:case`speed`:case`preservePitch`:i(u,typeof s[u]==`number`?gS(s[u]):s[u]);break;case`muted`:i(`muted`,s.muted===!0||null);break;case`fill`:i(`fill`,HPe(s.fill,c));break;case`cornerRadius`:{let e=s.cornerRadius;e.mixed&&vS(`per-corner radius`,a),i(`cornerRadius`,gS(e.uniform));break}case`assetId`:i(`src`,String(s.assetId));break;default:{let e=t.kind===`text`?eFe(u,t):void 0;e||vS(u,a),r.push(...e)}}}return l&&(n.tag===`audio`&&t.effects.length&&c(`effects on audio`),r.push(...BPe(e,t,c))),r}function NFe(e,t,n){let r=t.id,i=t.timeRange.start,a=i+t.timeRange.duration,o=i-e.timeRange.start,s=e.timeRange.start+e.timeRange.duration,c=Gh(n.timing.sourceIn,n.fps)??0,l=[],u={op:`retime`};Math.abs(o)>hS&&(u.start=pS(i,n.timing.start??n.timing.end,n.fps));let d=Math.abs(o)>hS&&Math.abs(a-s)<=hS;if(d&&(c+=o,c<-1e-6))throw new mS(`captions cannot start before their transcript (sourceIn below 0)`,r,`timeRange`);let f;return f=n.timing.end===void 0?n.captionStop===void 0?Math.abs(t.timeRange.duration-e.timeRange.duration)>hS:Math.abs(a-(i+n.captionStop-c))>hS:Math.abs(a-s)>hS,f&&(u.end=pS(a,n.timing.end??n.timing.start,n.fps)),(u.start!==void 0||u.end!==void 0)&&l.push(u),d&&l.push({op:`set-prop`,name:`sourceIn`,value:pS(Math.max(0,c),n.timing.sourceIn??n.timing.start,n.fps)}),l}function PFe(e,t,n){if(!e)return null;if(e.enabled||vS(`disabled mask`,n),e.src){let t={src:e.src};return e.feather&&(t.feather=gS(e.feather)),e.invert&&(t.invert=!0),t}let r={shape:e.shape,x:gS(e.x+t.x),y:gS(e.y+t.y),width:gS(e.width),height:gS(e.height)};return e.rotation&&(r.rotation=gS(e.rotation)),e.cornerRadius&&(r.cornerRadius=gS(e.cornerRadius)),e.feather&&(r.feather=gS(e.feather)),e.invert&&(r.invert=!0),e.shape===`path`&&(r.d=e.d??``),r}function FFe(e,t,n){if(e.kind===`group`&&e.children.length)throw new mS(`inserting a group with children is not supported yet`,e.id);if(Xx(e))throw new mS(`inserting captions from the editor is not supported yet; copy the <captions> element in the source`,e.id);if(e.kind===`rect`&&e.drawnBy)throw new mS(`${e.drawnBy===`html`?`an <html>`:`a <surface>`} is drawn by code: copy the element in the source to duplicate it`,e.id);let r={},i=e.transform;if(e.kind===`adjustment`)return{op:`insert`,tag:`adjustmentLayer`,props:IFe(e,t),...n?{before:n}:{}};e.kind!==`audio`&&(r.x=gS(i.x-i.anchorX*e.size.width),r.y=gS(i.y-i.anchorY*e.size.height),(e.kind!==`text`||e.size.width>0)&&(r.width=gS(e.size.width),r.height=gS(e.size.height)),e.opacity!==1&&(r.opacity=gS(e.opacity)),i.rotation&&(r.rotation=gS(i.rotation))),r.start=gS(e.timeRange.start);let a,o;switch(e.kind){case`rect`:a=`rect`,r.fill=HPe(e.fill,t=>vS(t,e.id)),e.cornerRadius.uniform&&(r.cornerRadius=gS(e.cornerRadius.uniform)),r.end=gS(e.timeRange.start+e.timeRange.duration);break;case`text`:a=`text`,o=e.text,r.fontSize=gS(e.fontSize),r.fill=HPe(e.fill,t=>vS(t,e.id)),e.fontFamily!==`sans-serif`&&(r.fontFamily=e.fontFamily),e.fontWeight!==400&&(r.fontWeight=e.fontWeight),e.align!==`left`&&(r.align=e.align),e.italic&&(r.fontStyle=`italic`),e.letterSpacing&&(r.letterSpacing=gS(e.letterSpacing)),e.textCase&&e.textCase!==`original`&&(r.textCase=e.textCase),e.textBaseline&&e.textBaseline!==`top`&&(r.textBaseline=e.textBaseline),e.ranges?.length&&vS(`inserting a text with ranges`,e.id),r.end=gS(e.timeRange.start+e.timeRange.duration);break;case`media`:{let n=t.assets.find(t=>t.id===e.assetId);a=n?.kind===`image`?`image`:`video`,r.src=e.assetId,e.trim.start&&(r.sourceIn=gS(e.trim.start)),a===`video`&&(Object.assign(r,ZFe(e)),e.volume!==1&&(r.volume=gS(e.volume)),e.muted&&(r.muted=!0));let i=n?.duration;(a===`image`||i==null||Math.abs(e.timeRange.duration-(i-e.trim.start)/e.speed)>hS)&&(r.end=gS(e.timeRange.start+e.timeRange.duration));break}case`audio`:{a=`audio`,r.src=e.assetId,e.trim.start&&(r.sourceIn=gS(e.trim.start)),e.volume!==1&&(r.volume=gS(e.volume)),e.muted&&(r.muted=!0),Object.assign(r,ZFe(e));let n=t.assets.find(t=>t.id===e.assetId)?.duration;(n==null||Math.abs(e.timeRange.duration-(n-e.trim.start)/e.speed)>hS)&&(r.end=gS(e.timeRange.start+e.timeRange.duration));break}case`group`:a=`group`;break;default:return vS(`${e.kind} clips`,e.id)}return e.effects.length&&(a===`audio`&&vS(`effects on audio`,e.id),r.effects=zPe(e,t=>vS(t,e.id))),e.mask&&((a===`audio`||a===`group`)&&vS(`a mask on ${a===`audio`?`audio`:`a group`}`,e.id),!e.mask.src&&a===`text`&&e.size.width<=0&&vS(`a shape mask on unsized text`,e.id),r.mask=PFe(e.mask,{x:0,y:0},e.id)),{op:`insert`,tag:a,props:r,...o===void 0?{}:{text:o},...n?{before:n}:{}}}function IFe(e,t){let n=t.scenes.find(t=>t.tracks.some(t=>t.clips.includes(e))),r=e.transform,{width:i,height:a}=e.size,o={},s=r.x-r.anchorX*i,c=r.y-r.anchorY*a;return Math.abs(s)>hS&&(o.x=gS(s)),Math.abs(c)>hS&&(o.y=gS(c)),(i!==n?.width||a!==n?.height)&&Object.assign(o,{width:gS(i),height:gS(a)}),r.anchorX!==.5&&(o.anchorX=gS(r.anchorX)),r.anchorY!==.5&&(o.anchorY=gS(r.anchorY)),r.rotation&&(o.rotation=gS(r.rotation)),(r.scaleX!==1||r.scaleY!==1)&&Object.assign(o,r.scaleX===r.scaleY?{scale:gS(r.scaleX)}:{scaleX:gS(r.scaleX),scaleY:gS(r.scaleY)}),e.hidden&&(o.hidden=!0),e.locked&&(o.locked=!0),e.constrainX&&e.constrainX!==`left`&&(o.constrainX=e.constrainX),e.constrainY&&e.constrainY!==`top`&&(o.constrainY=e.constrainY),o.start=gS(e.timeRange.start),o.end=gS(e.timeRange.start+e.timeRange.duration),o}function LFe(e,t){let n=[];return e.width!==t.width&&n.push({op:`set-prop`,name:`width`,value:t.width}),e.height!==t.height&&n.push({op:`set-prop`,name:`height`,value:t.height}),e.fps!==t.fps&&n.push({op:`set-prop`,name:`fps`,value:t.fps}),_S(e.background,t.background)||n.push({op:`set-prop`,name:`fill`,value:BFe(t.background,t.id,`scene background`)}),e.name!==t.name&&n.push({op:`set-prop`,name:`name`,value:t.name}),_S(e.markers,t.markers)||vS(`markers`),(e.x!==t.x||e.y!==t.y)&&vS(`scene canvas position`),n}function RFe(e,t,n,r){for(let[i,a]of t){let t=e.get(i);if(t){for(let e of[`solo`,`volume`,`mode`])t[e]!==a[e]&&vS(`track ${e}`);for(let e of[`hidden`,`locked`,`muted`]){if(t[e]===a[e])continue;let i=e===`muted`?a.clips.filter(e=>MPe.has(n.get(e.id)?.tag??``)):a.clips;a.clips.length>0&&i.length===0&&vS(`track muted (no clip on it has sound)`);for(let t of i)r.push({key:t.id,edit:{op:`set-prop`,name:e,value:a[e]?!0:null}})}}}}function zFe(e,t){let n=e.document,r;try{r=Ux(n,t)}catch(e){return{ok:!1,reason:e.message}}try{let t=[],i=e.sequences??new Map,a=DFe(n,i),o=DFe(r,i,a),s=(e,t)=>e.placed.has(t)||e.sequences.has(t),c=(e,t)=>e.placed.get(t)?.parent??e.sequences.get(t);(n.scenes.length!==r.scenes.length||n.scenes.some((e,t)=>e.id!==r.scenes[t]?.id))&&vS(`adding, removing or reordering scenes`),n.scenes.forEach((e,n)=>{for(let i of LFe(e,r.scenes[n]))t.push({key:e.id,edit:i})}),RFe(a.tracks,o.tracks,e.meta,t);for(let[n,{clip:r}]of o.placed){let i=a.placed.get(n);if(!i)continue;let o=e.meta.get(n);if(!o)throw new mS(`no source element for clip ${n}`,n);for(let e of MFe(i.clip,r,o))t.push({key:o.key,edit:e});r.kind===`text`&&i.clip.kind===`text`&&!_S(i.clip.ranges,r.ranges)&&t.push(...tFe(o.key,i.clip.ranges,r.ranges,e=>vS(e,n)))}let[l,u]=[sFe(n),sFe(r)];for(let n of o.placed.keys()){if(!a.placed.has(n)||fFe(l.get(n),u.get(n)))continue;let r=e.meta.get(n),i=cFe(r.authored.transition,u.get(n),r.fps,(e,t)=>pS(e,t,r.fps),e=>vS(e,n));t.push({key:r.key,edit:{op:`set-prop`,name:`transition`,value:i}})}for(let e of[...a.placed.keys(),...a.sequences.keys()]){if(s(o,e))continue;let n=c(a,e);(!s(a,n)||s(o,n))&&t.push({key:e,edit:{op:`remove`}})}for(let[e,n]of o.order){let i=OFe(n,e),l=OFe(a.order.get(e)??[],e).map(e=>e.key);if(_S(i.map(e=>e.key),l))continue;let u=e=>e.members.some(e=>s(a,e)),d=e=>o.placed.get(e)?.track!==a.placed.get(e)?.track,f=t=>t.members.every(t=>c(a,t)===e&&!d(t)),p=i.filter(u),m=p.flatMap((e,t)=>f(e)?[t]:[]),h=kFe(m.map(e=>l.indexOf(p[e].key))),g=new Set([...h].map(e=>m[e]));for(let n=p.length-1;n>=0;n--){if(g.has(n))continue;let r=p[n+1];t.push({key:p[n].key,edit:{op:`move`,parent:e,...r?{before:yS(r.key)}:{}}})}for(let n=0;n<i.length;n++){let a=i[n];if(u(a))continue;let s=a.members[0];o.placed.has(s)||vS(`adding a sequence`);let c=i.slice(n+1).find(u);t.push({key:e,edit:FFe(o.placed.get(s).clip,r,c&&yS(c.key))})}}return{ok:!0,edits:t,document:r}}catch(e){if(e instanceof mS)return{ok:!1,reason:e.reason,...e.clipId?{clipId:e.clipId}:{},...e.field?{field:e.field}:{}};throw e}}var mS,hS,gS,_S,vS,BFe,VFe,yS,HFe,UFe,WFe,GFe,KFe,qFe,JFe,YFe,XFe,ZFe,QFe=o((()=>{Yx(),TPe(),iS(),GPe(),XPe(),iFe(),aS(),wFe(),pFe(),e_(),mS=class extends Error{reason;clipId;field;constructor(e,t,n){super(e),this.reason=e,this.clipId=t,this.field=n}},hS=1e-6,gS=e=>Math.round(e*1e3)/1e3,_S=(e,t)=>JSON.stringify(e)===JSON.stringify(t),vS=(e,t)=>{throw new mS(`not in higgsedit's element vocabulary yet: ${e}`,t,e)},BFe=(e,t,n)=>(e.type!==`solid`&&vS(`${e.type} ${n}`,t),e.color),VFe=e=>[...e].toSorted((e,t)=>e.timeRange.start-t.timeRange.start),yS=e=>e.split(`/`).at(-1),HFe=(e,t)=>({x:e.transform.x-e.transform.anchorX*e.size.width-t.x,y:e.transform.y-e.transform.anchorY*e.size.height-t.y}),UFe=(e,t)=>e.tag===`text`&&e.authored[t]===void 0,WFe=(e,t)=>e.kind===`text`&&t.kind===`text`&&e.fontSize!==t.fontSize,GFe=e=>e.presetAnimations.filter(e=>!lFe(e)),KFe=new Set([`id`,`kind`,`children`,`origin`]),qFe=new Set([`opacity`,`blendMode`,`mask`,`effects`]),JFe=new Set([`x`,`y`,`width`,`height`,`rotation`,`scale`,`scaleX`,`scaleY`]),YFe=e=>e===`html`?`an <html>'s picture is its HTML children, drawn by code: edit them in the source`:`a <surface>'s picture is drawn by code into its canvas (ref): edit that code in the source`,XFe=new Set([`fill`,`stroke`,`drawnBy`]),ZFe=e=>({...e.speed===1?{}:{speed:gS(e.speed)},...e.preservePitch?{}:{preservePitch:!1}})})),$Fe,eIe,tIe=o((()=>{Yx(),vPe(),bPe(),QFe(),$Fe={canUndo:!1,canRedo:!1,undoName:null,redoName:null},eIe=class extends pPe{options;projection=null;run=null;timer;chain=Promise.resolve();server=$Fe;constructor(e){super(),this.options=e}load(e,t=`remote`){let n=this.projection===null;this.projection=e,n?this.open(e.document):this.replace(e.document,t)}current(){return this.projection}undoState(){return this.server}setServerUndo(e){this.server=e,this.emit({type:`history`,state:e})}execute(e){if(!this.projection)throw Error(`no project is mounted`);e=this.withConstraints(e),this.run&&(e.coalesceKey===null||this.run.key!==e.coalesceKey)&&this.flush();let t=this.run?.base??{document:this.snapshot()??this.projection.document,meta:this.projection.meta,...this.projection.sequences?{sequences:this.projection.sequences}:{}},n=[...this.run?.ops??[],...e.ops],r=zFe(t,n);if(!r.ok){this.options.onRefused?.({reason:r.reason,...r.clipId?{clipId:r.clipId}:{}});return}this.run={key:e.coalesceKey,name:e.name,base:t,ops:n},super.execute(e,`local`);let i=this.options.world(),a=[];for(let{key:e,edit:t}of r.edits)yPe(i,e,t)&&a.push(e);a.length&&this.options.onPatched?.(a),clearTimeout(this.timer),e.coalesceKey===null?this.flush():this.timer=setTimeout(()=>this.flush(),this.options.commitDelayMs??250)}withConstraints(e){let t=this.snapshot();if(!t||!this.projection)return e;let n;try{n=Ux(t,e.ops)}catch{return e}let r=gPe(t,n,this.projection.meta);return r.length?{...e,ops:[...e.ops,...r]}:e}flush(){clearTimeout(this.timer);let e=this.run;if(this.run=null,!e)return this.chain;let t=zFe(e.base,e.ops);return!t.ok||t.edits.length===0||(this.chain=this.chain.then(async()=>{try{let n=await this.options.transport.edit(e.name,t.edits);if(this.setServerUndo(n.undo),!n.ok){let e=n.results.find(e=>!e.ok)?.refused;this.options.onRefused?.({reason:e?.reason??`the edit was refused`,...e?.at?{at:e.at}:{},...e?.source?{source:e.source}:{}}),this.options.onRevert?.()}}catch(e){this.options.onRefused?.({reason:`could not reach higgsedit dev: ${e.message}`}),this.options.onRevert?.()}})),this.chain}undo(){return this.history(`undo`),this.server.canUndo}redo(){return this.history(`redo`),this.server.canRedo}history(e){return this.flush(),this.chain=this.chain.then(async()=>{let t=await this.options.transport[e]();this.setServerUndo(t.undo),!t.ok&&t.reason&&this.options.onRefused?.({reason:t.reason})}),this.chain}}})),bS,xS,nIe=o((()=>{Nm(),bS=class{value;equals;listeners=new Set;constructor(e,t=Object.is){this.value=e,this.equals=t}get(){return this.value}set(e){if(!this.equals(this.value,e)){this.value=e;for(let t of Array.from(this.listeners))t(e)}}subscribe(e){return this.listeners.add(e),km(()=>this.listeners.delete(e))}},xS=(e,t)=>{let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.is(e[n],t[n])||Array.isArray(e[n])&&JSON.stringify(e[n])===JSON.stringify(t[n]))}})),rIe,iIe,aIe=o((()=>{Tm(),Nm(),nIe(),rIe={now:()=>performance.now(),request:e=>requestAnimationFrame(e),cancel:e=>cancelAnimationFrame(e)},iIe=class{source;publish;scheduler;selection=new bS({clipIds:[],sceneId:null,enteredGroupId:null},xS);currentTime=new bS(0);playing=new bS(!1);activeSceneId=new bS(null);activeTool=new bS(`move`);camera=new bS({zoom:1,panX:0,panY:0},xS);timelineView=new bS({pxPerSecond:80,scrollX:0},xS);clipboard=new bS([]);loop=new bS(!1);workArea=new bS(null,(e,t)=>e===t||!!e&&!!t&&xS(e,t));speed=new bS(1);previewQuality=new bS(1);frameListeners=new Set;raf=null;renderQueued=!1;lastWall=0;scale=1;clock;constructor(e,t=()=>{},n=rIe){this.source=e,this.publish=t,this.scheduler=n}setClock(e){this.clock?.stop(),this.clock=e,this.playing.get()&&e?.start(this.currentTime.get())}setSource(e){this.source=e,this.requestRender()}setSelection(e){this.selection.set({...this.selection.get(),...e});let t=this.selection.get();this.publish(Ype,{clipIds:[...t.clipIds],sceneId:t.sceneId,enteredGroupId:t.enteredGroupId})}clearSelection(){this.setSelection({clipIds:[],enteredGroupId:null})}setActiveTool(e){this.activeTool.set(e),this.publish(Xpe,{tool:e})}setCamera(e){this.camera.set(e)}setTimelineView(e){this.timelineView.set({...this.timelineView.get(),...e})}setClipboard(e){this.clipboard.set(e),this.publish(Zpe,{count:e.length})}setActiveScene(e){this.activeSceneId.set(e),this.selection.get().sceneId===null&&this.setSelection({sceneId:e})}setPreviewQuality(e){e>0&&e<=1&&this.previewQuality.set(e)}setLoop(e){this.loop.set(e)}setWorkArea(e){if(!e)return this.workArea.set(null);let{duration:t,fps:n}=this.source.sceneSpan(this.activeSceneId.get()),r=e=>Math.min(Math.max(0,e),Math.max(0,t)),[i,a]=[r(Math.min(e.start,e.end)),r(Math.max(e.start,e.end))];this.workArea.set(a-i<1/n?null:{start:i,end:a})}bounds(){let e=this.workArea.get(),{duration:t}=this.source.sceneSpan(this.activeSceneId.get());return e?[e.start,e.end]:[0,t]}play(){this.playAt(1)}playAt(e){if(!Number.isFinite(e)||e===0)return;let t=this.playing.get();this.speed.set(e);let[n,r]=this.bounds(),i=this.currentTime.get();e>0&&(i>=r-1e-6||i<n)&&this.currentTime.set(n),e<0&&(i<=n+1e-6||i>r)&&this.currentTime.set(r),this.lastWall=this.scheduler.now(),e===1?this.clock?.start(this.currentTime.get()):this.clock?.stop(),!t&&(this.playing.set(!0),this.publish(Kpe,{time:this.currentTime.get()}),this.tick())}pause(){this.playing.get()&&(this.playing.set(!1),this.speed.set(1),this.raf!==null&&this.scheduler.cancel(this.raf),this.raf=null,this.clock?.stop(),this.publish(qpe,{time:this.currentTime.get()}),this.requestRender())}togglePlayback(){this.playing.get()?this.pause():this.play()}seek(e){let{duration:t}=this.source.sceneSpan(this.activeSceneId.get());this.currentTime.set(Math.min(Math.max(0,e),Math.max(0,t))),this.playing.get()&&this.speed.get()===1&&this.clock?.start(this.currentTime.get()),this.publish(Jpe,{time:this.currentTime.get()}),this.requestRender()}onFrame(e){return this.frameListeners.add(e),this.requestRender(),km(()=>this.frameListeners.delete(e))}requestRender(){this.playing.get()||this.renderQueued||(this.renderQueued=!0,this.scheduler.request(()=>{this.renderQueued=!1,this.emitFrame()}))}setPreviewScale(e){e>0&&Number.isFinite(e)&&(this.scale=e),this.requestRender()}tick(){this.raf=this.scheduler.request(()=>{if(!this.playing.get())return;let e=this.scheduler.now(),t=this.speed.get(),[n,r]=this.bounds(),i=this.currentTime.get(),a=i+(e-this.lastWall)/1e3*t,o=t===1?Math.max(i,this.clock?.time()??a):a;this.lastWall=e;let s=t>0?o>=r:o<=n;if(s&&this.loop.get()){let e=t>0?n:r;this.currentTime.set(e),t===1&&this.clock?.start(e)}else if(s){this.currentTime.set(t>0?r:n),this.emitFrame(),this.pause();return}else this.currentTime.set(o);this.emitFrame(),this.tick()})}emitFrame(){if(this.frameListeners.size===0)return;let{start:e}=this.source.sceneSpan(this.activeSceneId.get()),t=this.currentTime.get(),n=this.source.draw(e+t,this.playing.get(),this.scale);if(n)try{for(let e of Array.from(this.frameListeners))e(n,t)}finally{this.source.release(n)}}dispose(){this.raf!==null&&this.scheduler.cancel(this.raf),this.clock?.stop(),this.frameListeners.clear()}}}));async function SS(e,t){let n;try{n=await e.json()}catch{throw Error(`${t} returned invalid JSON (${e.status})`)}if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`${t} returned an invalid response`);let r=n;if(!e.ok)throw Error(typeof r.error==`string`?r.error:`${t} failed (${e.status})`);return r}function oIe(e){let t=t=>{let n=e[t];if(!Array.isArray(n)||!n.every(e=>typeof e==`string`))throw Error(`invalid native render capabilities`);return n},{sampleRates:n,audioOnly:r}=e;if(!Array.isArray(n)||!n.every(e=>typeof e==`number`&&Number.isFinite(e)&&e>0)||typeof r!=`boolean`)throw Error(`invalid native render capabilities`);return{containers:t(`containers`),videoCodecs:t(`videoCodecs`),audioCodecs:t(`audioCodecs`),sampleRates:n,audioOnly:r}}function sIe(e,t){return t.containers.includes(e.container)&&(e.video?t.videoCodecs.includes(e.video.codec):t.audioOnly&&e.audio!==null)&&(e.audio===null||t.audioCodecs.includes(e.audio.codec)&&t.sampleRates.includes(e.audio.sampleRate))}function cIe(e,t=()=>null){let n,r=()=>n??=fetch(`${e}/api/render/capabilities`).then(e=>SS(e,`render capabilities`)).then(oIe).catch(e=>{throw n=void 0,e});return{probe:async e=>sIe(e,await r()),start(n){let i={...n.spec,video:n.spec.video&&{...n.spec.video},audio:n.spec.audio&&{...n.spec.audio}},a=n.sceneId??t(),o=n.range&&{...n.range},s=n.onProgress,c=!1,l=null,u,d,f=()=>d??=fetch(`${e}/api/render/cancel?${new URLSearchParams({id:String(l)})}`,{method:`POST`}).then(e=>SS(e,`render cancellation`)).then(()=>{}).catch(e=>{u=e instanceof Error?e:Error(String(e))});return{result:(async()=>{if(!sIe(i,await r()))throw Error(`native export does not support ${i.container}/${i.video?.codec??`audio-only`}/${i.audio?.codec??`silent`}`);if(c)throw CS();let t=await SS(await fetch(`${e}/api/render`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({spec:i,...a===null?{}:{sceneId:a},fileName:i.fileName??`export.mp4`,...o?{from:o.start,to:o.end}:{}})}),`render start`);if(typeof t.id!=`string`||!/^[1-9]\d*$/.test(t.id))throw Error(`render start returned an invalid job id`);for(l=t.id,c&&await f();;){if(u)throw u;await new Promise(e=>setTimeout(e,lIe));let t=await fetch(`${e}/api/render?${new URLSearchParams({id:l})}`).then(e=>SS(e,`render status`));if(u)throw u;if(typeof t.total==`number`&&Number.isFinite(t.total)&&t.total>0&&typeof t.done==`number`&&Number.isFinite(t.done)&&s?.(Math.max(0,Math.min(1,t.done/t.total)),`render`),t.state===`done`){if(c)throw CS();if(typeof t.out!=`string`||!t.out.startsWith(`renders/`)||t.out.includes(`\\`)||t.out.split(`/`).some(e=>!e||e===`.`||e===`..`))throw Error(`render status returned an invalid output path`);return s?.(1,`finalize`),{kind:`uri`,uri:`${e}/project/${t.out.split(`/`).map(encodeURIComponent).join(`/`)}`}}if(t.state===`cancelled`)throw CS();if(t.state===`failed`)throw Error(typeof t.error==`string`?t.error:`render failed`);if(t.state!==`running`)throw Error(`render status returned an unknown job state`)}})(),cancel(){c=!0,l&&f()}}}}}var lIe,CS,uIe=o((()=>{Tm(),lIe=400,CS=()=>Object.assign(Error(`export cancelled`),{name:tme})}));function dIe(){let e=new pIe(`frame`),t=[],n=!1,r=e=>{let r=e,i=t.reduce((e,t)=>e+t.width*t.height,r.width*r.height);!n&&t.length<3&&i<=8294400?t.push(r):(r.width=0,r.height=0)};return{fromNative:(t,n)=>e.add(t,n,e=>e.close?.()),fromCanvas:(t,n)=>e.add(t,{width:t.width,height:t.height,timestamp:n,...Rpe}),render(n,i,a,o){let s=t.pop()??document.createElement(`canvas`);s.width!==n&&(s.width=n),s.height!==i&&(s.height=i);try{let t=o(s.getContext(`2d`));return e.add(s,{width:n,height:i,timestamp:a,...t,...Rpe},r)}catch(e){throw r(s),e}},dispose(){n=!0;for(let e of t)e.width=0,e.height=0;t.length=0},toNative:t=>e.get(t),info:t=>e.info(t),retain:t=>e.retain(t),release:t=>e.release(t)}}function fIe(){let e=new pIe(`audio`);return{fromPlanar:(t,n)=>e.add(t,{sampleRate:n,channels:t.length,frames:t[0]?.length??0}),toPlanar:t=>e.get(t),info:t=>e.info(t),retain:t=>e.retain(t),release:t=>e.release(t)}}var pIe,mIe=o((()=>{Tm(),pIe=class{kind;slots=[];free=[];constructor(e){this.kind=e}add(e,t,n){let r=this.free.pop()??this.slots.push({gen:0,value:null,info:null,refs:0})-1,i=this.slots[r];return i.value=e,i.info=t,i.refs=1,n?i.free=n:delete i.free,{kind:this.kind,index:r,gen:i.gen}}slot(e){let t=this.slots[e.index];return t&&t.gen===e.gen&&t.refs>0?t:null}get(e){return this.slot(e)?.value??null}info(e){return this.slot(e)?.info??null}retain(e){let t=this.slot(e);t&&t.refs++}release(e){let t=this.slot(e);t&&(--t.refs>0||(t.value!==null&&t.free?.(t.value),t.value=null,t.info=null,t.gen++,this.free.push(e.index)))}}}));async function hIe(e,t){t?.signal.throwIfAborted();let n=new MAe(e.id,e.uri),r=()=>n.dispose();t?.signal.addEventListener(`abort`,r,{once:!0});try{let{duration:e}=await n.ready;t?.signal.throwIfAborted();let r=Math.max(0,Math.min(t?.start??0,e)),i=Math.max(r,Math.min(t?.end??e,e)),a=i-r,o=a>0?Math.min(wS,t?.peaksPerSecond??wS,gIe/a):wS,s=new Float32Array(Math.min(gIe,Math.ceil(a*o))),c={peaks:s,peaksPerSecond:o,duration:e,start:r},l=0,u=-1/0;for await(let{buffer:e,timestamp:a}of n.chunks(r,i)){t?.signal.throwIfAborted();let n=e.sampleRate;for(let t=0;t<e.numberOfChannels;t++){let i=e.getChannelData(t);for(let e=0;e<i.length;e++){let t=Math.floor((a-r+e/n)*o);if(t<0||t>=s.length)continue;let c=Math.abs(i[e]);c>s[t]&&(s[t]=c),c>l&&(l=c)}}performance.now()-u>=250&&(u=performance.now(),t?.onProgress?.({...c,gain:l>0?1/l:1}))}if(t?.signal.throwIfAborted(),!t&&l>0){for(let e=0;e<s.length;e++)s[e]/=l;return{...c,gain:1}}return{...c,gain:l>0?1/l:1}}catch(e){if(t?.signal.throwIfAborted(),e instanceof jAe)return null;throw e}finally{t?.signal.removeEventListener(`abort`,r),n.dispose()}}var wS,gIe,_Ie,vIe=o((()=>{hx(),wS=100,gIe=6e3,_Ie={probe:e=>+(e.kind===`audio`||e.kind===`video`),ranges:!0,peaks:hIe}}));function yIe(e,t,n,r={}){let i=e.scenes.findIndex(e=>e.id===t),a=e.scenes[i];if(!a)return null;let o=r.range??n.timeRange,s={...n,timeRange:o},c=a.tracks,l=r.preferredTrackId?c.findIndex(e=>e.id===r.preferredTrackId):-1,u=l>=0?l:c.length-1,d=e=>{let t=c[e];if(t.mode===`sequential`){let n=t.clips.reduce((e,t)=>Math.max(e,t.timeRange.start+t.timeRange.duration),0),r={...s,timeRange:{start:n,duration:o.duration}};return{ops:[{op:`insert`,path:[`scenes`,i,`tracks`,e,`clips`],index:t.clips.length,value:r}],trackId:t.id,createdTrack:!1,clipIndex:t.clips.length}}let n=t.clips.filter(e=>e.timeRange.start<o.start).length;return{ops:[{op:`insert`,path:[`scenes`,i,`tracks`,e,`clips`],index:n,value:s}],trackId:t.id,createdTrack:!1,clipIndex:n}};if(c[u]?.mode===`sequential`)return d(u);let f=kPe(c,u,[s]);if(f>=0)return d(f);let p=s.kind===`audio`?0:c.length,m=Kx({name:`Track ${c.length+1}`,clips:[s]});return{ops:[{op:`insert`,path:[`scenes`,i,`tracks`],index:p,value:m}],trackId:m.id,createdTrack:!0,clipIndex:0}}function bIe(e,t,n){let r=e.scenes.findIndex(e=>e.id===t),i=e.scenes[r]?.tracks.findIndex(e=>e.id===n)??-1;if(r<0||i<0)return null;let a=e.scenes[r].tracks[i],o=[],s=0,c=a.clips.map((e,t)=>({c:e,i:t})).toSorted((e,t)=>e.c.timeRange.start-t.c.timeRange.start);for(let{c:e,i:t}of c)Math.abs(e.timeRange.start-s)>xIe&&o.push({op:`set`,path:[`scenes`,r,`tracks`,i,`clips`,t,`timeRange`,`start`],value:s}),s+=e.timeRange.duration;return o}var xIe,SIe,CIe=o((()=>{Yx(),iS(),xIe=1e-6,SIe={rangesOverlap:$x,canPlace:jPe,planClipPlacement:yIe,planSequentialPack:bIe}})),TS,wIe,TIe=o((()=>{TS=4,wIe=class{channels;speed;hop;size;search;window;input;mono;base=0;end=0;acc;frame=0;prev=0;drop;consumed=0;emitted=0;constructor(e,t,n){if(this.channels=e,this.speed=n,!(n>0))throw Error(`time stretch: speed must be positive, got ${n}`);this.hop=Math.max(64,Math.round(t/100)),this.size=2*this.hop,this.search=this.hop>>1,this.window=Float32Array.from({length:this.size},(e,t)=>.5-.5*Math.cos(2*Math.PI*t/this.size)),this.input=Array.from({length:e},()=>new Float32Array(8*this.size)),this.mono=new Float32Array(8*this.size),this.acc=Array.from({length:e},()=>new Float32Array(this.size)),this.end=this.hop,this.drop=this.hop}push(e){let t=e[0]?.length??0;return this.append(t,(t,n)=>this.input[t].set(e[t]??e[0],n)),this.consumed+=t,this.run(1/0)}flush(){let e=Math.round(this.consumed/this.speed),t=[];for(;this.emitted<e;)this.append(this.size,(e,t)=>this.input[e].fill(0,t,t+this.size)),t.push(this.run(e));let n=t.reduce((e,t)=>e+(t[0]?.length??0),0);return this.acc.map((e,r)=>{let i=new Float32Array(n),a=0;for(let e of t)i.set(e[r],a),a+=e[r].length;return i})}append(e,t){this.reserve(e);let n=this.end-this.base;for(let e=0;e<this.channels;e++)t(e,n);let r=this.mono;for(let t=n;t<n+e;t++){let e=0;for(let n=0;n<this.channels;n++)e+=this.input[n][t];r[t]=e/this.channels}this.end+=e}reserve(e){let t=Math.max(this.base,Math.min(this.nominal(this.frame)-this.search,this.prev+this.hop)),n=t-this.base,r=this.end-t,i=r+e>this.mono.length,a=t=>{let a=i?new Float32Array(Math.max(2*t.length,r+e)):t;return a.set(t.subarray(n,n+r)),a};(n!==0||i)&&(this.input=this.input.map(a),this.mono=a(this.mono),this.base=t)}nominal(e){return Math.round(e*this.hop*this.speed)}run(e){let t=this.acc.map(()=>[]);for(;;){let n=this.nominal(this.frame);if(Math.max(n+this.search,this.prev+this.hop)+this.size>this.end||this.emitted>=e)break;let r=this.frame===0?n:this.align(n);for(let e=0;e<this.channels;e++){let t=this.acc[e],n=this.input[e];for(let e=0,i=r-this.base;e<this.size;e++,i++)t[e]+=this.window[e]*n[i]}this.prev=r,this.frame++;let i=Math.min(this.drop,this.hop);this.drop-=i;let a=Math.min(this.hop-i,e-this.emitted);for(let e=0;e<this.channels;e++){let n=this.acc[e];a>0&&t[e].push(n.slice(i,i+a)),n.copyWithin(0,this.hop),n.fill(0,this.hop)}this.emitted+=Math.max(0,a)}return t.map(e=>{let t=new Float32Array(e.reduce((e,t)=>e+t.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t})}align(e){let t=Math.max(this.base,e-this.search),n=e+this.search,r=this.prev+this.hop-this.base,i=e=>{let t=this.mono,n=0,i=0;for(let a=0,o=e-this.base,s=r;a<this.hop;a++,o++,s++)n+=t[o]*t[s],i+=t[o]*t[o];return i>0?n/Math.sqrt(i):0},a=e,o=-1/0;for(let e=t;e<=n;e+=TS){let t=i(e);t>o&&([o,a]=[t,e])}let s=a;for(let e=Math.max(t,s-TS+1);e<=Math.min(n,s+TS-1);e++){let t=i(e);t>o&&([o,a]=[t,e])}return a}}})),EIe,DIe,OIe,kIe,AIe=o((()=>{hx(),TIe(),EIe=4,DIe=1.5,OIe=100,kIe=class{deps;ctx;master;analyser;anchor=null;generation=0;timer;voices=new Set;disposed=!1;muted=!1;samples=new Float32Array(2048);constructor(e){this.deps=e}context(){if(!this.ctx){let e=this.deps.createContext?.()??new AudioContext({latencyHint:`interactive`});this.master=e.createGain(),this.master.gain.value=+!this.muted,this.analyser=e.createAnalyser(),this.analyser.fftSize=this.samples.length,this.master.connect(this.analyser),this.analyser.connect(e.destination),this.ctx=e}return this.ctx}warm(){this.disposed||this.context()}start(e){if(this.disposed)return;let t=performance.now();this.stop();let n=this.context(),r=this.generation,i=n.currentTime,a=typeof OfflineAudioContext<`u`&&n instanceof OfflineAudioContext;!a&&n.state!==`running`&&n.resume().catch(()=>{});let o=()=>{if(r!==this.generation)return;if(!a&&(n.state!==`running`||n.currentTime<=i)){this.timer=setTimeout(o,EIe);return}let s=a?e:e+(performance.now()-t)/1e3;this.anchor={ctxTime:n.currentTime,rootTime:s};let c=this.deps.clips().filter(e=>e.end>s).toSorted((e,t)=>e.start-t.start),l=0,u=()=>{if(r!==this.generation)return;let e=this.anchor.rootTime+Math.max(0,n.currentTime-this.anchor.ctxTime);for(let t of this.voices)t.end<=e&&this.retire(t);for(;l<c.length&&c[l].start<=e+DIe;){let t=c[l++];t.end>e&&this.feed(t,e).catch(()=>{})}(l<c.length||this.voices.size)&&(this.timer=setTimeout(u,OIe))};u()};o()}stop(){this.generation++,clearTimeout(this.timer),this.timer=void 0,this.anchor=null;for(let e of this.voices)this.retire(e)}retire(e){if(!this.voices.delete(e))return;e.cancelled=!0,e.wake?.();let t=e.iterator;e.iterator=void 0,t?.return().catch(()=>{});for(let t of e.nodes){try{t.stop()}catch{}t.disconnect()}e.nodes.clear(),e.gain.disconnect()}time(){let e=this.ctx;return!e||!this.anchor||e.state!==`running`?null:this.anchor.rootTime+Math.max(0,e.currentTime-this.anchor.ctxTime)}setMuted(e){this.muted=e,this.master&&this.ctx&&this.master.gain.setValueAtTime(+!e,this.ctx.currentTime)}level(){if(!this.analyser)return 0;this.analyser.getFloatTimeDomainData(this.samples);let e=0;for(let t of this.samples)e+=t*t;return Math.sqrt(e/this.samples.length)}async feed(e,t){let n=this.ctx,r=this.anchor,i=Math.max(e.start,t),a=e=>r.ctxTime+(e-r.rootTime),o=n.createGain(),s={gain:o,end:e.end,nodes:new Set,cancelled:!1,decoded:!1},c=[i,e.start+e.fadeIn,e.end-e.fadeOut,e.end].filter(t=>t>=i&&t<=e.end).toSorted((e,t)=>e-t);o.gain.setValueAtTime(kbe(e,i),a(i));for(let t of c.slice(1))o.gain.linearRampToValueAtTime(kbe(e,Math.min(t,e.end-1e-6)),a(t));o.connect(this.master),this.voices.add(s);try{if(e.preservePitch&&e.speed!==1)return await this.stretched(e,i,s);let t=e.speed,r=e.sourceIn+(i-e.start)*t,o=e.sourceIn+(e.end-e.start)*t;for await(let c of this.chunks(e,s,r,o,a)){let r=e.start+(c.timestamp-e.sourceIn)/t,o=Math.max(0,i-r,n.currentTime-a(r)),l=o*t,u=Math.min(c.buffer.duration,(e.end-r)*t)-l;u<=0||this.play(c.buffer,s,a(r+o),l,u,t)}}finally{s.decoded=!0,s.nodes.size||this.retire(s)}}async*chunks(e,t,n,r,i){let a=this.ctx,o=this.deps.handle(e.src).chunks(n,r);t.iterator=o;let s=e.start+(n-e.sourceIn)/e.speed;try{for(;!t.cancelled;){for(;!t.cancelled&&i(s)-a.currentTime>DIe;)await new Promise(e=>{let n=()=>{clearTimeout(r),t.wake=void 0,e()},r=setTimeout(n,OIe);t.wake=n});if(t.cancelled)return;let n=await o.next();if(t.cancelled||n.done)return;let r=n.value;s=e.start+(r.timestamp+r.buffer.duration-e.sourceIn)/e.speed,yield r}}finally{t.iterator===o&&(t.iterator=void 0,o.return().catch(()=>{}))}}async stretched(e,t,n){let r=this.ctx,i=this.anchor,a=e=>i.ctxTime+(e-i.rootTime),o=e.speed,s=e.sourceIn+(t-e.start)*o,c=e.sourceIn+(e.end-e.start)*o,l,u=0,d=s,f=0,p=i=>{let o=i[0]?.length??0;if(o===0)return;let s=t+f/u;f+=o;let c=Math.max(0,r.currentTime-a(s)),l=Math.min(o/u,e.end-s)-c;if(l<=0)return;let d=r.createBuffer(i.length,o,u);i.forEach((e,t)=>d.copyToChannel(e,t)),this.play(d,n,a(s)+c,c,l,1)};for await(let t of this.chunks(e,n,s,c,a)){let e=t.buffer;u||=e.sampleRate,l??=new wIe(e.numberOfChannels,u,o);let n=Math.round((t.timestamp-d)*u);n>0&&p(l.push(Array.from({length:e.numberOfChannels},()=>new Float32Array(n))));let r=Math.max(0,-n),i=Math.min(e.length,Math.round((c-t.timestamp)*u));i<=r||(d=t.timestamp+i/u,p(l.push(Array.from({length:e.numberOfChannels},(t,n)=>e.getChannelData(n).subarray(r,i)))))}l&&!n.cancelled&&p(l.flush())}play(e,t,n,r,i,a){let o=this.ctx.createBufferSource();o.buffer=e,o.playbackRate.value=a,o.connect(t.gain),o.addEventListener(`ended`,()=>{t.nodes.delete(o),o.disconnect(),t.decoded&&!t.nodes.size&&this.retire(t)}),t.nodes.add(o),o.start(n,r,i)}dispose(){this.disposed=!0,this.stop(),this.ctx?.close().catch(()=>{}),this.ctx=void 0}}}));function jIe(e,t){if(!e)return null;let n=e.scenes.find(n=>n.id===(t??e.activeSceneId));if(!n)return null;let r=n.tracks[0]?.id.startsWith(NIe)?n.tracks[0].clips[0]:void 0,i=r?{x:-r.transform.x,y:-r.transform.y}:{x:0,y:0};return{sceneId:n.id.startsWith(NIe)?t??e.activeSceneId:n.id,width:n.width,height:n.height,origin:i}}function MIe(e){let t=new Set,n=new Set;return{onInvalidate(e){return n.add(e),{dispose:()=>{n.delete(e)}}},invalidateAll(e=`content`,r,i){for(let e of t)e.invalidate();for(let t of n)t(e,r,i)},create(n,r={}){let i=null,a=0,o=!1,s=r.scale??1,c=null,l=null,u=0,d=!1,f=t=>{let a=jIe(i,r.sceneId??null);if(!a||d)return;let o=c?[c.x*s,c.y*s,(c.x+c.width)*s,(c.y+c.height)*s]:void 0,l=e.draw(e.sceneStart(a.sceneId)+t,{width:a.width,height:a.height,origin:a.origin,scale:s,...o?{visible:o}:{}});if(l)try{n(l,t)}finally{e.release(l)}},p=()=>{l=e.request(()=>{if(!o||d)return;let t=e.now();a=r.followAudioClock?e.transportTime():a+(t-u)/1e3,u=t,f(a),p()})},m={setDocument(e){i=e,o||f(a)},play(){o||(o=!0,u=e.now(),p())},pause(){o=!1,l!==null&&e.cancel(l),l=null},seek(e){a=Math.max(0,e),f(a)},isPlaying:()=>o,time:()=>a,invalidate(){o||f(a)},setScale(e){e>0&&Number.isFinite(e)&&(s=e),o||f(a)},setVisible(e){c=e,o||f(a)},dispose(){d=!0,m.pause(),t.delete(m)}};return t.add(m),m}}}var NIe,PIe=o((()=>{NIe=`viewport-overflow:`}));function FIe(e,t){for(let n=e.get(hh)?.parent;n;n=n.get(hh)?.parent)if(n===t)return!0;return!1}function IIe(e,t){let n=[];for(let r=e.entity(t)?.get(hh)?.parent;r&&r.get(mh).tag!==`scene`;r=r.get(hh)?.parent)n.push(r.get(mh).key);return n}var LIe,RIe,zIe,BIe=o((()=>{hx(),nIe(),LIe=`capability:higgsedit/prerender`,RIe=150,zIe=class{origin;session;playhead;redraw;mode;status=new bS(new Map);inputs=new Map;ready=new Map;opening=new Map;ids=new Map;digests=new Map;stale=new Set;timer;viewScale=0;hits=0;misses=0;disposed=!1;client=Math.random().toString(36).slice(2);constructor(e,t,n,r,i=`auto`){this.origin=e,this.session=t,this.playhead=n,this.redraw=r,this.mode=new bS(i)}setMode(e){this.mode.set(e),this.freeze(),this.redraw(),this.ask()}async changed(){let e=await this.session.prerenderInputs();this.inputs=new Map(e.map(e=>[e.key,e])),this.stale.clear();for(let e of this.ready.keys())this.inputs.has(e)||this.drop(e);this.publish(),this.ask()}patched(e){for(let t of e){let e=this.session.entity(t);for(let t of this.inputs.keys()){let n=this.session.entity(t);n&&e&&(n===e||FIe(e,n))&&this.stale.add(t)}}this.stale.size&&this.publish()}viewed(e){!(e>0)||Math.abs(e-this.viewScale)<.001||(this.viewScale=e,this.ask())}onEvent(e){this.ids.get(e.node)===e.id&&(e.state===`ready`&&this.open(e.node,e.id),this.setState(e.node,e.state,e.done,e.total))}stats(){return{states:Object.fromEntries([...this.status.get()].map(([e,t])=>[e,t.state])),hits:this.hits,misses:this.misses}}picture=e=>{if(this.mode.get()!==`auto`||this.ready.size===0)return;let t=e.get(mh).key,n=this.ready.get(t);if(!n)return;if(this.stale.has(t)||this.inputs.get(t)?.digest!==n.digest){this.misses++;return}let r=n.handle.facts;if(!r)return;let i=e.get(zh),a=p_(r.timestamps,Math.max(0,r.timestamps[0])+i.local-n.entry.offset,r.fps);if(a<0||a>=n.entry.frames)return;let o=n.handle.peek(a);if(!o){this.misses++;return}this.hits++;let s=this.inputs.get(t);return{image:o,width:s.width,height:s.height}};warm(){if(this.mode.get()===`auto`)for(let[e,t]of this.ready){let n=this.session.entity(e),r=n?.get(zh);!r||r.active||r.local>=0||r.local<-.6||n.get(hh)?.parent?.get(zh)?.active&&t.handle.warm(0)}}dispose(){this.disposed=!0,clearTimeout(this.timer);for(let e of this.ready.keys())this.drop(e)}setState(e,t,n,r){let i=this.status.get().get(e);if(i&&i.state===t&&i.done===n&&i.total===r)return;let a=new Map(this.status.get());a.set(e,{key:e,owners:IIe(this.session,e),state:t,done:n,total:r}),this.status.set(a)}freeze(){let e=[];for(let t of this.inputs.keys()){let n=this.ready.get(t),r=this.mode.get()===`auto`&&!!n&&!this.stale.has(t)&&this.inputs.get(t)?.digest===n.digest,i=this.session.entity(t);i&&Rbe(i,r);let a=t.split(`/`).slice(0,-1).join(`/`);r&&a&&e.push(a)}this.session.mount?.document.setFrozen(e)}publish(){this.freeze();let e=new Map;for(let[t,n]of this.inputs){let r=this.status.get().get(t),i=this.ready.get(t)?.digest===n.digest&&!this.stale.has(t)?`ready`:r&&r.state!==`ready`?r.state:`stale`;e.set(t,{key:t,owners:IIe(this.session,t),state:i,done:r?.done??0,total:n.frames})}this.status.set(e)}ask(){clearTimeout(this.timer),this.timer=setTimeout(()=>void this.send(),RIe)}async send(){if(this.disposed)return;let e=this.mode.get()===`auto`?[...this.inputs.values()].map(e=>({...e,size:this.sizeFor(e)})):[],t;try{let n=await fetch(`${this.origin}/api/prerender`,{method:`POST`,body:JSON.stringify({targets:e,playhead:this.playhead(),client:this.client})});if(!n.ok)return;t=(await n.json()).statuses}catch{return}for(let n of t){this.ids.set(n.node,n.id);let t=e.find(e=>e.key===n.node);t&&this.digests.set(n.id,t.digest),n.state===`ready`&&this.open(n.node,n.id);let r=this.inputs.get(n.node),i=this.ready.get(n.node)?.digest===r?.digest&&n.state!==`ready`?`ready`:n.state;this.setState(n.node,i,n.done,n.total)}}sizeFor(e){let t=this.session.entity(e.key)?.get(hh)?.parent?.get(zh)?.matrix??[1,0,0,1,0,0],n=Math.hypot(t[2],t[3])||1;return Kje(e.height*n*(this.viewScale||1),e.height)}open(e,t){if(this.ready.get(e)?.id===t)return Promise.resolve();let n=this.opening.get(t);if(n)return n;let r=(async()=>{let n=`${this.origin}/preview/.higgsedit/prerender/${t}`,r=await fetch(`${n}.json`);if(!r.ok)return;let i=await r.json();if(i.inexact)return;let a=new Hje(`prerender:${e}`,`${n}.mp4`,i.opaque?void 0:`${n}.matte.mp4`);if(await a.ready,a.fit(i.height),await a.request(0),this.disposed||this.ids.get(e)!==t){a.dispose();return}this.drop(e),this.ready.set(e,{id:t,digest:this.digests.get(t)??``,entry:i,handle:a}),this.publish(),this.redraw()})().catch(()=>{}).finally(()=>this.opening.delete(t));return this.opening.set(t,r),r}drop(e){this.ready.get(e)?.handle.dispose(),this.ready.delete(e)}}}));async function VIe(e){let t=await e.json().catch(()=>({}));if(e.ok)return t;throw t.code===`unconfigured`?Error(KIe):e.status===504?Error(`The select server did not answer in time`):Error(typeof t.error==`string`?t.error:`Select failed (HTTP ${e.status})`)}function HIe(e){let t=e.objects;if(!(ES(e.width)&&ES(e.height)&&Array.isArray(t)&&t.every(e=>Array.isArray(e?.box)&&e.box.length===4&&Array.isArray(e.mask?.size)&&typeof e.mask.rle==`string`)))throw Error(`The select server sent a reply this editor does not understand`);return{width:e.width,height:e.height,time:ES(e.time)?e.time:0,objects:t}}function UIe(e){if(e.status===`succeeded`&&typeof e.mask==`string`)return{status:`succeeded`,mask:e.mask};if(e.status===`failed`)return{status:`failed`,error:typeof e.error==`string`?e.error:`Tracking failed`};let t=e.progress;return{status:e.status===`queued`?`queued`:`running`,progress:t&&ES(t.done)&&ES(t.total)?{done:t.done,total:t.total}:null}}function WIe(e,t){let n=(t,n,r)=>fetch(`${e}${t}`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(n),...r?{signal:r}:{}});return{async select(e,t){return HIe(await VIe(await n(`/api/select`,e,t)))},async track(e){let t=await VIe(await n(`/api/select/tracks`,e));if(typeof t.id!=`string`)throw Error(`The select server did not start the track`);return t.id},async trackStatus(t){return UIe(await VIe(await fetch(`${e}/api/select/tracks/${encodeURIComponent(t)}`)))},async sourceSize(e,n){if(n===`video`){let n=await t.video(e).ready;return[n.width,n.height]}let r=t.image(e);return await r.ready,[r.width,r.height]}}}var GIe,KIe,ES,qIe=o((()=>{GIe=`capability:higgsedit/select`,KIe=`No select server: set HIGGSEDIT_SELECT_URL and restart higgsedit dev`,ES=e=>typeof e==`number`&&Number.isFinite(e)}));function JIe(e){let t=new Set,n=new Map;return{describe(t){let r=n.get(t);return r||(r=fetch(`${e}/api/analyze?key=${encodeURIComponent(t)}&names=${XIe.join(`,`)}`).then(e=>e.json()),n.set(t,r)),r},onChange(e){return t.add(e),km(()=>t.delete(e))},changed(){n=new Map;for(let e of Array.from(t))e()}}}var YIe,XIe,ZIe=o((()=>{Nm(),YIe=`capability:higgsedit/source`,XIe=[`x`,`y`,`width`,`height`,`rotation`,`scale`,`opacity`,`fill`,`fontSize`,`start`,`end`,`animate`]})),QIe,$Ie=o((()=>{QIe=e=>typeof e==`object`&&!!e&&typeof e.projectSrc==`string`}));async function eLe(e,t){if(typeof document>`u`)return{duration:null,width:null,height:null};if(t===`image`){let t=new Image;return t.src=e,await t.decode().catch(()=>void 0),{duration:null,width:t.naturalWidth||null,height:t.naturalHeight||null}}let n=document.createElement(t===`audio`?`audio`:`video`);n.preload=`metadata`,n.src=e,await new Promise(e=>{n.addEventListener(`loadedmetadata`,()=>e(),{once:!0}),n.addEventListener(`error`,()=>e(),{once:!0})});let r=n;return{duration:Number.isFinite(n.duration)?n.duration:null,width:r.videoWidth||null,height:r.videoHeight||null}}function tLe(e){let t=async(t,n,r,i)=>{let a=rLe(i,r),o=e.mediaUrl(t),s=await eLe(o,a);return{id:t,name:r,kind:a,mimeType:i||`application/octet-stream`,byteSize:n,...s,uri:o,hash:`${r}:${n}`}},n=async(n,r,i)=>{let a=n instanceof Uint8Array?n.byteLength:n.size;if(!Number.isSafeInteger(a)||a<0)throw Error(`invalid media byte size`);let o;if(n instanceof Uint8Array||n instanceof Blob)o=await fetch(`${e.origin}/api/media/stream?name=${encodeURIComponent(r)}`,{method:`POST`,body:n});else{let t=await fetch(`${e.origin}/api/media/uploads?name=${encodeURIComponent(r)}`,{method:`POST`});if(!t.ok)throw Error(t.status===404?`Restart the local video editor to enable safe media imports`:`upload of ${r} failed: ${t.status} ${await t.text()}`);let{id:i,partBytes:s,maxBytes:c}=await t.json();if(!/^[a-f0-9-]{36}$/.test(i)||!Number.isSafeInteger(s)||s<1||s>2<<20)throw Error(`invalid media upload session`);let l=`${e.origin}/api/media/uploads/${i}`,u=!1;try{if(!Number.isSafeInteger(c)||c<1||a>c)throw Error(`upload of ${r} exceeds the ${c} byte limit`);for(let e=0;e<a;e+=s){let t=await n.slice(e,Math.min(a,e+s)).arrayBuffer(),i=await fetch(`${l}?offset=${e}`,{method:`PUT`,body:t});if(!i.ok)throw Error(`upload of ${r} failed: ${i.status} ${await i.text()}`)}o=await fetch(l,{method:`POST`}),u=o.ok}finally{u||await fetch(l,{method:`DELETE`}).catch(()=>{})}}if(!o.ok)throw Error(o.status===404?`Restart the local video editor to enable safe media imports`:`upload of ${r} failed: ${o.status} ${await o.text()}`);let{src:s,byteSize:c}=await o.json(),l=await t(s,c,s.split(`/`).at(-1),i);return e.onAsset(l),l},r=()=>{let t=e.document();return t?[{id:t.id,name:t.name,modifiedAt:t.modifiedAt}]:[]};return{probe:()=>1,listProjects:async()=>r(),loadDocument:async t=>e.document()?.id===t?e.document():null,saveDocument:async()=>{},deleteProject:async()=>{throw Error(DS)},createProject:async()=>{throw Error(DS)},renameProject:async()=>{throw Error(DS)},duplicateProject:async()=>{throw Error(DS)},readAssetBlob:async e=>fetch(e.uri).then(e=>e.blob()),writeAsset:(e,t)=>n(e,t.name,t.mimeType),storeAssetBytes:(e,t)=>n(e,t.name,t.mimeType),deleteAsset:async()=>{throw Error(`delete media files from the project folder`)},importFile:async r=>{let i=`getFile`in r?await r.getFile():r;if(QIe(i)){let n=await t(i.projectSrc,i.projectByteSize,i.name,i.type);return e.onAsset(n),n}return n(i,i.name,i.type)},listAssets:async()=>e.document()?.assets??[],async refreshAssets(){let{files:n}=await fetch(`${e.origin}/api/media`).then(e=>e.json()),r=new Set((e.document()?.assets??[]).map(e=>e.id)),i=await Promise.all(n.filter(e=>!r.has(e.src)).map(e=>t(e.src,e.byteSize,e.src.split(`/`).at(-1),``)));for(let t of i)e.onAsset(t);return i}}}var nLe,rLe,DS,iLe=o((()=>{$Ie(),nLe=[[/^video\//,`video`],[/^image\//,`image`],[/^audio\//,`audio`]],rLe=(e,t)=>nLe.find(([t])=>t.test(e))?.[1]??(/\.(png|jpe?g|webp|gif|avif|svg|bmp)$/i.test(t)?`image`:/\.(mp3|wav|ogg|m4a|aac|flac)$/i.test(t)?`audio`:`video`),DS="higgsedit dev edits one project folder; open another with `higgsedit dev <dir>`"}));function aLe(e){return{probe:e=>+(e.kind===`video`||e.kind===`image`),async filmstrip(t,n){let r=(t,r,i,a)=>{let o=document.createElement(`canvas`);o.width=Math.max(1,Math.round(n.size.width)),o.height=Math.max(1,Math.round(n.size.height));let s=o.getContext(`2d`),c=Math.max(o.width/r,o.height/i);return s.drawImage(t,(o.width-r*c)/2,(o.height-i*c)/2,r*c,i*c),e.fromCanvas(o,a)};if(t.kind===`image`){let e=new Image;return e.src=t.uri,await e.decode(),Array.from({length:n.count},()=>r(e,e.naturalWidth,e.naturalHeight,0))}let i=document.createElement(`video`);i.muted=!0,i.preload=`auto`,i.src=t.uri,await new Promise((e,n)=>{i.addEventListener(`loadeddata`,()=>e(),{once:!0}),i.addEventListener(`error`,()=>n(Error(`cannot decode ${t.name}`)),{once:!0})});let a=[],o=n.count>1?(n.end-n.start)/(n.count-1):0;for(let e=0;e<n.count;e++){let t=Math.min(i.duration-.01,n.start+e*o);await oLe(i,t),a.push(r(i,i.videoWidth,i.videoHeight,t))}return i.removeAttribute(`src`),i.load(),a}}}var oLe,sLe,cLe=o((()=>{oLe=(e,t)=>new Promise(n=>{let r=()=>{e.removeEventListener(`seeked`,r),e.removeEventListener(`error`,r),n()};e.addEventListener(`seeked`,r),e.addEventListener(`error`,r),e.currentTime=t}),sLe={mix:async()=>null}}));function lLe(e){let t=new Set,n=new Map,r=new Map,i=0,a,o=Promise.resolve(),s=!1,c=!1,l=()=>{for(let e of Array.from(t))e()},u=async()=>{if(s){c=!0;return}s=!0;try{do c=!1,await e.remount(new Map(n));while(c)}finally{s=!1}},d=()=>{clearTimeout(a),i===0&&(a=setTimeout(()=>void f(),e.commitDelayMs??250))},f=()=>{if(clearTimeout(a),!r.size)return o;let t=[...r.values()];r.clear();let i=t.length===1?`Change ${t[0].label}`:`Change variables`,s=t.map(({file:e,name:t,value:n})=>({key:``,edit:{op:`set-const`,file:e,name:t,value:n}}));return o=o.then(async()=>{let a=!1;try{let t=await e.write(i,s);if(e.onWritten?.(t),a=t.ok,!t.ok){let n=t.results.find(e=>!e.ok)?.refused;e.onRefused?.({reason:n?.reason??`the edit was refused`,...n?.at?{at:n.at}:{},...n?.source?{source:n.source}:{}})}}catch(t){e.onRefused?.({reason:`could not reach higgsedit dev: ${t.message}`})}for(let e of t){let t=gx(e.file,e.name);!r.has(t)&&(!a||n.get(t)===e.value)&&n.delete(t)}a||e.onRevert?.()}),o};return{entries:()=>e.entries().map(e=>{let t=n.get(gx(e.file,e.name));return t===void 0||t===e.value?e:{...e,value:t}}),onChange(e){return t.add(e),km(()=>t.delete(e))},set(t,i,a){let o=gx(t,i),s=e.entries().find(e=>e.file===t&&e.name===i);s&&(n.set(o,a),r.set(o,{file:t,name:i,label:s.label,value:a}),l(),u(),d())},beginGesture(){i++,clearTimeout(a)},endGesture(){i=Math.max(0,i-1),i===0&&r.size&&f()},overrides:()=>n,flush:f,changed:l}}var OS,uLe=o((()=>{cMe(),Nm(),OS=`capability:higgsedit/variables`}));function dLe(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&Object.values(e).every(e=>typeof e==`string`)}function fLe(e){let t=async(t,n)=>{let r=await fetch(`${e}${t}`,{method:`POST`,...n===void 0?{}:{body:JSON.stringify(n)}});if(!r.ok)throw Error(`${t}: ${r.status}`);return r.json()};return{edit:(e,n)=>t(`/api/edit`,{name:e,edits:n}),undo:()=>t(`/api/undo`),redo:()=>t(`/api/redo`)}}function pLe(e){let t=e.origin,n=`${t}/project`,r=e=>`${n}/${e.replace(/^\.\//,``)}`,i=new Am,a=new Set,o=null;i.add({dispose(){o!==null&&cancelAnimationFrame(o),a.clear()}});let s=new XNe({mediaBase:n,origin:t,videoBase:`${t}/preview`,mode:`live`,makeVideo:(e,t)=>new Hje(e,t)}),c=dIe(),l=fIe(),u=new Map,d=JIe(t),f=e=>z_(s.world).find(t=>t.get(mh)?.key===e)??z_(s.world)[0],p={sceneSpan(e){let t=f(e);if(!t)return{start:0,duration:0,fps:30};let n=K_(t),r=B_(s.world,t,n);return{start:r.start,duration:r.end-r.start,fps:n}},draw(e,t,n){let r=s.comp;if(!r)return null;let i=r.fps;return s.tick(Math.round(e*i),{time:e,playing:t,delta:1/i}),c.render(Math.max(1,Math.round(r.width*n)),Math.max(1,Math.round(r.height*n)),e,e=>s.drawLive(e,n,void 0,void 0,_.picture))},release:e=>c.release(e)},m=MIe({draw(e,t){let n=s.comp;return n?(s.tick(Math.round(e*n.fps),{time:e,playing:g.playing.get(),delta:1/n.fps}),_.viewed(t.scale),_.warm(),c.render(Math.max(1,Math.round(t.width*t.scale)),Math.max(1,Math.round(t.height*t.scale)),e,e=>s.drawLive(e,t.scale,t.origin,t.visible,_.picture))):null},release:e=>c.release(e),sceneStart:e=>p.sceneSpan(e).start,transportTime:()=>g.currentTime.get(),now:()=>performance.now(),request:e=>requestAnimationFrame(e),cancel:e=>cancelAnimationFrame(e)}),h=kme({documentExecutor:e=>x.execute(e),...e.settingsStore?{settingsStore:e.settingsStore}:{}}),g=new iIe(p,(e,t)=>h.bus.publish(e,t)),_=new zIe(t,s,()=>g.currentTime.get()+p.sceneSpan(g.activeSceneId.get()).start,()=>{g.requestRender(),m.invalidateAll()},e.previewMode?.get()??`auto`);i.add({dispose:()=>_.dispose()}),e.previewMode&&i.add(e.previewMode.subscribe(e=>_.setMode(e)));let v=new kIe({clips:()=>Obe(s.world),handle:e=>s.media.audio(e)});typeof requestIdleCallback==`function`&&requestIdleCallback(()=>v.warm(),{timeout:2e3});let y=()=>p.sceneSpan(g.activeSceneId.get()).start;g.setClock({start:e=>v.start(y()+e),stop:()=>v.stop(),time:()=>{let e=v.time();return e===null?null:e-y()}}),i.add(km(Ube(e=>m.invalidateAll(`html`,void 0,e)))),i.add(km(Cje(e=>m.invalidateAll(`media`,e)))),i.add(km(s.media.onReady(e=>{g.requestRender(),m.invalidateAll(`media`,e)}))),i.add(km(Kxe(()=>{g.requestRender(),m.invalidateAll()}))),e.previewMuted&&(v.setMuted(e.previewMuted.get()),i.add(e.previewMuted.subscribe(e=>v.setMuted(e))));let b=fLe(t),x=new eIe({transport:b,world:()=>s.world,onPatched:e=>{_.patched(e),g.requestRender(),m.invalidateAll()},onRevert:()=>void R.reload().catch(()=>{}),...e.onRefused?{onRefused:e.onRefused}:{}}),S=lLe({entries:()=>s.inspect,remount:e=>I(e),write:(e,t)=>b.edit(e,t),onWritten:e=>x.setServerUndo(e.undo),onRevert:()=>void L().catch(()=>{}),...e.onRefused?{onRefused:e.onRefused}:{}}),C=tLe({origin:t,mediaUrl:r,document:()=>x.snapshot(),onAsset:e=>{u.set(e.id,e);let t=x.current();t&&x.load(w(t),`remote`)}}),w=e=>{let t=new Set(e.document.assets.map(e=>e.id)),n=[...u.values()].filter(e=>!t.has(e.id));return n.length?{...e,document:{...e.document,assets:[...e.document.assets,...n]}}:e},T=()=>{g.requestRender();let t=p.draw(g.currentTime.get()+p.sceneSpan(g.activeSceneId.get()).start,!1,1);t&&c.release(t);let n=w(yFe(s.world,{name:e.name,mediaUrl:r}));x.load(n),(g.activeSceneId.get()===null||!n.document.scenes.some(e=>e.id===g.activeSceneId.get()))&&g.setActiveScene(n.document.activeSceneId||null);let i=new Set(x.current()?.meta.keys()),a=g.selection.get();a.clipIds.some(e=>!i.has(e))&&g.setSelection({clipIds:a.clipIds.filter(e=>i.has(e))}),g.requestRender(),m.invalidateAll(),d.changed(),S.changed(),g.playing.get()&&g.seek(g.currentTime.get())},E=Promise.resolve(),D=!1,O=0,k=new AbortController,A,j=[],M,N=e=>{let t=E.then(()=>D?void 0:e());return E=t.catch(()=>{}),t},P=(t,n)=>{D||e.onStatus?.(`${t}: ${n instanceof Error?n.message:String(n)}`)},F=e=>{s.durationsReady().then(()=>{D||O!==e||(T(),_.changed())}).catch(t=>{O===e&&P(`Media error`,t)})},I=e=>N(async()=>{if(!A)return;let t=++O;try{if(await s.load(A,j,e,M),D)return;T(),_.changed(),F(t)}catch(e){P(`Compile error`,e)}}),L=(n=!1)=>N(async()=>{let r=++O,i=performance.now();try{let a=await fetch(`${t}/api/files`,{signal:k.signal});if(!a.ok)throw Error(`/api/files: HTTP ${a.status}`);let o=await a.json();if(D)return;if(!o||typeof o!=`object`)throw Error(`the higgsedit dev server sent an invalid project`);let{files:c,modules:l,error:u,fonts:d,packages:f}=o;if(!l)throw Error(typeof u==`string`?u:`the higgsedit dev server sent no compiled modules; it predates server-side compile`);if(!dLe(l))throw Error(`the higgsedit dev server sent invalid compiled modules`);if(!dLe(c))throw Error(`the higgsedit dev server sent invalid source files`);if(d!==void 0&&(!Array.isArray(d)||d.some(e=>typeof e!=`string`)))throw Error(`the higgsedit dev server sent invalid fonts`);if(f!==void 0&&typeof f!=`string`)throw Error(`the higgsedit dev server sent an invalid package bundle`);if(n&&s.media.forgetAll(),await s.load(l,d,S.overrides(),f),D)return;T(),_.changed(),R.lastSources=c,A=l,j=d??[],M=f,e.onStatus?.(`Loaded in ${Math.round(performance.now()-i)} ms`),F(r)}catch(e){throw P(`Load error`,e),e}}),R={host:h,session:x,editor:g,reload:L,audio:v,media:s.media,prerender:_,async start(){if(i.add(h.registerCommand(`document.undo`,()=>void S.flush().then(()=>x.undo()))),i.add(h.registerCommand(`document.redo`,()=>void S.flush().then(()=>x.redo()))),i.add(h.registerCommand(`fable.session.play`,()=>g.play())),i.add(h.registerCommand(`fable.session.pause`,()=>g.pause())),i.add(h.registerCommand(`fable.session.togglePlayback`,()=>g.togglePlayback())),i.add(h.registerCommand(`fable.session.seekStart`,()=>g.seek(g.workArea.get()?.start??0))),i.add(h.registerCommand(`fable.session.seekEnd`,()=>g.seek(g.workArea.get()?.end??p.sceneSpan(g.activeSceneId.get()).duration))),i.add(h.provide(bm,x)),i.add(h.provide(Cm,g)),i.add(h.provide(xm,SIe)),i.add(h.provide(Upe,C)),i.add(h.provide(Sm,c)),i.add(h.provide(Gpe,m)),i.add(h.provide(Hpe,l)),i.add(h.provide(eme,cIe(t,()=>g.activeSceneId.get()))),i.add(h.provide(mLe,aLe(c))),i.add(h.provide(hLe,_Ie)),i.add(h.provide(gLe,sLe)),i.add(h.provide(YIe,d)),i.add(h.provide(GIe,WIe(t,s.media))),i.add(h.provide(LIe,_)),i.add(h.provide(OS,S)),h.assetStore.setBackend({get:async e=>x.snapshot()?.assets.find(t=>t.id===e)??null,list:async()=>x.snapshot()?.assets??[],readBlob:async e=>{let t=x.snapshot()?.assets.find(t=>t.id===e);if(!t)throw Error(`no asset ${e}`);return C.readAssetBlob(t)},write:(e,t)=>C.writeAsset(e,t)}),fetch(`${t}/api/history`,{signal:k.signal}).then(e=>e.json()).then(e=>{D||x.setServerUndo(e)},()=>{}),await L().catch(()=>{}),D)return;C.refreshAssets().catch(e=>P(`Media error`,e));let n=new EventSource(`${t}/api/events`);n.addEventListener(`message`,t=>{if(D)return;let n;try{n=JSON.parse(String(t.data))}catch(e){P(`Reload event error`,e);return}if(!n||typeof n!=`object`)return;if(n.type===`prerender`){_.onEvent(n);return}if(n.type===`proxy`){if(typeof n.src!=`string`)return;a.add(n.src),o===null&&(o=requestAnimationFrame(()=>{if(o=null,!D){for(let e of a)s.media.forget(e);a.clear(),g.requestRender(),m.invalidateAll(`content`)}}));return}if(n.type!==`change`)return;x.setServerUndo(n.undo);let r=performance.now();L(n.files.length===0).then(()=>{D||e.onStatus?.(`${n.origin===`editor`?`Saved`:`Reloaded`} ${n.files.join(`, `)} · ${Math.round(Date.now()-n.detectedAt)} ms after the write, ${Math.round(performance.now()-r)} ms to remount`)}).catch(()=>{})}),i.add({dispose:()=>n.close()}),h.registerAll(e.plugins),await h.start()},dispose(){D||(D=!0,O++,k.abort(),S.flush(),x.flush(),g.dispose(),v.dispose(),i.dispose(),h.dispose(),c.dispose())}};return R}var mLe,hLe,gLe,_Le=o((()=>{Tm(),Nm(),hx(),ZNe(),tIe(),aIe(),uIe(),mIe(),vIe(),CIe(),AIe(),PIe(),wFe(),BIe(),qIe(),ZIe(),iLe(),cLe(),uLe(),mLe=`capability:thumbs.source`,hLe=`capability:peaks.source`,gLe=`capability:engine.mixer`}));function kS(e){if(kLe)return kLe(e);let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function vLe(e){let t=``;for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t)}function yLe(e,t=``){return n=>{let r=n;r.type===`change`&&Array.isArray(r.files)&&(r.files.length===0?e.dropNamespace(t):e.drop(r.files.filter(e=>typeof e==`string`),t)),r.type===`proxy`&&typeof r.src==`string`&&e.drop([r.src],t)}}function AS(e,t){return new Promise((n,r)=>{let i=()=>{t.removeEventListener(`abort`,i),r(t.reason)};t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{t.removeEventListener(`abort`,i),t.aborted?r(t.reason):n(e)},e=>{t.removeEventListener(`abort`,i),r(e)}),t.aborted&&i()})}function jS(e){return new Response(kS(e.body),{status:e.status,headers:e.headers})}async function bLe(e,t){let n=e.signal;n.throwIfAborted();let r=new URL(`/api/media/uploads`,e.url);r.searchParams.set(`name`,new URL(e.url).searchParams.get(`name`)??``);let i=e.body?.getReader(),a=()=>{i?.cancel(n.reason).catch(()=>{})};n.addEventListener(`abort`,a,{once:!0});let o,s=!1,c=!1,l=()=>{if(o&&!c){c=!0;try{t({method:`DELETE`,path:o}).catch(()=>{})}catch{}}};try{let e=await AS(t({method:`POST`,path:r.pathname+r.search}).then(e=>{if(e.status===201){let{id:t}=JSON.parse(new TextDecoder().decode(kS(e.body)));if(typeof t!=`string`||!/^[a-f0-9-]{36}$/.test(t))throw Error(`invalid media upload session`);o=`/api/media/uploads/${t}`,n.aborted&&l()}return e}),n);if(e.status!==201)return jS(e);let a=JSON.parse(new TextDecoder().decode(kS(e.body)));if(!Number.isSafeInteger(a.partBytes)||Number(a.partBytes)<1||Number(a.partBytes)>2<<20||!Number.isSafeInteger(a.maxBytes)||Number(a.maxBytes)<1)throw Error(`invalid media upload limits`);let c=new Uint8Array(Number(a.partBytes)),u=0,d=0,f=async()=>{n.throwIfAborted();let e=await AS(t({method:`PUT`,path:`${o}?offset=${d}`,body:vLe(c.subarray(0,u))}),n);if(e.status!==200)return e;d+=u,u=0};for(;i;){n.throwIfAborted();let{value:e,done:t}=await AS(i.read(),n);if(t)break;if(d+u+e.byteLength>Number(a.maxBytes))throw Error(`media upload exceeds the ${a.maxBytes} byte limit`);for(let t=0;t<e.byteLength;){let n=Math.min(c.byteLength-u,e.byteLength-t);if(c.set(e.subarray(t,t+n),u),u+=n,t+=n,u===c.byteLength){let e=await f();if(e)return jS(e)}}}if(u){let e=await f();if(e)return jS(e)}n.throwIfAborted();let p=await AS(t({method:`POST`,path:o}),n);return s=p.status===200,jS(p)}finally{n.removeEventListener(`abort`,a),i?.cancel().catch(()=>{}),i?.releaseLock(),s||l()}}function xLe(e,t,n=globalThis.fetch.bind(globalThis),r=new OLe,i=``){let a=t=>e(`higgsedit_http`,t);return async(e,o)=>{let s=new Request(e,o);if(!s.url.startsWith(`${t}/`))return n(e,o);let c=s.url.slice(t.length),l=i+c,u=s.method.toUpperCase(),d=s.signal,f={};for(let e of[`if-none-match`,`if-modified-since`,`if-range`]){let t=s.headers.get(e);t!==null&&(f[e]=t)}let p=Object.keys(f).length?{headers:f}:{},m=e=>new Response(u===`HEAD`||e.status===304||e.status===204?null:kS(e.body),{status:e.status,headers:e.headers});if(u===`POST`&&[`/api/media`,`/api/media/stream`].includes(new URL(c,s.url).pathname))return bLe(s,a);if(u!==`GET`||!(c.startsWith(`/project/`)||c.startsWith(`/preview/`))){let e=u===`GET`||u===`HEAD`?void 0:vLe(new Uint8Array(await s.arrayBuffer()));return m(await a({method:u,path:c,...p,...e===void 0?{}:{body:e}}))}let h=wLe.exec(s.headers.get(`range`)??``),g=e=>{if(!e.current)throw Error(`${c}: changed while reading`)};if(Object.keys(f).length){let e=r.revision(l),t=await a({method:`HEAD`,path:c,...p});if(g(e),t.status!==200)return m(t);let n=Number(t.headers[`content-length`]);if(!Number.isSafeInteger(n)||n<0)throw Error(`${c}: missing media size`);let i=DLe(t.headers,n);r.setFile(l,i);let o=f[`if-range`];if(h&&o){let e=Date.parse(o),t=Date.parse(i.modified??``);(o.startsWith(`"`)?o===i.etag:!o.startsWith(`W/`)&&t<=Date.now()-6e4&&e===t)||(h=null)}}let _=r.revision(l),v=h?Number(h[1]):0,y=async e=>{g(_);let t=await a({method:`GET`,path:c,rangeStart:e*MS,rangeEnd:e*MS+MS-1});g(_);let n=kS(t.body);if(t.status!==200&&t.status!==206)throw Object.assign(Error(`${c}: ${t.status} at byte ${e*MS}`),{reply:t});let i=t.status===200?n.length:ALe(t.headers[`content-range`]),o=DLe(t.headers,i),s=r.file(l);if(s&&!ELe(s,o))throw r.dropPath(l),Error(`${c}: changed while reading`);return r.setFile(l,o),t.status===200?n.subarray(e*MS,e*MS+MS):n},b=async e=>{g(_);let t=await r.chunk(l,e,()=>y(e));return g(_),t};if(!r.file(l))try{await b(Math.floor(v/MS))}catch(e){let t=e.reply;if(t)return m(t);throw e}let{size:x,type:S,etag:C,modified:w,cacheControl:T}=r.file(l),E=Math.min(h?.[2]?Number(h[2]):x-1,x-1);if(v>E)return new Response(null,{status:416,headers:{"content-range":`bytes */${x}`}});let D=Math.floor(E/MS),O=Math.floor(v/MS),k=new ReadableStream({async pull(e){if(d.aborted)return e.error(d.reason);for(let e=O+1;e<=Math.min(O+4,D);e++)b(e).catch(()=>{});let t;try{t=await b(O)}catch(t){return e.error(t)}let n=Math.max(v,O*MS)-O*MS,r=Math.min(E,O*MS+t.length-1)-O*MS;if(r<n)return e.error(Error(`${c}: short read at byte ${O*MS}`));e.enqueue(t.slice(n,r+1)),++O>D&&e.close()}},{highWaterMark:0}),A=new Headers({"content-type":S,"content-length":String(E-v+1),"accept-ranges":`bytes`});return C&&A.set(`etag`,C),w&&A.set(`last-modified`,w),T&&A.set(`cache-control`,T),h?(A.set(`content-range`,`bytes ${v}-${E}/${x}`),new Response(k,{status:206,headers:A})):new Response(k,{status:200,headers:A})}}function SLe(e,t,n=globalThis.EventSource,r,i={}){let a=i.waitMs??2500;class o extends EventTarget{static CONNECTING=0;static OPEN=1;static CLOSED=2;CONNECTING=0;OPEN=1;CLOSED=2;url;withCredentials=!1;readyState=0;onopen=null;onmessage=null;onerror=null;abort=new AbortController;constructor(e,r){if(super(),this.url=String(e),!this.url.startsWith(`${t}/`)){if(!n)throw Error(`no EventSource for ${this.url}`);return new n(e,r)}this.loop()}async loop(){let t=-1,n=0;for(;!this.abort.signal.aborted;){let i;try{await PLe(n,this.abort.signal);let r=Date.now();if(i=await NLe(e,t,a,this.abort.signal),this.abort.signal.aborted)return;n=t>=0&&i.events.length===0?Math.max(0,a-(Date.now()-r)):0}catch{if(this.abort.signal.aborted)return;this.emit(new Event(`error`),this.onerror),n=jLe;continue}this.readyState===0&&(this.readyState=1,this.emit(new Event(`open`),this.onopen));for(let e of i.events){if(this.abort.signal.aborted)return;r?.(e),this.readyState!==2&&this.emit(new MessageEvent(`message`,{data:JSON.stringify(e)}),this.onmessage)}t=i.seq}}emit(e,t){t?.call(this,e),this.dispatchEvent(e)}close(){this.readyState=2,this.abort.abort()}}return o}var MS,CLe,wLe,TLe,ELe,DLe,OLe,kLe,ALe,jLe,NS,PS,MLe,NLe,PLe,FLe=o((()=>{MS=1<<20,CLe=256<<20,wLe=/^bytes=(\d+)-(\d*)$/,TLe=[`/project/`,`/preview/`],ELe=(e,t)=>e.size===t.size&&(e.etag||t.etag?e.etag===t.etag:e.modified===t.modified),DLe=(e,t)=>({size:t,type:e[`content-type`]??`application/octet-stream`,etag:e.etag,modified:e[`last-modified`],cacheControl:e[`cache-control`]}),OLe=class{limit;meta=new Map;chunks=new Map;sizes=new Map;revisions=new Map;bytes=0;constructor(e=CLe){this.limit=e}file(e){return this.meta.get(e)}setFile(e,t){let n=this.meta.get(e);n&&!ELe(n,t)&&this.dropPath(e),this.meta.set(e,t)}revision(e){let t=this.revisions.get(e);return t||this.revisions.set(e,t={current:!0}),t}chunk(e,t,n){let r=`${e}#${t}`,i=this.chunks.get(r);if(i)return this.chunks.delete(r),this.chunks.set(r,i),i;let a=n();return this.chunks.set(r,a),a.then(e=>{this.chunks.get(r)===a&&(this.sizes.set(r,e.length),this.bytes+=e.length,this.trim())},()=>{this.chunks.get(r)===a&&this.chunks.delete(r)}),a}drop(e,t=``){for(let n of e)for(let e of TLe)this.dropPath(t+e+n.replace(/^\.?\//,``))}dropNamespace(e=``){for(let t of new Set([...this.meta.keys(),...this.revisions.keys()]))t.startsWith(`${e}/`)&&this.dropPath(t)}dropPath(e){let t=this.revisions.get(e);t&&(t.current=!1),this.revisions.delete(e),this.meta.delete(e);for(let t of this.chunks.keys())t.slice(0,t.lastIndexOf(`#`))===e&&this.forget(t)}forget(e){this.chunks.delete(e),this.bytes-=this.sizes.get(e)??0,this.sizes.delete(e)}trim(){for(let e of this.chunks.keys()){if(this.bytes<=this.limit)return;this.sizes.has(e)&&this.forget(e)}}},kLe=Uint8Array.fromBase64,ALe=e=>Number(/\/(\d+)$/.exec(e??``)?.[1]??NaN),jLe=2500,NS=!1,PS=[],MLe=8,NLe=(e,t,n,r)=>new Promise((i,a)=>{if(r.aborted)return a(r.reason);if(NS&&PS.length>=MLe)return a(Error(`Editor event queue is full`));let o=!1,s=()=>{if(!o){let e=PS.indexOf(c);e>=0&&PS.splice(e,1)}a(r.reason)},c=()=>{o=!0,NS=!0,Promise.resolve().then(()=>(r.throwIfAborted(),e(`higgsedit_events`,{after:t,waitMs:n}))).then(e=>i(e),a).finally(()=>{r.removeEventListener(`abort`,s),NS=!1,PS.shift()?.()})};r.addEventListener(`abort`,s,{once:!0}),NS?PS.push(c):c()}),PLe=(e,t)=>new Promise((n,r)=>{if(t.aborted)return r(t.reason);let i,a=()=>{clearTimeout(i),typeof document<`u`&&document.removeEventListener(`visibilitychange`,s),t.removeEventListener(`abort`,o)},o=()=>{a(),r(t.reason)},s=()=>{(typeof document>`u`||document.visibilityState!==`hidden`)&&(a(),n())},c=()=>{typeof document<`u`&&document.visibilityState===`hidden`?document.addEventListener(`visibilitychange`,s):s()};t.addEventListener(`abort`,o,{once:!0}),e>0?i=setTimeout(c,e):c()})})),ILe=o((()=>{_Le(),tIe(),FLe(),uLe(),TPe(),ZIe(),GPe(),iS(),CIe(),qIe(),BIe()}));function LLe(e){let t=``;for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t)}function RLe(e,t,n){return async(r,i)=>{let a=r instanceof Request?r.url:String(r),o=i?.method??(r instanceof Request?r.method:`GET`);if(!a.startsWith(`${t}/`)||o.toUpperCase()!==`POST`)return n(r,i);let s=new Request(r,i);s.signal.throwIfAborted();let c=s.body?.getReader();if(!c)return n(s);let l,u=0,d=async()=>{let e=new Uint8Array(FS),t=0;for(;t<e.length;){if(s.signal.throwIfAborted(),!l||u===l.length){let e=await c.read();if(e.done)break;l=e.value,u=0}let n=Math.min(e.length-t,l.length-u);e.set(l.subarray(u,u+n),t),u+=n,t+=n}return t?e.subarray(0,t):null},f=crypto.randomUUID(),p=a.slice(t.length),m=!1,h=!1,g,_=()=>(m&&!h&&(g??=e(`video_editing_upload`,{id:f,path:p,offset:0,part:``,last:!1,cancel:!0}).catch(()=>void 0)),g),v=Promise.withResolvers(),y=()=>{c.cancel(s.signal.reason).catch(()=>void 0),_(),v.reject(s.signal.reason)};v.promise.catch(()=>void 0),s.signal.addEventListener(`abort`,y,{once:!0});try{s.signal.throwIfAborted();let t=await d(),r=await d();if(s.signal.throwIfAborted(),!r)return await n(new Request(a,{method:`POST`,headers:s.headers,body:t?new Blob([t]):null,signal:s.signal}));let i=0,o;for(;t;)s.signal.throwIfAborted(),m=!0,o=await Promise.race([e(`video_editing_upload`,{id:f,path:p,offset:i,part:LLe(t),last:r===null}),v.promise]),s.signal.throwIfAborted(),i+=t.length,t=r,r=t?await d():null;h=!0;let{status:c,headers:l,body:u}=o,g=Uint8Array.from(atob(u),e=>e.charCodeAt(0));return new Response(g.length?g:null,{status:c,headers:l})}finally{s.signal.removeEventListener(`abort`,y),c.cancel().catch(()=>void 0),c.releaseLock(),_()}}}var FS,zLe=o((()=>{FS=2<<20}));function BLe(e){let t=0,n=[];return async r=>{t>=e&&await new Promise(e=>n.push(e)),t++;try{return await r()}finally{t--,n.shift()?.()}}}function VLe(e){IS=e}function HLe(e){return LS.add(e),()=>LS.delete(e)}async function ULe(e){try{return(await fetch(`${e}/ping`,{signal:AbortSignal.timeout(qLe)})).ok}catch{return!1}}function WLe(e,t){let n=BLe(XLe),r=new OLe,i=e=>{if(!e.startsWith(`${t.base}/`))return null;let n=e.slice(t.base.length+1).split(`/`,1)[0];if(!/^[a-f0-9]{16}$/.test(n))throw TypeError(`The editor request must name a project session.`);return n},a=r=>async(i,a)=>{let o=YLe[i]??i,s={...a,project:r};try{return await(i===`higgsedit_events`?Yp(e,o,s):n(()=>Yp(e,o,s)))}catch(e){throw e instanceof Error&&e.message.startsWith(JLe)&&t.onLost(r),e}},o=async(e,n)=>{let o=e instanceof Request?e.url:String(e),s=i(o);if(!s)return t.fetch(e,n);if(t.mode===`direct`){let r=await t.fetch(e,n);return r.status===410&&t.onLost(s),r}let c=`${t.base}/${s}`,l=a(s);return RLe(l,c,xLe(l,c,t.fetch,r,c))(e,n)};class s extends EventTarget{static CONNECTING=0;static OPEN=1;static CLOSED=2;constructor(e,n){super();let o=i(String(e));return new(o?SLe(a(o),`${t.base}/${o}`,t.EventSource,t.mode===`bridge`?yLe(r,`${t.base}/${o}`):void 0,{waitMs:t.mode===`direct`?2e4:2500}):t.EventSource)(e,n)}}return{fetch:o,EventSource:s}}async function GLe(e,t,n){return QLe??=(async()=>{let n=t?await ULe(t):!1;RS=n?`direct`:`bridge`;let r=WLe(e,{base:n?t:KLe,mode:RS,fetch:globalThis.fetch.bind(globalThis),EventSource:globalThis.EventSource,onLost:ZLe});return globalThis.fetch=r.fetch,globalThis.EventSource=r.EventSource,RS})(),await QLe===`direct`?`${t}/${n}`:`${KLe}/${n}`}var KLe,qLe,JLe,YLe,XLe,IS,LS,ZLe,QLe,RS,$Le,eRe,tRe=o((()=>{ILe(),zLe(),Xp(),KLe=`https://higgsedit.invalid`,qLe=2500,JLe=`project-unknown`,YLe={higgsedit_http:`video_editing_http`,higgsedit_events:`video_editing_events`},XLe=6,IS=null,LS=new Set,ZLe=e=>{if(e===IS)for(let e of LS)e()},QLe=null,RS=`same-origin`,$Le=()=>IS,eRe=()=>RS})),X=u(_(),1);Wf(),tRe(),Xp();var nRe=1500,rRe=G({path:W().nullable(),session:W().optional(),name:W().optional(),roots:Af(W()).optional(),recent:Af(W()).optional(),names:Ff(W(),W()).optional(),usedAt:Ff(W(),Cf()).optional(),error:W().optional(),direct:Sf().nullable().optional()});function iRe(e,t){let[n,r]=(0,X.useState)({kind:`checking`}),[i,a]=(0,X.useState)(0),o=(0,X.useRef)(t??null),s=(0,X.useCallback)(e=>{e&&(o.current=e),a(e=>e+1)},[]),c=(0,X.useRef)(!1),l=n.kind===`open`?n.project.session:null,u=n.kind===`unavailable`;return(0,X.useEffect)(()=>{if(!e||u)return;VLe(l);let t=!0,n=null,i=()=>{n!==null&&clearTimeout(n),n=null,Yp(e,`video_editing_session`,o.current?{project:o.current}:{}).then(async a=>{let s=rRe.parse(a);if(!t)return;c.current=!0,s.session&&(o.current??=s.session);let u={roots:s.roots??[],recent:s.recent??[],names:s.names,usedAt:s.usedAt};if(!s.path||!s.session){r({kind:`none`,...u,...s.error?{error:s.error}:{}}),n=setTimeout(i,nRe);return}if(s.session===l){r(e=>e.kind===`open`?{...e,...u,project:{...e.project,name:s.name??e.project.name}}:e);return}let d=await GLe(e,s.direct,s.session);t&&(VLe(s.session),r({kind:`open`,...u,project:{path:s.path,session:s.session,name:s.name??`project`,origin:d}}))}).catch(()=>{t&&(c.current?n=setTimeout(i,nRe):r({kind:`unavailable`}))})},a=HLe(i);return i(),()=>{t=!1,a(),n!==null&&clearTimeout(n)}},[e,l,u,i]),{state:n,refresh:s}}Wf();var aRe=W().trim().min(1).max(120);function oRe(e){return(e.split(/[\\/]/).filter(Boolean).at(-1)??`Untitled project`).replace(/^Untitled project-[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i,`Untitled project`)}var zS=o((()=>{Tm(),Yx(),Nm()}));function BS(e,t){let n=e?.scenes.find(t=>t.id===e.activeSceneId);if(!e||!n)return[];let r=new Set(t),i=new Set(e.assets.filter(e=>e.kind===`video`).map(e=>e.id));return n.tracks.filter(e=>!e.locked).flatMap(t=>t.clips.filter(e=>r.has(e.id)&&!e.locked&&e.kind===`media`&&i.has(e.assetId)).sort((e,t)=>e.timeRange.start-t.timeRange.start).map(t=>({projectId:e.id,sceneId:n.id,clipId:t.id,assetId:t.assetId})))}function sRe(e,t){let n=BS(e,t);if(n.length&&n.length===t.length)return n;let r=e?.scenes.find(t=>t.id===e.activeSceneId)?.tracks.flatMap(e=>e.clips.filter(e=>t.includes(e.id)));throw!r?.length||r.length!==t.length?Error(`Select a video clip on the timeline to use this tool.`):r.some(t=>t.kind!==`media`||!e?.assets.some(e=>e.id===t.assetId&&e.kind===`video`))?Error(`This tool only works with video clips. Select a video clip on the timeline.`):Error(`Unlock the selected video clips and their tracks to use this tool.`)}function VS(e,t){if(e?.id!==t.projectId||e.activeSceneId!==t.sceneId)return null;let n=e.scenes.find(e=>e.id===t.sceneId);if(!n)return null;for(let[e,r]of n.tracks.entries()){let i=r.clips.find(e=>e.id===t.clipId);if(i?.kind===`media`&&i.assetId===t.assetId&&!i.locked&&!r.locked)return{scene:n,track:r,trackIndex:e,clip:i}}return null}function HS(){return typeof crypto<`u`&&`randomUUID`in crypto?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function cRe(e){return e.slice(0,40).replace(/[\\/:*?"<>|\n\r]+/g,` `).replace(/\s+/g,` `).trim()||`generated-media`}function lRe(e,t,n){let r=e.kind===`image`?5:e.duration??5,i=e.width!=null&&e.width>0?e.width:t.width,a=e.height!=null&&e.height>0?e.height:t.height,o=Math.min(t.width/i,t.height/a),s={id:HS(),name:e.name,transform:{...pRe,x:t.width/2,y:t.height/2,scaleX:o,scaleY:o},size:{width:i,height:a},opacity:1,blendMode:`normal`,effects:[],timeRange:{start:n,duration:r},animations:[],presetAnimations:[],mask:null,locked:!1,hidden:!1};return e.kind===`audio`?{...s,kind:`audio`,size:{width:0,height:0},transform:{...pRe},assetId:e.id,trim:{start:0,end:e.duration??r},speed:1,preservePitch:!0,volume:1,muted:!1}:{...s,kind:`media`,assetId:e.id,trim:{start:0,end:e.duration??r},speed:1,preservePitch:!0,volume:1,muted:!1,cornerRadius:{mixed:!1,uniform:0,tl:0,tr:0,br:0,bl:0}}}function uRe(e,t,n){let r=Math.max(0,t);for(let t of[...e?.clips??[]].sort((e,t)=>e.timeRange.start-t.timeRange.start)){let e=t.timeRange.start+t.timeRange.duration;if(!(e<=r+1e-6)){if(t.timeRange.start>=r+n-1e-6)break;r=e}}return r}function dRe(e,t,n,r,i){let a=e.scenes.find(t=>t.id===e.activeSceneId)??null;if(!a)return null;if(i&&`aboveSources`in i){let a=e,o=[],s=[];for(let e of i.aboveSources){let i=dRe(a,t,n,r,{aboveSource:e});if(!i)return null;o.push(...i.envelope.ops),s.push(i.clipId),a=Ux(a,i.envelope.ops)}return s.length?{clipId:s[0],clipIds:s,envelope:{id:HS(),name:`Add generated clips`,coalesceKey:null,ops:o}}:null}let o=e.assets.some(e=>e.id===t.id)?[]:[{op:`insert`,path:[`assets`],index:e.assets.length,value:US(t)}];if(i&&`aboveSource`in i){let n=VS(e,i.aboveSource);if(!n||t.kind===`audio`)return null;let r=lRe(t,a,n.clip.timeRange.start),s=i.aboveSource.resultRange===`clip`,c=i.aboveSource.resultRange===`extend`,l=s?0:n.clip.trim.start,u=s?1:n.clip.speed,d=((t.duration??n.clip.trim.end)-l)/u,f=s||c?d:Math.min(n.clip.timeRange.duration,d);if(f<=0)return null;r.timeRange.duration=f,r.trim={start:l,end:l+f*u},r.speed=u,r.preservePitch=n.clip.preservePitch,r.muted=n.clip.muted||n.track.muted,r.volume=n.clip.volume;let p=i.aboveSource.resultTrack,m=p?.sourceTrackId===n.track.id?p.id:void 0,h=a.tracks.findIndex(e=>e.id===m),g=a.tracks[h],_=g&&h>n.trackIndex&&!g.locked&&!g.hidden&&g.clips.every(e=>e.timeRange.start>=r.timeRange.start+f-1e-6||e.timeRange.start+e.timeRange.duration<=r.timeRange.start+1e-6),v=e.scenes.indexOf(a),y={...Kx(),...m&&!g?{id:m}:{},clips:[r]},b=_?{op:`insert`,path:[`scenes`,v,`tracks`,h,`clips`],index:g.clips.length,value:US(r)}:{op:`insert`,path:[`scenes`,v,`tracks`],index:n.trackIndex+1,value:US(y)};return{clipId:r.id,envelope:{id:HS(),name:`Add generated clip`,coalesceKey:null,ops:[...o,b,{op:`set`,path:[`scenes`,v,`tracks`,n.trackIndex,`clips`,n.track.clips.indexOf(n.clip),`hidden`],value:!0}]}}}let s=i?a.tracks.find(e=>e.id===i.preferredTrackId&&!e.locked&&!e.hidden)??a.tracks.find(e=>!e.locked&&!e.hidden&&(!e.clips.length||e.clips.some(e=>e.kind!==`audio`))):void 0,c=lRe(t,a,i?uRe(s,n,t.kind===`image`?5:t.duration??5):Math.max(n,0)),l=r.planClipPlacement(e,a.id,c,{preferredTrackId:s?.id});if(!l)return null;let u=[...o,...l.ops];return{envelope:{id:HS(),name:`Add generated clip`,ops:u,coalesceKey:null},clipId:c.id}}async function fRe(e,t){try{let n=e.snapshot();if(!n||t.projectId&&n.id!==t.projectId)return{ok:!1,message:`The video editor project changed`};let r=[];if(e.insertion&&`aboveSources`in e.insertion&&r.push(...e.insertion.aboveSources),e.insertion&&`aboveSource`in e.insertion&&r.push(e.insertion.aboveSource),r.some(e=>!VS(n,e)))return{ok:!1,message:`The source clip is no longer available for reframing`};let i=e.playhead(),a=await e.fetchResult(t);if(e.snapshot()?.id!==n.id||e.snapshot()?.activeSceneId!==n.activeSceneId)return{ok:!1,message:`The video editor project or scene changed`};let o=a.name.includes(`.`)?a.name.split(`.`).pop():`bin`,s=`projectSrc`in a?a:new File([a],`${cRe(t.prompt)}.${o}`,{type:a.type}),c=await e.importFile(s,{generationId:t.id,sourceUrl:t.resultUrl??void 0});Hp(t.id)&&e.rememberSource?.(c,t.id);let l=async()=>{let t=e.snapshot();if(!t||t.id!==n.id||t.activeSceneId!==n.activeSceneId)return{ok:!1,message:`The video editor project or scene changed`};let a=dRe(t,c,i,e.placement,e.insertion);if(!a)return{ok:!1,message:r.length?`The source clip changed or is locked`:`No active scene`};await e.execute(`document.apply`,a.envelope);let o=e.snapshot(),s=o?.scenes.find(e=>e.id===n.activeSceneId)?.tracks.flatMap(e=>e.clips),l=(a.clipIds??[a.clipId]).every(e=>s?.some(t=>t.id===e));return o?.id!==n.id||!l?{ok:!1,message:`The result was not added to the target timeline. Reopen that project and retry.`}:(o.activeSceneId===n.activeSceneId&&e.select(a.clipId),{ok:!0,clipId:a.clipId})};return await(e.commit?e.commit(l):l())}catch(e){return{ok:!1,message:e instanceof Error?e.message:`Import failed`}}}var pRe,US,WS=o((()=>{Gp(),zS(),pRe={x:0,y:0,scaleX:1,scaleY:1,rotation:0,skewX:0,skewY:0,anchorX:.5,anchorY:.5,flipX:!1,flipY:!1},US=e=>JSON.parse(JSON.stringify(e))}));function mRe(e,t,n){if(e?.id!==n.projectId||e.activeSceneId!==n.sceneId)throw Error(`The target project or scene is no longer open. Reopen its aspect ratio menu.`);let r=e.scenes.find(e=>e.id===n.sceneId);if(!r)throw Error(`Open a video scene first.`);let i=hRe.find(e=>{let[t,n]=e.split(`:`).map(Number);return Math.abs(r.width/r.height-t/n)<.001});if(!i)throw Error(`Choose 21:9, 16:9, 9:16, 4:3, 3:4 or 1:1 before adapting videos.`);let a=new Set(e.assets.filter(e=>e.kind===`video`).map(e=>e.id)),o=t.length?[...new Set(t)]:r.tracks.filter(e=>!e.hidden&&!e.locked).flatMap(e=>e.clips.filter(e=>!e.hidden&&!e.locked&&e.kind===`media`&&a.has(e.assetId)).map(e=>e.id));if(!o.length)throw Error(`Add an unlocked video to the timeline first.`);if(o.length>20)throw Error(`Select up to 20 video clips to adapt at a time.`);let s=sRe(e,o);return{target:{...n,clipIds:s.map(e=>e.clipId)},prompt:[`Adapt these videos to the timeline's ${i} aspect ratio (${r.width} × ${r.height}).`,`Use Higgsfield's reframe tool with aspect_ratio "${i}" to extend the image into the empty edges. The target format is already chosen; start the adaptation without asking me to choose an aspect ratio again.`,`Preserve the original subjects, content and motion; do not stretch or crop the video to fill the canvas. Keep the timeline size, source duration, audio and clip timing unchanged. Adapt only the attached source videos, with one result per unique source, and keep the originals available.`].join(`
279
+ `)&&r(`reordering text ranges`);for(let e of t)e.id&&!o.includes(e.id)&&i.push({key:e.id,edit:{op:`remove`}});return n.forEach((t,o)=>{let s=t.end??null;s!==null&&!(s>t.start)&&r(`a text range that ends before it starts`);let c=t.id?a.get(t.id):void 0;if(!c){let r=n.slice(o+1).find(e=>e.id&&a.has(e.id))?.id;i.push({key:e,edit:{op:`insert`,tag:`textRange`,props:rFe($Pe(t)),...r?{before:r}:{}}});return}let[l,u]=[$Pe(c),$Pe(t)];for(let e of Object.keys(u))l[e]!==u[e]&&i.push({key:t.id,edit:{op:`set-prop`,name:e,value:u[e]}})}),i}var uS,nFe,rFe,dS,iFe=o((()=>{hx(),uS=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,nFe=e=>e===`bold`?700:e===`normal`?400:uS(e),rFe=e=>Object.fromEntries(Object.entries(e).filter(([,e])=>e!==null)),dS=(e,t)=>[{op:`set-prop`,name:e,value:t}]}));function aFe(e,t,n){e.forEach((r,i)=>{let a=vve(t(r.id),n);if(!a)return;let o=e[i+1],s=o&&Cve(r.timeRange.start+r.timeRange.duration,o.timeRange.start,n)?o:void 0,c=`${r.id}:transition`,l=a.duration/2;r.presetAnimations.push({id:`${c}:out`,preset:a.type,direction:`out`,duration:l,easing:uFe,params:{transitionId:c,transitionPeerId:s?.id??``}}),s?.presetAnimations.push({id:`${c}:in`,preset:a.type,direction:`in`,duration:l,easing:uFe,params:{transitionId:c,transitionPeerId:r.id}})})}function oFe(e,t){for(let n of e)t(n),n.kind===`group`&&oFe(n.children,t)}function sFe(e){let t=new Map,n=[];for(let r of e.scenes)for(let e of r.tracks)oFe(e.clips,e=>{for(let r of e.presetAnimations)lFe(r)&&(r.direction===`in`?t.set(r.params.transitionId,r.duration):n.push([e.id,r]))});return new Map(n.map(([e,n])=>[e,{type:n.preset,duration:n.duration+(t.get(n.params.transitionId)??n.duration)}]))}function cFe(e,t,n,r,i){if(!t)return null;if($g.includes(t.type)||i(`${t.type} transition`),typeof e!=`object`||!e||Array.isArray(e))return{type:t.type,duration:r(t.duration,void 0)};let a={...e},o=a.duration;return t.type!==(a.type??t_.type)&&(a.type=t.type),Math.abs(t.duration-(Gh(o,n)??xve(t.type)))>dFe&&(a.duration=r(t.duration,o)),a}var lFe,uFe,dFe,fFe,pFe=o((()=>{e_(),hx(),lFe=e=>typeof e.params.transitionId==`string`,uFe={kind:`linear`},dFe=1e-6,fFe=(e,t)=>e===t||!!e&&!!t&&e.type===t.type&&Math.abs(e.duration-t.duration)<dFe}));function mFe(e,t,n){return e===`x`?t.x:e===`y`?t.y:e===`maskX`?-n.x:e===`maskY`?-n.y:0}function hFe(e,t,n){return e?{enabled:!0,shape:e.shape??`rectangle`,x:fS(e.x,n.x+t.width/2)-n.x,y:fS(e.y,n.y+t.height/2)-n.y,width:fS(e.width,t.width),height:fS(e.height,t.height),rotation:fS(e.rotation,0),cornerRadius:fS(e.cornerRadius,0),feather:fS(e.feather,0),invert:e.invert===!0,d:e.shape===`path`?e.d??``:null,...e.src?{src:e.src}:{}}:null}function gFe(e,t,n,r,i){let a=[],o={};for(let[s,c]of Object.entries(t??{})){let t=bFe[s];if(!t){o[s]=c;continue}let l=mFe(s,r,i);a.push({id:`${e}:${t}`,property:t,effectId:null,effectParam:null,gradientStopIndex:null,keyframes:c.map((r,i)=>({id:`${e}:${t}:${i}`,time:Gh(r[0],n)??0,value:typeof r[1]==`number`?r[1]+l:r[1],easing:PPe(r[2])}))})}return{tracks:a,unmapped:o}}function _Fe(e,t,n,r,i,a,o,s){let c=t.get(mh),l=c.tag;if(l===`stage`||l===`scene`)return null;let u=o_(t),d=t.get(gh)??{},f=B_(e,t,r),p=!Number.isFinite(f.end),m=p?Math.max(f.start,i):f.end,[h,g,_,v]=t.get(zh)?.bounds??[0,0,0,0],y=l===`captions`?SPe(e,t,u,n,r):void 0,b=u.width===void 0&&_>h&&!y,x=l===`adjustmentLayer`,S=y?y.box.width:fS(u.width,x?n.width:b?_-h:l===`text`?0:100),C=y?y.box.height:fS(u.height,x?n.height:u.height===void 0&&v>g?v-g:l===`text`?0:100),w={x:b?h:0,y:u.height===void 0&&v>g?g:0},T=fS(u.anchorX,x?.5:0),E=fS(u.anchorY,x?.5:0),D={x:T*S+w.x,y:E*C+w.y},O=c.key,k=gFe(O,t.get(Mh)?.animate,r,D,w),A=LPe(O,u.effects,r),j=typeof u.scale==`number`?u.scale:void 0,M={id:O,name:c.name??c.id??l,transform:uPe({x:(y?y.box.x:fS(u.x,0))+D.x,y:(y?y.box.y:fS(u.y,0))+D.y,scaleX:fS(u.scaleX,j??1),scaleY:fS(u.scaleY,j??1),rotation:fS(u.rotation,0),anchorX:T,anchorY:E}),size:{width:S,height:C},opacity:fS(u.opacity,1),timeRange:{start:f.start,duration:Math.max(0,m-f.start)},animations:[...k.tracks,...A.tracks],effects:A.effects,presetAnimations:KPe(O,u,r),blendMode:u.blend??`normal`,mask:hFe(u.mask,{width:S,height:C},w),hidden:u.hidden===!0,locked:u.locked===!0,...typeof u.constrainX==`string`&&u.constrainX!==`left`?{constrainX:u.constrainX}:{},...typeof u.constrainY==`string`&&u.constrainY!==`top`?{constrainY:u.constrainY}:{}},N=l===`video`||l===`audio`?e.get(c_)?.durations.get(String(u.src)):void 0;a.set(O,{key:O,tag:l,sceneId:n.id,fps:r,timing:{...d.start===void 0?{}:{start:d.start},...d.end===void 0?{}:{end:d.end},...d.sourceIn===void 0?{}:{sourceIn:d.sourceIn}},openEnded:p,boxOffset:w,...N===void 0?{}:{mediaDuration:N},...y?.stop===void 0?{}:{captionStop:y.stop},accessors:new Set(c.accessors),unmappedAnimate:k.unmapped,authored:u});let P=u.fill;switch(l){case`rect`:return nPe({...M,fill:VPe(P,`#ffffff`),cornerRadius:qx(fS(u.cornerRadius,0))});case`surface`:case`html`:return{...nPe({...M,fill:{type:`solid`,color:`#00000000`},cornerRadius:qx(fS(u.cornerRadius,0))}),drawnBy:l};case`text`:return{...Gx({...M,text:String(u.text??``),fontSize:fS(u.fontSize,48),fontFamily:typeof u.fontFamily==`string`?u.fontFamily:`sans-serif`,fontWeight:u.fontWeight===`bold`?700:fS(u.fontWeight,400),lineHeight:fS(u.lineHeight,1.2),align:u.align??`left`,fill:VPe(P,`#ffffff`)}),...ZPe(t,u)};case`video`:case`image`:case`audio`:{let n=String(t.get(kh)?.src??``);if(!o.has(n)||l===`video`&&o.get(n)?.kind===`audio`){let t=n.split(`.`).at(-1)?.toLowerCase()??``;o.set(n,{id:n,name:n.split(`/`).at(-1)??n,kind:SFe(l),mimeType:CFe[t]??`application/octet-stream`,byteSize:0,duration:e.get(c_)?.durations.get(n)??null,width:null,height:null,uri:s.mediaUrl(n),hash:null})}let i=hbe(e,t,r),a=V_(t),c={start:i,end:i+(M.timeRange?.duration??0)*a},d={...M,assetId:n,trim:c,volume:fS(u.volume,1),muted:u.muted===!0,speed:a,preservePitch:u.preservePitch!==!1};if(l===`audio`)return iPe({...d,size:{width:0,height:0}});let f=rPe({...d,cornerRadius:qx(fS(u.cornerRadius,0))});return u.fit===`cover`||u.fit===`contain`||u.fit===`fill`?{...f,layoutFit:u.fit}:f}case`captions`:return y.clip(M);case`adjustmentLayer`:return aPe(M);case`group`:{let c=l_(t).map(t=>_Fe(e,t,n,r,i,a,o,s)).filter(e=>e!==null);return oPe({...M,children:c})}case`sequence`:{let l=vFe(e,t,n,r,i,a,o,s);return oPe({...M,name:c.name??c.id??`Sequence`,children:l})}default:return null}}function vFe(e,t,n,r,i,a,o,s){let c=l_(t).map(t=>_Fe(e,t,n,r,i,a,o,s)).filter(e=>e!==null);return aFe(c,e=>a.get(e)?.authored.transition,r),c}function yFe(e,t){let n=new Map,r=new Map,i=new Map,a=[];for(let o of z_(e)){let s=o.get(mh),c=o.get(jh)??{},l=K_(o),u=o_(o),d=B_(e,o,l),f=d.end-d.start,p=cPe({id:s.key,name:s.name??s.id??`Scene`,width:fS(c.width,1920),height:fS(c.height,1080),fps:l,background:{type:`solid`,color:typeof u.fill==`string`?u.fill:`#000000`}});p.tracks=EPe(l_(o).flatMap(a=>{let o=a.get(mh);if(o.tag===`sequence`){let s=`track:${o.key}`;return i.set(s,o.key),[Kx({id:s,name:o.name??o.id??`Sequence`,clips:vFe(e,a,p,l,f,n,r,t)})]}let s=_Fe(e,a,p,l,f,n,r,t);return s?[s]:[]}),e=>MPe.has(n.get(e.id)?.tag??``)),p.duration=f,a.push(p)}return{document:{id:`higgsedit:${t.name}`,name:t.name,schemaVersion:2,scenes:a,activeSceneId:a[0]?.id??``,assets:[...r.values()],createdAt:0,modifiedAt:0},meta:n,sequences:i}}var bFe,xFe,fS,SFe,CFe,wFe=o((()=>{e_(),Tm(),Yx(),aS(),iS(),GPe(),XPe(),TPe(),iFe(),pFe(),hx(),bFe={x:`positionX`,y:`positionY`,width:`width`,height:`height`,rotation:`rotation`,scale:`scale`,scaleX:`scaleX`,scaleY:`scaleY`,opacity:`opacity`,cornerRadius:`radius`,fill:`color`,maskX:`maskX`,maskY:`maskY`,maskWidth:`maskWidth`,maskHeight:`maskHeight`},xFe=Object.fromEntries(Object.entries(bFe).map(([e,t])=>[t,e])),fS=(e,t)=>typeof e==`number`&&Number.isFinite(e)?e:t,SFe=e=>e===`image`?`image`:e===`audio`?`audio`:`video`,CFe={mp4:`video/mp4`,mov:`video/quicktime`,webm:`video/webm`,png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,webp:`image/webp`,gif:`image/gif`,mp3:`audio/mpeg`,wav:`audio/wav`,m4a:`audio/mp4`,aac:`audio/aac`}}));function pS(e,t,n){if(typeof t==`string`&&/f$/i.test(t.trim()))return`${Math.round(e*n)}f`;if(typeof t==`string`&&t.includes(`:`)){let n=t.split(`:`).length===3,r=Math.max(0,e),i=Math.floor(r/3600),a=Math.floor(r%3600/60),o=gS(r%60),s=(o<10?`0`:``)+String(o),c=String(a).padStart(2,`0`);return n||i>0?`${String(i).padStart(2,`0`)}:${c}:${s}`:`${c}:${s}`}return gS(e)}function TFe(e){let t=eS(e);return t?[t,...e.clips.filter(e=>e!==t)]:[...e.clips]}function EFe(e,t,n,r){let i=[...e.clips.filter(n=>t.placed.get(n.id)?.track===e.id).toSorted((e,t)=>n.get(e.id)-n.get(t.id)),...VFe(e.clips.filter(n=>t.placed.get(n.id)?.track!==e.id))];if(r&&rS(r,i[0])){let e=i.findIndex(e=>!rS(r,e));e>0&&i.unshift(...i.splice(e,1))}return i}function DFe(e,t,n){let r=new Map,i=new Map,a=new Map,o=new Map,s=(e,t,n,a)=>{for(let o of e)r.set(o.id,{clip:o,parent:t,scene:n,track:a}),o.kind===`group`&&(i.set(o.id,o.children.map(e=>e.id)),s(o.children,o.id,n,a))};for(let r of e.scenes){let e=[],c=new Map(n?.order.get(r.id)?.map((e,t)=>[e,t])),l=null;for(let u of r.tracks){a.set(u.id,u);let d=t.get(u.id);if(d){let t=VFe(u.clips);o.set(d,r.id),e.push(d),i.set(d,t.map(e=>e.id)),s(t,d,r.id,u.id),l=null}else if(u.clips.length>0){let t=n?EFe(u,n,c,l):TFe(u);e.push(...t.map(e=>e.id)),s(t,r.id,r.id,u.id),l=t}}i.set(r.id,e)}return{placed:r,order:i,tracks:a,sequences:o}}function OFe(e,t){let n=t.split(`/`).length,r=[];for(let t of e){let e=t.split(`/`),i=e.length>n?e.slice(0,n).join(`/`):t,a=r.at(-1);if(a?.key===i)a.members.push(t);else if(r.some(e=>e.key===i))throw new mS(`"${yS(i)}" is one component; its layers move together`,t);else r.push({key:i,members:[t]})}return r}function kFe(e){let t=[],n=Array.from({length:e.length},()=>-1);for(let r=0;r<e.length;r++){let i=0,a=t.length;for(;i<a;){let n=i+a>>1;e[t[n]]<e[r]?i=n+1:a=n}i>0&&(n[r]=t[i-1]),t[i]=r}let r=new Set;for(let e=t.at(-1)??-1;e>=0;e=n[e])r.add(e);return r}function AFe(e,t){let n={...t.unmappedAnimate},r=e.transform.anchorX*e.size.width+t.boxOffset.x,i=e.transform.anchorY*e.size.height+t.boxOffset.y;for(let a of cS(e)){let o=xFe[a.property];if((!o||a.effectId!==null||a.gradientStopIndex!==null)&&vS(`${a.property} animation`,e.id),t.tag===`adjustmentLayer`&&!JFe.has(o)&&vS(`${a.property} animation on an adjustment layer`,e.id),o===`fill`&&(t.tag===`surface`||t.tag===`html`))throw new mS(YFe(t.tag),e.id,`animations`);n[o]=a.keyframes.map(n=>{let a=FPe(n.easing);typeof a==`object`&&vS(a.refused,e.id);let s=mFe(o,{x:r,y:i},t.boxOffset),c=typeof n.value==`number`?gS(n.value-s):n.value;return a===`linear`?[gS(n.time),c]:[gS(n.time),c,a]})}return n}function jFe(e,t,n,r,i){let a=n.boxOffset[r];return UFe(n,i)?WFe(e,t)?e.size[i]?a*t.size[i]/e.size[i]:a:e.size[i]===t.size[i]?a:0:a}function MFe(e,t,n){let r=[],i=(e,t)=>r.push({op:`set-prop`,name:e,value:t}),a=t.id,o=e,s=t,c=e=>vS(e,a),l=!1;for(let u of new Set([...Object.keys(o),...Object.keys(s)]))if(!(KFe.has(u)||_S(o[u],s[u]))){if(n.tag===`sequence`&&u!==`name`&&vS(`${u} of a <sequence>`,a),n.tag===`adjustmentLayer`&&qFe.has(u)&&vS(`${u} on an adjustment layer`,a),(n.tag===`surface`||n.tag===`html`)&&XFe.has(u))throw new mS(YFe(n.tag),a,u);switch(u){case`name`:i(`name`,t.name);break;case`transform`:case`size`:{if(u===`size`&&!_S(o.transform,s.transform))break;let r=t.transform,c=e.transform;for(let e of[`skewX`,`skewY`,`flipX`,`flipY`])r[e]!==c[e]&&vS(e,a);let[l,d]=[HFe(e,n.boxOffset),HFe(t,n.boxOffset)];if(Xx(e)&&Xx(t))for(let[e,r]of[[`x`,`offsetX`],[`y`,`offsetY`]]){let a=d[e]-l[e];if(!(Math.abs(a)<=hS)){if(n.authored[e]!==void 0)i(e,gS(d[e]));else{let e=gS(t.captions[r]+a);i(r,e===0?null:e)}}}else for(let[r,a]of[[`x`,`width`],[`y`,`height`]]){let o=d[r]+n.boxOffset[r]-jFe(e,t,n,r,a);Math.abs(l[r]-o)>hS&&i(r,gS(o))}r.rotation!==c.rotation&&i(`rotation`,gS(r.rotation)),r.anchorX!==c.anchorX&&i(`anchorX`,gS(r.anchorX)),r.anchorY!==c.anchorY&&i(`anchorY`,gS(r.anchorY)),(r.scaleX!==c.scaleX||r.scaleY!==c.scaleY)&&(n.authored.scale!==void 0&&n.authored.scaleX===void 0&&n.authored.scaleY===void 0&&r.scaleX===r.scaleY?i(`scale`,gS(r.scaleX)):(r.scaleX!==c.scaleX&&i(`scaleX`,gS(r.scaleX)),r.scaleY!==c.scaleY&&i(`scaleY`,gS(r.scaleY))));for(let r of[`width`,`height`])e.size[r]!==t.size[r]&&!(UFe(n,r)&&WFe(e,t))&&i(r,gS(t.size[r]));break}case`opacity`:i(`opacity`,gS(t.opacity));break;case`locked`:i(`locked`,t.locked?!0:null);break;case`constrainX`:i(`constrainX`,t.constrainX&&t.constrainX!==`left`?t.constrainX:null);break;case`constrainY`:i(`constrainY`,t.constrainY&&t.constrainY!==`top`?t.constrainY:null);break;case`hidden`:i(`hidden`,t.hidden?!0:null);break;case`timeRange`:{if(n.tag===`captions`){r.push(...NFe(e,t,n));break}let i=t.timeRange.start,o=i+t.timeRange.duration,s=i-e.timeRange.start,c={op:`retime`},l=e.timeRange.start+e.timeRange.duration;if(typeof n.authored.syncTo==`string`){let i=(t.kind===`media`||t.kind===`audio`)&&e.kind===t.kind?(t.trim.start-e.trim.start)/t.speed:0;if(Math.abs(s-i)>hS)throw new mS(`${a} is placed by syncTo="${n.authored.syncTo}"; remove syncTo to move it by hand`,a,`timeRange`);Math.abs(o-l)>hS&&r.push({op:`retime`,end:pS(o,n.timing.end??n.timing.start,n.fps)});break}Math.abs(s)>hS&&(c.start=pS(i,n.timing.start??n.timing.end,n.fps));let u;if(n.timing.end!==void 0)u=Math.abs(o-l)>hS;else if(n.openEnded)u=Math.abs(t.timeRange.duration-e.timeRange.duration)>hS;else if(n.tag===`group`)u=Math.abs(t.timeRange.duration-e.timeRange.duration)>hS;else if(n.mediaDuration!==void 0){let[e,r]=t.kind===`media`||t.kind===`audio`?[t.trim.start,t.speed]:[0,1];u=Math.abs(o-(i+(n.mediaDuration-e)/r))>hS}else u=Math.abs(o-l)>hS;u&&(c.end=pS(o,n.timing.end??n.timing.start,n.fps)),(c.start!==void 0||c.end!==void 0)&&r.push(c);break}case`trim`:if(t.kind!==`media`&&t.kind!==`audio`||e.kind!==t.kind)break;Math.abs(t.trim.start-e.trim.start)>hS&&i(`sourceIn`,pS(t.trim.start,n.timing.sourceIn??n.timing.start,n.fps));break;case`animations`:_S(cS(e),cS(t))||i(`animate`,AFe(t,n)),l=!0;break;case`effects`:l=!0;break;case`blendMode`:i(`blend`,t.blendMode===`normal`?null:t.blendMode);break;case`mask`:i(`mask`,PFe(t.mask,n.boxOffset,a));break;case`presetAnimations`:{let r=n.tag===`video`||n.tag===`audio`,o=e=>vS(e,a),s=n.tag===`text`,[c,l]=[qPe(GFe(e),r,o,s),qPe(GFe(t),r,o,s)];for(let e of[`enter`,`exit`,`fadeIn`,`fadeOut`])_S(c[e],l[e])||i(e,l[e]);break}case`text`:if(n.tag===`captions`)throw new mS(`caption text comes from its transcript: edit the transcript file or point src at another`,a,`text`);r.push({op:`set-text`,text:String(s.text)});break;case`captions`:if(!Xx(e)||!Xx(t))return vS(u,a);try{r.push(...CPe(e.captions,t.captions))}catch(e){throw e instanceof Qx?new mS(e.reason,a,e.field):e}break;case`fontSize`:case`fontFamily`:case`lineHeight`:case`align`:case`fontWeight`:case`volume`:case`speed`:case`preservePitch`:i(u,typeof s[u]==`number`?gS(s[u]):s[u]);break;case`muted`:i(`muted`,s.muted===!0||null);break;case`fill`:i(`fill`,HPe(s.fill,c));break;case`cornerRadius`:{let e=s.cornerRadius;e.mixed&&vS(`per-corner radius`,a),i(`cornerRadius`,gS(e.uniform));break}case`assetId`:i(`src`,String(s.assetId));break;default:{let e=t.kind===`text`?eFe(u,t):void 0;e||vS(u,a),r.push(...e)}}}return l&&(n.tag===`audio`&&t.effects.length&&c(`effects on audio`),r.push(...BPe(e,t,c))),r}function NFe(e,t,n){let r=t.id,i=t.timeRange.start,a=i+t.timeRange.duration,o=i-e.timeRange.start,s=e.timeRange.start+e.timeRange.duration,c=Gh(n.timing.sourceIn,n.fps)??0,l=[],u={op:`retime`};Math.abs(o)>hS&&(u.start=pS(i,n.timing.start??n.timing.end,n.fps));let d=Math.abs(o)>hS&&Math.abs(a-s)<=hS;if(d&&(c+=o,c<-1e-6))throw new mS(`captions cannot start before their transcript (sourceIn below 0)`,r,`timeRange`);let f;return f=n.timing.end===void 0?n.captionStop===void 0?Math.abs(t.timeRange.duration-e.timeRange.duration)>hS:Math.abs(a-(i+n.captionStop-c))>hS:Math.abs(a-s)>hS,f&&(u.end=pS(a,n.timing.end??n.timing.start,n.fps)),(u.start!==void 0||u.end!==void 0)&&l.push(u),d&&l.push({op:`set-prop`,name:`sourceIn`,value:pS(Math.max(0,c),n.timing.sourceIn??n.timing.start,n.fps)}),l}function PFe(e,t,n){if(!e)return null;if(e.enabled||vS(`disabled mask`,n),e.src){let t={src:e.src};return e.feather&&(t.feather=gS(e.feather)),e.invert&&(t.invert=!0),t}let r={shape:e.shape,x:gS(e.x+t.x),y:gS(e.y+t.y),width:gS(e.width),height:gS(e.height)};return e.rotation&&(r.rotation=gS(e.rotation)),e.cornerRadius&&(r.cornerRadius=gS(e.cornerRadius)),e.feather&&(r.feather=gS(e.feather)),e.invert&&(r.invert=!0),e.shape===`path`&&(r.d=e.d??``),r}function FFe(e,t,n){if(e.kind===`group`&&e.children.length)throw new mS(`inserting a group with children is not supported yet`,e.id);if(Xx(e))throw new mS(`inserting captions from the editor is not supported yet; copy the <captions> element in the source`,e.id);if(e.kind===`rect`&&e.drawnBy)throw new mS(`${e.drawnBy===`html`?`an <html>`:`a <surface>`} is drawn by code: copy the element in the source to duplicate it`,e.id);let r={},i=e.transform;if(e.kind===`adjustment`)return{op:`insert`,tag:`adjustmentLayer`,props:IFe(e,t),...n?{before:n}:{}};e.kind!==`audio`&&(r.x=gS(i.x-i.anchorX*e.size.width),r.y=gS(i.y-i.anchorY*e.size.height),(e.kind!==`text`||e.size.width>0)&&(r.width=gS(e.size.width),r.height=gS(e.size.height)),e.opacity!==1&&(r.opacity=gS(e.opacity)),i.rotation&&(r.rotation=gS(i.rotation))),r.start=gS(e.timeRange.start);let a,o;switch(e.kind){case`rect`:a=`rect`,r.fill=HPe(e.fill,t=>vS(t,e.id)),e.cornerRadius.uniform&&(r.cornerRadius=gS(e.cornerRadius.uniform)),r.end=gS(e.timeRange.start+e.timeRange.duration);break;case`text`:a=`text`,o=e.text,r.fontSize=gS(e.fontSize),r.fill=HPe(e.fill,t=>vS(t,e.id)),e.fontFamily!==`sans-serif`&&(r.fontFamily=e.fontFamily),e.fontWeight!==400&&(r.fontWeight=e.fontWeight),e.align!==`left`&&(r.align=e.align),e.italic&&(r.fontStyle=`italic`),e.letterSpacing&&(r.letterSpacing=gS(e.letterSpacing)),e.textCase&&e.textCase!==`original`&&(r.textCase=e.textCase),e.textBaseline&&e.textBaseline!==`top`&&(r.textBaseline=e.textBaseline),e.ranges?.length&&vS(`inserting a text with ranges`,e.id),r.end=gS(e.timeRange.start+e.timeRange.duration);break;case`media`:{let n=t.assets.find(t=>t.id===e.assetId);a=n?.kind===`image`?`image`:`video`,r.src=e.assetId,e.trim.start&&(r.sourceIn=gS(e.trim.start)),a===`video`&&(Object.assign(r,ZFe(e)),e.volume!==1&&(r.volume=gS(e.volume)),e.muted&&(r.muted=!0));let i=n?.duration;(a===`image`||i==null||Math.abs(e.timeRange.duration-(i-e.trim.start)/e.speed)>hS)&&(r.end=gS(e.timeRange.start+e.timeRange.duration));break}case`audio`:{a=`audio`,r.src=e.assetId,e.trim.start&&(r.sourceIn=gS(e.trim.start)),e.volume!==1&&(r.volume=gS(e.volume)),e.muted&&(r.muted=!0),Object.assign(r,ZFe(e));let n=t.assets.find(t=>t.id===e.assetId)?.duration;(n==null||Math.abs(e.timeRange.duration-(n-e.trim.start)/e.speed)>hS)&&(r.end=gS(e.timeRange.start+e.timeRange.duration));break}case`group`:a=`group`;break;default:return vS(`${e.kind} clips`,e.id)}return e.effects.length&&(a===`audio`&&vS(`effects on audio`,e.id),r.effects=zPe(e,t=>vS(t,e.id))),e.mask&&((a===`audio`||a===`group`)&&vS(`a mask on ${a===`audio`?`audio`:`a group`}`,e.id),!e.mask.src&&a===`text`&&e.size.width<=0&&vS(`a shape mask on unsized text`,e.id),r.mask=PFe(e.mask,{x:0,y:0},e.id)),{op:`insert`,tag:a,props:r,...o===void 0?{}:{text:o},...n?{before:n}:{}}}function IFe(e,t){let n=t.scenes.find(t=>t.tracks.some(t=>t.clips.includes(e))),r=e.transform,{width:i,height:a}=e.size,o={},s=r.x-r.anchorX*i,c=r.y-r.anchorY*a;return Math.abs(s)>hS&&(o.x=gS(s)),Math.abs(c)>hS&&(o.y=gS(c)),(i!==n?.width||a!==n?.height)&&Object.assign(o,{width:gS(i),height:gS(a)}),r.anchorX!==.5&&(o.anchorX=gS(r.anchorX)),r.anchorY!==.5&&(o.anchorY=gS(r.anchorY)),r.rotation&&(o.rotation=gS(r.rotation)),(r.scaleX!==1||r.scaleY!==1)&&Object.assign(o,r.scaleX===r.scaleY?{scale:gS(r.scaleX)}:{scaleX:gS(r.scaleX),scaleY:gS(r.scaleY)}),e.hidden&&(o.hidden=!0),e.locked&&(o.locked=!0),e.constrainX&&e.constrainX!==`left`&&(o.constrainX=e.constrainX),e.constrainY&&e.constrainY!==`top`&&(o.constrainY=e.constrainY),o.start=gS(e.timeRange.start),o.end=gS(e.timeRange.start+e.timeRange.duration),o}function LFe(e,t){let n=[];return e.width!==t.width&&n.push({op:`set-prop`,name:`width`,value:t.width}),e.height!==t.height&&n.push({op:`set-prop`,name:`height`,value:t.height}),e.fps!==t.fps&&n.push({op:`set-prop`,name:`fps`,value:t.fps}),_S(e.background,t.background)||n.push({op:`set-prop`,name:`fill`,value:BFe(t.background,t.id,`scene background`)}),e.name!==t.name&&n.push({op:`set-prop`,name:`name`,value:t.name}),_S(e.markers,t.markers)||vS(`markers`),(e.x!==t.x||e.y!==t.y)&&vS(`scene canvas position`),n}function RFe(e,t,n,r){for(let[i,a]of t){let t=e.get(i);if(t){for(let e of[`solo`,`volume`,`mode`])t[e]!==a[e]&&vS(`track ${e}`);for(let e of[`hidden`,`locked`,`muted`]){if(t[e]===a[e])continue;let i=e===`muted`?a.clips.filter(e=>MPe.has(n.get(e.id)?.tag??``)):a.clips;a.clips.length>0&&i.length===0&&vS(`track muted (no clip on it has sound)`);for(let t of i)r.push({key:t.id,edit:{op:`set-prop`,name:e,value:a[e]?!0:null}})}}}}function zFe(e,t){let n=e.document,r;try{r=Ux(n,t)}catch(e){return{ok:!1,reason:e.message}}try{let t=[],i=e.sequences??new Map,a=DFe(n,i),o=DFe(r,i,a),s=(e,t)=>e.placed.has(t)||e.sequences.has(t),c=(e,t)=>e.placed.get(t)?.parent??e.sequences.get(t);(n.scenes.length!==r.scenes.length||n.scenes.some((e,t)=>e.id!==r.scenes[t]?.id))&&vS(`adding, removing or reordering scenes`),n.scenes.forEach((e,n)=>{for(let i of LFe(e,r.scenes[n]))t.push({key:e.id,edit:i})}),RFe(a.tracks,o.tracks,e.meta,t);for(let[n,{clip:r}]of o.placed){let i=a.placed.get(n);if(!i)continue;let o=e.meta.get(n);if(!o)throw new mS(`no source element for clip ${n}`,n);for(let e of MFe(i.clip,r,o))t.push({key:o.key,edit:e});r.kind===`text`&&i.clip.kind===`text`&&!_S(i.clip.ranges,r.ranges)&&t.push(...tFe(o.key,i.clip.ranges,r.ranges,e=>vS(e,n)))}let[l,u]=[sFe(n),sFe(r)];for(let n of o.placed.keys()){if(!a.placed.has(n)||fFe(l.get(n),u.get(n)))continue;let r=e.meta.get(n),i=cFe(r.authored.transition,u.get(n),r.fps,(e,t)=>pS(e,t,r.fps),e=>vS(e,n));t.push({key:r.key,edit:{op:`set-prop`,name:`transition`,value:i}})}for(let e of[...a.placed.keys(),...a.sequences.keys()]){if(s(o,e))continue;let n=c(a,e);(!s(a,n)||s(o,n))&&t.push({key:e,edit:{op:`remove`}})}for(let[e,n]of o.order){let i=OFe(n,e),l=OFe(a.order.get(e)??[],e).map(e=>e.key);if(_S(i.map(e=>e.key),l))continue;let u=e=>e.members.some(e=>s(a,e)),d=e=>o.placed.get(e)?.track!==a.placed.get(e)?.track,f=t=>t.members.every(t=>c(a,t)===e&&!d(t)),p=i.filter(u),m=p.flatMap((e,t)=>f(e)?[t]:[]),h=kFe(m.map(e=>l.indexOf(p[e].key))),g=new Set([...h].map(e=>m[e]));for(let n=p.length-1;n>=0;n--){if(g.has(n))continue;let r=p[n+1];t.push({key:p[n].key,edit:{op:`move`,parent:e,...r?{before:yS(r.key)}:{}}})}for(let n=0;n<i.length;n++){let a=i[n];if(u(a))continue;let s=a.members[0];o.placed.has(s)||vS(`adding a sequence`);let c=i.slice(n+1).find(u);t.push({key:e,edit:FFe(o.placed.get(s).clip,r,c&&yS(c.key))})}}return{ok:!0,edits:t,document:r}}catch(e){if(e instanceof mS)return{ok:!1,reason:e.reason,...e.clipId?{clipId:e.clipId}:{},...e.field?{field:e.field}:{}};throw e}}var mS,hS,gS,_S,vS,BFe,VFe,yS,HFe,UFe,WFe,GFe,KFe,qFe,JFe,YFe,XFe,ZFe,QFe=o((()=>{Yx(),TPe(),iS(),GPe(),XPe(),iFe(),aS(),wFe(),pFe(),e_(),mS=class extends Error{reason;clipId;field;constructor(e,t,n){super(e),this.reason=e,this.clipId=t,this.field=n}},hS=1e-6,gS=e=>Math.round(e*1e3)/1e3,_S=(e,t)=>JSON.stringify(e)===JSON.stringify(t),vS=(e,t)=>{throw new mS(`not in higgsedit's element vocabulary yet: ${e}`,t,e)},BFe=(e,t,n)=>(e.type!==`solid`&&vS(`${e.type} ${n}`,t),e.color),VFe=e=>[...e].toSorted((e,t)=>e.timeRange.start-t.timeRange.start),yS=e=>e.split(`/`).at(-1),HFe=(e,t)=>({x:e.transform.x-e.transform.anchorX*e.size.width-t.x,y:e.transform.y-e.transform.anchorY*e.size.height-t.y}),UFe=(e,t)=>e.tag===`text`&&e.authored[t]===void 0,WFe=(e,t)=>e.kind===`text`&&t.kind===`text`&&e.fontSize!==t.fontSize,GFe=e=>e.presetAnimations.filter(e=>!lFe(e)),KFe=new Set([`id`,`kind`,`children`,`origin`]),qFe=new Set([`opacity`,`blendMode`,`mask`,`effects`]),JFe=new Set([`x`,`y`,`width`,`height`,`rotation`,`scale`,`scaleX`,`scaleY`]),YFe=e=>e===`html`?`an <html>'s picture is its HTML children, drawn by code: edit them in the source`:`a <surface>'s picture is drawn by code into its canvas (ref): edit that code in the source`,XFe=new Set([`fill`,`stroke`,`drawnBy`]),ZFe=e=>({...e.speed===1?{}:{speed:gS(e.speed)},...e.preservePitch?{}:{preservePitch:!1}})})),$Fe,eIe,tIe=o((()=>{Yx(),vPe(),bPe(),QFe(),$Fe={canUndo:!1,canRedo:!1,undoName:null,redoName:null},eIe=class extends pPe{options;projection=null;run=null;timer;chain=Promise.resolve();server=$Fe;constructor(e){super(),this.options=e}load(e,t=`remote`){let n=this.projection===null;this.projection=e,n?this.open(e.document):this.replace(e.document,t)}current(){return this.projection}undoState(){return this.server}setServerUndo(e){this.server=e,this.emit({type:`history`,state:e})}execute(e){if(!this.projection)throw Error(`no project is mounted`);e=this.withConstraints(e),this.run&&(e.coalesceKey===null||this.run.key!==e.coalesceKey)&&this.flush();let t=this.run?.base??{document:this.snapshot()??this.projection.document,meta:this.projection.meta,...this.projection.sequences?{sequences:this.projection.sequences}:{}},n=[...this.run?.ops??[],...e.ops],r=zFe(t,n);if(!r.ok){this.options.onRefused?.({reason:r.reason,...r.clipId?{clipId:r.clipId}:{}});return}this.run={key:e.coalesceKey,name:e.name,base:t,ops:n},super.execute(e,`local`);let i=this.options.world(),a=[];for(let{key:e,edit:t}of r.edits)yPe(i,e,t)&&a.push(e);a.length&&this.options.onPatched?.(a),clearTimeout(this.timer),e.coalesceKey===null?this.flush():this.timer=setTimeout(()=>this.flush(),this.options.commitDelayMs??250)}withConstraints(e){let t=this.snapshot();if(!t||!this.projection)return e;let n;try{n=Ux(t,e.ops)}catch{return e}let r=gPe(t,n,this.projection.meta);return r.length?{...e,ops:[...e.ops,...r]}:e}flush(){clearTimeout(this.timer);let e=this.run;if(this.run=null,!e)return this.chain;let t=zFe(e.base,e.ops);return!t.ok||t.edits.length===0||(this.chain=this.chain.then(async()=>{try{let n=await this.options.transport.edit(e.name,t.edits);if(this.setServerUndo(n.undo),!n.ok){let e=n.results.find(e=>!e.ok)?.refused;this.options.onRefused?.({reason:e?.reason??`the edit was refused`,...e?.at?{at:e.at}:{},...e?.source?{source:e.source}:{}}),this.options.onRevert?.()}}catch(e){this.options.onRefused?.({reason:`could not reach higgsedit dev: ${e.message}`}),this.options.onRevert?.()}})),this.chain}undo(){return this.history(`undo`),this.server.canUndo}redo(){return this.history(`redo`),this.server.canRedo}history(e){return this.flush(),this.chain=this.chain.then(async()=>{let t=await this.options.transport[e]();this.setServerUndo(t.undo),!t.ok&&t.reason&&this.options.onRefused?.({reason:t.reason})}),this.chain}}})),bS,xS,nIe=o((()=>{Nm(),bS=class{value;equals;listeners=new Set;constructor(e,t=Object.is){this.value=e,this.equals=t}get(){return this.value}set(e){if(!this.equals(this.value,e)){this.value=e;for(let t of Array.from(this.listeners))t(e)}}subscribe(e){return this.listeners.add(e),km(()=>this.listeners.delete(e))}},xS=(e,t)=>{let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.is(e[n],t[n])||Array.isArray(e[n])&&JSON.stringify(e[n])===JSON.stringify(t[n]))}})),rIe,iIe,aIe=o((()=>{Tm(),Nm(),nIe(),rIe={now:()=>performance.now(),request:e=>requestAnimationFrame(e),cancel:e=>cancelAnimationFrame(e)},iIe=class{source;publish;scheduler;selection=new bS({clipIds:[],sceneId:null,enteredGroupId:null},xS);currentTime=new bS(0);playing=new bS(!1);activeSceneId=new bS(null);activeTool=new bS(`move`);camera=new bS({zoom:1,panX:0,panY:0},xS);timelineView=new bS({pxPerSecond:80,scrollX:0},xS);clipboard=new bS([]);loop=new bS(!1);workArea=new bS(null,(e,t)=>e===t||!!e&&!!t&&xS(e,t));speed=new bS(1);previewQuality=new bS(1);frameListeners=new Set;raf=null;renderQueued=!1;lastWall=0;scale=1;clock;constructor(e,t=()=>{},n=rIe){this.source=e,this.publish=t,this.scheduler=n}setClock(e){this.clock?.stop(),this.clock=e,this.playing.get()&&e?.start(this.currentTime.get())}setSource(e){this.source=e,this.requestRender()}setSelection(e){this.selection.set({...this.selection.get(),...e});let t=this.selection.get();this.publish(Ype,{clipIds:[...t.clipIds],sceneId:t.sceneId,enteredGroupId:t.enteredGroupId})}clearSelection(){this.setSelection({clipIds:[],enteredGroupId:null})}setActiveTool(e){this.activeTool.set(e),this.publish(Xpe,{tool:e})}setCamera(e){this.camera.set(e)}setTimelineView(e){this.timelineView.set({...this.timelineView.get(),...e})}setClipboard(e){this.clipboard.set(e),this.publish(Zpe,{count:e.length})}setActiveScene(e){this.activeSceneId.set(e),this.selection.get().sceneId===null&&this.setSelection({sceneId:e})}setPreviewQuality(e){e>0&&e<=1&&this.previewQuality.set(e)}setLoop(e){this.loop.set(e)}setWorkArea(e){if(!e)return this.workArea.set(null);let{duration:t,fps:n}=this.source.sceneSpan(this.activeSceneId.get()),r=e=>Math.min(Math.max(0,e),Math.max(0,t)),[i,a]=[r(Math.min(e.start,e.end)),r(Math.max(e.start,e.end))];this.workArea.set(a-i<1/n?null:{start:i,end:a})}bounds(){let e=this.workArea.get(),{duration:t}=this.source.sceneSpan(this.activeSceneId.get());return e?[e.start,e.end]:[0,t]}play(){this.playAt(1)}playAt(e){if(!Number.isFinite(e)||e===0)return;let t=this.playing.get();this.speed.set(e);let[n,r]=this.bounds(),i=this.currentTime.get();e>0&&(i>=r-1e-6||i<n)&&this.currentTime.set(n),e<0&&(i<=n+1e-6||i>r)&&this.currentTime.set(r),this.lastWall=this.scheduler.now(),e===1?this.clock?.start(this.currentTime.get()):this.clock?.stop(),!t&&(this.playing.set(!0),this.publish(Kpe,{time:this.currentTime.get()}),this.tick())}pause(){this.playing.get()&&(this.playing.set(!1),this.speed.set(1),this.raf!==null&&this.scheduler.cancel(this.raf),this.raf=null,this.clock?.stop(),this.publish(qpe,{time:this.currentTime.get()}),this.requestRender())}togglePlayback(){this.playing.get()?this.pause():this.play()}seek(e){let{duration:t}=this.source.sceneSpan(this.activeSceneId.get());this.currentTime.set(Math.min(Math.max(0,e),Math.max(0,t))),this.playing.get()&&this.speed.get()===1&&this.clock?.start(this.currentTime.get()),this.publish(Jpe,{time:this.currentTime.get()}),this.requestRender()}onFrame(e){return this.frameListeners.add(e),this.requestRender(),km(()=>this.frameListeners.delete(e))}requestRender(){this.playing.get()||this.renderQueued||(this.renderQueued=!0,this.scheduler.request(()=>{this.renderQueued=!1,this.emitFrame()}))}setPreviewScale(e){e>0&&Number.isFinite(e)&&(this.scale=e),this.requestRender()}tick(){this.raf=this.scheduler.request(()=>{if(!this.playing.get())return;let e=this.scheduler.now(),t=this.speed.get(),[n,r]=this.bounds(),i=this.currentTime.get(),a=i+(e-this.lastWall)/1e3*t,o=t===1?Math.max(i,this.clock?.time()??a):a;this.lastWall=e;let s=t>0?o>=r:o<=n;if(s&&this.loop.get()){let e=t>0?n:r;this.currentTime.set(e),t===1&&this.clock?.start(e)}else if(s){this.currentTime.set(t>0?r:n),this.emitFrame(),this.pause();return}else this.currentTime.set(o);this.emitFrame(),this.tick()})}emitFrame(){if(this.frameListeners.size===0)return;let{start:e}=this.source.sceneSpan(this.activeSceneId.get()),t=this.currentTime.get(),n=this.source.draw(e+t,this.playing.get(),this.scale);if(n)try{for(let e of Array.from(this.frameListeners))e(n,t)}finally{this.source.release(n)}}dispose(){this.raf!==null&&this.scheduler.cancel(this.raf),this.clock?.stop(),this.frameListeners.clear()}}}));async function SS(e,t){let n;try{n=await e.json()}catch{throw Error(`${t} returned invalid JSON (${e.status})`)}if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`${t} returned an invalid response`);let r=n;if(!e.ok)throw Error(typeof r.error==`string`?r.error:`${t} failed (${e.status})`);return r}function oIe(e){let t=t=>{let n=e[t];if(!Array.isArray(n)||!n.every(e=>typeof e==`string`))throw Error(`invalid native render capabilities`);return n},{sampleRates:n,audioOnly:r}=e;if(!Array.isArray(n)||!n.every(e=>typeof e==`number`&&Number.isFinite(e)&&e>0)||typeof r!=`boolean`)throw Error(`invalid native render capabilities`);return{containers:t(`containers`),videoCodecs:t(`videoCodecs`),audioCodecs:t(`audioCodecs`),sampleRates:n,audioOnly:r}}function sIe(e,t){return t.containers.includes(e.container)&&(e.video?t.videoCodecs.includes(e.video.codec):t.audioOnly&&e.audio!==null)&&(e.audio===null||t.audioCodecs.includes(e.audio.codec)&&t.sampleRates.includes(e.audio.sampleRate))}function cIe(e,t=()=>null){let n,r=()=>n??=fetch(`${e}/api/render/capabilities`).then(e=>SS(e,`render capabilities`)).then(oIe).catch(e=>{throw n=void 0,e});return{probe:async e=>sIe(e,await r()),start(n){let i={...n.spec,video:n.spec.video&&{...n.spec.video},audio:n.spec.audio&&{...n.spec.audio}},a=n.sceneId??t(),o=n.range&&{...n.range},s=n.onProgress,c=!1,l=null,u,d,f=()=>d??=fetch(`${e}/api/render/cancel?${new URLSearchParams({id:String(l)})}`,{method:`POST`}).then(e=>SS(e,`render cancellation`)).then(()=>{}).catch(e=>{u=e instanceof Error?e:Error(String(e))});return{result:(async()=>{if(!sIe(i,await r()))throw Error(`native export does not support ${i.container}/${i.video?.codec??`audio-only`}/${i.audio?.codec??`silent`}`);if(c)throw CS();let t=await SS(await fetch(`${e}/api/render`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({spec:i,...a===null?{}:{sceneId:a},fileName:i.fileName??`export.mp4`,...o?{from:o.start,to:o.end}:{}})}),`render start`);if(typeof t.id!=`string`||!/^[1-9]\d*$/.test(t.id))throw Error(`render start returned an invalid job id`);for(l=t.id,c&&await f();;){if(u)throw u;await new Promise(e=>setTimeout(e,lIe));let t=await fetch(`${e}/api/render?${new URLSearchParams({id:l})}`).then(e=>SS(e,`render status`));if(u)throw u;if(typeof t.total==`number`&&Number.isFinite(t.total)&&t.total>0&&typeof t.done==`number`&&Number.isFinite(t.done)&&s?.(Math.max(0,Math.min(1,t.done/t.total)),`render`),t.state===`done`){if(c)throw CS();if(typeof t.out!=`string`||!t.out.startsWith(`renders/`)||t.out.includes(`\\`)||t.out.split(`/`).some(e=>!e||e===`.`||e===`..`))throw Error(`render status returned an invalid output path`);return s?.(1,`finalize`),{kind:`uri`,uri:`${e}/project/${t.out.split(`/`).map(encodeURIComponent).join(`/`)}`}}if(t.state===`cancelled`)throw CS();if(t.state===`failed`)throw Error(typeof t.error==`string`?t.error:`render failed`);if(t.state!==`running`)throw Error(`render status returned an unknown job state`)}})(),cancel(){c=!0,l&&f()}}}}}var lIe,CS,uIe=o((()=>{Tm(),lIe=400,CS=()=>Object.assign(Error(`export cancelled`),{name:tme})}));function dIe(){let e=new pIe(`frame`),t=[],n=!1,r=e=>{let r=e,i=t.reduce((e,t)=>e+t.width*t.height,r.width*r.height);!n&&t.length<3&&i<=8294400?t.push(r):(r.width=0,r.height=0)};return{fromNative:(t,n)=>e.add(t,n,e=>e.close?.()),fromCanvas:(t,n)=>e.add(t,{width:t.width,height:t.height,timestamp:n,...Rpe}),render(n,i,a,o){let s=t.pop()??document.createElement(`canvas`);s.width!==n&&(s.width=n),s.height!==i&&(s.height=i);try{let t=o(s.getContext(`2d`));return e.add(s,{width:n,height:i,timestamp:a,...t,...Rpe},r)}catch(e){throw r(s),e}},dispose(){n=!0;for(let e of t)e.width=0,e.height=0;t.length=0},toNative:t=>e.get(t),info:t=>e.info(t),retain:t=>e.retain(t),release:t=>e.release(t)}}function fIe(){let e=new pIe(`audio`);return{fromPlanar:(t,n)=>e.add(t,{sampleRate:n,channels:t.length,frames:t[0]?.length??0}),toPlanar:t=>e.get(t),info:t=>e.info(t),retain:t=>e.retain(t),release:t=>e.release(t)}}var pIe,mIe=o((()=>{Tm(),pIe=class{kind;slots=[];free=[];constructor(e){this.kind=e}add(e,t,n){let r=this.free.pop()??this.slots.push({gen:0,value:null,info:null,refs:0})-1,i=this.slots[r];return i.value=e,i.info=t,i.refs=1,n?i.free=n:delete i.free,{kind:this.kind,index:r,gen:i.gen}}slot(e){let t=this.slots[e.index];return t&&t.gen===e.gen&&t.refs>0?t:null}get(e){return this.slot(e)?.value??null}info(e){return this.slot(e)?.info??null}retain(e){let t=this.slot(e);t&&t.refs++}release(e){let t=this.slot(e);t&&(--t.refs>0||(t.value!==null&&t.free?.(t.value),t.value=null,t.info=null,t.gen++,this.free.push(e.index)))}}}));async function hIe(e,t){t?.signal.throwIfAborted();let n=new MAe(e.id,e.uri),r=()=>n.dispose();t?.signal.addEventListener(`abort`,r,{once:!0});try{let{duration:e}=await n.ready;t?.signal.throwIfAborted();let r=Math.max(0,Math.min(t?.start??0,e)),i=Math.max(r,Math.min(t?.end??e,e)),a=i-r,o=a>0?Math.min(wS,t?.peaksPerSecond??wS,gIe/a):wS,s=new Float32Array(Math.min(gIe,Math.ceil(a*o))),c={peaks:s,peaksPerSecond:o,duration:e,start:r},l=0,u=-1/0;for await(let{buffer:e,timestamp:a}of n.chunks(r,i)){t?.signal.throwIfAborted();let n=e.sampleRate;for(let t=0;t<e.numberOfChannels;t++){let i=e.getChannelData(t);for(let e=0;e<i.length;e++){let t=Math.floor((a-r+e/n)*o);if(t<0||t>=s.length)continue;let c=Math.abs(i[e]);c>s[t]&&(s[t]=c),c>l&&(l=c)}}performance.now()-u>=250&&(u=performance.now(),t?.onProgress?.({...c,gain:l>0?1/l:1}))}if(t?.signal.throwIfAborted(),!t&&l>0){for(let e=0;e<s.length;e++)s[e]/=l;return{...c,gain:1}}return{...c,gain:l>0?1/l:1}}catch(e){if(t?.signal.throwIfAborted(),e instanceof jAe)return null;throw e}finally{t?.signal.removeEventListener(`abort`,r),n.dispose()}}var wS,gIe,_Ie,vIe=o((()=>{hx(),wS=100,gIe=6e3,_Ie={probe:e=>+(e.kind===`audio`||e.kind===`video`),ranges:!0,peaks:hIe}}));function yIe(e,t,n,r={}){let i=e.scenes.findIndex(e=>e.id===t),a=e.scenes[i];if(!a)return null;let o=r.range??n.timeRange,s={...n,timeRange:o},c=a.tracks,l=r.preferredTrackId?c.findIndex(e=>e.id===r.preferredTrackId):-1,u=l>=0?l:c.length-1,d=e=>{let t=c[e];if(t.mode===`sequential`){let n=t.clips.reduce((e,t)=>Math.max(e,t.timeRange.start+t.timeRange.duration),0),r={...s,timeRange:{start:n,duration:o.duration}};return{ops:[{op:`insert`,path:[`scenes`,i,`tracks`,e,`clips`],index:t.clips.length,value:r}],trackId:t.id,createdTrack:!1,clipIndex:t.clips.length}}let n=t.clips.filter(e=>e.timeRange.start<o.start).length;return{ops:[{op:`insert`,path:[`scenes`,i,`tracks`,e,`clips`],index:n,value:s}],trackId:t.id,createdTrack:!1,clipIndex:n}};if(c[u]?.mode===`sequential`)return d(u);let f=kPe(c,u,[s]);if(f>=0)return d(f);let p=s.kind===`audio`?0:c.length,m=Kx({name:`Track ${c.length+1}`,clips:[s]});return{ops:[{op:`insert`,path:[`scenes`,i,`tracks`],index:p,value:m}],trackId:m.id,createdTrack:!0,clipIndex:0}}function bIe(e,t,n){let r=e.scenes.findIndex(e=>e.id===t),i=e.scenes[r]?.tracks.findIndex(e=>e.id===n)??-1;if(r<0||i<0)return null;let a=e.scenes[r].tracks[i],o=[],s=0,c=a.clips.map((e,t)=>({c:e,i:t})).toSorted((e,t)=>e.c.timeRange.start-t.c.timeRange.start);for(let{c:e,i:t}of c)Math.abs(e.timeRange.start-s)>xIe&&o.push({op:`set`,path:[`scenes`,r,`tracks`,i,`clips`,t,`timeRange`,`start`],value:s}),s+=e.timeRange.duration;return o}var xIe,SIe,CIe=o((()=>{Yx(),iS(),xIe=1e-6,SIe={rangesOverlap:$x,canPlace:jPe,planClipPlacement:yIe,planSequentialPack:bIe}})),TS,wIe,TIe=o((()=>{TS=4,wIe=class{channels;speed;hop;size;search;window;input;mono;base=0;end=0;acc;frame=0;prev=0;drop;consumed=0;emitted=0;constructor(e,t,n){if(this.channels=e,this.speed=n,!(n>0))throw Error(`time stretch: speed must be positive, got ${n}`);this.hop=Math.max(64,Math.round(t/100)),this.size=2*this.hop,this.search=this.hop>>1,this.window=Float32Array.from({length:this.size},(e,t)=>.5-.5*Math.cos(2*Math.PI*t/this.size)),this.input=Array.from({length:e},()=>new Float32Array(8*this.size)),this.mono=new Float32Array(8*this.size),this.acc=Array.from({length:e},()=>new Float32Array(this.size)),this.end=this.hop,this.drop=this.hop}push(e){let t=e[0]?.length??0;return this.append(t,(t,n)=>this.input[t].set(e[t]??e[0],n)),this.consumed+=t,this.run(1/0)}flush(){let e=Math.round(this.consumed/this.speed),t=[];for(;this.emitted<e;)this.append(this.size,(e,t)=>this.input[e].fill(0,t,t+this.size)),t.push(this.run(e));let n=t.reduce((e,t)=>e+(t[0]?.length??0),0);return this.acc.map((e,r)=>{let i=new Float32Array(n),a=0;for(let e of t)i.set(e[r],a),a+=e[r].length;return i})}append(e,t){this.reserve(e);let n=this.end-this.base;for(let e=0;e<this.channels;e++)t(e,n);let r=this.mono;for(let t=n;t<n+e;t++){let e=0;for(let n=0;n<this.channels;n++)e+=this.input[n][t];r[t]=e/this.channels}this.end+=e}reserve(e){let t=Math.max(this.base,Math.min(this.nominal(this.frame)-this.search,this.prev+this.hop)),n=t-this.base,r=this.end-t,i=r+e>this.mono.length,a=t=>{let a=i?new Float32Array(Math.max(2*t.length,r+e)):t;return a.set(t.subarray(n,n+r)),a};(n!==0||i)&&(this.input=this.input.map(a),this.mono=a(this.mono),this.base=t)}nominal(e){return Math.round(e*this.hop*this.speed)}run(e){let t=this.acc.map(()=>[]);for(;;){let n=this.nominal(this.frame);if(Math.max(n+this.search,this.prev+this.hop)+this.size>this.end||this.emitted>=e)break;let r=this.frame===0?n:this.align(n);for(let e=0;e<this.channels;e++){let t=this.acc[e],n=this.input[e];for(let e=0,i=r-this.base;e<this.size;e++,i++)t[e]+=this.window[e]*n[i]}this.prev=r,this.frame++;let i=Math.min(this.drop,this.hop);this.drop-=i;let a=Math.min(this.hop-i,e-this.emitted);for(let e=0;e<this.channels;e++){let n=this.acc[e];a>0&&t[e].push(n.slice(i,i+a)),n.copyWithin(0,this.hop),n.fill(0,this.hop)}this.emitted+=Math.max(0,a)}return t.map(e=>{let t=new Float32Array(e.reduce((e,t)=>e+t.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t})}align(e){let t=Math.max(this.base,e-this.search),n=e+this.search,r=this.prev+this.hop-this.base,i=e=>{let t=this.mono,n=0,i=0;for(let a=0,o=e-this.base,s=r;a<this.hop;a++,o++,s++)n+=t[o]*t[s],i+=t[o]*t[o];return i>0?n/Math.sqrt(i):0},a=e,o=-1/0;for(let e=t;e<=n;e+=TS){let t=i(e);t>o&&([o,a]=[t,e])}let s=a;for(let e=Math.max(t,s-TS+1);e<=Math.min(n,s+TS-1);e++){let t=i(e);t>o&&([o,a]=[t,e])}return a}}})),EIe,DIe,OIe,kIe,AIe=o((()=>{hx(),TIe(),EIe=4,DIe=1.5,OIe=100,kIe=class{deps;ctx;master;analyser;anchor=null;generation=0;timer;voices=new Set;disposed=!1;muted=!1;samples=new Float32Array(2048);constructor(e){this.deps=e}context(){if(!this.ctx){let e=this.deps.createContext?.()??new AudioContext({latencyHint:`interactive`});this.master=e.createGain(),this.master.gain.value=+!this.muted,this.analyser=e.createAnalyser(),this.analyser.fftSize=this.samples.length,this.master.connect(this.analyser),this.analyser.connect(e.destination),this.ctx=e}return this.ctx}warm(){this.disposed||this.context()}start(e){if(this.disposed)return;let t=performance.now();this.stop();let n=this.context(),r=this.generation,i=n.currentTime,a=typeof OfflineAudioContext<`u`&&n instanceof OfflineAudioContext;!a&&n.state!==`running`&&n.resume().catch(()=>{});let o=()=>{if(r!==this.generation)return;if(!a&&(n.state!==`running`||n.currentTime<=i)){this.timer=setTimeout(o,EIe);return}let s=a?e:e+(performance.now()-t)/1e3;this.anchor={ctxTime:n.currentTime,rootTime:s};let c=this.deps.clips().filter(e=>e.end>s).toSorted((e,t)=>e.start-t.start),l=0,u=()=>{if(r!==this.generation)return;let e=this.anchor.rootTime+Math.max(0,n.currentTime-this.anchor.ctxTime);for(let t of this.voices)t.end<=e&&this.retire(t);for(;l<c.length&&c[l].start<=e+DIe;){let t=c[l++];t.end>e&&this.feed(t,e).catch(()=>{})}(l<c.length||this.voices.size)&&(this.timer=setTimeout(u,OIe))};u()};o()}stop(){this.generation++,clearTimeout(this.timer),this.timer=void 0,this.anchor=null;for(let e of this.voices)this.retire(e)}retire(e){if(!this.voices.delete(e))return;e.cancelled=!0,e.wake?.();let t=e.iterator;e.iterator=void 0,t?.return().catch(()=>{});for(let t of e.nodes){try{t.stop()}catch{}t.disconnect()}e.nodes.clear(),e.gain.disconnect()}time(){let e=this.ctx;return!e||!this.anchor||e.state!==`running`?null:this.anchor.rootTime+Math.max(0,e.currentTime-this.anchor.ctxTime)}setMuted(e){this.muted=e,this.master&&this.ctx&&this.master.gain.setValueAtTime(+!e,this.ctx.currentTime)}level(){if(!this.analyser)return 0;this.analyser.getFloatTimeDomainData(this.samples);let e=0;for(let t of this.samples)e+=t*t;return Math.sqrt(e/this.samples.length)}async feed(e,t){let n=this.ctx,r=this.anchor,i=Math.max(e.start,t),a=e=>r.ctxTime+(e-r.rootTime),o=n.createGain(),s={gain:o,end:e.end,nodes:new Set,cancelled:!1,decoded:!1},c=[i,e.start+e.fadeIn,e.end-e.fadeOut,e.end].filter(t=>t>=i&&t<=e.end).toSorted((e,t)=>e-t);o.gain.setValueAtTime(kbe(e,i),a(i));for(let t of c.slice(1))o.gain.linearRampToValueAtTime(kbe(e,Math.min(t,e.end-1e-6)),a(t));o.connect(this.master),this.voices.add(s);try{if(e.preservePitch&&e.speed!==1)return await this.stretched(e,i,s);let t=e.speed,r=e.sourceIn+(i-e.start)*t,o=e.sourceIn+(e.end-e.start)*t;for await(let c of this.chunks(e,s,r,o,a)){let r=e.start+(c.timestamp-e.sourceIn)/t,o=Math.max(0,i-r,n.currentTime-a(r)),l=o*t,u=Math.min(c.buffer.duration,(e.end-r)*t)-l;u<=0||this.play(c.buffer,s,a(r+o),l,u,t)}}finally{s.decoded=!0,s.nodes.size||this.retire(s)}}async*chunks(e,t,n,r,i){let a=this.ctx,o=this.deps.handle(e.src).chunks(n,r);t.iterator=o;let s=e.start+(n-e.sourceIn)/e.speed;try{for(;!t.cancelled;){for(;!t.cancelled&&i(s)-a.currentTime>DIe;)await new Promise(e=>{let n=()=>{clearTimeout(r),t.wake=void 0,e()},r=setTimeout(n,OIe);t.wake=n});if(t.cancelled)return;let n=await o.next();if(t.cancelled||n.done)return;let r=n.value;s=e.start+(r.timestamp+r.buffer.duration-e.sourceIn)/e.speed,yield r}}finally{t.iterator===o&&(t.iterator=void 0,o.return().catch(()=>{}))}}async stretched(e,t,n){let r=this.ctx,i=this.anchor,a=e=>i.ctxTime+(e-i.rootTime),o=e.speed,s=e.sourceIn+(t-e.start)*o,c=e.sourceIn+(e.end-e.start)*o,l,u=0,d=s,f=0,p=i=>{let o=i[0]?.length??0;if(o===0)return;let s=t+f/u;f+=o;let c=Math.max(0,r.currentTime-a(s)),l=Math.min(o/u,e.end-s)-c;if(l<=0)return;let d=r.createBuffer(i.length,o,u);i.forEach((e,t)=>d.copyToChannel(e,t)),this.play(d,n,a(s)+c,c,l,1)};for await(let t of this.chunks(e,n,s,c,a)){let e=t.buffer;u||=e.sampleRate,l??=new wIe(e.numberOfChannels,u,o);let n=Math.round((t.timestamp-d)*u);n>0&&p(l.push(Array.from({length:e.numberOfChannels},()=>new Float32Array(n))));let r=Math.max(0,-n),i=Math.min(e.length,Math.round((c-t.timestamp)*u));i<=r||(d=t.timestamp+i/u,p(l.push(Array.from({length:e.numberOfChannels},(t,n)=>e.getChannelData(n).subarray(r,i)))))}l&&!n.cancelled&&p(l.flush())}play(e,t,n,r,i,a){let o=this.ctx.createBufferSource();o.buffer=e,o.playbackRate.value=a,o.connect(t.gain),o.addEventListener(`ended`,()=>{t.nodes.delete(o),o.disconnect(),t.decoded&&!t.nodes.size&&this.retire(t)}),t.nodes.add(o),o.start(n,r,i)}dispose(){this.disposed=!0,this.stop(),this.ctx?.close().catch(()=>{}),this.ctx=void 0}}}));function jIe(e,t){if(!e)return null;let n=e.scenes.find(n=>n.id===(t??e.activeSceneId));if(!n)return null;let r=n.tracks[0]?.id.startsWith(NIe)?n.tracks[0].clips[0]:void 0,i=r?{x:-r.transform.x,y:-r.transform.y}:{x:0,y:0};return{sceneId:n.id.startsWith(NIe)?t??e.activeSceneId:n.id,width:n.width,height:n.height,origin:i}}function MIe(e){let t=new Set,n=new Set;return{onInvalidate(e){return n.add(e),{dispose:()=>{n.delete(e)}}},invalidateAll(e=`content`,r,i){for(let e of t)e.invalidate();for(let t of n)t(e,r,i)},create(n,r={}){let i=null,a=0,o=!1,s=r.scale??1,c=null,l=null,u=0,d=!1,f=t=>{let a=jIe(i,r.sceneId??null);if(!a||d)return;let o=c?[c.x*s,c.y*s,(c.x+c.width)*s,(c.y+c.height)*s]:void 0,l=e.draw(e.sceneStart(a.sceneId)+t,{width:a.width,height:a.height,origin:a.origin,scale:s,...o?{visible:o}:{}});if(l)try{n(l,t)}finally{e.release(l)}},p=()=>{l=e.request(()=>{if(!o||d)return;let t=e.now();a=r.followAudioClock?e.transportTime():a+(t-u)/1e3,u=t,f(a),p()})},m={setDocument(e){i=e,o||f(a)},play(){o||(o=!0,u=e.now(),p())},pause(){o=!1,l!==null&&e.cancel(l),l=null},seek(e){a=Math.max(0,e),f(a)},isPlaying:()=>o,time:()=>a,invalidate(){o||f(a)},setScale(e){e>0&&Number.isFinite(e)&&(s=e),o||f(a)},setVisible(e){c=e,o||f(a)},dispose(){d=!0,m.pause(),t.delete(m)}};return t.add(m),m}}}var NIe,PIe=o((()=>{NIe=`viewport-overflow:`}));function FIe(e,t){for(let n=e.get(hh)?.parent;n;n=n.get(hh)?.parent)if(n===t)return!0;return!1}function IIe(e,t){let n=[];for(let r=e.entity(t)?.get(hh)?.parent;r&&r.get(mh).tag!==`scene`;r=r.get(hh)?.parent)n.push(r.get(mh).key);return n}var LIe,RIe,zIe,BIe=o((()=>{hx(),nIe(),LIe=`capability:higgsedit/prerender`,RIe=150,zIe=class{origin;session;playhead;redraw;mode;status=new bS(new Map);inputs=new Map;ready=new Map;opening=new Map;ids=new Map;digests=new Map;stale=new Set;timer;viewScale=0;hits=0;misses=0;disposed=!1;client=Math.random().toString(36).slice(2);constructor(e,t,n,r,i=`auto`){this.origin=e,this.session=t,this.playhead=n,this.redraw=r,this.mode=new bS(i)}setMode(e){this.mode.set(e),this.freeze(),this.redraw(),this.ask()}async changed(){let e=await this.session.prerenderInputs();this.inputs=new Map(e.map(e=>[e.key,e])),this.stale.clear();for(let e of this.ready.keys())this.inputs.has(e)||this.drop(e);this.publish(),this.ask()}patched(e){for(let t of e){let e=this.session.entity(t);for(let t of this.inputs.keys()){let n=this.session.entity(t);n&&e&&(n===e||FIe(e,n))&&this.stale.add(t)}}this.stale.size&&this.publish()}viewed(e){!(e>0)||Math.abs(e-this.viewScale)<.001||(this.viewScale=e,this.ask())}onEvent(e){this.ids.get(e.node)===e.id&&(e.state===`ready`&&this.open(e.node,e.id),this.setState(e.node,e.state,e.done,e.total))}stats(){return{states:Object.fromEntries([...this.status.get()].map(([e,t])=>[e,t.state])),hits:this.hits,misses:this.misses}}picture=e=>{if(this.mode.get()!==`auto`||this.ready.size===0)return;let t=e.get(mh).key,n=this.ready.get(t);if(!n)return;if(this.stale.has(t)||this.inputs.get(t)?.digest!==n.digest){this.misses++;return}let r=n.handle.facts;if(!r)return;let i=e.get(zh),a=p_(r.timestamps,Math.max(0,r.timestamps[0])+i.local-n.entry.offset,r.fps);if(a<0||a>=n.entry.frames)return;let o=n.handle.peek(a);if(!o){this.misses++;return}this.hits++;let s=this.inputs.get(t);return{image:o,width:s.width,height:s.height}};warm(){if(this.mode.get()===`auto`)for(let[e,t]of this.ready){let n=this.session.entity(e),r=n?.get(zh);!r||r.active||r.local>=0||r.local<-.6||n.get(hh)?.parent?.get(zh)?.active&&t.handle.warm(0)}}dispose(){this.disposed=!0,clearTimeout(this.timer);for(let e of this.ready.keys())this.drop(e)}setState(e,t,n,r){let i=this.status.get().get(e);if(i&&i.state===t&&i.done===n&&i.total===r)return;let a=new Map(this.status.get());a.set(e,{key:e,owners:IIe(this.session,e),state:t,done:n,total:r}),this.status.set(a)}freeze(){let e=[];for(let t of this.inputs.keys()){let n=this.ready.get(t),r=this.mode.get()===`auto`&&!!n&&!this.stale.has(t)&&this.inputs.get(t)?.digest===n.digest,i=this.session.entity(t);i&&Rbe(i,r);let a=t.split(`/`).slice(0,-1).join(`/`);r&&a&&e.push(a)}this.session.mount?.document.setFrozen(e)}publish(){this.freeze();let e=new Map;for(let[t,n]of this.inputs){let r=this.status.get().get(t),i=this.ready.get(t)?.digest===n.digest&&!this.stale.has(t)?`ready`:r&&r.state!==`ready`?r.state:`stale`;e.set(t,{key:t,owners:IIe(this.session,t),state:i,done:r?.done??0,total:n.frames})}this.status.set(e)}ask(){clearTimeout(this.timer),this.timer=setTimeout(()=>void this.send(),RIe)}async send(){if(this.disposed)return;let e=this.mode.get()===`auto`?[...this.inputs.values()].map(e=>({...e,size:this.sizeFor(e)})):[],t;try{let n=await fetch(`${this.origin}/api/prerender`,{method:`POST`,body:JSON.stringify({targets:e,playhead:this.playhead(),client:this.client})});if(!n.ok)return;t=(await n.json()).statuses}catch{return}for(let n of t){this.ids.set(n.node,n.id);let t=e.find(e=>e.key===n.node);t&&this.digests.set(n.id,t.digest),n.state===`ready`&&this.open(n.node,n.id);let r=this.inputs.get(n.node),i=this.ready.get(n.node)?.digest===r?.digest&&n.state!==`ready`?`ready`:n.state;this.setState(n.node,i,n.done,n.total)}}sizeFor(e){let t=this.session.entity(e.key)?.get(hh)?.parent?.get(zh)?.matrix??[1,0,0,1,0,0],n=Math.hypot(t[2],t[3])||1;return Kje(e.height*n*(this.viewScale||1),e.height)}open(e,t){if(this.ready.get(e)?.id===t)return Promise.resolve();let n=this.opening.get(t);if(n)return n;let r=(async()=>{let n=`${this.origin}/preview/.higgsedit/prerender/${t}`,r=await fetch(`${n}.json`);if(!r.ok)return;let i=await r.json();if(i.inexact)return;let a=new Hje(`prerender:${e}`,`${n}.mp4`,i.opaque?void 0:`${n}.matte.mp4`);if(await a.ready,a.fit(i.height),await a.request(0),this.disposed||this.ids.get(e)!==t){a.dispose();return}this.drop(e),this.ready.set(e,{id:t,digest:this.digests.get(t)??``,entry:i,handle:a}),this.publish(),this.redraw()})().catch(()=>{}).finally(()=>this.opening.delete(t));return this.opening.set(t,r),r}drop(e){this.ready.get(e)?.handle.dispose(),this.ready.delete(e)}}}));async function VIe(e){let t=await e.json().catch(()=>({}));if(e.ok)return t;throw t.code===`unconfigured`?Error(KIe):e.status===504?Error(`The select server did not answer in time`):Error(typeof t.error==`string`?t.error:`Select failed (HTTP ${e.status})`)}function HIe(e){let t=e.objects;if(!(ES(e.width)&&ES(e.height)&&Array.isArray(t)&&t.every(e=>Array.isArray(e?.box)&&e.box.length===4&&Array.isArray(e.mask?.size)&&typeof e.mask.rle==`string`)))throw Error(`The select server sent a reply this editor does not understand`);return{width:e.width,height:e.height,time:ES(e.time)?e.time:0,objects:t}}function UIe(e){if(e.status===`succeeded`&&typeof e.mask==`string`)return{status:`succeeded`,mask:e.mask};if(e.status===`failed`)return{status:`failed`,error:typeof e.error==`string`?e.error:`Tracking failed`};let t=e.progress;return{status:e.status===`queued`?`queued`:`running`,progress:t&&ES(t.done)&&ES(t.total)?{done:t.done,total:t.total}:null}}function WIe(e,t){let n=(t,n,r)=>fetch(`${e}${t}`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(n),...r?{signal:r}:{}});return{async select(e,t){return HIe(await VIe(await n(`/api/select`,e,t)))},async track(e){let t=await VIe(await n(`/api/select/tracks`,e));if(typeof t.id!=`string`)throw Error(`The select server did not start the track`);return t.id},async trackStatus(t){return UIe(await VIe(await fetch(`${e}/api/select/tracks/${encodeURIComponent(t)}`)))},async sourceSize(e,n){if(n===`video`){let n=await t.video(e).ready;return[n.width,n.height]}let r=t.image(e);return await r.ready,[r.width,r.height]}}}var GIe,KIe,ES,qIe=o((()=>{GIe=`capability:higgsedit/select`,KIe=`No select server: set HIGGSEDIT_SELECT_URL and restart higgsedit dev`,ES=e=>typeof e==`number`&&Number.isFinite(e)}));function JIe(e){let t=new Set,n=new Map;return{describe(t){let r=n.get(t);return r||(r=fetch(`${e}/api/analyze?key=${encodeURIComponent(t)}&names=${XIe.join(`,`)}`).then(e=>e.json()),n.set(t,r)),r},onChange(e){return t.add(e),km(()=>t.delete(e))},changed(){n=new Map;for(let e of Array.from(t))e()}}}var YIe,XIe,ZIe=o((()=>{Nm(),YIe=`capability:higgsedit/source`,XIe=[`x`,`y`,`width`,`height`,`rotation`,`scale`,`opacity`,`fill`,`fontSize`,`start`,`end`,`animate`]})),QIe,$Ie=o((()=>{QIe=e=>typeof e==`object`&&!!e&&typeof e.projectSrc==`string`}));async function eLe(e,t){if(typeof document>`u`)return{duration:null,width:null,height:null};if(t===`image`){let t=new Image;return t.src=e,await t.decode().catch(()=>void 0),{duration:null,width:t.naturalWidth||null,height:t.naturalHeight||null}}let n=document.createElement(t===`audio`?`audio`:`video`);n.preload=`metadata`,n.src=e,await new Promise(e=>{n.addEventListener(`loadedmetadata`,()=>e(),{once:!0}),n.addEventListener(`error`,()=>e(),{once:!0})});let r=n;return{duration:Number.isFinite(n.duration)?n.duration:null,width:r.videoWidth||null,height:r.videoHeight||null}}function tLe(e){let t=async(t,n,r,i)=>{let a=rLe(i,r),o=e.mediaUrl(t),s=await eLe(o,a);return{id:t,name:r,kind:a,mimeType:i||`application/octet-stream`,byteSize:n,...s,uri:o,hash:`${r}:${n}`}},n=async(n,r,i)=>{let a=n instanceof Uint8Array?n.byteLength:n.size;if(!Number.isSafeInteger(a)||a<0)throw Error(`invalid media byte size`);let o;if(n instanceof Uint8Array||n instanceof Blob)o=await fetch(`${e.origin}/api/media/stream?name=${encodeURIComponent(r)}`,{method:`POST`,body:n});else{let t=await fetch(`${e.origin}/api/media/uploads?name=${encodeURIComponent(r)}`,{method:`POST`});if(!t.ok)throw Error(t.status===404?`Restart the local video editor to enable safe media imports`:`upload of ${r} failed: ${t.status} ${await t.text()}`);let{id:i,partBytes:s,maxBytes:c}=await t.json();if(!/^[a-f0-9-]{36}$/.test(i)||!Number.isSafeInteger(s)||s<1||s>2<<20)throw Error(`invalid media upload session`);let l=`${e.origin}/api/media/uploads/${i}`,u=!1;try{if(!Number.isSafeInteger(c)||c<1||a>c)throw Error(`upload of ${r} exceeds the ${c} byte limit`);for(let e=0;e<a;e+=s){let t=await n.slice(e,Math.min(a,e+s)).arrayBuffer(),i=await fetch(`${l}?offset=${e}`,{method:`PUT`,body:t});if(!i.ok)throw Error(`upload of ${r} failed: ${i.status} ${await i.text()}`)}o=await fetch(l,{method:`POST`}),u=o.ok}finally{u||await fetch(l,{method:`DELETE`}).catch(()=>{})}}if(!o.ok)throw Error(o.status===404?`Restart the local video editor to enable safe media imports`:`upload of ${r} failed: ${o.status} ${await o.text()}`);let{src:s,byteSize:c}=await o.json(),l=await t(s,c,s.split(`/`).at(-1),i);return e.onAsset(l),l},r=()=>{let t=e.document();return t?[{id:t.id,name:t.name,modifiedAt:t.modifiedAt}]:[]};return{probe:()=>1,listProjects:async()=>r(),loadDocument:async t=>e.document()?.id===t?e.document():null,saveDocument:async()=>{},deleteProject:async()=>{throw Error(DS)},createProject:async()=>{throw Error(DS)},renameProject:async()=>{throw Error(DS)},duplicateProject:async()=>{throw Error(DS)},readAssetBlob:async e=>fetch(e.uri).then(e=>e.blob()),writeAsset:(e,t)=>n(e,t.name,t.mimeType),storeAssetBytes:(e,t)=>n(e,t.name,t.mimeType),deleteAsset:async()=>{throw Error(`delete media files from the project folder`)},importFile:async r=>{let i=`getFile`in r?await r.getFile():r;if(QIe(i)){let n=await t(i.projectSrc,i.projectByteSize,i.name,i.type);return e.onAsset(n),n}return n(i,i.name,i.type)},listAssets:async()=>e.document()?.assets??[],async refreshAssets(){let{files:n}=await fetch(`${e.origin}/api/media`).then(e=>e.json()),r=new Set((e.document()?.assets??[]).map(e=>e.id)),i=await Promise.all(n.filter(e=>!r.has(e.src)).map(e=>t(e.src,e.byteSize,e.src.split(`/`).at(-1),``)));for(let t of i)e.onAsset(t);return i}}}var nLe,rLe,DS,iLe=o((()=>{$Ie(),nLe=[[/^video\//,`video`],[/^image\//,`image`],[/^audio\//,`audio`]],rLe=(e,t)=>nLe.find(([t])=>t.test(e))?.[1]??(/\.(png|jpe?g|webp|gif|avif|svg|bmp)$/i.test(t)?`image`:/\.(mp3|wav|ogg|m4a|aac|flac)$/i.test(t)?`audio`:`video`),DS="higgsedit dev edits one project folder; open another with `higgsedit dev <dir>`"}));function aLe(e){return{probe:e=>+(e.kind===`video`||e.kind===`image`),async filmstrip(t,n){let r=(t,r,i,a)=>{let o=document.createElement(`canvas`);o.width=Math.max(1,Math.round(n.size.width)),o.height=Math.max(1,Math.round(n.size.height));let s=o.getContext(`2d`),c=Math.max(o.width/r,o.height/i);return s.drawImage(t,(o.width-r*c)/2,(o.height-i*c)/2,r*c,i*c),e.fromCanvas(o,a)};if(t.kind===`image`){let e=new Image;return e.src=t.uri,await e.decode(),Array.from({length:n.count},()=>r(e,e.naturalWidth,e.naturalHeight,0))}let i=document.createElement(`video`);i.muted=!0,i.preload=`auto`,i.src=t.uri,await new Promise((e,n)=>{i.addEventListener(`loadeddata`,()=>e(),{once:!0}),i.addEventListener(`error`,()=>n(Error(`cannot decode ${t.name}`)),{once:!0})});let a=[],o=n.count>1?(n.end-n.start)/(n.count-1):0;for(let e=0;e<n.count;e++){let t=Math.min(i.duration-.01,n.start+e*o);await oLe(i,t),a.push(r(i,i.videoWidth,i.videoHeight,t))}return i.removeAttribute(`src`),i.load(),a}}}var oLe,sLe,cLe=o((()=>{oLe=(e,t)=>new Promise(n=>{let r=()=>{e.removeEventListener(`seeked`,r),e.removeEventListener(`error`,r),n()};e.addEventListener(`seeked`,r),e.addEventListener(`error`,r),e.currentTime=t}),sLe={mix:async()=>null}}));function lLe(e){let t=new Set,n=new Map,r=new Map,i=0,a,o=Promise.resolve(),s=!1,c=!1,l=()=>{for(let e of Array.from(t))e()},u=async()=>{if(s){c=!0;return}s=!0;try{do c=!1,await e.remount(new Map(n));while(c)}finally{s=!1}},d=()=>{clearTimeout(a),i===0&&(a=setTimeout(()=>void f(),e.commitDelayMs??250))},f=()=>{if(clearTimeout(a),!r.size)return o;let t=[...r.values()];r.clear();let i=t.length===1?`Change ${t[0].label}`:`Change variables`,s=t.map(({file:e,name:t,value:n})=>({key:``,edit:{op:`set-const`,file:e,name:t,value:n}}));return o=o.then(async()=>{let a=!1;try{let t=await e.write(i,s);if(e.onWritten?.(t),a=t.ok,!t.ok){let n=t.results.find(e=>!e.ok)?.refused;e.onRefused?.({reason:n?.reason??`the edit was refused`,...n?.at?{at:n.at}:{},...n?.source?{source:n.source}:{}})}}catch(t){e.onRefused?.({reason:`could not reach higgsedit dev: ${t.message}`})}for(let e of t){let t=gx(e.file,e.name);!r.has(t)&&(!a||n.get(t)===e.value)&&n.delete(t)}a||e.onRevert?.()}),o};return{entries:()=>e.entries().map(e=>{let t=n.get(gx(e.file,e.name));return t===void 0||t===e.value?e:{...e,value:t}}),onChange(e){return t.add(e),km(()=>t.delete(e))},set(t,i,a){let o=gx(t,i),s=e.entries().find(e=>e.file===t&&e.name===i);s&&(n.set(o,a),r.set(o,{file:t,name:i,label:s.label,value:a}),l(),u(),d())},beginGesture(){i++,clearTimeout(a)},endGesture(){i=Math.max(0,i-1),i===0&&r.size&&f()},overrides:()=>n,flush:f,changed:l}}var OS,uLe=o((()=>{cMe(),Nm(),OS=`capability:higgsedit/variables`}));function dLe(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&Object.values(e).every(e=>typeof e==`string`)}function fLe(e){let t=async(t,n)=>{let r=await fetch(`${e}${t}`,{method:`POST`,...n===void 0?{}:{body:JSON.stringify(n)}});if(!r.ok)throw Error(`${t}: ${r.status}`);return r.json()};return{edit:(e,n)=>t(`/api/edit`,{name:e,edits:n}),undo:()=>t(`/api/undo`),redo:()=>t(`/api/redo`)}}function pLe(e){let t=e.origin,n=`${t}/project`,r=e=>`${n}/${e.replace(/^\.\//,``)}`,i=new Am,a=new Set,o=null;i.add({dispose(){o!==null&&cancelAnimationFrame(o),a.clear()}});let s=new XNe({mediaBase:n,origin:t,videoBase:`${t}/preview`,mode:`live`,makeVideo:(e,t)=>new Hje(e,t)}),c=dIe(),l=fIe(),u=new Map,d=JIe(t),f=e=>z_(s.world).find(t=>t.get(mh)?.key===e)??z_(s.world)[0],p={sceneSpan(e){let t=f(e);if(!t)return{start:0,duration:0,fps:30};let n=K_(t),r=B_(s.world,t,n);return{start:r.start,duration:r.end-r.start,fps:n}},draw(e,t,n){let r=s.comp;if(!r)return null;let i=r.fps;return s.tick(Math.round(e*i),{time:e,playing:t,delta:1/i}),c.render(Math.max(1,Math.round(r.width*n)),Math.max(1,Math.round(r.height*n)),e,e=>s.drawLive(e,n,void 0,void 0,_.picture))},release:e=>c.release(e)},m=MIe({draw(e,t){let n=s.comp;return n?(s.tick(Math.round(e*n.fps),{time:e,playing:g.playing.get(),delta:1/n.fps}),_.viewed(t.scale),_.warm(),c.render(Math.max(1,Math.round(t.width*t.scale)),Math.max(1,Math.round(t.height*t.scale)),e,e=>s.drawLive(e,t.scale,t.origin,t.visible,_.picture))):null},release:e=>c.release(e),sceneStart:e=>p.sceneSpan(e).start,transportTime:()=>g.currentTime.get(),now:()=>performance.now(),request:e=>requestAnimationFrame(e),cancel:e=>cancelAnimationFrame(e)}),h=kme({documentExecutor:e=>x.execute(e),...e.settingsStore?{settingsStore:e.settingsStore}:{}}),g=new iIe(p,(e,t)=>h.bus.publish(e,t)),_=new zIe(t,s,()=>g.currentTime.get()+p.sceneSpan(g.activeSceneId.get()).start,()=>{g.requestRender(),m.invalidateAll()},e.previewMode?.get()??`auto`);i.add({dispose:()=>_.dispose()}),e.previewMode&&i.add(e.previewMode.subscribe(e=>_.setMode(e)));let v=new kIe({clips:()=>Obe(s.world),handle:e=>s.media.audio(e)});typeof requestIdleCallback==`function`&&requestIdleCallback(()=>v.warm(),{timeout:2e3});let y=()=>p.sceneSpan(g.activeSceneId.get()).start;g.setClock({start:e=>v.start(y()+e),stop:()=>v.stop(),time:()=>{let e=v.time();return e===null?null:e-y()}}),i.add(km(Ube(e=>m.invalidateAll(`html`,void 0,e)))),i.add(km(Cje(e=>m.invalidateAll(`media`,e)))),i.add(km(s.media.onReady(e=>{g.requestRender(),m.invalidateAll(`media`,e)}))),i.add(km(Kxe(()=>{g.requestRender(),m.invalidateAll()}))),e.previewMuted&&(v.setMuted(e.previewMuted.get()),i.add(e.previewMuted.subscribe(e=>v.setMuted(e))));let b=fLe(t),x=new eIe({transport:b,world:()=>s.world,onPatched:e=>{_.patched(e),g.requestRender(),m.invalidateAll()},onRevert:()=>void R.reload().catch(()=>{}),...e.onRefused?{onRefused:e.onRefused}:{}}),S=lLe({entries:()=>s.inspect,remount:e=>I(e),write:(e,t)=>b.edit(e,t),onWritten:e=>x.setServerUndo(e.undo),onRevert:()=>void L().catch(()=>{}),...e.onRefused?{onRefused:e.onRefused}:{}}),C=tLe({origin:t,mediaUrl:r,document:()=>x.snapshot(),onAsset:e=>{u.set(e.id,e);let t=x.current();t&&x.load(w(t),`remote`)}}),w=e=>{let t=new Set(e.document.assets.map(e=>e.id)),n=[...u.values()].filter(e=>!t.has(e.id));return n.length?{...e,document:{...e.document,assets:[...e.document.assets,...n]}}:e},T=()=>{g.requestRender();let t=p.draw(g.currentTime.get()+p.sceneSpan(g.activeSceneId.get()).start,!1,1);t&&c.release(t);let n=w(yFe(s.world,{name:e.name,mediaUrl:r}));x.load(n),(g.activeSceneId.get()===null||!n.document.scenes.some(e=>e.id===g.activeSceneId.get()))&&g.setActiveScene(n.document.activeSceneId||null);let i=new Set(x.current()?.meta.keys()),a=g.selection.get();a.clipIds.some(e=>!i.has(e))&&g.setSelection({clipIds:a.clipIds.filter(e=>i.has(e))}),g.requestRender(),m.invalidateAll(),d.changed(),S.changed(),g.playing.get()&&g.seek(g.currentTime.get())},E=Promise.resolve(),D=!1,O=0,k=new AbortController,A,j=[],M,N=e=>{let t=E.then(()=>D?void 0:e());return E=t.catch(()=>{}),t},P=(t,n)=>{D||e.onStatus?.(`${t}: ${n instanceof Error?n.message:String(n)}`)},F=e=>{s.durationsReady().then(()=>{D||O!==e||(T(),_.changed())}).catch(t=>{O===e&&P(`Media error`,t)})},I=e=>N(async()=>{if(!A)return;let t=++O;try{if(await s.load(A,j,e,M),D)return;T(),_.changed(),F(t)}catch(e){P(`Compile error`,e)}}),L=(n=!1)=>N(async()=>{let r=++O,i=performance.now();try{let a=await fetch(`${t}/api/files`,{signal:k.signal});if(!a.ok)throw Error(`/api/files: HTTP ${a.status}`);let o=await a.json();if(D)return;if(!o||typeof o!=`object`)throw Error(`the higgsedit dev server sent an invalid project`);let{files:c,modules:l,error:u,fonts:d,packages:f}=o;if(!l)throw Error(typeof u==`string`?u:`the higgsedit dev server sent no compiled modules; it predates server-side compile`);if(!dLe(l))throw Error(`the higgsedit dev server sent invalid compiled modules`);if(!dLe(c))throw Error(`the higgsedit dev server sent invalid source files`);if(d!==void 0&&(!Array.isArray(d)||d.some(e=>typeof e!=`string`)))throw Error(`the higgsedit dev server sent invalid fonts`);if(f!==void 0&&typeof f!=`string`)throw Error(`the higgsedit dev server sent an invalid package bundle`);if(n&&s.media.forgetAll(),await s.load(l,d,S.overrides(),f),D)return;T(),_.changed(),R.lastSources=c,A=l,j=d??[],M=f,e.onStatus?.(`Loaded in ${Math.round(performance.now()-i)} ms`),F(r)}catch(e){throw P(`Load error`,e),e}}),R={host:h,session:x,editor:g,reload:L,audio:v,media:s.media,prerender:_,async start(){if(i.add(h.registerCommand(`document.undo`,()=>void S.flush().then(()=>x.undo()))),i.add(h.registerCommand(`document.redo`,()=>void S.flush().then(()=>x.redo()))),i.add(h.registerCommand(`fable.session.play`,()=>g.play())),i.add(h.registerCommand(`fable.session.pause`,()=>g.pause())),i.add(h.registerCommand(`fable.session.togglePlayback`,()=>g.togglePlayback())),i.add(h.registerCommand(`fable.session.seekStart`,()=>g.seek(g.workArea.get()?.start??0))),i.add(h.registerCommand(`fable.session.seekEnd`,()=>g.seek(g.workArea.get()?.end??p.sceneSpan(g.activeSceneId.get()).duration))),i.add(h.provide(bm,x)),i.add(h.provide(Cm,g)),i.add(h.provide(xm,SIe)),i.add(h.provide(Upe,C)),i.add(h.provide(Sm,c)),i.add(h.provide(Gpe,m)),i.add(h.provide(Hpe,l)),i.add(h.provide(eme,cIe(t,()=>g.activeSceneId.get()))),i.add(h.provide(mLe,aLe(c))),i.add(h.provide(hLe,_Ie)),i.add(h.provide(gLe,sLe)),i.add(h.provide(YIe,d)),i.add(h.provide(GIe,WIe(t,s.media))),i.add(h.provide(LIe,_)),i.add(h.provide(OS,S)),h.assetStore.setBackend({get:async e=>x.snapshot()?.assets.find(t=>t.id===e)??null,list:async()=>x.snapshot()?.assets??[],readBlob:async e=>{let t=x.snapshot()?.assets.find(t=>t.id===e);if(!t)throw Error(`no asset ${e}`);return C.readAssetBlob(t)},write:(e,t)=>C.writeAsset(e,t)}),fetch(`${t}/api/history`,{signal:k.signal}).then(e=>e.json()).then(e=>{D||x.setServerUndo(e)},()=>{}),await L().catch(()=>{}),D)return;C.refreshAssets().catch(e=>P(`Media error`,e));let n=new EventSource(`${t}/api/events`);n.addEventListener(`message`,t=>{if(D)return;let n;try{n=JSON.parse(String(t.data))}catch(e){P(`Reload event error`,e);return}if(!n||typeof n!=`object`)return;if(n.type===`prerender`){_.onEvent(n);return}if(n.type===`proxy`){if(typeof n.src!=`string`)return;a.add(n.src),o===null&&(o=requestAnimationFrame(()=>{if(o=null,!D){for(let e of a)s.media.forget(e);a.clear(),g.requestRender(),m.invalidateAll(`content`)}}));return}if(n.type!==`change`)return;x.setServerUndo(n.undo);let r=performance.now();L(n.files.length===0).then(()=>{D||e.onStatus?.(`${n.origin===`editor`?`Saved`:`Reloaded`} ${n.files.join(`, `)} · ${Math.round(Date.now()-n.detectedAt)} ms after the write, ${Math.round(performance.now()-r)} ms to remount`)}).catch(()=>{})}),i.add({dispose:()=>n.close()}),h.registerAll(e.plugins),await h.start()},dispose(){D||(D=!0,O++,k.abort(),S.flush(),x.flush(),g.dispose(),v.dispose(),i.dispose(),h.dispose(),c.dispose())}};return R}var mLe,hLe,gLe,_Le=o((()=>{Tm(),Nm(),hx(),ZNe(),tIe(),aIe(),uIe(),mIe(),vIe(),CIe(),AIe(),PIe(),wFe(),BIe(),qIe(),ZIe(),iLe(),cLe(),uLe(),mLe=`capability:thumbs.source`,hLe=`capability:peaks.source`,gLe=`capability:engine.mixer`}));function kS(e){if(kLe)return kLe(e);let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function vLe(e){let t=``;for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t)}function yLe(e,t=``){return n=>{let r=n;r.type===`change`&&Array.isArray(r.files)&&(r.files.length===0?e.dropNamespace(t):e.drop(r.files.filter(e=>typeof e==`string`),t)),r.type===`proxy`&&typeof r.src==`string`&&e.drop([r.src],t)}}function AS(e,t){return new Promise((n,r)=>{let i=()=>{t.removeEventListener(`abort`,i),r(t.reason)};t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{t.removeEventListener(`abort`,i),t.aborted?r(t.reason):n(e)},e=>{t.removeEventListener(`abort`,i),r(e)}),t.aborted&&i()})}function jS(e){return new Response(kS(e.body),{status:e.status,headers:e.headers})}async function bLe(e,t){let n=e.signal;n.throwIfAborted();let r=new URL(`/api/media/uploads`,e.url);r.searchParams.set(`name`,new URL(e.url).searchParams.get(`name`)??``);let i=e.body?.getReader(),a=()=>{i?.cancel(n.reason).catch(()=>{})};n.addEventListener(`abort`,a,{once:!0});let o,s=!1,c=!1,l=()=>{if(o&&!c){c=!0;try{t({method:`DELETE`,path:o}).catch(()=>{})}catch{}}};try{let e=await AS(t({method:`POST`,path:r.pathname+r.search}).then(e=>{if(e.status===201){let{id:t}=JSON.parse(new TextDecoder().decode(kS(e.body)));if(typeof t!=`string`||!/^[a-f0-9-]{36}$/.test(t))throw Error(`invalid media upload session`);o=`/api/media/uploads/${t}`,n.aborted&&l()}return e}),n);if(e.status!==201)return jS(e);let a=JSON.parse(new TextDecoder().decode(kS(e.body)));if(!Number.isSafeInteger(a.partBytes)||Number(a.partBytes)<1||Number(a.partBytes)>2<<20||!Number.isSafeInteger(a.maxBytes)||Number(a.maxBytes)<1)throw Error(`invalid media upload limits`);let c=new Uint8Array(Number(a.partBytes)),u=0,d=0,f=async()=>{n.throwIfAborted();let e=await AS(t({method:`PUT`,path:`${o}?offset=${d}`,body:vLe(c.subarray(0,u))}),n);if(e.status!==200)return e;d+=u,u=0};for(;i;){n.throwIfAborted();let{value:e,done:t}=await AS(i.read(),n);if(t)break;if(d+u+e.byteLength>Number(a.maxBytes))throw Error(`media upload exceeds the ${a.maxBytes} byte limit`);for(let t=0;t<e.byteLength;){let n=Math.min(c.byteLength-u,e.byteLength-t);if(c.set(e.subarray(t,t+n),u),u+=n,t+=n,u===c.byteLength){let e=await f();if(e)return jS(e)}}}if(u){let e=await f();if(e)return jS(e)}n.throwIfAborted();let p=await AS(t({method:`POST`,path:o}),n);return s=p.status===200,jS(p)}finally{n.removeEventListener(`abort`,a),i?.cancel().catch(()=>{}),i?.releaseLock(),s||l()}}function xLe(e,t,n=globalThis.fetch.bind(globalThis),r=new OLe,i=``){let a=t=>e(`higgsedit_http`,t);return async(e,o)=>{let s=new Request(e,o);if(!s.url.startsWith(`${t}/`))return n(e,o);let c=s.url.slice(t.length),l=i+c,u=s.method.toUpperCase(),d=s.signal,f={};for(let e of[`if-none-match`,`if-modified-since`,`if-range`]){let t=s.headers.get(e);t!==null&&(f[e]=t)}let p=Object.keys(f).length?{headers:f}:{},m=e=>new Response(u===`HEAD`||e.status===304||e.status===204?null:kS(e.body),{status:e.status,headers:e.headers});if(u===`POST`&&[`/api/media`,`/api/media/stream`].includes(new URL(c,s.url).pathname))return bLe(s,a);if(u!==`GET`||!(c.startsWith(`/project/`)||c.startsWith(`/preview/`))){let e=u===`GET`||u===`HEAD`?void 0:vLe(new Uint8Array(await s.arrayBuffer()));return m(await a({method:u,path:c,...p,...e===void 0?{}:{body:e}}))}let h=wLe.exec(s.headers.get(`range`)??``),g=e=>{if(!e.current)throw Error(`${c}: changed while reading`)};if(Object.keys(f).length){let e=r.revision(l),t=await a({method:`HEAD`,path:c,...p});if(g(e),t.status!==200)return m(t);let n=Number(t.headers[`content-length`]);if(!Number.isSafeInteger(n)||n<0)throw Error(`${c}: missing media size`);let i=DLe(t.headers,n);r.setFile(l,i);let o=f[`if-range`];if(h&&o){let e=Date.parse(o),t=Date.parse(i.modified??``);(o.startsWith(`"`)?o===i.etag:!o.startsWith(`W/`)&&t<=Date.now()-6e4&&e===t)||(h=null)}}let _=r.revision(l),v=h?Number(h[1]):0,y=async e=>{g(_);let t=await a({method:`GET`,path:c,rangeStart:e*MS,rangeEnd:e*MS+MS-1});g(_);let n=kS(t.body);if(t.status!==200&&t.status!==206)throw Object.assign(Error(`${c}: ${t.status} at byte ${e*MS}`),{reply:t});let i=t.status===200?n.length:ALe(t.headers[`content-range`]),o=DLe(t.headers,i),s=r.file(l);if(s&&!ELe(s,o))throw r.dropPath(l),Error(`${c}: changed while reading`);return r.setFile(l,o),t.status===200?n.subarray(e*MS,e*MS+MS):n},b=async e=>{g(_);let t=await r.chunk(l,e,()=>y(e));return g(_),t};if(!r.file(l))try{await b(Math.floor(v/MS))}catch(e){let t=e.reply;if(t)return m(t);throw e}let{size:x,type:S,etag:C,modified:w,cacheControl:T}=r.file(l),E=Math.min(h?.[2]?Number(h[2]):x-1,x-1);if(v>E)return new Response(null,{status:416,headers:{"content-range":`bytes */${x}`}});let D=Math.floor(E/MS),O=Math.floor(v/MS),k=new ReadableStream({async pull(e){if(d.aborted)return e.error(d.reason);for(let e=O+1;e<=Math.min(O+4,D);e++)b(e).catch(()=>{});let t;try{t=await b(O)}catch(t){return e.error(t)}let n=Math.max(v,O*MS)-O*MS,r=Math.min(E,O*MS+t.length-1)-O*MS;if(r<n)return e.error(Error(`${c}: short read at byte ${O*MS}`));e.enqueue(t.slice(n,r+1)),++O>D&&e.close()}},{highWaterMark:0}),A=new Headers({"content-type":S,"content-length":String(E-v+1),"accept-ranges":`bytes`});return C&&A.set(`etag`,C),w&&A.set(`last-modified`,w),T&&A.set(`cache-control`,T),h?(A.set(`content-range`,`bytes ${v}-${E}/${x}`),new Response(k,{status:206,headers:A})):new Response(k,{status:200,headers:A})}}function SLe(e,t,n=globalThis.EventSource,r,i={}){let a=i.waitMs??2500;class o extends EventTarget{static CONNECTING=0;static OPEN=1;static CLOSED=2;CONNECTING=0;OPEN=1;CLOSED=2;url;withCredentials=!1;readyState=0;onopen=null;onmessage=null;onerror=null;abort=new AbortController;constructor(e,r){if(super(),this.url=String(e),!this.url.startsWith(`${t}/`)){if(!n)throw Error(`no EventSource for ${this.url}`);return new n(e,r)}this.loop()}async loop(){let t=-1,n=0;for(;!this.abort.signal.aborted;){let i;try{await PLe(n,this.abort.signal);let r=Date.now();if(i=await NLe(e,t,a,this.abort.signal),this.abort.signal.aborted)return;n=t>=0&&i.events.length===0?Math.max(0,a-(Date.now()-r)):0}catch{if(this.abort.signal.aborted)return;this.emit(new Event(`error`),this.onerror),n=jLe;continue}this.readyState===0&&(this.readyState=1,this.emit(new Event(`open`),this.onopen));for(let e of i.events){if(this.abort.signal.aborted)return;r?.(e),this.readyState!==2&&this.emit(new MessageEvent(`message`,{data:JSON.stringify(e)}),this.onmessage)}t=i.seq}}emit(e,t){t?.call(this,e),this.dispatchEvent(e)}close(){this.readyState=2,this.abort.abort()}}return o}var MS,CLe,wLe,TLe,ELe,DLe,OLe,kLe,ALe,jLe,NS,PS,MLe,NLe,PLe,FLe=o((()=>{MS=1<<20,CLe=256<<20,wLe=/^bytes=(\d+)-(\d*)$/,TLe=[`/project/`,`/preview/`],ELe=(e,t)=>e.size===t.size&&(e.etag||t.etag?e.etag===t.etag:e.modified===t.modified),DLe=(e,t)=>({size:t,type:e[`content-type`]??`application/octet-stream`,etag:e.etag,modified:e[`last-modified`],cacheControl:e[`cache-control`]}),OLe=class{limit;meta=new Map;chunks=new Map;sizes=new Map;revisions=new Map;bytes=0;constructor(e=CLe){this.limit=e}file(e){return this.meta.get(e)}setFile(e,t){let n=this.meta.get(e);n&&!ELe(n,t)&&this.dropPath(e),this.meta.set(e,t)}revision(e){let t=this.revisions.get(e);return t||this.revisions.set(e,t={current:!0}),t}chunk(e,t,n){let r=`${e}#${t}`,i=this.chunks.get(r);if(i)return this.chunks.delete(r),this.chunks.set(r,i),i;let a=n();return this.chunks.set(r,a),a.then(e=>{this.chunks.get(r)===a&&(this.sizes.set(r,e.length),this.bytes+=e.length,this.trim())},()=>{this.chunks.get(r)===a&&this.chunks.delete(r)}),a}drop(e,t=``){for(let n of e)for(let e of TLe)this.dropPath(t+e+n.replace(/^\.?\//,``))}dropNamespace(e=``){for(let t of new Set([...this.meta.keys(),...this.revisions.keys()]))t.startsWith(`${e}/`)&&this.dropPath(t)}dropPath(e){let t=this.revisions.get(e);t&&(t.current=!1),this.revisions.delete(e),this.meta.delete(e);for(let t of this.chunks.keys())t.slice(0,t.lastIndexOf(`#`))===e&&this.forget(t)}forget(e){this.chunks.delete(e),this.bytes-=this.sizes.get(e)??0,this.sizes.delete(e)}trim(){for(let e of this.chunks.keys()){if(this.bytes<=this.limit)return;this.sizes.has(e)&&this.forget(e)}}},kLe=Uint8Array.fromBase64,ALe=e=>Number(/\/(\d+)$/.exec(e??``)?.[1]??NaN),jLe=2500,NS=!1,PS=[],MLe=8,NLe=(e,t,n,r)=>new Promise((i,a)=>{if(r.aborted)return a(r.reason);if(NS&&PS.length>=MLe)return a(Error(`Editor event queue is full`));let o=!1,s=()=>{if(!o){let e=PS.indexOf(c);e>=0&&PS.splice(e,1)}a(r.reason)},c=()=>{o=!0,NS=!0,Promise.resolve().then(()=>(r.throwIfAborted(),e(`higgsedit_events`,{after:t,waitMs:n}))).then(e=>i(e),a).finally(()=>{r.removeEventListener(`abort`,s),NS=!1,PS.shift()?.()})};r.addEventListener(`abort`,s,{once:!0}),NS?PS.push(c):c()}),PLe=(e,t)=>new Promise((n,r)=>{if(t.aborted)return r(t.reason);let i,a=()=>{clearTimeout(i),typeof document<`u`&&document.removeEventListener(`visibilitychange`,s),t.removeEventListener(`abort`,o)},o=()=>{a(),r(t.reason)},s=()=>{(typeof document>`u`||document.visibilityState!==`hidden`)&&(a(),n())},c=()=>{typeof document<`u`&&document.visibilityState===`hidden`?document.addEventListener(`visibilitychange`,s):s()};t.addEventListener(`abort`,o,{once:!0}),e>0?i=setTimeout(c,e):c()})})),ILe=o((()=>{_Le(),tIe(),FLe(),uLe(),TPe(),ZIe(),GPe(),iS(),CIe(),qIe(),BIe(),iLe()}));function LLe(e){let t=``;for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t)}function RLe(e,t,n){return async(r,i)=>{let a=r instanceof Request?r.url:String(r),o=i?.method??(r instanceof Request?r.method:`GET`);if(!a.startsWith(`${t}/`)||o.toUpperCase()!==`POST`)return n(r,i);let s=new Request(r,i);s.signal.throwIfAborted();let c=s.body?.getReader();if(!c)return n(s);let l,u=0,d=async()=>{let e=new Uint8Array(FS),t=0;for(;t<e.length;){if(s.signal.throwIfAborted(),!l||u===l.length){let e=await c.read();if(e.done)break;l=e.value,u=0}let n=Math.min(e.length-t,l.length-u);e.set(l.subarray(u,u+n),t),u+=n,t+=n}return t?e.subarray(0,t):null},f=crypto.randomUUID(),p=a.slice(t.length),m=!1,h=!1,g,_=()=>(m&&!h&&(g??=e(`video_editing_upload`,{id:f,path:p,offset:0,part:``,last:!1,cancel:!0}).catch(()=>void 0)),g),v=Promise.withResolvers(),y=()=>{c.cancel(s.signal.reason).catch(()=>void 0),_(),v.reject(s.signal.reason)};v.promise.catch(()=>void 0),s.signal.addEventListener(`abort`,y,{once:!0});try{s.signal.throwIfAborted();let t=await d(),r=await d();if(s.signal.throwIfAborted(),!r)return await n(new Request(a,{method:`POST`,headers:s.headers,body:t?new Blob([t]):null,signal:s.signal}));let i=0,o;for(;t;)s.signal.throwIfAborted(),m=!0,o=await Promise.race([e(`video_editing_upload`,{id:f,path:p,offset:i,part:LLe(t),last:r===null}),v.promise]),s.signal.throwIfAborted(),i+=t.length,t=r,r=t?await d():null;h=!0;let{status:c,headers:l,body:u}=o,g=Uint8Array.from(atob(u),e=>e.charCodeAt(0));return new Response(g.length?g:null,{status:c,headers:l})}finally{s.signal.removeEventListener(`abort`,y),c.cancel().catch(()=>void 0),c.releaseLock(),_()}}}var FS,zLe=o((()=>{FS=2<<20}));function BLe(e){let t=0,n=[];return async r=>{t>=e&&await new Promise(e=>n.push(e)),t++;try{return await r()}finally{t--,n.shift()?.()}}}function VLe(e){IS=e}function HLe(e){return LS.add(e),()=>LS.delete(e)}async function ULe(e){try{return(await fetch(`${e}/ping`,{signal:AbortSignal.timeout(qLe)})).ok}catch{return!1}}function WLe(e,t){let n=BLe(XLe),r=new OLe,i=e=>{if(!e.startsWith(`${t.base}/`))return null;let n=e.slice(t.base.length+1).split(`/`,1)[0];if(!/^[a-f0-9]{16}$/.test(n))throw TypeError(`The editor request must name a project session.`);return n},a=r=>async(i,a)=>{let o=YLe[i]??i,s={...a,project:r};try{return await(i===`higgsedit_events`?Yp(e,o,s):n(()=>Yp(e,o,s)))}catch(e){throw e instanceof Error&&e.message.startsWith(JLe)&&t.onLost(r),e}},o=async(e,n)=>{let o=e instanceof Request?e.url:String(e),s=i(o);if(!s)return t.fetch(e,n);if(t.mode===`direct`){let r=await t.fetch(e,n);return r.status===410&&t.onLost(s),r}let c=`${t.base}/${s}`,l=a(s);return RLe(l,c,xLe(l,c,t.fetch,r,c))(e,n)};class s extends EventTarget{static CONNECTING=0;static OPEN=1;static CLOSED=2;constructor(e,n){super();let o=i(String(e));return new(o?SLe(a(o),`${t.base}/${o}`,t.EventSource,t.mode===`bridge`?yLe(r,`${t.base}/${o}`):void 0,{waitMs:t.mode===`direct`?2e4:2500}):t.EventSource)(e,n)}}return{fetch:o,EventSource:s}}async function GLe(e,t,n){return QLe??=(async()=>{let n=t?await ULe(t):!1;RS=n?`direct`:`bridge`;let r=WLe(e,{base:n?t:KLe,mode:RS,fetch:globalThis.fetch.bind(globalThis),EventSource:globalThis.EventSource,onLost:ZLe});return globalThis.fetch=r.fetch,globalThis.EventSource=r.EventSource,RS})(),await QLe===`direct`?`${t}/${n}`:`${KLe}/${n}`}var KLe,qLe,JLe,YLe,XLe,IS,LS,ZLe,QLe,RS,$Le,eRe,tRe=o((()=>{ILe(),zLe(),Xp(),KLe=`https://higgsedit.invalid`,qLe=2500,JLe=`project-unknown`,YLe={higgsedit_http:`video_editing_http`,higgsedit_events:`video_editing_events`},XLe=6,IS=null,LS=new Set,ZLe=e=>{if(e===IS)for(let e of LS)e()},QLe=null,RS=`same-origin`,$Le=()=>IS,eRe=()=>RS})),X=u(_(),1);Wf(),tRe(),Xp();var nRe=1500,rRe=G({path:W().nullable(),session:W().optional(),name:W().optional(),roots:Af(W()).optional(),recent:Af(W()).optional(),names:Ff(W(),W()).optional(),usedAt:Ff(W(),Cf()).optional(),error:W().optional(),direct:Sf().nullable().optional()});function iRe(e,t){let[n,r]=(0,X.useState)({kind:`checking`}),[i,a]=(0,X.useState)(0),o=(0,X.useRef)(t??null),s=(0,X.useCallback)(e=>{e&&(o.current=e),a(e=>e+1)},[]),c=(0,X.useRef)(!1),l=n.kind===`open`?n.project.session:null,u=n.kind===`unavailable`;return(0,X.useEffect)(()=>{if(!e||u)return;VLe(l);let t=!0,n=null,i=()=>{n!==null&&clearTimeout(n),n=null,Yp(e,`video_editing_session`,o.current?{project:o.current}:{}).then(async a=>{let s=rRe.parse(a);if(!t)return;c.current=!0,s.session&&(o.current??=s.session);let u={roots:s.roots??[],recent:s.recent??[],names:s.names,usedAt:s.usedAt};if(!s.path||!s.session){r({kind:`none`,...u,...s.error?{error:s.error}:{}}),n=setTimeout(i,nRe);return}if(s.session===l){r(e=>e.kind===`open`?{...e,...u,project:{...e.project,name:s.name??e.project.name}}:e);return}let d=await GLe(e,s.direct,s.session);t&&(VLe(s.session),r({kind:`open`,...u,project:{path:s.path,session:s.session,name:s.name??`project`,origin:d}}))}).catch(()=>{t&&(c.current?n=setTimeout(i,nRe):r({kind:`unavailable`}))})},a=HLe(i);return i(),()=>{t=!1,a(),n!==null&&clearTimeout(n)}},[e,l,u,i]),{state:n,refresh:s}}Wf();var aRe=W().trim().min(1).max(120);function oRe(e){return(e.split(/[\\/]/).filter(Boolean).at(-1)??`Untitled project`).replace(/^Untitled project-[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i,`Untitled project`)}var zS=o((()=>{Tm(),Yx(),Nm()}));function BS(e,t){let n=e?.scenes.find(t=>t.id===e.activeSceneId);if(!e||!n)return[];let r=new Set(t),i=new Set(e.assets.filter(e=>e.kind===`video`).map(e=>e.id));return n.tracks.filter(e=>!e.locked).flatMap(t=>t.clips.filter(e=>r.has(e.id)&&!e.locked&&e.kind===`media`&&i.has(e.assetId)).sort((e,t)=>e.timeRange.start-t.timeRange.start).map(t=>({projectId:e.id,sceneId:n.id,clipId:t.id,assetId:t.assetId})))}function sRe(e,t){let n=BS(e,t);if(n.length&&n.length===t.length)return n;let r=e?.scenes.find(t=>t.id===e.activeSceneId)?.tracks.flatMap(e=>e.clips.filter(e=>t.includes(e.id)));throw!r?.length||r.length!==t.length?Error(`Select a video clip on the timeline to use this tool.`):r.some(t=>t.kind!==`media`||!e?.assets.some(e=>e.id===t.assetId&&e.kind===`video`))?Error(`This tool only works with video clips. Select a video clip on the timeline.`):Error(`Unlock the selected video clips and their tracks to use this tool.`)}function VS(e,t){if(e?.id!==t.projectId||e.activeSceneId!==t.sceneId)return null;let n=e.scenes.find(e=>e.id===t.sceneId);if(!n)return null;for(let[e,r]of n.tracks.entries()){let i=r.clips.find(e=>e.id===t.clipId);if(i?.kind===`media`&&i.assetId===t.assetId&&!i.locked&&!r.locked)return{scene:n,track:r,trackIndex:e,clip:i}}return null}function HS(){return typeof crypto<`u`&&`randomUUID`in crypto?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function cRe(e){return e.slice(0,40).replace(/[\\/:*?"<>|\n\r]+/g,` `).replace(/\s+/g,` `).trim()||`generated-media`}function lRe(e,t,n){let r=e.kind===`image`?5:e.duration??5,i=e.width!=null&&e.width>0?e.width:t.width,a=e.height!=null&&e.height>0?e.height:t.height,o=Math.min(t.width/i,t.height/a),s={id:HS(),name:e.name,transform:{...pRe,x:t.width/2,y:t.height/2,scaleX:o,scaleY:o},size:{width:i,height:a},opacity:1,blendMode:`normal`,effects:[],timeRange:{start:n,duration:r},animations:[],presetAnimations:[],mask:null,locked:!1,hidden:!1};return e.kind===`audio`?{...s,kind:`audio`,size:{width:0,height:0},transform:{...pRe},assetId:e.id,trim:{start:0,end:e.duration??r},speed:1,preservePitch:!0,volume:1,muted:!1}:{...s,kind:`media`,assetId:e.id,trim:{start:0,end:e.duration??r},speed:1,preservePitch:!0,volume:1,muted:!1,cornerRadius:{mixed:!1,uniform:0,tl:0,tr:0,br:0,bl:0}}}function uRe(e,t,n){let r=Math.max(0,t);for(let t of[...e?.clips??[]].sort((e,t)=>e.timeRange.start-t.timeRange.start)){let e=t.timeRange.start+t.timeRange.duration;if(!(e<=r+1e-6)){if(t.timeRange.start>=r+n-1e-6)break;r=e}}return r}function dRe(e,t,n,r,i){let a=e.scenes.find(t=>t.id===e.activeSceneId)??null;if(!a)return null;if(i&&`aboveSources`in i){let a=e,o=[],s=[];for(let e of i.aboveSources){let i=dRe(a,t,n,r,{aboveSource:e});if(!i)return null;o.push(...i.envelope.ops),s.push(i.clipId),a=Ux(a,i.envelope.ops)}return s.length?{clipId:s[0],clipIds:s,envelope:{id:HS(),name:`Add generated clips`,coalesceKey:null,ops:o}}:null}let o=e.assets.some(e=>e.id===t.id)?[]:[{op:`insert`,path:[`assets`],index:e.assets.length,value:US(t)}];if(i&&`aboveSource`in i){let n=VS(e,i.aboveSource);if(!n||t.kind===`audio`)return null;let r=lRe(t,a,n.clip.timeRange.start),s=i.aboveSource.resultRange===`clip`,c=i.aboveSource.resultRange===`extend`,l=s?0:n.clip.trim.start,u=s?1:n.clip.speed,d=((t.duration??n.clip.trim.end)-l)/u,f=s||c?d:Math.min(n.clip.timeRange.duration,d);if(f<=0)return null;r.timeRange.duration=f,r.trim={start:l,end:l+f*u},r.speed=u,r.preservePitch=n.clip.preservePitch,r.muted=n.clip.muted||n.track.muted,r.volume=n.clip.volume;let p=i.aboveSource.resultTrack,m=p?.sourceTrackId===n.track.id?p.id:void 0,h=a.tracks.findIndex(e=>e.id===m),g=a.tracks[h],_=g&&h>n.trackIndex&&!g.locked&&!g.hidden&&g.clips.every(e=>e.timeRange.start>=r.timeRange.start+f-1e-6||e.timeRange.start+e.timeRange.duration<=r.timeRange.start+1e-6),v=e.scenes.indexOf(a),y={...Kx(),...m&&!g?{id:m}:{},clips:[r]},b=_?{op:`insert`,path:[`scenes`,v,`tracks`,h,`clips`],index:g.clips.length,value:US(r)}:{op:`insert`,path:[`scenes`,v,`tracks`],index:n.trackIndex+1,value:US(y)};return{clipId:r.id,envelope:{id:HS(),name:`Add generated clip`,coalesceKey:null,ops:[...o,b,{op:`set`,path:[`scenes`,v,`tracks`,n.trackIndex,`clips`,n.track.clips.indexOf(n.clip),`hidden`],value:!0}]}}}let s=i?a.tracks.find(e=>e.id===i.preferredTrackId&&!e.locked&&!e.hidden)??a.tracks.find(e=>!e.locked&&!e.hidden&&(!e.clips.length||e.clips.some(e=>e.kind!==`audio`))):void 0,c=lRe(t,a,i?uRe(s,n,t.kind===`image`?5:t.duration??5):Math.max(n,0)),l=r.planClipPlacement(e,a.id,c,{preferredTrackId:s?.id});if(!l)return null;let u=[...o,...l.ops];return{envelope:{id:HS(),name:`Add generated clip`,ops:u,coalesceKey:null},clipId:c.id}}async function fRe(e,t){try{let n=e.snapshot();if(!n||t.projectId&&n.id!==t.projectId)return{ok:!1,message:`The video editor project changed`};let r=[];if(e.insertion&&`aboveSources`in e.insertion&&r.push(...e.insertion.aboveSources),e.insertion&&`aboveSource`in e.insertion&&r.push(e.insertion.aboveSource),r.some(e=>!VS(n,e)))return{ok:!1,message:`The source clip is no longer available for reframing`};let i=e.playhead(),a=await e.fetchResult(t);if(e.snapshot()?.id!==n.id||e.snapshot()?.activeSceneId!==n.activeSceneId)return{ok:!1,message:`The video editor project or scene changed`};let o=a.name.includes(`.`)?a.name.split(`.`).pop():`bin`,s=`projectSrc`in a?a:new File([a],`${cRe(t.prompt)}.${o}`,{type:a.type}),c=await e.importFile(s,{generationId:t.id,sourceUrl:t.resultUrl??void 0});Hp(t.id)&&e.rememberSource?.(c,t.id);let l=async()=>{let t=e.snapshot();if(!t||t.id!==n.id||t.activeSceneId!==n.activeSceneId)return{ok:!1,message:`The video editor project or scene changed`};let a=dRe(t,c,i,e.placement,e.insertion);if(!a)return{ok:!1,message:r.length?`The source clip changed or is locked`:`No active scene`};await e.execute(`document.apply`,a.envelope);let o=e.snapshot(),s=o?.scenes.find(e=>e.id===n.activeSceneId)?.tracks.flatMap(e=>e.clips),l=(a.clipIds??[a.clipId]).every(e=>s?.some(t=>t.id===e));return o?.id!==n.id||!l?{ok:!1,message:`The result was not added to the target timeline. Reopen that project and retry.`}:(o.activeSceneId===n.activeSceneId&&e.select(a.clipId),{ok:!0,clipId:a.clipId})};return await(e.commit?e.commit(l):l())}catch(e){return{ok:!1,message:e instanceof Error?e.message:`Import failed`}}}var pRe,US,WS=o((()=>{Gp(),zS(),pRe={x:0,y:0,scaleX:1,scaleY:1,rotation:0,skewX:0,skewY:0,anchorX:.5,anchorY:.5,flipX:!1,flipY:!1},US=e=>JSON.parse(JSON.stringify(e))}));function mRe(e,t,n){if(e?.id!==n.projectId||e.activeSceneId!==n.sceneId)throw Error(`The target project or scene is no longer open. Reopen its aspect ratio menu.`);let r=e.scenes.find(e=>e.id===n.sceneId);if(!r)throw Error(`Open a video scene first.`);let i=hRe.find(e=>{let[t,n]=e.split(`:`).map(Number);return Math.abs(r.width/r.height-t/n)<.001});if(!i)throw Error(`Choose 21:9, 16:9, 9:16, 4:3, 3:4 or 1:1 before adapting videos.`);let a=new Set(e.assets.filter(e=>e.kind===`video`).map(e=>e.id)),o=t.length?[...new Set(t)]:r.tracks.filter(e=>!e.hidden&&!e.locked).flatMap(e=>e.clips.filter(e=>!e.hidden&&!e.locked&&e.kind===`media`&&a.has(e.assetId)).map(e=>e.id));if(!o.length)throw Error(`Add an unlocked video to the timeline first.`);if(o.length>20)throw Error(`Select up to 20 video clips to adapt at a time.`);let s=sRe(e,o);return{target:{...n,clipIds:s.map(e=>e.clipId)},prompt:[`Adapt these videos to the timeline's ${i} aspect ratio (${r.width} × ${r.height}).`,`Use Higgsfield's reframe tool with aspect_ratio "${i}" to extend the image into the empty edges. The target format is already chosen; start the adaptation without asking me to choose an aspect ratio again.`,`Preserve the original subjects, content and motion; do not stretch or crop the video to fill the canvas. Keep the timeline size, source duration, audio and clip timing unchanged. Adapt only the attached source videos, with one result per unique source, and keep the originals available.`].join(`
280
280
  `)}}var hRe,gRe=o((()=>{WS(),hRe=[`21:9`,`16:9`,`9:16`,`4:3`,`3:4`,`1:1`]}));function _Re(e){return`https://static.higgsfield.ai/video-edit-form/v2/color-map/${{inferno:`magma`,magma:`inferno`}[e]??e}.webp`}function vRe(e){return{...JS[e]}}function yRe(e,t){switch(e){case`reframe`:return[{key:`aspect_ratio`,label:`Aspect ratio`,options:KS([`9:16`,`3:4`,`1:1`,`4:3`,`16:9`,`21:9`])},{key:`resolution`,label:`Quality`,options:TRe}];case`upscale`:return[{key:`resolution`,label:`Resolution`,options:ORe[String(t.model)]??[]},{key:`fps`,label:`Frame rate`,options:t.model===`bytedance`?KS([`30`,`60`]):[{value:`original`,label:`Original`},...qS]}];case`sdr-to-hdr`:return[{key:`output_format`,label:`Output format`,options:[{value:`h265`,label:`H.265 10-bit`},{value:`prores`,label:`ProRes 10-bit`},{value:`exr`,label:`EXR 16-bit`}]}];case`depth-map`:return[{key:`resolution`,label:`Resolution`,options:[{value:`auto`,label:`Auto`},...KS([`360p`,`480p`,`720p`,`1080p`])]}];default:return[]}}function bRe(e,t,n,r){if(e===`upscale`&&n===`model`){let n={...t,model:r};for(let t of yRe(e,n))t.options.some(e=>e.value===String(n[t.key]))||(n[t.key]=t.options[0].value);return n}return{...t,[n]:r}}function xRe(e,t,n){if(!e)return[];let r=n===`selected_clips`?t:e.scenes.find(t=>t.id===e.activeSceneId)?.tracks.flatMap(t=>t.hidden?[]:t.clips.filter(t=>t.kind===`media`&&e.assets.some(e=>e.id===t.assetId&&e.kind===`video`)).map(e=>e.id))??[];return[...new Set(r)]}function SRe(e,t,n){if(!e)throw Error(`Open a video project first.`);let r=xRe(e,t,n);if(!r.length)throw Error(n===`selected_clips`?`Select video clips on the timeline, or choose Full video.`:`Add a video to the timeline first.`);if(r.length>20)throw Error(`Choose up to 20 video clips per request.`);if(BS(e,r).length!==r.length)throw Error(`Choose unlocked video clips. Locked clips and other layer types cannot be processed.`);return{projectId:e.id,sceneId:e.activeSceneId,clipIds:r}}function CRe(e,t,n,r=[]){let i={};for(let t of Object.keys(JS[e]))i[t]=n[t]??JS[e][t];for(let t of yRe(e,n))if(!t.options.some(e=>e.value===String(i[t.key])))throw Error(`Choose a valid ${t.label.toLowerCase()}.`);let a={output_format:e===`remove-background`?[`mask`,`cut`]:[`h265`,`prores`,`exr`],extension_mode:[`forward`,`backward`],bitrate_mode:[`high`,`standard`],resolution:e===`extend`?[`480p`,`720p`,`1080p`]:[],generate_audio:[!0,!1],side_by_side:[!0,!1],model_version:[`standard`,`pro`],preset:[`common`,`aigc`,`short_series`,`ugc`,`old_film`],enhancement:[`slp-2.5`,`prob-4`,`ahq-12`,`iris-3`,`rhea-1`,`ghq-5`,`thd-3`]};for(let[e,t]of Object.entries(a))if(e in i&&t.length&&!t.includes(i[e]))throw Error(`Choose a valid ${e.replaceAll(`_`,` `)}.`);if(String(i.prompt??``).length>6e4)throw Error(`Use a prompt of up to 60,000 characters.`);if(r.length&&e!==`extend`)throw Error(`References are only supported for Extend Video.`);if(r.some(e=>!e.media_id||![`image`,`audio`].includes(e.kind))||r.filter(e=>e.kind===`image`).length>30||r.filter(e=>e.kind===`audio`).length>10)throw Error(`Use up to 30 image and 10 audio references.`);let o=t===`full_video`?`all video clips in the current timeline`:`the selected video clips`,s,c;switch(e){case`reframe`:c=`reframe`,s=`Reframe ${o} with Higgsfield.`;break;case`remove-background`:if(c=`sam_3_video`,!String(i.prompt).trim())throw Error(`Describe which elements to remove or keep.`);s=`Remove the background from ${o} with Higgsfield. ${String(i.prompt).trim()}`,i.apply_mask=i.output_format===`cut`,delete i.output_format;break;case`upscale`:if(!DRe.some(e=>e.value===i.model))throw Error(`Choose an upscale model.`);s=`Upscale ${o} with Higgsfield.`,c=i.model===`bytedance`?`bytedance_video_upscale`:`topaz_video`,c===`topaz_video`?(i.aspect_ratio=`auto`,i.enhancement={model:i.model===`slp-2.5`?`slp-2.5`:String(i.enhancement),params:null},i.frame_interpolation=i.fps===`original`?null:{model:`apo-8`,fps:Number(i.fps),slowmo:1},delete i.fps,delete i.model_version,delete i.preset):(i.fps=Number(i.fps),delete i.enhancement),delete i.model;break;case`fps-boost`:if(c=`fps_boost`,!qS.some(e=>e.value===String(i.fps)))throw Error(`Choose a supported frame rate.`);i.fps=Number(i.fps),i.variant=`topaz`,s=`Change the frame rate of ${o} with Higgsfield.`;break;case`extend`:if(c=`seedance_2_5`,i.mode=`video_extension`,!Number.isInteger(i.duration)||Number(i.duration)<4||Number(i.duration)>30)throw Error(`Choose a duration between 4 and 30 seconds.`);s=`Extend ${o} with Higgsfield.${String(i.prompt).trim()?` ${String(i.prompt).trim()}`:``}`;break;case`sdr-to-hdr`:c=`topaz_hyperion_2_5`,s=`Convert ${o} from SDR to HDR with Higgsfield.`;break;case`depth-map`:if(c=`depth_anything_video`,!ERe.includes(i.colormap))throw Error(`Choose a color map.`);if(!Number.isInteger(i.max_frames)||Number(i.max_frames)<1||Number(i.max_frames)>1800)throw Error(`Max frames must be between 1 and 1800.`);i.variant=`VDA-Large`,s=`Generate depth maps for ${o} with Higgsfield.`}return{prompt:s,context:{tool:e,model:c,source_scope:t,parameters:i,...r.length?{references:r}:{}},preparation:wRe(e)}}function wRe(e){return e===`reframe`?`reframe`:e===`extend`?`extend`:`clip`}var GS,KS,TRe,qS,ERe,JS,DRe,ORe,YS=o((()=>{WS(),GS={reframe:`Reframe`,"remove-background":`Remove BG`,upscale:`Upscale`,"fps-boost":`FPS Boost`,extend:`Extend Video`,"sdr-to-hdr":`SDR to HDR`,"depth-map":`Depth Map`},KS=e=>e.map(e=>({value:e,label:e})),TRe=KS([`480p`,`720p`,`1080p`]),qS=KS([`24`,`30`,`60`,`120`]),ERe=[`grayscale`,`turbo`,`inferno`,`magma`,`viridis`],JS={reframe:{aspect_ratio:`9:16`,resolution:`720p`},"remove-background":{prompt:``,output_format:`mask`},upscale:{model:`slp-2.5`,resolution:`2160p`,fps:`original`,enhancement:`prob-4`,model_version:`standard`,preset:`common`},"fps-boost":{fps:`24`},extend:{extension_mode:`forward`,prompt:``,duration:5,resolution:`1080p`,bitrate_mode:`high`,generate_audio:!0},"sdr-to-hdr":{output_format:`h265`},"depth-map":{colormap:`grayscale`,resolution:`auto`,max_frames:1800,side_by_side:!0}},DRe=[{value:`slp-2.5`,label:`Topaz Starlight Precise`},{value:`bytedance`,label:`ByteDance Upscale`},{value:`prob-4`,label:`Topaz Video`}],ORe={bytedance:[{value:`1080p`,label:`1080p`},...[`2k`,`4k`].map(e=>({value:e,label:e.toUpperCase()}))],"prob-4":[{value:`1080p`,label:`1080p`},{value:`2160p`,label:`4K`}],"slp-2.5":[{value:`1080p`,label:`1080p`},{value:`2160p`,label:`4K`}]}})),XS,ZS=o((()=>{XS=class{value;listeners=new Set;constructor(e){this.value=e}get(){return this.value}set(e){if(!Object.is(e,this.value)){this.value=e;for(let t of Array.from(this.listeners))t(e)}}subscribe(e){return this.listeners.add(e),{dispose:()=>this.listeners.delete(e)}}}}));function QS(e){let t=ARe.get(e);return t||(t=new XS(null),ARe.set(e,t)),t}function kRe(e,t,n,r){let i=e.snapshot();if(!i)throw Error(`Open a video project first.`);if(r){if(r.projectId!==i.id||r.sceneId!==i.activeSceneId)throw Error(`The target project is no longer open.`);SRe(i,r.clipIds,`selected_clips`),t.setSelection({clipIds:r.clipIds,sceneId:r.sceneId})}QS(e).set({tool:n,projectId:i.id,sceneId:i.activeSceneId})}var ARe,jRe=o((()=>{ZS(),YS(),ARe=new WeakMap}));function MRe(e,t,n){let r=n=>e?`higgsfield:editor:media-source:${JSON.stringify([e,t??null,n.id])}`:void 0,i=new Map,a=new Map,o=new Map;try{n??=typeof window>`u`?void 0:window.localStorage}catch{}function s(e,t){for(i.delete(e),i.set(e,t);i.size>NRe;)i.delete(i.keys().next().value)}function c(e,t){let i=eC(e),a=o.get(e.id);a&&(a.key=i),s(i,t);try{let a=r(e);a&&n?.setItem(a,JSON.stringify({key:i,mediaId:t}))}catch{}}function l(e){let t=eC(e),a=i.get(t);if(!a)try{let i=r(e),o=i&&n?.getItem(i),s=o?JSON.parse(o):void 0;s?.key===t&&typeof s?.mediaId==`string`&&s.mediaId.length&&(a=s.mediaId)}catch{return}return a&&s(t,a),a}return{remember:c,async resolve(e,t,n){if(e.kind!==`video`&&e.kind!==`image`)throw Error(`Select an image or video first.`);let r=eC(e),i=o.get(e.id);i&&(i.key=r);let u=l(e);if(u)return u;let d=a.get(r);if(d)return d;let f=i??{key:r,count:0};f.count++,o.set(e.id,f);let p=t=>(f.key===r?c(e,t):s(r,t),t),m=e.kind,h=(async()=>{let r=await t(),i=await n(new File([r],e.name,{type:e.mimeType}),m);return p(i)})();a.set(r,h);try{return await h}finally{a.get(r)===h&&a.delete(r),--f.count===0&&o.delete(e.id)}}}}function $S(e,t,n){return(t.mediaSources??=MRe()).resolve(n,async()=>await e.assets.readBlob(n.id),t.upload)}var NRe,eC,tC=o((()=>{NRe=200,eC=e=>JSON.stringify([e.id,e.kind,e.uri,e.hash,e.canonicalRevision??null,e.byteSize])}));function nC(e){let t=FRe.get(e);return t||(t=new XS(null),FRe.set(e,t)),t}function PRe(e,t,n){typeof matchMedia==`function`&&matchMedia(`(prefers-reduced-motion: reduce)`).matches||nC(e).set({documentId:t,clipId:n,startedAt:performance.now()})}var FRe,IRe=o((()=>{ZS(),FRe=new WeakMap}));async function rC(e,t,n,r=t.activeSceneId){if(n.some(e=>e.kind===`image`||e.kind===`video`))try{await e.commands.execute(`fable.panel-viewport.zoomToFit`,{documentId:t.id,sceneId:r,scope:`scene`})}catch(t){e.log.warn(`Could not fit imported media in the viewport`,String(t))}}var iC=o((()=>{}));function LRe(e,t,n,r=()=>{}){let i=new XS([]),a=new XS([]),o=new XS(null),s=new XS(null),c=new XS(null),l=new Map,u=t.queueSession??new Map,d=new Map,f=new Set,p=(e,t)=>`${e}:${t}`,m=(e,t)=>{f.add(p(e,t)),f.size>200&&f.delete(f.values().next().value)},h=!1,g,_=Promise.resolve(),v=e=>{let t=_.then(e);return _=t.catch(()=>{}),t},y,b,x,S,C=null,w,T,E=!1;function D(){if(S&&!h){E=!0;try{u.set(S,{startedAt:C,items:i.get(),dismissed:[...f],selectedId:s.get(),imageStartedAt:w})}finally{E=!1}}}function O(e){C===null&&!i.get().length||b||(b=t.watchVideoFeed(e,()=>i.get(),j,t=>{h||S!==e||o.set(t?`Could not sync videos. Retrying…`:null)},C??void 0,w,C!==null))}let k=Promise.all([e.require(bm),e.require(Cm),e.require(xm),e.require(`capability:storage/local`)]).then(([e,t,r,a])=>{y=e;let l=(e,t)=>{b?.(),b=void 0,C=t?.startedAt??null,w=t?.imageStartedAt,f.clear();for(let e of t?.dismissed??[])f.add(e);i.set(t?.items??[]),s.set(t?.selectedId??null),o.set(null);for(let e of i.get())n(e);e&&O(e)},d=()=>{let t=e.snapshot()?.id;h||t===S||(T?.(),S=t,c.set(null),l(t,t?u.get(t):void 0),T=t?u.subscribe?.(t,e=>{!h&&!E&&S===t&&l(t,e)}):void 0)};return h||(x=e.onEvent(d),d()),{document:e,session:t,placement:r,storage:a}});k.catch(t=>e.log.error(`Generation queue could not connect`,String(t)));function A(e){let t=i.get(),r=t.find(t=>t.id===e.id);r&&Object.keys(e).every(t=>r[t]===e[t])||(r?.status!==`completed`||!r.resultUrl||e.status===`completed`&&e.resultUrl)&&(i.set(r?t.map(t=>t.id===e.id?e:t):[...t,e]),D(),n(e))}function j(e){h||e.projectId!==y?.snapshot()?.id||f.has(p(e.projectId,e.id))||!i.get().some(t=>t.id===e.id)&&i.get().length>=100||A(e)}async function M(n){let{document:a,session:o,placement:s,storage:c}=await k,l=a.snapshot();if(h||!l||l.id!==n.projectId)throw Error(`The video editor project changed`);let u=l.scenes.find(e=>e.id===l.activeSceneId),d=o.currentTime.get(),f=new Set(o.selection.get().clipIds),p=u?.tracks.find(e=>!e.locked&&!e.hidden&&(!e.clips.length||e.clips.some(e=>e.kind!==`audio`))&&e.clips.some(e=>f.has(e.id)))??u?.tracks.find(e=>!e.locked&&!e.hidden&&(!e.clips.length||e.clips.some(e=>e.kind!==`audio`))&&e.clips.some(e=>e.timeRange.start<=d&&d<e.timeRange.start+e.timeRange.duration)),g=await fRe({fetchResult:t.fetchResultFile,rememberSource:t.mediaSources?.remember,importFile:c.importFile.bind(c),snapshot:()=>h?null:a.snapshot(),placement:s,commit:v,execute:(t,n)=>e.commands.execute(t,n),playhead:()=>d,insertion:{afterPlayhead:!0,preferredTrackId:p?.id},select:t=>{o.setSelection({clipIds:[t]});let r=a.snapshot()?.scenes.find(e=>e.id===l.activeSceneId)?.tracks.flatMap(e=>e.clips).find(e=>e.id===t);r&&(o.pause(),o.seek(r.timeRange.start),o.setTimelineView({scrollX:Math.max(0,r.timeRange.start*o.timelineView.get().pxPerSecond-24)}),PRe(a,l.id,t),rC(e,l,[{kind:n.kind}]))}},n);if(!g.ok)throw Error(g.message);r(n.id),m(n.projectId,n.id),i.set(i.get().filter(e=>e.id!==n.id||e.projectId!==n.projectId)),D()}function N(e,t=`video`){return g||(g=k.then(async({document:n})=>{let r=n.snapshot()?.id;if(h||!r)throw Error(`Open a video editor project first`);let i=C===null,a=t===`image`&&w===void 0;a&&(w=Date.now(),b?.(),b=void 0),i&&(C=Date.now(),b?.(),b=void 0),(i||a)&&(D(),O(r));try{await e()}catch(e){throw a&&S===r&&(w=void 0,b?.(),b=void 0,i||O(r),D()),i&&S===r&&(b?.(),b=void 0,C=null,o.set(null),D(),O(r)),e}}).finally(()=>{g=void 0}),g)}return{items:i,importing:a,syncError:o,selectedId:s,creationDraft:c,select(e){!h&&i.get().some(t=>t.id===e)&&(s.set(e),D())},sendRequest:N,async createMedia(e,t){let{document:n}=await k,r=n.snapshot()?.id;if(h||!r)throw Error(`Open a video editor project first`);(c.get()?.kind!==e||t!==void 0)&&c.set({projectId:r,kind:e,prompt:t})},submitVideos(e,n){let r=l.get(e);if(r)return r;let i=k.then(async({document:r})=>{if(h||r.snapshot()?.id!==e)throw Error(`The video editor project changed`);let i=await n();if(!i.length)return;let a=t.submittedVideos(i,e);if(!h&&r.snapshot()?.id===e){a.forEach(j),s.set(a[0].id),D(),O(e);return}let o=u.get(e),c=new Set(o?.dismissed),l=new Map(o?.items.map(e=>[e.id,e]));for(let t of a)c.has(p(e,t.id))||l.set(t.id,t);u.set(e,{startedAt:o?.startedAt??null,imageStartedAt:o?.imageStartedAt,items:[...l.values()].slice(-100),dismissed:o?.dismissed??[],selectedId:a[0].id})}).finally(()=>l.delete(e));return l.set(e,i),i},accept(e){let t=d.get(e);if(t)return t;if(f.has(p(y?.snapshot()?.id,e)))return Promise.resolve();let n=i.get().find(t=>t.id===e);if(!n||n.status!==`completed`||!n.resultUrl)return Promise.reject(Error(`Video is not ready to add`));a.set([...a.get(),e]);let r=M(n).finally(()=>{d.delete(e),a.set(a.get().filter(t=>t!==e))});return d.set(e,r),r},async refresh(e){let n=i.get().find(t=>t.id===e);if(!n||h||n.projectId!==y?.snapshot()?.id)return;let r=await t.getJob(e);!h&&n.projectId===y?.snapshot()?.id&&j({...r,projectId:n.projectId})},dismiss(e){d.has(e)||(m(y?.snapshot()?.id,e),i.set(i.get().filter(t=>t.id!==e)),D())},dispose(){h=!0,b?.(),T?.(),x?.dispose()}}}var aC,oC=o((()=>{zS(),ZS(),WS(),IRe(),iC(),aC=`capability:ai/generation-queue`}));function RRe(e){return BRe.includes(e)}function zRe(e){return HRe[e]??e}var BRe,VRe,HRe,URe=o((()=>{BRe=[`completed`,`failed`,`canceled`],VRe={"16:9":`Wide`,"9:16":`Vertical`,"1:1":`Square`,"4:3":`Classic`,"3:4":`Tall`},HRe={kling:`Kling`,google:`Google`,wan:`Wan`,minimax:`MiniMax`,bytedance:`ByteDance`,xai:`xAI`,higgsfield:`Higgsfield`,bfl:`BFL`,alibaba:`Alibaba`}}));function WRe(e,t){return new Promise(n=>{let r=setTimeout(i,e);function i(){clearTimeout(r),t?.removeEventListener(`abort`,i),n()}t?.addEventListener(`abort`,i,{once:!0})})}async function*GRe(e,t,n){let r=n?.signal,i=n?.pollMs??KRe,a=await e.getJob(t);for(yield a;!RRe(a.status);){if(r?.aborted||(await WRe(i,r),r?.aborted))return a;i=Math.min(qRe,i*JRe),a=await e.getJob(t),yield a}return a}var KRe,qRe,JRe,YRe=o((()=>{URe(),KRe=2500,qRe=5e3,JRe=1.2}));function XRe(e,t,n,r){let i=t.reframeSession??new Map,a,o,s=new Set,c,l,u,d=0,f=!1,p=e=>i.get(e)??ZRe();function m(e){let t=n()?.assets.find(t=>t.id===e.assetId);if(!t)throw Error(`The source media is no longer available.`);return eC(t)}function h(e,t,n,r=!1){let o=p(t),s=o.jobs.find(({job:t})=>t.id===e);if(!s)return;let c=o.requests.find(e=>e.mediaId===s.mediaId)?.source,u=r?o.handled:[...o.handled.filter(t=>t!==e),e].slice(-100),d={...o.placements};c&&n&&(d[e]={sceneId:c.sceneId,sourceClipId:c.clipId,clipId:n}),i.set(t,{...o,jobs:o.jobs.filter(({job:t})=>t.id!==e),handled:u,failures:s.job.status===`failed`?[...(o.failures??[]).filter(({job:t})=>t.id!==e),{job:s.job,sources:o.requests.filter(e=>e.mediaId===s.mediaId).map(({source:e})=>e)}].slice(-100):o.failures,placements:Object.fromEntries(Object.entries(d).filter(([e])=>u.includes(e)))}),queueMicrotask(()=>{let e=p(t);e.jobs.some(({mediaId:e})=>e===s.mediaId)||(i.set(t,{...e,requests:e.requests.filter(e=>e.mediaId!==s.mediaId||!o.requests.includes(e))}),!f&&l===t&&!p(t).requests.length&&(a?.(),a=void 0))})}function g(){let n=l,o=u;if(f||a||!n||!o)return;let c=()=>p(n).requests.filter(({source:e})=>e.sceneId===o),d=c();if(!d.length)return;let m=p(n).jobs.filter(({mediaId:e})=>d.some(t=>t.mediaId===e));s=new Set(m.map(({job:e})=>e.id));for(let{job:e,mediaId:t}of m){let i=d.filter(e=>e.mediaId===t).map(({source:e})=>e);r(e,i[0],i),(e.status===`failed`||e.status===`canceled`)&&h(e.id,n)}a=t.watchReframes(()=>[...new Map(c().map(({mediaId:e,startedAt:t})=>[e,{mediaId:e,projectId:n,startedAt:t}])).values()],(e,t)=>{if(f||l!==n||u!==o)return;let a=p(n),d=c().filter(e=>e.mediaId===t).map(({source:e})=>e);if(!d.length||a.handled.includes(e.id))return;s.add(e.id);let m=a.jobs.find(t=>t.job.id===e.id)?.job,g={...e,editorTool:e.editorTool??m?.editorTool,status:e.status===`completed`&&!e.resultUrl?`in_progress`:e.status};i.set(n,{...a,jobs:[...a.jobs.filter(t=>t.job.id!==e.id),{job:g,mediaId:t}]}),r(g,d[0],d),(e.status===`failed`||e.status===`canceled`)&&h(e.id,n)},t=>{t&&e.log.warn(`Reframe status sync will retry`,String(t))},Math.min(...d.map(({startedAt:e})=>e)),m)}function _(){let e=n();if(!(f||e?.id===l&&e?.activeSceneId===u)){d++,a?.(),a=void 0,o?.(),s=new Set,l=e?.id,u=e?.activeSceneId,o=(e&&i.subscribe?.(e.id,()=>{queueMicrotask(()=>{if(f||l!==e.id)return;let t=p(e.id),n=new Set(t.requests.filter(({source:e})=>e.sceneId===u).map(({mediaId:e})=>e));t.jobs.some(({job:e,mediaId:t})=>n.has(t)&&!s.has(e.id))&&(a?.(),a=void 0,g())})}))??void 0;for(let t of e?p(e.id).failures??[]:[]){let e=t.sources[0];e?.sceneId===u&&r(t.job,e,t.sources)}g()}}let v=e.require(bm).then(e=>{f||(c=e.onEvent(_),_())});v.catch(t=>e.log.error(`Reframe could not connect`,String(t)));function y(e){let t=[...new Map((Array.isArray(e)?e:[e]).map(e=>[sC(e),e])).values()];if(f)throw Error(`The editor closed. Reopen it before continuing.`);if(!t.length||t.some(e=>!VS(n(),e)))throw Error(`Select unlocked video clips first.`);if(t.length>20)throw Error(`Select up to 20 video clips at a time.`);return t}return{async request(e,n){let r=y(e),i=[r.length>1?`Reframe each selected video separately with Higgsfield, preserving its content and motion.`:`Reframe the selected video with Higgsfield, preserving its content and motion.`,n?`Target aspect ratio: ${n}.`:`Ask me which aspect ratio I want before starting.`].join(`
281
281
  `);await t.requestReframe(i,{projectId:r[0].projectId,sceneId:r[0].sceneId,clipIds:r.map(e=>e.clipId)})},async prepare(r,a=`reframe`,o){await v,_();let s=y(r).map(e=>a===`reframe`?e:{...e,resultRange:a===`extend`?`extend`:`source`}),c=JSON.stringify(s.map(e=>[m(e),VS(n(),e)?.clip])),l=d,u=Date.now(),h=new Set(p(s[0].projectId).requests.map(({source:e})=>e.clipId));for(let e of s)h.add(e.clipId);if(h.size>20)throw Error(`Reframe supports up to 20 pending clips. Finish a pending Reframe before adding more.`);let b=new Map,x=s.values(),S=!1,C=await Promise.allSettled(Array.from({length:Math.min(3,s.length)},async()=>{for(let r of x){if(f||l!==d||S)return;let i=m(r);try{let o=n()?.assets.find(e=>e.id===r.assetId);if(o?.kind!==`video`)throw Error(`Select a video clip first.`);if(a===`reframe`&&(o.duration===null||!Number.isFinite(o.duration)||o.duration<=0||o.duration>60))throw Error(`Reframe needs a source video with a known duration of up to 60 seconds.`);b.set(i,await $S(e,t,o))}catch(e){throw S=!0,e}}}));if(f||l!==d)throw Error(`Source preparation was canceled. Reopen the editor and retry.`);let w=C.find(e=>e.status===`rejected`);if(w?.status===`rejected`)throw w.reason;if(c!==JSON.stringify(s.map(e=>[m(e),VS(n(),e)?.clip])))throw Error(`The source clip changed. Select it again.`);let T=s[0].projectId,E=p(T),D=new Map;for(let{source:e}of E.requests)e.resultTrack&&s.some(t=>sC(t)===sC(e))&&D.set(e.resultTrack.sourceTrackId,e.resultTrack.id);let O=s.map(e=>{let t=b.get(m(e));if(E.requests.filter(e=>e.mediaId===t).length&&E.jobs.some(e=>e.mediaId===t))throw Error(`This source is already generating. Wait for it to finish before starting another edit.`);if(s.length>1){let t=VS(n(),e).track.id,r=D.get(t)??HS();D.set(t,r),e={...e,resultTrack:{id:r,sourceTrackId:t}}}return{source:e,mediaId:t,startedAt:u,...o?{requestId:o}:{}}});return i.set(T,{...E,requests:[...E.requests.filter(e=>!O.some(t=>t.mediaId===e.mediaId)),...O]}),g(),s.map(e=>{let t=n(),r=VS(t,e).clip,i=t?.assets.find(t=>t.id===e.assetId);return{clip_id:r.id,media_id:b.get(m(e)),source_range:{...r.trim},playback_speed:r.speed,...a===`reframe`?{source_duration:i?.duration??void 0}:{}}})},cancelPreparation(e,t){let n=p(e),r=n.requests.filter(e=>e.requestId!==t||n.jobs.some(t=>t.mediaId===e.mediaId));r.length!==n.requests.length&&(i.set(e,{...n,requests:r}),l===e&&!r.length&&(a?.(),a=void 0))},async track(e,t){let n=Array.isArray(t)?t:[t],r=n[0];if(!r||n.some(e=>e.projectId!==r.projectId||e.sceneId!==r.sceneId))throw Error(`Result targets must belong to one project and scene.`);await v,_();let o=p(r.projectId),s=o.jobs.find(t=>t.job.id===e.id);if(o.handled.includes(e.id))return;let c=s?.mediaId??`job:${e.id}`,d=o.requests.filter(e=>e.mediaId===c),m=new Set(n.map(sC));if(d.length&&(d.length!==m.size||d.some(e=>!m.has(sC(e.source)))))throw Error(`This result already belongs to another clip.`);i.set(r.projectId,{...o,requests:d.length?o.requests:[...o.requests,...n.map(e=>({mediaId:c,source:e,startedAt:Date.now()}))],jobs:[...o.jobs.filter(t=>t.job.id!==e.id),{job:e,mediaId:c}]}),!f&&l===r.projectId&&u===r.sceneId&&(a?.(),a=void 0,g())},dismissFailure(e,t){let n=p(t);i.set(t,{...n,failures:n.failures?.filter(({job:t})=>t.id!==e)})},placement:(e,t)=>p(t).placements?.[e],finish:h,release:(e,t)=>h(e,t,void 0,!0),dispose(){f=!0,d++,a?.(),o?.(),c?.dispose()}}}var ZRe,sC,QRe=o((()=>{tC(),zS(),WS(),ZRe=()=>({requests:[],jobs:[],handled:[]}),sC=e=>JSON.stringify([e.projectId,e.sceneId,e.clipId,e.assetId,e.resultRange??null])}));function $Re(e,t,n,r){let i=new XS(null),a,o,s=!1;function c(e){let t=n(),r=VS(t,e),i=t?.assets.find(t=>t.id===e.assetId);if(s||!r||i?.kind!==`video`)throw Error(`The source clip or project changed. Return to it and try again.`);return JSON.stringify([eC(i),r.clip])}function l(e){if(c(e.source)!==e.fingerprint)throw Error(`The source clip changed. Start a new request with its current settings.`)}function u(e,t){a&&!s&&i.set({tool:a.input.tool,projectId:a.input.target.projectId,phase:e,total:a.entries.length,started:a.index,message:t})}async function d(){if(!a)return;let o=a,{input:c,entries:d}=o,f=GS[c.tool];u(`submitting`);try{for(let e of d.slice(o.index))l(e),r.pending(e.placeholderId,e.source,f);for(let r of d.slice(o.index)){if(l(r),r.request)continue;let i=n().assets.find(e=>e.id===r.source.assetId);if(c.tool===`reframe`&&(i.duration===null||!Number.isFinite(i.duration)||i.duration<=0||i.duration>60))throw Error(`Reframe supports source videos with a known duration of up to 60 seconds.`);let a=await $S(e,t,i);l(r),r.request={context:c.request.context,mediaId:a,duration:i.duration,projectId:r.source.projectId,label:f}}for(;o.index<d.length;){let e=d[o.index],n=d.slice(o.index).filter(t=>t.request.mediaId===e.request.mediaId);for(let e of n)l(e);let i=await t.submitClipTool({...e.request,useUnlim:o.useUnlim});if(!i.submitted){u(`choice`,i.choice.message);return}let a=d.slice(o.index).filter(e=>!n.includes(e));d.splice(o.index,d.length-o.index,...n,...a),o.index+=n.length;for(let e of i.jobs)await r.track({...e,editorTool:c.tool},n.map(e=>e.source));for(let e of n)r.removePending(e.placeholderId);u(`submitting`)}a=void 0,s||i.set(null)}catch(e){u(`error`,e instanceof Error?e.message:`Could not start generation. Try again.`)}finally{for(let e of d)r.removePending(e.placeholderId)}}function f(){return o||(o=d().finally(()=>{o=void 0}),o)}return{state:i,start(e){if(s)return Promise.reject(Error(`The editor is no longer open.`));if(a)return Promise.reject(Error(`Finish or cancel the current generation request first.`));let t=n();if(t?.id!==e.target.projectId||t.activeSceneId!==e.target.sceneId)return Promise.reject(Error(`The target project or scene is no longer open.`));let r=BS(t,e.target.clipIds);if(!r.length||r.length>20||r.length!==new Set(e.target.clipIds).size)return Promise.reject(Error(`Select up to 20 unlocked video clips.`));let i=new Map;return a={input:e,entries:r.map(n=>{let a=VS(t,n).track.id;return r.length>1&&(i.has(a)||i.set(a,HS()),n={...n,resultTrack:{id:i.get(a),sourceTrackId:a}}),e.request.preparation!==`reframe`&&(n={...n,resultRange:e.request.preparation===`extend`?`extend`:`source`}),{source:n,fingerprint:c(n),placeholderId:`tool-${HS()}`}}),index:0},f()},resume(e){return!a||s?Promise.resolve():(e!==void 0&&(a.useUnlim=e),f())},cancel(){o||(a=void 0,i.set(null))},dispose(){s=!0}}}var eze,tze=o((()=>{ZS(),tC(),WS(),YS(),eze=`capability:ai/tool-generation`}));function nze(e,t){let n=!1,r;function i(e){let n=t();if(!n||!e.length)throw Error(`Select unlocked video clips first.`);if(e.length>20)throw Error(`Select up to 20 video clips at a time.`);return{doc:n,clips:e.map(e=>{let t=VS(n,e)?.clip;if(!t)throw Error(`Select unlocked video clips first.`);return t})}}async function a(t,n){let{doc:r}=i(n);await e.requestClipAction(`${rze[t]} Wait for my answer before making any changes or starting any generation.`,{projectId:r.id,sceneId:r.activeSceneId,clipIds:n.map(e=>e.clipId)},ize[t]??`clip`)}return{request(e,t){if(n)return Promise.resolve();let i=JSON.stringify([e,t]);if(r)return r.key===i?r.promise:Promise.reject(Error(`A clip request is being sent. Please wait and try again.`));let o=a(e,t).finally(()=>{r=void 0});return r={key:i,promise:o},o},dispose(){n=!0}}}var rze,ize,aze=o((()=>{WS(),rze={"auto-cut":`Create an automatic cut of the selected video clips with Higgsfield. First ask me about the target duration and editing style.`,edit:`Edit the selected video clips with Higgsfield. First ask me what changes I want.`,upscale:`Upscale the selected video clips with Higgsfield. First ask me which target resolution I want.`,extend:`Extend the selected video clips with Higgsfield. First ask me how the videos should continue and how much duration to add.`,"fps-boost":`Increase the frame rate of the selected video clips with Higgsfield. First ask me which target frame rate I want.`,reframe:`Reframe the selected video clips with Higgsfield, preserving their content and motion. First ask me which target aspect ratio I want.`,"remove-background":`Remove the background from the selected video clips with Higgsfield. First ask me which elements to keep or remove and whether I want a mask or a cutout.`,"sdr-to-hdr":`Convert the selected video clips from SDR to HDR with Higgsfield. First ask me which output format I want.`,"depth-map":`Generate a depth map for the selected video clips with Higgsfield. First ask me which color map and output resolution I want.`},ize={reframe:`reframe`,extend:`extend`}}));function oze(e,t){let n=new XS(!1),r=new XS(`video`),i=new XS(!1),a=new XS([]),o=new XS([]),s=new XS([]),c=new XS(null),l=new XS({}),u=new XS([]),d=new XS([]),f=new XS([]),p=new XS(null),m=new XS(null),h=new XS(null),g=e=>{O||h.set({message:e instanceof Error?e.message:String(e)})},_=new XS([]),v=new XS(null),y=new XS(null),b=new Map,x=new Set,S=new Set,C=new Map,w=new Map,T=new Map,E=!1,D=!1,O=!1,k=Promise.resolve(),A=e=>{let t=k.then(e);return k=t.catch(()=>{}),t},j=null,M=null,N=null,P=null,F=nze(t,()=>M?.snapshot()??null);e.require(Cm).then(e=>j=e),e.require(bm).then(e=>M=e),e.require(sze).then(e=>N=e),e.require(xm).then(e=>P=e);let I=(e,t,n,r,i,a)=>{let o=(w.get(e)??[void 0]).map(o=>{let s=o?VS(M?.snapshot()??null,o)?.clip:null,c=s?.timeRange.start??(a===void 0?j?.currentTime.get()??0:Math.max(0,a));return{jobId:e,projectId:C.get(e)??M?.snapshot()?.id??null,label:t,kind:n,start:c,duration:s?.timeRange.duration??(n===`image`?5:Math.max(r,.5)),status:i,source:o}}),c=s.get(),l=c.findIndex(t=>t.jobId===e),u=c.filter(t=>t.jobId!==e);return u.splice(l<0?u.length:l,0,...o),s.set(u),o[0]},L=e=>{let t=s.get();t.some(t=>t.jobId===e.id&&(t.status!==e.status||t.error!==e.error||t.creditsRefunded!==e.creditsRefunded))&&s.set(t.map(t=>t.jobId===e.id?{...t,status:e.status,error:e.error,creditsRefunded:e.creditsRefunded}:t))},R=e=>{let t=s.get();t.some(t=>t.jobId===e)&&s.set(t.filter(t=>t.jobId!==e))},z=e=>s.get().find(t=>t.jobId===e)?.start??null,ee=e=>{let t=a.get(),n=t.findIndex(t=>t.id===e.id);a.set(n>=0?t.map((t,r)=>r===n?e:t):[...t,e]);let r=e.projectId??C.get(e.id);if(r){C.set(e.id,r);let t=o.get(),n=t.findIndex(t=>t.id===e.id),i={...e,projectId:r};o.set(n>=0?t.map((e,t)=>t===n?i:e):[...t,i])}L(e),e.status===`canceled`&&R(e.id),e.status===`completed`&&!S.has(e.id)&&!x.has(e.id)&&(x.add(e.id),V(e))};async function B(n){let r=w.get(n.id),i=r?.[0],a=N?N.importFile.bind(N):(await e.require(sze)).importFile,o=M??await e.require(`capability:document.session`),s=P??await e.require(`capability:document.placement`),c=await fRe({fetchResult:t.fetchResultFile,rememberSource:t.mediaSources?.remember,importFile:a,snapshot:()=>O?null:o.snapshot(),commit:A,placement:s,execute:(t,n)=>e.commands.execute(t,n),playhead:()=>z(n.id)??j?.currentTime.get()??0,select:e=>{i?.resultTrack||j?.setSelection({clipIds:[e]})},insertion:r?{aboveSources:r}:void 0},n),u=o.snapshot();if(i&&!c.ok&&(O||u?.id!==i.projectId||u?.activeSceneId!==i.sceneId))return x.delete(n.id),R(n.id),{kind:`error`,message:c.message};i&&(c.ok?ue.finish(n.id,i.projectId,c.clipId):ue.release(n.id,i.projectId)),R(n.id),w.has(n.id)&&!c.ok&&g(c.message),w.delete(n.id);let d=c.ok?{kind:`added`}:{kind:`error`,message:c.message};return O?d:(l.set({...l.get(),[n.id]:d}),c.ok||ee({...n,status:`failed`,resultUrl:null,error:c.message}),d)}function V(e){let t=T.get(e.id);if(t)return t;let n=B(e).finally(()=>T.delete(e.id));return T.set(e.id,n),n}let H=e=>{if(b.has(e))return;let n=new AbortController;b.set(e,n),(async()=>{try{let r=GRe(t,e,{signal:n.signal});for(;;){let e=await r.next();if(e.value&&!O&&ee(e.value),e.done)break}}catch{}finally{b.delete(e)}})()};function te(e){let t=M?.snapshot();if(e&&(t?.id!==e.projectId||t.activeSceneId!==e.sceneId))throw Error(`The target project or scene is no longer open. Return to it before continuing.`);return e?.clipIds??j?.selection.get().clipIds??[]}function ne(e){let t=M?.snapshot()??null,n=te(e)[0]??null;if(!t||!n)return null;let r=t.scenes.find(e=>e.id===t.activeSceneId);for(let e of r?.tracks??[]){let t=e.clips.find(e=>e.id===n);if(t)return t}return null}function re(e,t){if(!e||!t)return`16:9`;let n=e/t;return[[`21:9`,21/9],[`16:9`,16/9],[`4:3`,4/3],[`1:1`,1],[`3:4`,3/4],[`9:16`,9/16]].reduce((e,t)=>Math.abs(t[1]-n)<Math.abs(e[1]-n)?t:e)[0]}async function ie(t){let n=M?.snapshot(),r=ne(t);if(!n||!r||!(`assetId`in r))return null;let i=await e.assets.get(r.assetId).catch(()=>null);return!i||i.kind!==`video`?null:{tool:`scene-lighting`,projectId:n.id,sceneId:n.activeSceneId,clipId:r.id,assetId:r.assetId,assetName:i.name,assetMimeType:i.mimeType,assetDuration:i.duration??null,sourceAspectRatio:re(i.width,i.height)}}function ae(e){let t=BS(M?.snapshot()??null,te(e));return t.length?{tool:`reframe`,sources:t}:null}function oe(e,t,n,r,i,a){return{id:e,modelId:t,prompt:n,kind:r,status:i,resultUrl:null,thumbnailUrl:null,error:a,createdAt:Date.now(),credits:null,projectId:null}}function se(e,t,n){ee(oe(HS(),`transform`,t,e,`failed`,n))}async function ce(n,r,i,o,s,c,l,u,d){try{if(O||!VS(M?.snapshot()??null,d))throw Error(`The source clip changed. Select it again.`);let r=M?.snapshot()?.assets.find(e=>e.id===s.assetId);if(!r||r.kind!==c)throw Error(`The source media changed.`);let i=await $S(e,t,r);if(O||!VS(M?.snapshot()??null,d))throw Error(`The source clip changed. Select it again.`);let o=await l(i);a.set(a.get().filter(e=>e.id!==n)),R(n),w.delete(n),await ue.track({...o,projectId:d.projectId},d)}catch(e){R(n),w.delete(n),ee(oe(n,r,i,o,`failed`,e instanceof Error?e.message:u))}}async function le(){if(u.get().length>0)return;let e=await t.listModels().catch(()=>null);e&&(u.set(e.models),d.set(e.transforms??[]),f.set(e.editApps??[]))}let U=LRe(e,t,e=>{S.add(e.id),ee(e)},e=>{S.delete(e),x.add(e),l.set({...l.get(),[e]:{kind:`added`}})}),ue=XRe(e,t,()=>M?.snapshot()??null,(e,t,n)=>{if(x.has(e.id))return;if(t.resultTrack&&!w.has(e.id)){let e=j?.selection.get().clipIds;e?.some(e=>n.some(t=>t.clipId===e))&&j?.setSelection({clipIds:e.filter(e=>!n.some(t=>t.clipId===e))})}(e.status===`failed`||e.status===`canceled`)&&g(e.error??`The clip operation did not complete. Try again.`),w.set(e.id,n),C.set(e.id,t.projectId);let r=VS(M?.snapshot()??null,t)?.clip;I(e.id,e.prompt,e.kind,r?.timeRange.duration??5,e.status,r?.timeRange.start??0),ee(e)}),de=$Re(e,t,()=>M?.snapshot()??null,{track:(e,t)=>ue.track(e,t),pending(e,t,n){w.set(e,[t]),C.set(e,t.projectId),I(e,n,`video`,5,`queued`)},removePending(e){R(e),w.delete(e),C.delete(e)}});return{toolGeneration:de,generationQueue:U,open:n,mediaKind:r,createVideo:()=>U.createMedia(`video`),settingsOpen:i,jobs:a,projectGenerations:o,pending:s,draft:c,ingest:l,models:u,transforms:d,editApps:f,editTarget:p,toolTarget:m,reframeError:h,sceneLightingPresets:_,sceneLightingPresetsError:v,modelsError:y,loadModels(){E||u.get().length>0||(E=!0,t.listModels().then(e=>{u.set(e.models),d.set(e.transforms??[]),f.set(e.editApps??[]),y.set(e.models.length>0?null:`No models available`)}).catch(e=>y.set(e instanceof Error?e.message:`Model catalog unavailable`)).finally(()=>E=!1))},async submit(n){let r=M??await e.require(`capability:document.session`);M=r;let i=r.snapshot()?.id??null,a=await t.submitVideo({...n,projectId:i});return i&&C.set(a.id,i),I(a.id,a.prompt,a.kind,n.duration,a.status),ee(a),H(a.id),a},trackExternal(e){S.add(e.jobId),C.set(e.jobId,e.projectId);let t=I(e.jobId,e.label,e.kind,e.duration,e.status,e.start),n=oe(e.jobId,e.modelId,e.label,e.kind,e.status,null);return ee({...n,createdAt:e.createdAt??n.createdAt}),RRe(e.status)||H(e.jobId),t},async importTracked(e,n){let r=l.get()[e];if(r)return r;let i=await t.getJob(e);if(i.status!==`completed`)throw Error(`Generation ${e} is not completed`);let a=s.get().find(t=>t.jobId===e);a&&n!==void 0?s.set(s.get().map(t=>t.jobId===e?{...t,start:Math.max(0,n)}:t)):a||I(i.id,i.prompt,i.kind,5,i.status,n),S.add(e),ee(i),x.add(e);let o=await V(i);return S.delete(e),o},async attachResult(e,t){let n=ue.placement(e.id,t.projectId);if(n){if(n.sceneId!==t.sceneId||n.sourceClipId!==t.clipId)throw Error(`This result already belongs to another clip.`);let e=M?.snapshot();if(e?.id!==t.projectId||e.activeSceneId!==t.sceneId)throw Error(`Reopen the target project and scene first.`);if(!e.scenes.find(e=>e.id===t.sceneId)?.tracks.some(e=>e.clips.some(e=>e.id===n.clipId)))throw Error(`The result was added, then removed or undone. Read the timeline before making another edit.`);return{kind:`added`}}let r=l.get()[e.id];if(r?.kind===`added`)return r;if(!VS(M?.snapshot()??null,t))throw Error(`The source clip changed. Select it again.`);r?.kind===`error`&&x.delete(e.id);let i={...e,projectId:t.projectId};if(await ue.track(i,t),e.status===`completed`)return await(T.get(e.id)??Promise.resolve(l.get()[e.id]??{kind:`error`,message:`Result was not placed. Read the timeline and retry.`}));if(e.status===`failed`||e.status===`canceled`)throw Error(e.error??`Generation failed`);return{kind:`tracking`}},cancelPreparation:(e,t)=>ue.cancelPreparation(e,t),async prepareSources(e,t,n){try{return await ue.prepare(e,t,n)}catch(e){throw g(e),e}},async adaptToTimeline(e){let n=mRe(M?.snapshot()??null,j?.selection.get().clipIds??[],e);await t.requestReframe(n.prompt,n.target)},async requestClipAction(e,t){let r=te(t),i=sRe(M?.snapshot()??null,r);n.set(!1),m.set(null),p.set(null),await F.request(e,i)},async transformSelection(n,r){if(n.action===`reframe`){let e=ae(r);if(!e){g(`Select a video clip first`);return}try{await ue.request(e.sources,n.aspect)}catch(e){g(e)}return}let i=n.action===`remove-background`?`Remove Background`:`Upscale`,a=M?.snapshot(),o=ne(r);if(!a||!o||!(`assetId`in o)){se(`video`,i,`Select a media clip first`);return}let s=await e.assets.get(o.assetId).catch(()=>null);if(!s){se(`video`,i,`Clip asset not found`);return}await le();let c=d.get(),l=n.action===`remove-background`?{id:`video-background-remover`,name:`Remove Background`,description:`Remove the video background`,kind:`video`,inputKind:`video`,aspectRatios:[],defaultAspect:null}:c.find(e=>e.inputKind===s.kind&&e.id.includes(`upscale`));if(!l){se(s.kind===`image`?`image`:`video`,i,`Transform unavailable on this server`);return}if(l.inputKind!==s.kind){se(l.kind,i,`${l.name} needs a ${l.inputKind} clip`);return}let u={projectId:a.id,sceneId:a.activeSceneId,clipId:o.id,assetId:o.assetId,resultRange:`source`},f=`${i} — ${s.name}`,p=HS();w.set(p,[u]),ee(oe(p,l.id,f,l.kind,`queued`,null)),I(p,f,l.kind,s.duration??5,`queued`),await ce(p,l.id,f,l.kind,{assetId:o.assetId,name:s.name,mimeType:s.mimeType},s.kind===`image`?`image`:`video`,e=>t.submitTransform({transformId:l.id,mediaId:e,aspectRatio:null,sourceDuration:s.duration??null,label:f,projectId:u.projectId}),`Transform failed to start`,u)},async openTool(e,r){let i=e===`reframe`?ae(r):await ie(r);if(!i){e===`reframe`?g(`Select a video clip first`):se(`video`,`Change scene & lighting`,`Select a video clip first`);return}if(p.set(null),m.set(i),n.set(e!==`reframe`),i.tool===`reframe`){try{await ue.request(i.sources)}catch(e){g(e)}return}e!==`scene-lighting`||_.get().length>0||D||(D=!0,v.set(null),t.listSceneLightingPresets().then(e=>_.set(e)).catch(e=>v.set(e instanceof Error?e.message:`Scene lighting presets unavailable`)).finally(()=>D=!1))},async submitReframe(e){let t=m.get();if(t?.tool===`reframe`){m.set(null);try{await ue.request(t.sources,e)}catch(e){g(e)}}},async submitSceneLighting(e,n){let r=m.get();if(!r||r.tool!==`scene-lighting`)return;let i=`${e.name} — ${r.assetName}`,a=HS();w.set(a,[r]),ee(oe(a,`video-scene-lighting`,i,`video`,`queued`,null)),I(a,i,`video`,r.assetDuration??5,`queued`),m.set(null),await ce(a,`video-scene-lighting`,i,`video`,{assetId:r.assetId,name:r.assetName,mimeType:r.assetMimeType},`video`,a=>t.submitSceneLighting({mediaId:a,presetId:e.id,aspectRatio:n,sourceDuration:r.assetDuration,label:i,projectId:r.projectId}),`Scene lighting failed to start`,{...r,resultRange:`source`})},async toggleEditApp(t){if(n.get()&&p.get()?.app.id===t){p.set(null);return}await le();let r=f.get().find(e=>e.id===t);if(!r){se(`video`,`AI edit`,`Edit app unavailable on this server`);return}let i=M?.snapshot(),a=ne();if(!i||!a||!(`assetId`in a)){se(`video`,r.name,`Select a media clip first`);return}let o=await e.assets.get(a.assetId).catch(()=>null);if(!o||o.kind!==`video`){se(`video`,r.name,`${r.name} needs a video clip`);return}p.set({app:r,projectId:i.id,sceneId:i.activeSceneId,clipId:a.id,assetId:a.assetId,assetName:o.name,assetMimeType:o.mimeType,assetDuration:o.duration??null,sourceAspectRatio:re(o.width,o.height)}),m.set(null),n.set(!0)},async submitEdit(e){let n=p.get();if(!n)return;let r=`${n.app.name} — ${n.assetName}`,i=HS();w.set(i,[n]),ee(oe(i,n.app.id,r,`video`,`queued`,null)),I(i,r,`video`,n.assetDuration??5,`queued`),p.set(null),await ce(i,n.app.id,r,`video`,{assetId:n.assetId,name:n.assetName,mimeType:n.assetMimeType},`video`,i=>t.submitEdit({appId:n.app.id,mediaId:i,prompt:e,sourceDuration:n.assetDuration,aspectRatio:n.sourceAspectRatio,resolution:`720p`,generateAudio:!0,label:r,projectId:n.projectId}),`Edit failed to start`,{...n,resultRange:`source`})},async regenerate(e){let t=a.get().find(t=>t.id===e),r=w.get(e)?.[0];if(!t||O)return;if(!r)return U.createMedia(t.kind,t.prompt||void 0);let i=M?.snapshot();if(!VS(i??null,r)||!i||i.activeSceneId!==r.sceneId)throw Error(`The source clip changed. Return to its project and select it again.`);let o=i.assets.find(e=>e.id===r.assetId);if(o?.kind!==`video`)throw Error(`Select a video clip to edit.`);let s=t.editorTool??t.modelId,c=Object.hasOwn(GS,s)?s:null;if(c&&M&&j){kRe(M,j,c,{projectId:r.projectId,sceneId:r.sceneId,clipIds:w.get(e).map(e=>e.clipId)}),n.set(!1);return}if(await le(),O||!VS(M?.snapshot()??null,r))throw Error(`The source clip changed. Select it again.`);let l=f.get().find(e=>e.id===`edit-video`);if(!l)throw Error(`Video editing is unavailable in this host.`);j?.setSelection({clipIds:[r.clipId],sceneId:r.sceneId}),p.set({...r,app:l,prompt:t.prompt,assetName:o.name,assetMimeType:o.mimeType,assetDuration:o.duration??null,sourceAspectRatio:re(o.width,o.height)}),m.set(null),n.set(!0)},dismiss(e){b.get(e)?.abort(),b.delete(e),S.delete(e),a.set(a.get().filter(t=>t.id!==e));let t=C.get(e);t&&ue.dismissFailure(e,t),C.delete(e),w.delete(e),o.set(o.get().filter(t=>t.id!==e)),R(e);let{[e]:n,...r}=l.get();l.set(r)},busy(e){return e.status===`queued`||e.status===`in_progress`||!S.has(e.id)&&e.status===`completed`&&!l.get()[e.id]},awaitingImport(e){return S.has(e)&&a.get().some(t=>t.id===e&&t.status===`completed`)},dispose(){O=!0,de.dispose(),U.dispose(),F.dispose(),ue.dispose(),i.set(!1),p.set(null),m.set(null);for(let e of b.values())e.abort();b.clear(),S.clear(),C.clear(),w.clear(),T.clear(),s.set([]),o.set([]),c.set(null)}}}var sze,cC,cze,lze=o((()=>{gRe(),YS(),jRe(),tC(),oC(),ZS(),zS(),YRe(),URe(),WS(),QRe(),tze(),aze(),sze=`capability:storage/local`,cC=`capability:ai/pending-clips`,cze=`capability:ai/project-generations`}));function uze(e,t,n,r){let i=()=>{let i=t.snapshot();i?e.setPending(i.id,i.activeSceneId,n.pending.get(),r.state.get()?.phase===`choice`):e.reset()},a=t.onEvent(i),o=n.pending.subscribe(i),s=r.state.subscribe(i);return i(),()=>{a.dispose(),o.dispose(),s.dispose(),e.reset()}}function dze(e,t,n){let r=e.ownerDocument.defaultView,i=e.inert,a=()=>n.stop(),o=()=>{e.inert=i||n.state.get()!==null,e.setAttribute(`aria-busy`,String(n.state.get()!==null))},s=e=>{n.state.get()&&(e instanceof KeyboardEvent&&e.key===`Escape`&&a(),e.preventDefault(),e.stopImmediatePropagation())},c=n.state.subscribe(o),l=[`keydown`,`pointerdown`,`pointermove`,`mousedown`,`mousemove`,`click`,`dblclick`,`contextmenu`,`wheel`,`touchstart`,`touchmove`,`dragstart`,`dragover`,`drop`];for(let e of l)r?.addEventListener(e,s,{capture:!0,passive:!1});return t.addEventListener?.(`toolcancelled`,a),o(),()=>{c.dispose();for(let e of l)r?.removeEventListener(e,s,!0);t.removeEventListener?.(`toolcancelled`,a),e.inert=i,e.removeAttribute(`aria-busy`),n.reset()}}var fze=o((()=>{})),lC,uC,pze,mze,hze,gze,_ze,dC,fC=o((()=>{lC=u(_(),1),uC=u(_(),1),pze=e=>{let t=uC.useId();return uC.createElement(_ze,{...e,instanceId:t})},mze=0,hze=typeof uC.useId==`function`?void 0:class extends uC.Component{state={};componentDidMount(){this.setState({instanceId:`legacy-${++mze}`})}render(){return uC.createElement(_ze,{...this.props.iconProps,instanceId:this.state.instanceId})}},gze=uC.forwardRef((e,t)=>hze?uC.createElement(hze,{iconProps:{...e,svgRef:t}}):uC.createElement(pze,{...e,svgRef:t})),gze.displayName=`CentralIconBase`,_ze=({children:e,size:t=24,ariaLabel:n,color:r,ariaHidden:i,"aria-hidden":a,"aria-label":o,role:s,svgRef:c,renderShapes:l,style:u,mode:d=`masked`,maskId:f,instanceId:p,...m})=>{let h=p?`${f}-${p}`:f,g=d!==`raw`&&!!f,_=a??i??!0,v=_===!0||_===`true`,y=o??n,b=l?l(h??p??`icon`):e;return uC.createElement(`svg`,{...m,ref:c,"aria-hidden":_,"aria-label":o,role:s??(v?void 0:`img`),width:typeof t==`number`?`${t}px`:t,height:typeof t==`number`?`${t}px`:t,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,style:{color:r,...u}},y&&!v&&uC.createElement(`title`,null,y),g?uC.createElement(uC.Fragment,null,uC.createElement(`mask`,{id:h,maskUnits:`userSpaceOnUse`,x:`0`,y:`0`,width:`24`,height:`24`},uC.createElement(`rect`,{width:`24`,height:`24`,fill:`#000`}),uC.createElement(`g`,{fill:`none`,style:{color:`#fff`}},b)),uC.createElement(`rect`,{width:`24`,height:`24`,fill:`currentColor`,mask:`url(#${h})`})):b)},dC=lC.memo(lC.forwardRef((e,t)=>lC.createElement(gze,{...e,ref:t,ariaLabel:`checkmark-2-medium`,maskId:`round-outlined-radius-2-stroke-1.5-IconCheckmark2Medium`},lC.createElement(`path`,{d:`M5 13.875L9.2 18L19 7`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`}))))}));function pC(e){im({appearance:`editor`,variant:`error`,message:e instanceof Error?e.message:`Could not complete this action. Try again.`})}function mC(e,t,n,r){im({variant:`success`,appearance:`editor`,message:e,description:t,icon:n??(0,gC.jsx)(dC,{size:16}),...r?{action:r}:{}})}function hC(e){e<1||mC(e===1?`Asset added`:`${e} assets added`,void 0,(0,gC.jsx)(Bfe,{size:16}))}function vze(e){im({variant:`success`,appearance:`editor`,message:`Saved`,description:`All changes saved`,dismissible:!1,icon:(0,gC.jsx)(dC,{size:16}),...e?{action:{label:`Show in folder`,onClick:e}}:{}})}var gC,_C=o((()=>{fC(),Hfe(),um(),gC=q()}));function vC(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,document.body.appendChild(r),r.click(),r.remove(),setTimeout(()=>URL.revokeObjectURL(n),6e4)}var yC=o((()=>{})),bC,xC,yze,SC,bze,xze,Sze,Cze,wze=o((()=>{Wf(),bC=W().min(1).max(200),xC=Af(Nf([bC,Cf().int().nonnegative()])).min(3).max(24),yze=Pf(`op`,[G({op:K(`set`),path:xC,value:aae()}),G({op:K(`insert`),path:xC,index:Cf().int().nonnegative(),value:aae()}),G({op:K(`remove`),path:xC,index:Cf().int().nonnegative()}),G({op:K(`move`),path:xC,from:Cf().int().nonnegative(),to:Cf().int().nonnegative()})]),SC={video_editor_read_timeline:G({request_id:bC.optional(),view:If([`auto`,`summary`,`clips`,`assets`]).optional(),scope:If([`scene`,`selection`]).optional(),clip_ids:Af(bC).min(1).max(200).optional(),time_range:G({start:Cf().nonnegative(),end:Cf().positive()}).optional(),offset:Cf().int().nonnegative().max(2**53-1).optional(),limit:Cf().int().min(1).max(100).optional(),expected_revision:bC.optional(),text_offset:Cf().int().nonnegative().max(2**53-1).optional()}).strict().refine(e=>!e.time_range||e.time_range.end>e.time_range.start,{message:`time_range.end must be after time_range.start (timeline seconds).`}).refine(e=>!((e.offset??0)>0||(e.text_offset??0)>0)||!!(e.request_id&&e.expected_revision),{message:`Continuation requires the original request_id and expected_revision.`}).refine(e=>e.text_offset===void 0||e.view===`clips`&&e.clip_ids?.length===1&&!e.offset,{message:`text_offset requires view=clips, exactly one clip_id, and offset=0.`}).refine(e=>e.view!==`assets`||e.scope===void 0&&e.clip_ids===void 0&&e.time_range===void 0,{message:`Asset pages do not accept clip scope, IDs or time filters.`}),video_editor_apply_timeline:G({request_id:bC,expected_revision:bC,operation_id:bC,ops:Af(yze).min(1).max(500)}),video_editor_attach_result:G({request_id:bC,source_clip_id:bC,job_id:bC.optional(),result_id:bC.optional(),result_url:Sf().max(8192).optional(),range:If([`source`,`clip`,`extend`]),label:W().min(1).max(200).optional()}).refine(e=>!!e.job_id!=!!(e.result_url&&e.result_id),{message:`Provide either job_id or both result_id and result_url.`})},Object.keys(SC),bze=G({isError:wf().optional(),content:Af(G({type:K(`text`),text:W().max(5e5)})).max(10),structuredContent:Ff(W(),aae()).optional()}),xze=G({editor_session_id:xf()}),Sze=xze.extend({connection_id:xf(),writer_token:W().min(32).max(128)}),Sze.extend({results:Af(G({id:xf(),result:bze})).max(8).default([])}),Cze=`higgsfield/timeline-channel`}));async function Tze(e,t,n,r=e){let i=Oze.get(e);i||(i=new WeakMap,Oze.set(e,i));let a=i,o=new AbortController,s=()=>o.abort();n?.addEventListener(`abort`,s,{once:!0}),n?.aborted&&o.abort();let c=async(t,n)=>{let r=await e.callServerTool({name:t,arguments:n},{signal:o.signal});if(r.isError)throw hfe(r,`The editor connection failed.`);return r._meta?.[Cze]},l=t=>e.callServerTool({name:`video_editor_disconnect_timeline`,arguments:t}).catch(()=>{}),u,d;try{u=Eze.parse(await c(`video_editor_connect_timeline`,a.get(r)??{})),d=u,o.signal.throwIfAborted()}catch(e){throw n?.removeEventListener(`abort`,s),u&&l(u),e}a.set(r,d),CC.set(e,d);let f=new Map,p=[],m=e=>new Promise(t=>{let n=()=>{clearTimeout(r),o.signal.removeEventListener(`abort`,n),t()},r=setTimeout(n,e);o.signal.addEventListener(`abort`,n,{once:!0}),o.signal.aborted&&n()});return(async()=>{let n=0;for(;!o.signal.aborted&&CC.get(e)===d;)try{let r=Date.now(),i=p.length>0,{commands:a}=Dze.parse(await c(`video_editor_exchange_timeline`,{...d,results:p}));p=[],n=0;for(let n of a){if(o.signal.aborted||CC.get(e)!==d)break;if(n.expiresAt<=Date.now())continue;let r=f.get(n.id);if(!r){try{let e=SC[n.name].parse(n.input);r=bze.parse(await t(n.name,e))}catch(e){r={isError:!0,content:[{type:`text`,text:e instanceof Error?e.message:`Could not execute the timeline command.`}]}}f.set(n.id,r),f.size>32&&f.delete(f.keys().next().value)}p.push({id:n.id,result:r})}!a.length&&!i&&Date.now()-r<1e3&&await m(1e3)}catch(t){if(o.signal.aborted||CC.get(e)!==d)break;if(n++,n>=3)try{let t=Eze.parse(await c(`video_editor_connect_timeline`,d));if(t.editor_session_id!==d.editor_session_id||t.writer_token!==d.writer_token)throw Error(`The editor connection changed.`);if(o.signal.aborted){l(t);break}d=t,a.set(r,d),CC.set(e,d)}catch{}n===1&&console.warn(`[video-editor] timeline connection interrupted`,t),await m(Math.min(5e3,500*2**Math.min(n,4)))}})(),()=>{o.abort(),n?.removeEventListener(`abort`,s),CC.get(e)===d&&CC.delete(e),l(d)}}var Eze,Dze,CC,Oze,kze,Aze=o((()=>{Wf(),Xp(),wze(),Eze=G({editor_session_id:xf(),connection_id:xf(),writer_token:W().min(32)}),Dze=G({commands:Af(G({id:xf(),name:If([`video_editor_read_timeline`,`video_editor_apply_timeline`,`video_editor_attach_result`]),input:Ff(W(),Of()),expiresAt:Cf().finite()})).max(8)}),CC=new WeakMap,Oze=new WeakMap,kze=e=>CC.get(e)?.editor_session_id}));async function jze(e,t){for(t.sending=!0;t.pending;){let n=t.pending;t.pending=void 0;try{let t=await e.updateModelContext(n.context);if(`isError`in t&&t.isError)throw Error(`The host rejected editor context.`);n.resolve()}catch(e){n.reject(e)}}t.sending=!1}function wC(e,t,n){let r=Mze.get(e);r||(r={parts:new Map,sending:!1},Mze.set(e,r)),n?r.parts.set(t,n):r.parts.delete(t);let i={content:[...r.parts.values()].flatMap(e=>e.content??[]),structuredContent:Object.assign({},...[...r.parts.values()].map(e=>e.structuredContent))};if(r.pending)r.pending.context=i;else{let e,t,n=new Promise((n,r)=>{e=n,t=r});r.pending={context:i,promise:n,resolve:e,reject:t}}let a=r.pending.promise;return r.sending||jze(e,r),a}var Mze,Nze=o((()=>{Mze=new WeakMap}));function Pze(e,t,n,r){let i=TC.get(e);i||(i=new Map,TC.set(e,i));let a=i.get(t);if(a)return n.cancel(),a;let o=r().finally(()=>{i.get(t)===o&&i.delete(t)});return i.set(t,o),o}function Fze(e,t){return TC.delete(e),DC.set(e,t),()=>{DC.get(e)===t&&(DC.delete(e),EC.delete(e),`updateModelContext`in e&&wC(e,`generation`).catch(()=>{}))}}function Ize(e,t){let n=DC.get(e);if(!n)return{text:Lze(t)};let r=n(t,`clip`,`edit`,!0);return{request:r,text:Rze(e,r,`edit`)}}function Lze({sceneId:e,clipIds:t}){let n=$Le();return[`This is for the local project open in the Higgsfield Video Editor panel. Edit it with the video_editing_* tools: video_editing_outline for element ids and timing, video_editing_edit to change them, video_editing_preview_frames to check the result.`,...n?[`Project: ${n}. Pass it as project to every video_editing_* tool call.`]:[],`Scene: ${e}${t.length?`; elements: ${t.join(`, `)}`:``}.`].join(`
282
282
  `)}function Rze(e,t,n){return[`This request edits the open Higgsfield Video Editor timeline. Timeline request ID: ${t.id}.`,`Editor session ID: ${kze(e)}. Pass it as editor_session_id to every timeline tool.`,`Target project: ${t.target.projectId}; scene: ${t.target.sceneId}; clips: ${t.target.clipIds.join(`, `)}.`,...n===`transition`?[`Apply a native junction transition using transition_cuts from video_editor_read_timeline. Each cut includes the sidebar's apply_ops template and available presets. Do not create an overlay, group, duplicate clip or separate track for a transition.`]:[],`Keep this request ID when I answer your clarification. Before editing or generating, call Higgsfield's video_editor_read_timeline with request_id. This browser timeline is separate from video_editing_* disk projects; do not switch projects or return a standalone file instead of editing this timeline.`,`Use video_editor_apply_timeline for native edits, including captions, effects and transitions. For a generated replacement call video_editor_attach_result with request_id, source_clip_id and the real job_id immediately after submission so the editor can show progress and place its result. For externally rendered media, upload and confirm it first, then attach its HTTPS result_url with a stable result_id. Read the timeline again and confirm placement before reporting completion. These are MCP server tools from the Higgsfield plugin. Discover them in the plugin tool catalog; do not confuse them with video_editing_* or assume reselection or reopening is required. If a tool returns an error, report that actual error and keep the request context.`].join(`