conformtools 0.6.29 → 0.6.30
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.
- package/dist/{account-F4ODJBD2.js → account-B7ZF6OQM.js} +1 -1
- package/dist/{bridge-GLW34YZF.js → bridge-4ZKCOIOA.js} +1 -1
- package/dist/{chunk-HZBGG7HI.js → chunk-2XB3P2Q5.js} +1 -1
- package/dist/{chunk-NTPDZOPF.js → chunk-3QYAWIID.js} +1 -1
- package/dist/{chunk-ZE7BP4AE.js → chunk-463MBAHG.js} +1 -1
- package/dist/{chunk-BZE7IP6U.js → chunk-4QGSPWXM.js} +52 -52
- package/dist/{chunk-WJS6NM7T.js → chunk-KMDKF7EJ.js} +1 -1
- package/dist/{chunk-QDL3XYOE.js → chunk-KWJVI7VL.js} +203 -203
- package/dist/{chunk-RVKNGIE3.js → chunk-TBODUVBP.js} +2 -2
- package/dist/{chunk-7DH6DFYL.js → chunk-ZL562JIE.js} +1 -1
- package/dist/{chunk-KD7UGCLT.js → chunk-ZNBXAGOK.js} +2 -2
- package/dist/{chunk-WWE2FXAQ.js → chunk-ZTXOFGJY.js} +1 -1
- package/dist/cli.js +1 -1
- package/dist/demo-engine-I35YCWFG.js +3 -0
- package/dist/{engine-LFB243Q6.js → engine-WJLTTZSK.js} +2 -2
- package/dist/{framing-KHUFARKE.js → framing-AYR35WRJ.js} +1 -1
- package/dist/{host-relink-L7I75SUH.js → host-relink-ACZC6TG2.js} +1 -1
- package/dist/{hosted-5Y5VX6X6.js → hosted-SPL5V4NR.js} +1 -1
- package/dist/{hosts-QMGBN2E6.js → hosts-RSOGNUPK.js} +1 -1
- package/dist/http.js +2 -2
- package/dist/{inspect-GP6B6UPD.js → inspect-B6KD6ZTA.js} +1 -1
- package/dist/mcp.js +1 -1
- package/dist/resolve-bridge.py +5 -2
- package/dist/{store-K4W2LVRN.js → store-INNJPUPR.js} +1 -1
- package/dist/{timeline-HTG23FEH.js → timeline-EXRRCS47.js} +1 -1
- package/package.json +1 -1
- package/dist/demo-engine-5HWLXPDJ.js +0 -3
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
-
import{a as Oe,b as dt}from"./chunk-7DH6DFYL.js";import{Qb as pt}from"./chunk-BZE7IP6U.js";import{a as mt}from"./chunk-HZBGG7HI.js";import{b as Ee,d as ut}from"./chunk-NU3X7P4N.js";import{m as lt}from"./chunk-KD7UGCLT.js";import{A as tt,C as pe,D as Y,H as rt,J as me,O as q,P as nt,S as de,V as ot,Y as st,Z as it,b as F,ba as at,ca as fe,ea as I,h as H,j as Te,p as Pe,s as Xe,t as Ze,v as ce,w as le,y as ue,z as et}from"./chunk-QQBDHVUU.js";import{M as ct,S as X}from"./chunk-C2ESM27Z.js";function ft(r,e){let t=async()=>{throw new Error(`${r}: ${e}`)},n={ok:!1,reason:e};return{host:r,wired:!1,support:async()=>({export:n,open:n,render:n,markers:n}),export:t,open:t,renderStart:t,renderStatus:t,renderCancel:t}}async function an(r,e,t,n){let o=new Promise(s=>n?.addEventListener("abort",()=>s(),{once:!0}));for(;e.state==="queued"||e.state==="rendering";){if(t?.(e.percent,100,"rendering"),await Promise.race([o.then(()=>!0),new Promise(i=>setTimeout(()=>i(!1),1e3))]))return await r.renderCancel(e.job_id);e=await r.renderStatus(e.job_id)}return e}var Kt=ArrayBuffer,O=Uint8Array,ge=Uint16Array,Qt=Int16Array;var he=Int32Array,Me=function(r,e,t){if(O.prototype.slice)return O.prototype.slice.call(r,e,t);(e==null||e<0)&&(e=0),(t==null||t>r.length)&&(t=r.length);var n=new O(t-e);return n.set(r.subarray(e,t)),n},ee=function(r,e,t,n){if(O.prototype.fill)return O.prototype.fill.call(r,e,t,n);for((t==null||t<0)&&(t=0),(n==null||n>r.length)&&(n=r.length);t<n;++t)r[t]=e;return r},Yt=function(r,e,t,n){if(O.prototype.copyWithin)return O.prototype.copyWithin.call(r,e,t,n);for((t==null||t<0)&&(t=0),(n==null||n>r.length)&&(n=r.length);t<n;)r[e++]=r[t++]};var Xt=["invalid zstd data","window size too large (>2046MB)","invalid block type","FSE accuracy too high","match distance too far back","unexpected EOF"],$=function(r,e,t){var n=new Error(e||Xt[r]);if(n.code=r,Error.captureStackTrace&&Error.captureStackTrace(n,$),!t)throw n;return n},gt=function(r,e,t){for(var n=0,o=0;n<t;++n)o|=r[e++]<<(n<<3);return o},Zt=function(r,e){return(r[e]|r[e+1]<<8|r[e+2]<<16|r[e+3]<<24)>>>0},er=function(r,e){var t=r[0]|r[1]<<8|r[2]<<16;if(t==3126568&&r[3]==253){var n=r[4],o=n>>5&1,s=n>>2&1,i=n&3,c=n>>6;n&8&&$(0);var a=6-o,l=i==3?4:i,u=gt(r,a,l);a+=l;var d=c?1<<c:o,f=gt(r,a,d)+(c==1&&256),h=f;if(!o){var p=1<<10+(r[5]>>3);h=p+(p>>3)*(r[5]&7)}h>2145386496&&$(1);var m=new O((e==1?f||h:e?0:h)+12);return m[0]=1,m[4]=4,m[8]=8,{b:a+d,y:0,l:0,d:u,w:e&&e!=1?e:m.subarray(12),e:h,o:new he(m.buffer,0,3),u:f,c:s,m:Math.min(131072,h)}}else if((t>>4|r[3]<<20)==25481893)return Zt(r,4)+8;$(0)},B=function(r){for(var e=0;1<<e<=r;++e);return e-1},te=function(r,e,t){var n=(e<<3)+4,o=(r[e]&15)+5;o>t&&$(3);for(var s=1<<o,i=s,c=-1,a=-1,l=-1,u=s,d=new Kt(512+(s<<2)),f=new Qt(d,0,256),h=new ge(d,0,256),p=new ge(d,512,s),m=512+(s<<1),g=new O(d,m,s),S=new O(d,m+s);c<255&&i>0;){var _=B(i+1),v=n>>3,R=(1<<_+1)-1,k=(r[v]|r[v+1]<<8|r[v+2]<<16)>>(n&7)&R,b=(1<<_)-1,w=R-i-1,T=k&b;if(T<w?(n+=_,k=T):(n+=_+1,k>b&&(k-=w)),f[++c]=--k,k==-1?(i+=k,g[--u]=c):i-=k,!k)do{var P=n>>3;a=(r[P]|r[P+1]<<8)>>(n&7)&3,n+=2,c+=a}while(a==3)}(c>255||i)&&$(0);for(var E=0,N=(s>>1)+(s>>3)+3,C=s-1,M=0;M<=c;++M){var y=f[M];if(y<1){h[M]=-y;continue}for(l=0;l<y;++l){g[E]=M;do E=E+N&C;while(E>=u)}}for(E&&$(0),l=0;l<s;++l){var x=h[g[l]]++,L=S[l]=o-B(x);p[l]=(x<<L)-s}return[n+7>>3,{b:o,s:g,n:S,t:p}]},tr=function(r,e){var t=0,n=-1,o=new O(292),s=r[e],i=o.subarray(0,256),c=o.subarray(256,268),a=new ge(o.buffer,268);if(s<128){var l=te(r,e+1,6),u=l[0],d=l[1];e+=s;var f=u<<3,h=r[e];h||$(0);for(var p=0,m=0,g=d.b,S=g,_=(++e<<3)-8+B(h);_-=g,!(_<f);){var v=_>>3;if(p+=(r[v]|r[v+1]<<8)>>(_&7)&(1<<g)-1,i[++n]=d.s[p],_-=S,_<f)break;v=_>>3,m+=(r[v]|r[v+1]<<8)>>(_&7)&(1<<S)-1,i[++n]=d.s[m],g=d.n[p],p=d.t[p],S=d.n[m],m=d.t[m]}++n>255&&$(0)}else{for(n=s-127;t<n;t+=2){var R=r[++e];i[t]=R>>4,i[t+1]=R&15}++e}var k=0;for(t=0;t<n;++t){var b=i[t];b>11&&$(0),k+=b&&1<<b-1}var w=B(k)+1,T=1<<w,P=T-k;for(P&P-1&&$(0),i[n++]=B(P)+1,t=0;t<n;++t){var b=i[t];++c[i[t]=b&&w+1-b]}var E=new O(T<<1),N=E.subarray(0,T),C=E.subarray(T);for(a[w]=0,t=w;t>0;--t){var M=a[t];ee(C,t,M,a[t-1]=M+c[t]*(1<<w-t))}for(a[0]!=T&&$(0),t=0;t<n;++t){var y=i[t];if(y){var x=a[y];ee(N,t,x,a[y]=x+(1<<w-y))}}return[e,{n:C,b:w,s:N}]},rr=te(new O([81,16,99,140,49,198,24,99,12,33,196,24,99,102,102,134,70,146,4]),0,6)[1],nr=te(new O([33,20,196,24,99,140,33,132,16,66,8,33,132,16,66,8,33,68,68,68,68,68,68,68,68,36,9]),0,6)[1],or=te(new O([32,132,16,66,102,70,68,68,68,68,36,73,2]),0,5)[1],ht=function(r,e){for(var t=r.length,n=new he(t),o=0;o<t;++o)n[o]=e,e+=1<<r[o];return n},$e=new O(new he([0,0,0,0,16843009,50528770,134678020,202050057,269422093]).buffer,0,36),sr=ht($e,0),Ne=new O(new he([0,0,0,0,0,0,0,0,16843009,50528770,117769220,185207048,252579084,16]).buffer,0,53),ir=ht(Ne,3),Z=function(r,e,t){var n=r.length,o=e.length,s=r[n-1],i=(1<<t.b)-1,c=-t.b;s||$(0);for(var a=0,l=t.b,u=(n<<3)-8+B(s)-l,d=-1;u>c&&d<o;){var f=u>>3,h=(r[f]|r[f+1]<<8|r[f+2]<<16)>>(u&7);a=(a<<l|h)&i,e[++d]=t.s[a],u-=l=t.n[a]}(u!=c||d+1!=o)&&$(0)},ar=function(r,e,t){var n=6,o=e.length,s=o+3>>2,i=s<<1,c=s+i;Z(r.subarray(n,n+=r[0]|r[1]<<8),e.subarray(0,s),t),Z(r.subarray(n,n+=r[2]|r[3]<<8),e.subarray(s,i),t),Z(r.subarray(n,n+=r[4]|r[5]<<8),e.subarray(i,c),t),Z(r.subarray(n),e.subarray(c),t)},cr=function(r,e,t){var n,o=e.b,s=r[o],i=s>>1&3;e.l=s&1;var c=s>>3|r[o+1]<<5|r[o+2]<<13,a=(o+=3)+c;if(i==1)return o>=r.length?void 0:(e.b=o+1,t?(ee(t,r[o],e.y,e.y+=c),t):ee(new O(c),r[o]));if(!(a>r.length)){if(i==0)return e.b=a,t?(t.set(r.subarray(o,a),e.y),e.y+=c,t):Me(r,o,a);if(i==2){var l=r[o],u=l&3,d=l>>2&3,f=l>>4,h=0,p=0;u<2?d&1?f|=r[++o]<<4|(d&2&&r[++o]<<12):f=l>>3:(p=d,d<2?(f|=(r[++o]&63)<<4,h=r[o]>>6|r[++o]<<2):d==2?(f|=r[++o]<<4|(r[++o]&3)<<12,h=r[o]>>2|r[++o]<<6):(f|=r[++o]<<4|(r[++o]&63)<<12,h=r[o]>>6|r[++o]<<2|r[++o]<<10)),++o;var m=t?t.subarray(e.y,e.y+e.m):new O(e.m),g=m.length-f;if(u==0)m.set(r.subarray(o,o+=f),g);else if(u==1)ee(m,r[o++],g);else{var S=e.h;if(u==2){var _=tr(r,o);h+=o-(o=_[0]),e.h=S=_[1]}else S||$(0);(p?ar:Z)(r.subarray(o,o+=h),m.subarray(g),S)}var v=r[o++];if(v){v==255?v=(r[o++]|r[o++]<<8)+32512:v>127&&(v=v-128<<8|r[o++]);var R=r[o++];R&3&&$(0);for(var k=[nr,or,rr],b=2;b>-1;--b){var w=R>>(b<<1)+2&3;if(w==1){var T=new O([0,0,r[o++]]);k[b]={s:T.subarray(2,3),n:T.subarray(0,1),t:new ge(T.buffer,0,1),b:0}}else w==2?(n=te(r,o,9-(b&1)),o=n[0],k[b]=n[1]):w==3&&(e.t||$(0),k[b]=e.t[b])}var P=e.t=k,E=P[0],N=P[1],C=P[2],M=r[a-1];M||$(0);var y=(a<<3)-8+B(M)-C.b,x=y>>3,L=0,ne=(r[x]|r[x+1]<<8)>>(y&7)&(1<<C.b)-1;x=(y-=N.b)>>3;var oe=(r[x]|r[x+1]<<8)>>(y&7)&(1<<N.b)-1;x=(y-=E.b)>>3;var se=(r[x]|r[x+1]<<8)>>(y&7)&(1<<E.b)-1;for(++v;--v;){var Re=C.s[ne],Je=C.n[ne],Ae=E.s[se],We=E.n[se],Ke=N.s[oe],Qe=N.n[oe];x=(y-=Ke)>>3;var Ye=1<<Ke,U=Ye+((r[x]|r[x+1]<<8|r[x+2]<<16|r[x+3]<<24)>>>(y&7)&Ye-1);x=(y-=Ne[Ae])>>3;var W=ir[Ae]+((r[x]|r[x+1]<<8|r[x+2]<<16)>>(y&7)&(1<<Ne[Ae])-1);x=(y-=$e[Re])>>3;var ie=sr[Re]+((r[x]|r[x+1]<<8|r[x+2]<<16)>>(y&7)&(1<<$e[Re])-1);if(x=(y-=Je)>>3,ne=C.t[ne]+((r[x]|r[x+1]<<8)>>(y&7)&(1<<Je)-1),x=(y-=We)>>3,se=E.t[se]+((r[x]|r[x+1]<<8)>>(y&7)&(1<<We)-1),x=(y-=Qe)>>3,oe=N.t[oe]+((r[x]|r[x+1]<<8)>>(y&7)&(1<<Qe)-1),U>3)e.o[2]=e.o[1],e.o[1]=e.o[0],e.o[0]=U-=3;else{var ae=U-(ie!=0);ae?(U=ae==3?e.o[0]-1:e.o[ae],ae>1&&(e.o[2]=e.o[1]),e.o[1]=e.o[0],e.o[0]=U):U=e.o[0]}for(var b=0;b<ie;++b)m[L+b]=m[g+b];L+=ie,g+=ie;var K=L-U;if(K<0){var Q=-K,Wt=e.e+K;Q>W&&(Q=W);for(var b=0;b<Q;++b)m[L+b]=e.w[Wt+b];L+=Q,W-=Q,K=0}for(var b=0;b<W;++b)m[L+b]=m[K+b];L+=W}if(L!=g)for(;g<m.length;)m[L++]=m[g++];else L=m.length;t?e.y+=L:m=Me(m,0,L)}else if(t){if(e.y+=f,g)for(var b=0;b<f;++b)m[b]=m[g+b]}else g&&(m=Me(m,g));return e.b=a,m}$(2)}},lr=function(r,e){if(r.length==1)return r[0];for(var t=new O(e),n=0,o=0;n<r.length;++n){var s=r[n];t.set(s,o),o+=s.length}return t};function we(r,e){for(var t=[],n=+!e,o=0,s=0;r.length;){var i=er(r,n||e);if(typeof i=="object"){for(n?(e=null,i.w.length==i.u&&(t.push(e=i.w),s+=i.u)):(t.push(e),i.e=0);!i.l;){var c=cr(r,i,e);c||$(5),e?i.e=i.y:(t.push(c),s+=c.length,Yt(i.w,0,c.length),i.w.set(c,i.w.length-c.length))}o=i.b+i.c*4}else o=i;r=r.subarray(o)}return lr(t,s)}function D(r){let e=[],t=0,n=()=>{let s=0,i=1;for(;;){let c=r[t++];if(s+=(c&127)*i,i*=128,!(c&128))return s}},o=s=>Array.from(s,i=>i.toString(16).padStart(2,"0")).join("");for(;t<r.length;){let s=t,i=n(),c=Math.floor(i/8),a=i&7,l;if(a===0){let u=t;n(),l=r.slice(u,t)}else if(a===2){let u=n();l=r.slice(t,t+u),t+=u}else if(a===5)l=r.slice(t,t+4),t+=4;else if(a===1)l=r.slice(t,t+8),t+=8;else throw new Error(`wire type ${a}`);e.push([c,a,o(r.slice(s,t)),l])}return e}var ur=r=>Array.from(r,e=>e.toString(16).padStart(2,"0")).join(""),_t=r=>Uint8Array.from(r.match(/../g)??[],e=>parseInt(e,16));function ye(r){let e=r.trim().toLowerCase();if(e.startsWith("80"))return e;if(e.startsWith("81"))return"80"+ur(we(_t(e.slice(2))));throw new Error(`grade body: unknown encoding 0x${e.slice(0,2)}`)}function wt(r){let e={};for(let t of r.matchAll(/<ListMgt::LmVersion DbId="[^"]+">([\s\S]*?)<\/ListMgt::LmVersion>/g)){let n=/<Name>([^<]*)<\/Name>/.exec(t[1])?.[1],o=/<Body>([0-9a-fA-F]+)<\/Body>/.exec(t[1])?.[1];n&&o&&(e[n]=ye(o))}return e}function yt(r){let e=new Map;for(let t of r.matchAll(/<ListMgt::LmVersion DbId="([^"]+)">([\s\S]*?)<\/ListMgt::LmVersion>/g)){let n=/<Body>([0-9a-fA-F]+)<\/Body>/.exec(t[2])?.[1];n&&e.set(t[1],ye(n))}return e}function bt(r){let e=X(r),t=l=>new TextDecoder().decode(e[l]),n=Object.keys(e).find(l=>l.startsWith("SeqContainer/")&&l.endsWith(".xml"));if(!n)throw new Error("grade bodies: no SeqContainer in the .drt");let o=new Map,s=new Map,i=Object.keys(e).filter(l=>l.startsWith("MediaPool/")&&l.endsWith(".xml"));for(let l of i)for(let u of t(l).matchAll(/<Sm2MpVideoClip DbId="([^"]+)">([\s\S]*?)<\/Sm2MpVideoClip>/g)){let d=/<pLmVerTable>([\s\S]*?)<\/pLmVerTable>/.exec(u[2]);d&&(o.set(u[1],wt(d[1])),s.set(u[1],yt(d[1])))}let c=new Map,a=0;for(let l of t(n).matchAll(/<Sm2TiTrack DbId="[^"]+">([\s\S]*?)<\/Sm2TiTrack>/g))if(/<Type>([^<]*)<\/Type>/.exec(l[1])?.[1]==="0"){a++;for(let u of l[1].matchAll(/<Sm2TiVideoClip DbId="[^"]+">([\s\S]*?)<\/Sm2TiVideoClip>/g)){let d=u[1],f=/<Start>(-?\d+)<\/Start>/.exec(d)?.[1],h=/<Name>([^<]*)<\/Name>/.exec(d)?.[1]??"";if(f===void 0)continue;let p=/<pLmVerTable>([\s\S]*?)<\/pLmVerTable>/.exec(d),m=/<MediaRef>([^<]+)<\/MediaRef>/.exec(d)?.[1],g=p&&/<pActive>([^<]+)<\/pActive>/.exec(p[1])?.[1],S=g?yt(p[1]).get(g)??(m?s.get(m)?.get(g):void 0):void 0;c.set(`${a}:${f}`,{name:h,local:p?wt(p[1]):{},remote:m&&o.get(m)||{},...S?{active:S}:{}})}}return c}function fn(r){let e=a=>D(a),t=a=>{let l=0,u=1;for(let d of a)if(l+=(d&127)*u,u*=128,!(d&128))break;return l},n=e(_t(r.slice(2))).find(a=>a[0]===3&&a[1]===2&&e(a[3]).some(l=>l[0]===8&&t(l[3])===84)),s=(n?e(n[3]).filter(a=>a[0]===9).flatMap(a=>e(a[3])):[]).find(a=>a[0]===1&&a[1]===2&&e(a[3]).some(l=>l[0]===1&&l[1]===0&&t(l[3])===10));return s?e(s[3]).filter(a=>a[0]===6&&a[1]===2).map(a=>{let l=e(a[3]),u=t(l.find(h=>h[0]===1&&h[1]===0)?.[3]??new Uint8Array([0]))/2,d=l.find(h=>h[0]===2&&h[1]===2)?.[3]??new Uint8Array,f={t:u,zoom:1,height:1,rotation:0,pan:0,tilt:0,flip_x:!1,flip_y:!1};for(let h of e(d)){if(h[0]===5&&h[1]===2){let R=e(h[3]);f.ease_in=t(R.find(k=>k[0]===1)?.[3]??new Uint8Array([1])),f.ease_out=t(R.find(k=>k[0]===2)?.[3]??new Uint8Array([1]));continue}if(h[0]!==3||h[1]!==2)continue;let p=e(h[3]),m=t(p.find(R=>R[0]===1)?.[3]??new Uint8Array),g=p.find(R=>R[0]===2)?.[3],S=g&&e(g).find(R=>R[0]===1&&R[1]===5),_=g&&e(g).find(R=>R[0]===2&&R[1]===0),v=S?new DataView(S[3].buffer,S[3].byteOffset,4).getFloat32(0,!0):_?t(_[3]):void 0;v!==void 0&&(m===271581186?f.height=v:m===271581187?f.zoom=v:m===271581188?f.rotation=v:m===271581189?f.pan=v:m===271581190?f.tilt=v:m===271581191?f.flip_y=!!v:m===271581192&&(f.flip_x=!!v))}return f}).sort((a,l)=>a.t-l.t):[]}var pr=r=>Array.from(r,e=>e.toString(16).padStart(2,"0")).join(""),V=r=>Uint8Array.from(r.match(/../g)??[],e=>parseInt(e,16)),St=r=>{let e=[];do e.push(r&127|(r>127?128:0)),r=Math.floor(r/128);while(r);return e};function vt(r){let e=V(r.trim());if(e.length<9)throw new Error("EffectFiltersBA: too short");if(e[8]===128)return e.slice(9);if(e[8]===129)return we(e.slice(9));throw new Error(`EffectFiltersBA: unknown encoding 0x${e[8].toString(16)}`)}function mr(r){let e=new Uint8Array(9);return new DataView(e.buffer).setUint32(0,2),new DataView(e.buffer).setUint32(4,r.length+1),e[8]=128,pr(new Uint8Array([...e,...r]))}var Ce=r=>{let e=D(r).find(t=>t[0]===1&&t[1]===0);return e?dr(e[3]):-1};function dr(r){let e=0,t=1;for(let n of r)if(e+=(n&127)*t,t*=128,!(n&128))break;return e}var Le=(r,e)=>new Uint8Array([...St(r<<3|2),...St(e.length),...e]);function fr(r,e){let t=new DataView(r.buffer,r.byteOffset,r.byteLength),n=-t.getInt32(0)/16;if(!Number.isInteger(n)||n<2||r.length!==4+n*16||r[10]!==12)return r;let o=Array.from({length:n},(a,l)=>({frame:t.getUint32(4+l*16,!0),value:t.getFloat64(4+l*16+8,!0)})),s=o.map(a=>e(a.frame));if(!s.slice(0,-1).some(Boolean))return r;let i=new Uint8Array(4+n*64),c=new DataView(i.buffer);return c.setInt32(0,-(n*64)),o.forEach((a,l)=>{let u=4+l*64;c.setUint32(u,a.frame,!0),i[u+6]=13,c.setFloat64(u+8,a.value,!0);let d=l>0?s[l-1]:void 0,f=l<n-1?s[l]:void 0;d&&c.setFloat64(u+16,-(d.in/10)*(a.frame-o[l-1].frame),!0),f&&c.setFloat64(u+32,f.out/10*(o[l+1].frame-a.frame),!0)}),i}function gr(r,e){let t=[];for(let n of D(r))if(n[0]===9&&n[1]===2&&n[3].length){let o=D(n[3]).map(s=>s[0]===10&&s[1]===2?[...Le(10,fr(s[3],e))]:[...V(s[2])]).flat();t.push(...Le(9,new Uint8Array(o)))}else t.push(...V(n[2]));return new Uint8Array(t)}function hr(r){let e=[];for(let t of D(r)){if(t[0]!==9||t[1]!==2||!t[3].length)continue;let n=D(t[3]).find(i=>i[0]===10&&i[1]===2)?.[3];if(!n||n.length<4)continue;let o=new DataView(n.buffer,n.byteOffset,n.byteLength),s=-o.getInt32(0)/16;Number.isInteger(s)&&s>e.length&&n.length===4+s*16&&Array.from({length:s},(i,c)=>n[4+c*16+6]).every(i=>i===12)&&(e=Array.from({length:s},(i,c)=>o.getUint32(4+c*16,!0)))}return e}function wr(r,e){let t=D(e).find(s=>s[0]===1&&s[1]===2&&Ce(s[3])===4);if(!t)throw new Error("the written clip carries no Transform group");let n=[],o=!1;for(let s of r?D(r):[]){if(s[0]===1&&s[1]===2&&Ce(s[3])===4){o||(n.push(...V(t[2])),o=!0);continue}n.push(...V(s[2]))}return o||n.push(...V(t[2])),new Uint8Array(n)}function xt(r){let e=[],t=0;for(let n of r.matchAll(/<Sm2TiTrack DbId="[^"]+">([\s\S]*?)<\/Sm2TiTrack>/g)){if(/<Type>([^<]*)<\/Type>/.exec(n[1])?.[1]!=="0")continue;t++;let o=n.index+n[0].indexOf(n[1]);for(let s of n[1].matchAll(/<Sm2TiVideoClip DbId="[^"]+">([\s\S]*?)<\/Sm2TiVideoClip>/g)){let i=/<Start>(-?\d+)<\/Start>/.exec(s[1])?.[1];i!==void 0&&e.push({track:t,start:Number(i),at:o+s.index,end:o+s.index+s[0].length,body:s[0]})}}return e}var kt=r=>Object.keys(r).find(e=>e.startsWith("SeqContainer/")&&e.endsWith(".xml"));function Rt(r,e,t,n){let o=X(r),s=X(e),i=kt(o),c=kt(s);if(!i||!c)throw new Error("no SeqContainer in the .drt");let a=new TextDecoder().decode(o[i]),l=xt(a),u=xt(new TextDecoder().decode(s[c])),d=[],f=[],h=[];for(let m of t){let g=`V${m.item.track}@${m.item.start}`,S=l.find(y=>y.track===m.item.track&&y.start===m.item.start+n),_=S?l.filter(y=>y.track===S.track).indexOf(S):-1,v=_>=0?u.filter(y=>y.track===m.item.track)[_]:void 0,R=v&&/<EffectFiltersBA>([0-9a-fA-F]+)<\/EffectFiltersBA>/.exec(v.body)?.[1];if(!S||!R){f.push(g);continue}let k=/<EffectFiltersBA>([0-9a-fA-F]*)<\/EffectFiltersBA>/.exec(S.body),b=D(vt(R)),w=b.find(y=>y[0]===1&&y[1]===2&&Ce(y[3])===4),T=w?hr(w[3]):[];if(T.length!==m.keys.length){f.push(`${g} (the engine wrote ${T.length} keys for ${m.keys.length})`);continue}let P=new Map(T.map((y,x)=>[y,m.keys[x].shape])),E=new Uint8Array(b.flatMap(y=>y===w?[...Le(1,gr(y[3],x=>P.get(x)))]:[...V(y[2])])),N=wr(k?.[1]?vt(k[1]):null,E),C=`<EffectFiltersBA>${mr(N)}</EffectFiltersBA>`,M=k?S.body.replace(k[0],C):S.body.replace(/(<\/Sm2TiVideoClip>)$/,`${C}$1`);h.push({at:S.at,end:S.end,body:M}),d.push(g)}for(let m of h.sort((g,S)=>S.at-g.at))a=a.slice(0,m.at)+m.body+a.slice(m.end);let p={...o,[i]:new TextEncoder().encode(a)};return{drt:ct(p),keyed:d,missing:f}}function At(r,e,t){let n=r.source_range,o=r.timeline_range,s=n?.start.rate||t,i=n?.start.value??0,c=n?.duration&&o?.duration&&o.duration.value?n.duration.value/n.duration.rate/(o.duration.value/o.duration.rate)*s/t:s/t,a=[],l=0;for(let f of e){let h={value:i+f.t*c,rate:s},p=(m,g)=>a.push({id:`${r.id}-align-${l++}`,parameter_path:m,time:h,value:g,interp:"linear"});p("scale",f.transform.scale_x),e.some(m=>Math.abs(m.transform.scale_y-m.transform.scale_x)>.001)&&p("scale.y",f.transform.scale_y),p("position.x",f.transform.position_x),p("position.y",f.transform.position_y),p("rotation",f.transform.rotation)}let u=e[0].transform,d=(r.keyframes??[]).filter(f=>!/^(scale|position|rotation)/.test(String(f.parameter_path)));Object.assign(r,{scale:u.scale_x,position_x:u.position_x,position_y:u.position_y,rotation:u.rotation,keyframes:[...d,...a]}),Math.abs(u.scale_y-u.scale_x)>.001&&Object.assign(r,{scale_x:u.scale_x,scale_y:u.scale_y}),u.flip_h?r.flip_horizontal=!0:delete r.flip_horizontal,u.flip_v?r.flip_vertical=!0:delete r.flip_vertical}function Ot(r=H()){if(r==="win32"){let e=F("PROGRAMDATA")??"C:\\ProgramData",t=F("PROGRAMFILES")??"C:\\Program Files";return{api:`${e}\\Blackmagic Design\\DaVinci Resolve\\Support\\Developer\\Scripting`,lib:`${t}\\Blackmagic Design\\DaVinci Resolve\\fusionscript.dll`}}return r==="linux"?{api:"/opt/resolve/Developer/Scripting",lib:"/opt/resolve/libs/Fusion/fusionscript.so"}:{api:"/Library/Application Support/Blackmagic Design/DaVinci Resolve/Developer/Scripting",lib:"/Applications/DaVinci Resolve/DaVinci Resolve.app/Contents/Libraries/Fusion/fusionscript.so"}}async function yr(r){let e=F("RESOLVE_SCRIPT_LIB");if(e)return e;if(r==="darwin"){let n=(await de("ps",["-axo","comm="])).stdout.split(`
|
|
3
|
+
import{a as Oe,b as dt}from"./chunk-ZL562JIE.js";import{Rb as pt}from"./chunk-4QGSPWXM.js";import{a as mt}from"./chunk-2XB3P2Q5.js";import{b as Ee,d as ut}from"./chunk-NU3X7P4N.js";import{m as lt}from"./chunk-ZNBXAGOK.js";import{A as tt,C as pe,D as Y,H as rt,J as me,O as q,P as nt,S as de,V as ot,Y as st,Z as it,b as F,ba as at,ca as fe,ea as I,h as H,j as Te,p as Pe,s as Xe,t as Ze,v as ce,w as le,y as ue,z as et}from"./chunk-QQBDHVUU.js";import{M as ct,S as X}from"./chunk-C2ESM27Z.js";function ft(r,e){let t=async()=>{throw new Error(`${r}: ${e}`)},n={ok:!1,reason:e};return{host:r,wired:!1,support:async()=>({export:n,open:n,render:n,markers:n}),export:t,open:t,renderStart:t,renderStatus:t,renderCancel:t}}async function an(r,e,t,n){let o=new Promise(s=>n?.addEventListener("abort",()=>s(),{once:!0}));for(;e.state==="queued"||e.state==="rendering";){if(t?.(e.percent,100,"rendering"),await Promise.race([o.then(()=>!0),new Promise(i=>setTimeout(()=>i(!1),1e3))]))return await r.renderCancel(e.job_id);e=await r.renderStatus(e.job_id)}return e}var Kt=ArrayBuffer,O=Uint8Array,ge=Uint16Array,Qt=Int16Array;var he=Int32Array,Me=function(r,e,t){if(O.prototype.slice)return O.prototype.slice.call(r,e,t);(e==null||e<0)&&(e=0),(t==null||t>r.length)&&(t=r.length);var n=new O(t-e);return n.set(r.subarray(e,t)),n},ee=function(r,e,t,n){if(O.prototype.fill)return O.prototype.fill.call(r,e,t,n);for((t==null||t<0)&&(t=0),(n==null||n>r.length)&&(n=r.length);t<n;++t)r[t]=e;return r},Yt=function(r,e,t,n){if(O.prototype.copyWithin)return O.prototype.copyWithin.call(r,e,t,n);for((t==null||t<0)&&(t=0),(n==null||n>r.length)&&(n=r.length);t<n;)r[e++]=r[t++]};var Xt=["invalid zstd data","window size too large (>2046MB)","invalid block type","FSE accuracy too high","match distance too far back","unexpected EOF"],$=function(r,e,t){var n=new Error(e||Xt[r]);if(n.code=r,Error.captureStackTrace&&Error.captureStackTrace(n,$),!t)throw n;return n},gt=function(r,e,t){for(var n=0,o=0;n<t;++n)o|=r[e++]<<(n<<3);return o},Zt=function(r,e){return(r[e]|r[e+1]<<8|r[e+2]<<16|r[e+3]<<24)>>>0},er=function(r,e){var t=r[0]|r[1]<<8|r[2]<<16;if(t==3126568&&r[3]==253){var n=r[4],o=n>>5&1,s=n>>2&1,i=n&3,c=n>>6;n&8&&$(0);var a=6-o,l=i==3?4:i,u=gt(r,a,l);a+=l;var d=c?1<<c:o,f=gt(r,a,d)+(c==1&&256),h=f;if(!o){var p=1<<10+(r[5]>>3);h=p+(p>>3)*(r[5]&7)}h>2145386496&&$(1);var m=new O((e==1?f||h:e?0:h)+12);return m[0]=1,m[4]=4,m[8]=8,{b:a+d,y:0,l:0,d:u,w:e&&e!=1?e:m.subarray(12),e:h,o:new he(m.buffer,0,3),u:f,c:s,m:Math.min(131072,h)}}else if((t>>4|r[3]<<20)==25481893)return Zt(r,4)+8;$(0)},B=function(r){for(var e=0;1<<e<=r;++e);return e-1},te=function(r,e,t){var n=(e<<3)+4,o=(r[e]&15)+5;o>t&&$(3);for(var s=1<<o,i=s,c=-1,a=-1,l=-1,u=s,d=new Kt(512+(s<<2)),f=new Qt(d,0,256),h=new ge(d,0,256),p=new ge(d,512,s),m=512+(s<<1),g=new O(d,m,s),S=new O(d,m+s);c<255&&i>0;){var _=B(i+1),v=n>>3,R=(1<<_+1)-1,k=(r[v]|r[v+1]<<8|r[v+2]<<16)>>(n&7)&R,b=(1<<_)-1,w=R-i-1,T=k&b;if(T<w?(n+=_,k=T):(n+=_+1,k>b&&(k-=w)),f[++c]=--k,k==-1?(i+=k,g[--u]=c):i-=k,!k)do{var P=n>>3;a=(r[P]|r[P+1]<<8)>>(n&7)&3,n+=2,c+=a}while(a==3)}(c>255||i)&&$(0);for(var E=0,N=(s>>1)+(s>>3)+3,C=s-1,M=0;M<=c;++M){var y=f[M];if(y<1){h[M]=-y;continue}for(l=0;l<y;++l){g[E]=M;do E=E+N&C;while(E>=u)}}for(E&&$(0),l=0;l<s;++l){var x=h[g[l]]++,L=S[l]=o-B(x);p[l]=(x<<L)-s}return[n+7>>3,{b:o,s:g,n:S,t:p}]},tr=function(r,e){var t=0,n=-1,o=new O(292),s=r[e],i=o.subarray(0,256),c=o.subarray(256,268),a=new ge(o.buffer,268);if(s<128){var l=te(r,e+1,6),u=l[0],d=l[1];e+=s;var f=u<<3,h=r[e];h||$(0);for(var p=0,m=0,g=d.b,S=g,_=(++e<<3)-8+B(h);_-=g,!(_<f);){var v=_>>3;if(p+=(r[v]|r[v+1]<<8)>>(_&7)&(1<<g)-1,i[++n]=d.s[p],_-=S,_<f)break;v=_>>3,m+=(r[v]|r[v+1]<<8)>>(_&7)&(1<<S)-1,i[++n]=d.s[m],g=d.n[p],p=d.t[p],S=d.n[m],m=d.t[m]}++n>255&&$(0)}else{for(n=s-127;t<n;t+=2){var R=r[++e];i[t]=R>>4,i[t+1]=R&15}++e}var k=0;for(t=0;t<n;++t){var b=i[t];b>11&&$(0),k+=b&&1<<b-1}var w=B(k)+1,T=1<<w,P=T-k;for(P&P-1&&$(0),i[n++]=B(P)+1,t=0;t<n;++t){var b=i[t];++c[i[t]=b&&w+1-b]}var E=new O(T<<1),N=E.subarray(0,T),C=E.subarray(T);for(a[w]=0,t=w;t>0;--t){var M=a[t];ee(C,t,M,a[t-1]=M+c[t]*(1<<w-t))}for(a[0]!=T&&$(0),t=0;t<n;++t){var y=i[t];if(y){var x=a[y];ee(N,t,x,a[y]=x+(1<<w-y))}}return[e,{n:C,b:w,s:N}]},rr=te(new O([81,16,99,140,49,198,24,99,12,33,196,24,99,102,102,134,70,146,4]),0,6)[1],nr=te(new O([33,20,196,24,99,140,33,132,16,66,8,33,132,16,66,8,33,68,68,68,68,68,68,68,68,36,9]),0,6)[1],or=te(new O([32,132,16,66,102,70,68,68,68,68,36,73,2]),0,5)[1],ht=function(r,e){for(var t=r.length,n=new he(t),o=0;o<t;++o)n[o]=e,e+=1<<r[o];return n},$e=new O(new he([0,0,0,0,16843009,50528770,134678020,202050057,269422093]).buffer,0,36),sr=ht($e,0),Ne=new O(new he([0,0,0,0,0,0,0,0,16843009,50528770,117769220,185207048,252579084,16]).buffer,0,53),ir=ht(Ne,3),Z=function(r,e,t){var n=r.length,o=e.length,s=r[n-1],i=(1<<t.b)-1,c=-t.b;s||$(0);for(var a=0,l=t.b,u=(n<<3)-8+B(s)-l,d=-1;u>c&&d<o;){var f=u>>3,h=(r[f]|r[f+1]<<8|r[f+2]<<16)>>(u&7);a=(a<<l|h)&i,e[++d]=t.s[a],u-=l=t.n[a]}(u!=c||d+1!=o)&&$(0)},ar=function(r,e,t){var n=6,o=e.length,s=o+3>>2,i=s<<1,c=s+i;Z(r.subarray(n,n+=r[0]|r[1]<<8),e.subarray(0,s),t),Z(r.subarray(n,n+=r[2]|r[3]<<8),e.subarray(s,i),t),Z(r.subarray(n,n+=r[4]|r[5]<<8),e.subarray(i,c),t),Z(r.subarray(n),e.subarray(c),t)},cr=function(r,e,t){var n,o=e.b,s=r[o],i=s>>1&3;e.l=s&1;var c=s>>3|r[o+1]<<5|r[o+2]<<13,a=(o+=3)+c;if(i==1)return o>=r.length?void 0:(e.b=o+1,t?(ee(t,r[o],e.y,e.y+=c),t):ee(new O(c),r[o]));if(!(a>r.length)){if(i==0)return e.b=a,t?(t.set(r.subarray(o,a),e.y),e.y+=c,t):Me(r,o,a);if(i==2){var l=r[o],u=l&3,d=l>>2&3,f=l>>4,h=0,p=0;u<2?d&1?f|=r[++o]<<4|(d&2&&r[++o]<<12):f=l>>3:(p=d,d<2?(f|=(r[++o]&63)<<4,h=r[o]>>6|r[++o]<<2):d==2?(f|=r[++o]<<4|(r[++o]&3)<<12,h=r[o]>>2|r[++o]<<6):(f|=r[++o]<<4|(r[++o]&63)<<12,h=r[o]>>6|r[++o]<<2|r[++o]<<10)),++o;var m=t?t.subarray(e.y,e.y+e.m):new O(e.m),g=m.length-f;if(u==0)m.set(r.subarray(o,o+=f),g);else if(u==1)ee(m,r[o++],g);else{var S=e.h;if(u==2){var _=tr(r,o);h+=o-(o=_[0]),e.h=S=_[1]}else S||$(0);(p?ar:Z)(r.subarray(o,o+=h),m.subarray(g),S)}var v=r[o++];if(v){v==255?v=(r[o++]|r[o++]<<8)+32512:v>127&&(v=v-128<<8|r[o++]);var R=r[o++];R&3&&$(0);for(var k=[nr,or,rr],b=2;b>-1;--b){var w=R>>(b<<1)+2&3;if(w==1){var T=new O([0,0,r[o++]]);k[b]={s:T.subarray(2,3),n:T.subarray(0,1),t:new ge(T.buffer,0,1),b:0}}else w==2?(n=te(r,o,9-(b&1)),o=n[0],k[b]=n[1]):w==3&&(e.t||$(0),k[b]=e.t[b])}var P=e.t=k,E=P[0],N=P[1],C=P[2],M=r[a-1];M||$(0);var y=(a<<3)-8+B(M)-C.b,x=y>>3,L=0,ne=(r[x]|r[x+1]<<8)>>(y&7)&(1<<C.b)-1;x=(y-=N.b)>>3;var oe=(r[x]|r[x+1]<<8)>>(y&7)&(1<<N.b)-1;x=(y-=E.b)>>3;var se=(r[x]|r[x+1]<<8)>>(y&7)&(1<<E.b)-1;for(++v;--v;){var Re=C.s[ne],Je=C.n[ne],Ae=E.s[se],We=E.n[se],Ke=N.s[oe],Qe=N.n[oe];x=(y-=Ke)>>3;var Ye=1<<Ke,U=Ye+((r[x]|r[x+1]<<8|r[x+2]<<16|r[x+3]<<24)>>>(y&7)&Ye-1);x=(y-=Ne[Ae])>>3;var W=ir[Ae]+((r[x]|r[x+1]<<8|r[x+2]<<16)>>(y&7)&(1<<Ne[Ae])-1);x=(y-=$e[Re])>>3;var ie=sr[Re]+((r[x]|r[x+1]<<8|r[x+2]<<16)>>(y&7)&(1<<$e[Re])-1);if(x=(y-=Je)>>3,ne=C.t[ne]+((r[x]|r[x+1]<<8)>>(y&7)&(1<<Je)-1),x=(y-=We)>>3,se=E.t[se]+((r[x]|r[x+1]<<8)>>(y&7)&(1<<We)-1),x=(y-=Qe)>>3,oe=N.t[oe]+((r[x]|r[x+1]<<8)>>(y&7)&(1<<Qe)-1),U>3)e.o[2]=e.o[1],e.o[1]=e.o[0],e.o[0]=U-=3;else{var ae=U-(ie!=0);ae?(U=ae==3?e.o[0]-1:e.o[ae],ae>1&&(e.o[2]=e.o[1]),e.o[1]=e.o[0],e.o[0]=U):U=e.o[0]}for(var b=0;b<ie;++b)m[L+b]=m[g+b];L+=ie,g+=ie;var K=L-U;if(K<0){var Q=-K,Wt=e.e+K;Q>W&&(Q=W);for(var b=0;b<Q;++b)m[L+b]=e.w[Wt+b];L+=Q,W-=Q,K=0}for(var b=0;b<W;++b)m[L+b]=m[K+b];L+=W}if(L!=g)for(;g<m.length;)m[L++]=m[g++];else L=m.length;t?e.y+=L:m=Me(m,0,L)}else if(t){if(e.y+=f,g)for(var b=0;b<f;++b)m[b]=m[g+b]}else g&&(m=Me(m,g));return e.b=a,m}$(2)}},lr=function(r,e){if(r.length==1)return r[0];for(var t=new O(e),n=0,o=0;n<r.length;++n){var s=r[n];t.set(s,o),o+=s.length}return t};function we(r,e){for(var t=[],n=+!e,o=0,s=0;r.length;){var i=er(r,n||e);if(typeof i=="object"){for(n?(e=null,i.w.length==i.u&&(t.push(e=i.w),s+=i.u)):(t.push(e),i.e=0);!i.l;){var c=cr(r,i,e);c||$(5),e?i.e=i.y:(t.push(c),s+=c.length,Yt(i.w,0,c.length),i.w.set(c,i.w.length-c.length))}o=i.b+i.c*4}else o=i;r=r.subarray(o)}return lr(t,s)}function D(r){let e=[],t=0,n=()=>{let s=0,i=1;for(;;){let c=r[t++];if(s+=(c&127)*i,i*=128,!(c&128))return s}},o=s=>Array.from(s,i=>i.toString(16).padStart(2,"0")).join("");for(;t<r.length;){let s=t,i=n(),c=Math.floor(i/8),a=i&7,l;if(a===0){let u=t;n(),l=r.slice(u,t)}else if(a===2){let u=n();l=r.slice(t,t+u),t+=u}else if(a===5)l=r.slice(t,t+4),t+=4;else if(a===1)l=r.slice(t,t+8),t+=8;else throw new Error(`wire type ${a}`);e.push([c,a,o(r.slice(s,t)),l])}return e}var ur=r=>Array.from(r,e=>e.toString(16).padStart(2,"0")).join(""),_t=r=>Uint8Array.from(r.match(/../g)??[],e=>parseInt(e,16));function ye(r){let e=r.trim().toLowerCase();if(e.startsWith("80"))return e;if(e.startsWith("81"))return"80"+ur(we(_t(e.slice(2))));throw new Error(`grade body: unknown encoding 0x${e.slice(0,2)}`)}function wt(r){let e={};for(let t of r.matchAll(/<ListMgt::LmVersion DbId="[^"]+">([\s\S]*?)<\/ListMgt::LmVersion>/g)){let n=/<Name>([^<]*)<\/Name>/.exec(t[1])?.[1],o=/<Body>([0-9a-fA-F]+)<\/Body>/.exec(t[1])?.[1];n&&o&&(e[n]=ye(o))}return e}function yt(r){let e=new Map;for(let t of r.matchAll(/<ListMgt::LmVersion DbId="([^"]+)">([\s\S]*?)<\/ListMgt::LmVersion>/g)){let n=/<Body>([0-9a-fA-F]+)<\/Body>/.exec(t[2])?.[1];n&&e.set(t[1],ye(n))}return e}function bt(r){let e=X(r),t=l=>new TextDecoder().decode(e[l]),n=Object.keys(e).find(l=>l.startsWith("SeqContainer/")&&l.endsWith(".xml"));if(!n)throw new Error("grade bodies: no SeqContainer in the .drt");let o=new Map,s=new Map,i=Object.keys(e).filter(l=>l.startsWith("MediaPool/")&&l.endsWith(".xml"));for(let l of i)for(let u of t(l).matchAll(/<Sm2MpVideoClip DbId="([^"]+)">([\s\S]*?)<\/Sm2MpVideoClip>/g)){let d=/<pLmVerTable>([\s\S]*?)<\/pLmVerTable>/.exec(u[2]);d&&(o.set(u[1],wt(d[1])),s.set(u[1],yt(d[1])))}let c=new Map,a=0;for(let l of t(n).matchAll(/<Sm2TiTrack DbId="[^"]+">([\s\S]*?)<\/Sm2TiTrack>/g))if(/<Type>([^<]*)<\/Type>/.exec(l[1])?.[1]==="0"){a++;for(let u of l[1].matchAll(/<Sm2TiVideoClip DbId="[^"]+">([\s\S]*?)<\/Sm2TiVideoClip>/g)){let d=u[1],f=/<Start>(-?\d+)<\/Start>/.exec(d)?.[1],h=/<Name>([^<]*)<\/Name>/.exec(d)?.[1]??"";if(f===void 0)continue;let p=/<pLmVerTable>([\s\S]*?)<\/pLmVerTable>/.exec(d),m=/<MediaRef>([^<]+)<\/MediaRef>/.exec(d)?.[1],g=p&&/<pActive>([^<]+)<\/pActive>/.exec(p[1])?.[1],S=g?yt(p[1]).get(g)??(m?s.get(m)?.get(g):void 0):void 0;c.set(`${a}:${f}`,{name:h,local:p?wt(p[1]):{},remote:m&&o.get(m)||{},...S?{active:S}:{}})}}return c}function fn(r){let e=a=>D(a),t=a=>{let l=0,u=1;for(let d of a)if(l+=(d&127)*u,u*=128,!(d&128))break;return l},n=e(_t(r.slice(2))).find(a=>a[0]===3&&a[1]===2&&e(a[3]).some(l=>l[0]===8&&t(l[3])===84)),s=(n?e(n[3]).filter(a=>a[0]===9).flatMap(a=>e(a[3])):[]).find(a=>a[0]===1&&a[1]===2&&e(a[3]).some(l=>l[0]===1&&l[1]===0&&t(l[3])===10));return s?e(s[3]).filter(a=>a[0]===6&&a[1]===2).map(a=>{let l=e(a[3]),u=t(l.find(h=>h[0]===1&&h[1]===0)?.[3]??new Uint8Array([0]))/2,d=l.find(h=>h[0]===2&&h[1]===2)?.[3]??new Uint8Array,f={t:u,zoom:1,height:1,rotation:0,pan:0,tilt:0,flip_x:!1,flip_y:!1};for(let h of e(d)){if(h[0]===5&&h[1]===2){let R=e(h[3]);f.ease_in=t(R.find(k=>k[0]===1)?.[3]??new Uint8Array([1])),f.ease_out=t(R.find(k=>k[0]===2)?.[3]??new Uint8Array([1]));continue}if(h[0]!==3||h[1]!==2)continue;let p=e(h[3]),m=t(p.find(R=>R[0]===1)?.[3]??new Uint8Array),g=p.find(R=>R[0]===2)?.[3],S=g&&e(g).find(R=>R[0]===1&&R[1]===5),_=g&&e(g).find(R=>R[0]===2&&R[1]===0),v=S?new DataView(S[3].buffer,S[3].byteOffset,4).getFloat32(0,!0):_?t(_[3]):void 0;v!==void 0&&(m===271581186?f.height=v:m===271581187?f.zoom=v:m===271581188?f.rotation=v:m===271581189?f.pan=v:m===271581190?f.tilt=v:m===271581191?f.flip_y=!!v:m===271581192&&(f.flip_x=!!v))}return f}).sort((a,l)=>a.t-l.t):[]}var pr=r=>Array.from(r,e=>e.toString(16).padStart(2,"0")).join(""),V=r=>Uint8Array.from(r.match(/../g)??[],e=>parseInt(e,16)),St=r=>{let e=[];do e.push(r&127|(r>127?128:0)),r=Math.floor(r/128);while(r);return e};function vt(r){let e=V(r.trim());if(e.length<9)throw new Error("EffectFiltersBA: too short");if(e[8]===128)return e.slice(9);if(e[8]===129)return we(e.slice(9));throw new Error(`EffectFiltersBA: unknown encoding 0x${e[8].toString(16)}`)}function mr(r){let e=new Uint8Array(9);return new DataView(e.buffer).setUint32(0,2),new DataView(e.buffer).setUint32(4,r.length+1),e[8]=128,pr(new Uint8Array([...e,...r]))}var Ce=r=>{let e=D(r).find(t=>t[0]===1&&t[1]===0);return e?dr(e[3]):-1};function dr(r){let e=0,t=1;for(let n of r)if(e+=(n&127)*t,t*=128,!(n&128))break;return e}var Le=(r,e)=>new Uint8Array([...St(r<<3|2),...St(e.length),...e]);function fr(r,e){let t=new DataView(r.buffer,r.byteOffset,r.byteLength),n=-t.getInt32(0)/16;if(!Number.isInteger(n)||n<2||r.length!==4+n*16||r[10]!==12)return r;let o=Array.from({length:n},(a,l)=>({frame:t.getUint32(4+l*16,!0),value:t.getFloat64(4+l*16+8,!0)})),s=o.map(a=>e(a.frame));if(!s.slice(0,-1).some(Boolean))return r;let i=new Uint8Array(4+n*64),c=new DataView(i.buffer);return c.setInt32(0,-(n*64)),o.forEach((a,l)=>{let u=4+l*64;c.setUint32(u,a.frame,!0),i[u+6]=13,c.setFloat64(u+8,a.value,!0);let d=l>0?s[l-1]:void 0,f=l<n-1?s[l]:void 0;d&&c.setFloat64(u+16,-(d.in/10)*(a.frame-o[l-1].frame),!0),f&&c.setFloat64(u+32,f.out/10*(o[l+1].frame-a.frame),!0)}),i}function gr(r,e){let t=[];for(let n of D(r))if(n[0]===9&&n[1]===2&&n[3].length){let o=D(n[3]).map(s=>s[0]===10&&s[1]===2?[...Le(10,fr(s[3],e))]:[...V(s[2])]).flat();t.push(...Le(9,new Uint8Array(o)))}else t.push(...V(n[2]));return new Uint8Array(t)}function hr(r){let e=[];for(let t of D(r)){if(t[0]!==9||t[1]!==2||!t[3].length)continue;let n=D(t[3]).find(i=>i[0]===10&&i[1]===2)?.[3];if(!n||n.length<4)continue;let o=new DataView(n.buffer,n.byteOffset,n.byteLength),s=-o.getInt32(0)/16;Number.isInteger(s)&&s>e.length&&n.length===4+s*16&&Array.from({length:s},(i,c)=>n[4+c*16+6]).every(i=>i===12)&&(e=Array.from({length:s},(i,c)=>o.getUint32(4+c*16,!0)))}return e}function wr(r,e){let t=D(e).find(s=>s[0]===1&&s[1]===2&&Ce(s[3])===4);if(!t)throw new Error("the written clip carries no Transform group");let n=[],o=!1;for(let s of r?D(r):[]){if(s[0]===1&&s[1]===2&&Ce(s[3])===4){o||(n.push(...V(t[2])),o=!0);continue}n.push(...V(s[2]))}return o||n.push(...V(t[2])),new Uint8Array(n)}function xt(r){let e=[],t=0;for(let n of r.matchAll(/<Sm2TiTrack DbId="[^"]+">([\s\S]*?)<\/Sm2TiTrack>/g)){if(/<Type>([^<]*)<\/Type>/.exec(n[1])?.[1]!=="0")continue;t++;let o=n.index+n[0].indexOf(n[1]);for(let s of n[1].matchAll(/<Sm2TiVideoClip DbId="[^"]+">([\s\S]*?)<\/Sm2TiVideoClip>/g)){let i=/<Start>(-?\d+)<\/Start>/.exec(s[1])?.[1];i!==void 0&&e.push({track:t,start:Number(i),at:o+s.index,end:o+s.index+s[0].length,body:s[0]})}}return e}var kt=r=>Object.keys(r).find(e=>e.startsWith("SeqContainer/")&&e.endsWith(".xml"));function Rt(r,e,t,n){let o=X(r),s=X(e),i=kt(o),c=kt(s);if(!i||!c)throw new Error("no SeqContainer in the .drt");let a=new TextDecoder().decode(o[i]),l=xt(a),u=xt(new TextDecoder().decode(s[c])),d=[],f=[],h=[];for(let m of t){let g=`V${m.item.track}@${m.item.start}`,S=l.find(y=>y.track===m.item.track&&y.start===m.item.start+n),_=S?l.filter(y=>y.track===S.track).indexOf(S):-1,v=_>=0?u.filter(y=>y.track===m.item.track)[_]:void 0,R=v&&/<EffectFiltersBA>([0-9a-fA-F]+)<\/EffectFiltersBA>/.exec(v.body)?.[1];if(!S||!R){f.push(g);continue}let k=/<EffectFiltersBA>([0-9a-fA-F]*)<\/EffectFiltersBA>/.exec(S.body),b=D(vt(R)),w=b.find(y=>y[0]===1&&y[1]===2&&Ce(y[3])===4),T=w?hr(w[3]):[];if(T.length!==m.keys.length){f.push(`${g} (the engine wrote ${T.length} keys for ${m.keys.length})`);continue}let P=new Map(T.map((y,x)=>[y,m.keys[x].shape])),E=new Uint8Array(b.flatMap(y=>y===w?[...Le(1,gr(y[3],x=>P.get(x)))]:[...V(y[2])])),N=wr(k?.[1]?vt(k[1]):null,E),C=`<EffectFiltersBA>${mr(N)}</EffectFiltersBA>`,M=k?S.body.replace(k[0],C):S.body.replace(/(<\/Sm2TiVideoClip>)$/,`${C}$1`);h.push({at:S.at,end:S.end,body:M}),d.push(g)}for(let m of h.sort((g,S)=>S.at-g.at))a=a.slice(0,m.at)+m.body+a.slice(m.end);let p={...o,[i]:new TextEncoder().encode(a)};return{drt:ct(p),keyed:d,missing:f}}function At(r,e,t){let n=r.source_range,o=r.timeline_range,s=n?.start.rate||t,i=n?.start.value??0,c=n?.duration&&o?.duration&&o.duration.value?n.duration.value/n.duration.rate/(o.duration.value/o.duration.rate)*s/t:s/t,a=[],l=0;for(let f of e){let h={value:i+f.t*c,rate:s},p=(m,g)=>a.push({id:`${r.id}-align-${l++}`,parameter_path:m,time:h,value:g,interp:"linear"});p("scale",f.transform.scale_x),e.some(m=>Math.abs(m.transform.scale_y-m.transform.scale_x)>.001)&&p("scale.y",f.transform.scale_y),p("position.x",f.transform.position_x),p("position.y",f.transform.position_y),p("rotation",f.transform.rotation)}let u=e[0].transform,d=(r.keyframes??[]).filter(f=>!/^(scale|position|rotation)/.test(String(f.parameter_path)));Object.assign(r,{scale:u.scale_x,position_x:u.position_x,position_y:u.position_y,rotation:u.rotation,keyframes:[...d,...a]}),Math.abs(u.scale_y-u.scale_x)>.001&&Object.assign(r,{scale_x:u.scale_x,scale_y:u.scale_y}),u.flip_h?r.flip_horizontal=!0:delete r.flip_horizontal,u.flip_v?r.flip_vertical=!0:delete r.flip_vertical}function Ot(r=H()){if(r==="win32"){let e=F("PROGRAMDATA")??"C:\\ProgramData",t=F("PROGRAMFILES")??"C:\\Program Files";return{api:`${e}\\Blackmagic Design\\DaVinci Resolve\\Support\\Developer\\Scripting`,lib:`${t}\\Blackmagic Design\\DaVinci Resolve\\fusionscript.dll`}}return r==="linux"?{api:"/opt/resolve/Developer/Scripting",lib:"/opt/resolve/libs/Fusion/fusionscript.so"}:{api:"/Library/Application Support/Blackmagic Design/DaVinci Resolve/Developer/Scripting",lib:"/Applications/DaVinci Resolve/DaVinci Resolve.app/Contents/Libraries/Fusion/fusionscript.so"}}async function yr(r){let e=F("RESOLVE_SCRIPT_LIB");if(e)return e;if(r==="darwin"){let n=(await de("ps",["-axo","comm="])).stdout.split(`
|
|
4
4
|
`).map(o=>o.trim()).find(o=>/\/Contents\/MacOS\/Resolve$/.test(o));if(n){let o=n.replace(/\/MacOS\/Resolve$/,"/Libraries/Fusion/fusionscript.so");if(await ce(o))return o}}return Ot(r).lib}async function Mt(){for(let r of["./bridge.py","./resolve-bridge.py"]){let e=Ze(new URL(r,import.meta.url));if(await le(e))return e}throw new Error("resolve: bridge.py is missing from this install")}var je=new Map;function _r(r){return je.has(r)||je.set(r,de(r,["-c","import sys; print(sys.base_prefix)"],{timeoutMs:2e4}).then(e=>e.stdout.trim().split(`
|
|
5
5
|
`).pop()||void 0).catch(()=>{})),je.get(r)}var br=["PYTHON3HOME","FUSION_PYTHON3HOME","FUSION_PYTHON3_HOME","FUSION_PYTHON36_HOME"];async function $t(r,e){let{api:t}=Ot(r),n=r==="win32"?await _r(e):void 0;return{RESOLVE_SCRIPT_API:F("RESOLVE_SCRIPT_API")??t,RESOLVE_SCRIPT_LIB:await yr(r),PYTHONPATH:I(F("RESOLVE_SCRIPT_API")??t,"Modules"),...n?Object.fromEntries(br.map(o=>[o,n])):{}}}function Nt(r,e=""){let t=r.match(/^Fatal Python error: (.+)$/m)?.[1]?.trim();return t?`the Resolve bridge crashed inside Resolve's scripting library (${t}); the next call starts a fresh one`:r.trim().split(`
|
|
6
6
|
`).map(o=>o.trim()).filter(o=>o&&o!=="<no Python frame>"&&!/^(Current thread|Thread) 0x/.test(o)).pop()||e}var G=null;async function Sr(r,e,t){if(G?.busy)return null;if(!G){let s=H(),i=Te(),c="",a={io:null,busy:!1,waiting:null,last:""};if(a.io=ot(i,[await Mt(),"serve"],l=>{c+=new TextDecoder().decode(l);let u;for(;(u=c.indexOf(`
|
|
7
7
|
`))>=0;){let d=c.slice(0,u);c=c.slice(u+1);let f=a.waiting;a.waiting=null,f?.(d)}},l=>{a.last=/^the Resolve bridge crashed/.test(a.last)?a.last:Nt(l,a.last)},{env:await $t(s,i)}),a.io.exited.then(()=>{G===a&&(G=null),a.waiting?.("")}),G)return a.io.close(),null;G=a}let n=G;n.busy=!0,n.io.hold(!0);let o;try{let s=new Promise(a=>{n.waiting=a}),c=await n.io.write(new TextEncoder().encode(JSON.stringify({action:r,args:e})+`
|
|
8
8
|
`)).then(()=>!0,()=>!1)?await Promise.race([s,new Promise(a=>{o=setTimeout(()=>a(null),t)})]):"";if(c===null)return n.io.close(),{ok:!1,why:"bridge",detail:`no answer from Resolve within ${Math.round(t/1e3)} s`};try{return JSON.parse(c)}catch{return{ok:!1,why:"bridge",detail:n.last||"the Resolve bridge stopped"}}}finally{clearTimeout(o),n.waiting=null,n.busy=!1,n.io.hold(!1)}}var vr=async(r,e,t)=>(F("CONFORM_RESOLVE_ONESHOT")!=="1"?await Sr(r,e,t).catch(()=>null):null)??xr(r,e,t),xr=async(r,e,t)=>{let n=H(),o=Te(),s=await q("ct-bridge-"),i=I(s,"args.json"),c;try{await pe(i,JSON.stringify(e)),c=await de(o,[await Mt(),r,`@${i}`],{env:await $t(n,o),timeoutMs:t})}finally{await me(s).catch(()=>{})}let a=c.stdout.trim().split(`
|
|
9
|
-
`).pop()??"";try{return JSON.parse(a)}catch{return{ok:!1,why:"bridge",detail:c.code==="ENOENT"||/Microsoft Store/.test(c.stderr)?`${o} is not installed (Resolve's scripting needs Python 3: python.org)`:Nt(c.stderr)||(typeof c.code=="string"?`the Resolve bridge could not start: ${c.code}`:`no answer from Resolve within ${Math.round(t/1e3)} s`)}}},kr=1500,Tt=Promise.resolve(),Pt=0;function Rr(r){let e=Tt.catch(()=>{}).then(async()=>{let t=Pt+kr-Date.now();t>0&&await new Promise(n=>setTimeout(n,t));try{return await r()}finally{Pt=Date.now()}});return Tt=e,e}var z=class extends Error{constructor(t,n){super(n);this.why=t}},Ar={module:"Install DaVinci Resolve (its scripting module ships with it).",no_connection:"Start Resolve and set Preferences > System > General > External scripting using: Local (Resolve Studio).",no_project:"Open a project in Resolve."},_e=class{constructor(e=vr){this.runner=e;this.host="resolve";this.restore=new Map;this.startNotes=new Map}async call(e,t={},n=6e4){let o=await this.runner(e,t,n);if(o.ok)return o;throw o.why==="resolve_error"&&/NoneType' object is not callable/.test(String(o.detail))&&!(await this.runner("version",{},1e4)).ok?new z("host_quit",`resolve: Resolve stopped responding during ${e} (it may have quit; see its log, ResolveDebug.txt). Restart Resolve and try again.`):new z(o.why??"unknown",`resolve: ${o.detail||o.why}`)}async support(){let e=await this.runner("version",{},15e3),t=e.ok?e.product==="DaVinci Resolve Studio"?{ok:!0}:{ok:!1,reason:`${e.product} has no external scripting (Resolve Studio has)`}:{ok:!1,reason:e.detail??String(e.why),setup:Ar[e.why??""]};return{export:t,open:t,render:t,markers:t}}async current(){return await this.call("current")}async project(e){return await this.call("project",e,e.export_dir||e.grades?9e5:12e4)}async clipLut(e){return await this.call("clip_lut",e,6e4)}async items(e){return e.selected?await Rr(()=>this.call("items",e,15e3)):await this.call("items",e,e.follow?15e3:12e4)}async apply(e){let t=e.ops.filter(o=>o.op==="edit_keys");if(t.length){let o=e.ops.filter(a=>a.op!=="edit_keys"),s=o.length?await this.apply({...e,ops:o}):{project:"",timeline:e.timeline??"",results:[],undo:[],applied:0,failed:0},i=await this.alignedCopy(e,t),c=i.results.filter(a=>a.ok).length;return{...s,project:s.project||i.project,timeline:s.timeline||i.timeline,results:[...s.results,...i.results],applied:s.applied+c,failed:s.failed+i.results.length-c}}let n=e.ops.filter(o=>(o.op==="grade_sizing"&&(o.target==="input"||o.target==="node")&&!o.reset||o.op==="node_structure"||o.op==="copy_nodes")&&o.item&&"track"in o.item);for(let o of n){let s=o.node_structure??o.structure_path;if(!s)continue;let i=/<Body>([0-9a-fA-F]+)<\/Body>/.exec(new TextDecoder().decode(await ue(s)))?.[1];if(!i)throw new z("usage",`${s}: not a Resolve grade still (.drx with a <Body>)`);o.structure=ye(i),o.structure_name=s}if(n.length){let{grades:o,t0:s}=await this.grades(e.timeline,e.into?{into:e.into,scratch_project:e.scratch_project}:{}),i=c=>{let a=c.item;return o.get(`${a.track}:${a.start+s}`)};for(let c of n){let a=i(c);if(a&&(c.bodies={local:a.local,remote:a.remote}),c.op==="copy_nodes"){let l=c.from;c.from_body=o.get(`${l.track}:${l.start+s}`)?.active}}}return await this.call("apply",e,6e4+e.ops.length*200)}async alignedCopy(e,t){let n=e.into?{into:e.into,scratch_project:e.scratch_project}:{},o=await q("ct-aligned-"),s=i=>({project:"",timeline:e.timeline??"",results:t.map(()=>({op:"edit_keys",ok:!1,refused:["aligned copy"],detail:`refused: ${i}; nothing changed`}))});try{let i=I(o,"export.drt"),c=await this.call("export",{timeline:e.timeline,out_path:i,...n}),a=String(c.timeline),l=Number(c.start_frame??0),{session:u}=await pt(i,"drt"),d=u.timelines[0],f=(d.fps_num??24)/(d.fps_den??1),h=d.tracks.filter(w=>String(w.kind).toLowerCase()==="video"),p=w=>Math.round(w.value*f/w.rate),m=[],g=[];for(let w of t){let T=h[w.item.track-1]?.items.find(P=>{let E=P.timeline_range?.start;return E&&[w.item.start,w.item.start+l].includes(p(E))});T?(At(T,w.keys,f),m.push(w)):g.push(`V${w.item.track}@${w.item.start}`)}let S=await lt("resolve-drt",u),_=typeof S.body=="string"?new TextEncoder().encode(S.body):S.body,v=Rt(await ue(i),_,m,l);if(!v.keyed.length)return s(`no clip could be keyed (${[...g,...v.missing].join(", ")})`);let R=I(o,`${a.replace(/[^\w.-]+/g,"_").slice(0,100)}_ALIGNED.drt`);await tt(R,v.drt);let k=await this.call("open",{path:R,name:`${a} ALIGNED`,link_existing:!0,same_as:a,...n}),b=new Map([...g.map(w=>[w,"not found in the timeline's export"]),...v.missing.map(w=>[w.split(" ")[0],w])]);return{project:String(k.project??""),timeline:String(k.timeline??""),results:t.map(w=>{let T=`V${w.item.track}@${w.item.start}`;return b.has(T)?{op:"edit_keys",ok:!1,refused:["not keyed"],detail:`refused: ${b.get(T)}; nothing changed`}:{op:"edit_keys",ok:!0,detail:`${w.keys.length} Edit-page keyframes on "${k.timeline}" (a copy of "${a}" with every grade and setting; "${a}" itself unchanged)`}})}}catch(i){return s(i instanceof Error?i.message:String(i))}finally{await me(o).catch(()=>{})}}async grades(e,t){let n=await q("ct-grades-");try{let o=I(n,"grades.drt"),s=await this.call("export",{timeline:e,out_path:o,...t});return{grades:await ue(o).then(bt).catch(()=>new Map),t0:Number(s.start_frame??0)}}finally{await me(n).catch(()=>{})}}async presets(e){return await this.call("presets",e,12e4)}async presetAuthor(e){return await this.call("preset_author",e,6e4)}async export(e){if(!e.out_path)throw new z("usage","resolve: export needs out_path");let t=await this.call("export",{timeline:e.timeline,out_path:e.out_path,...e.clip_id?{clip_id:e.clip_id}:{}});return{path:String(t.path),format:"drt",project:String(t.project),timeline:String(t.timeline)}}async open(e){let t=await this.call("open",{path:e.path,into:e.into??"current",name:e.name,media_dir:e.media_dirs?.[0],stay:e.stay??!1,folder:e.folder,create_folder:e.create_folder??!1,link_existing:e.link_existing??!1,...e.settings_from?{settings_from:e.settings_from}:{}},3e5),n=[...t.notes??[]];return(e.media_dirs?.length??0)>1&&n.push(`Resolve searches one media folder per import; used ${e.media_dirs[0]}`),{project:String(t.project),timeline:String(t.timeline),notes:n,restored:!!t.restored,...t.folder?{folder:String(t.folder)}:{},...t.settings?{settings:String(t.settings)}:{}}}async renderStart(e){let t=await this.call("render_start",{...e}),n=String(t.job_id);if(t.queued)return{job_id:n,state:"queued",percent:0,notes:["left in Resolve's render queue: start it on the Deliver page"]};this.restore.set(n,t.restore);let o=t.rejected_settings??[];return o.length&&this.startNotes.set(n,[`Resolve refused render setting(s) ${o.join(", ")} for this format; the rest were applied`]),{job_id:n,state:"queued",percent:0}}async renderStatus(e){let t=await this.call("render_status",{job_id:e},15e3),n={job_id:e,state:t.state,percent:Number(t.percent??0)};if(t.error&&(n.error=String(t.error)),n.state==="complete"||n.state==="failed"){let o=await this.call("render_finish",{job_id:e,restore:this.restore.get(e)});this.restore.delete(e),o.output&&(n.outputs=[String(o.output)]);let s=[...this.startNotes.get(e)??[],...o.tracks?[Et(o)]:[]];this.startNotes.delete(e),s.length&&(n.notes=s)}return n}async renderCancel(e){let t=await this.call("render_cancel",{job_id:e,restore:this.restore.get(e)});return this.restore.delete(e),{job_id:e,state:"cancelled",percent:0,...t.output?{outputs:[String(t.output)]}:{},...t.tracks?{notes:[Et(t)]}:{}}}},Et=r=>{let e=r.tracks.map(t=>`V${t}`).join(", ");return r.tracks_restored?`video track(s) ${e} switched back on`:`could NOT switch video track(s) ${e} back on: re-enable them on the Edit page`};async function Rn(r,e){let t=[];for await(let n of nt(r))n.isFile&&n.name.startsWith(e)&&t.push(I(r,n.name));return t.sort()}var Tr="ws://localhost:1985",Ct="localhost",Lt="conform_tools",jt="conform.tools ",Ft="Video_Full",Pr=r=>!!r&&typeof r=="object"&&"_handle"in r&&"_id"in r,J=class extends Error{constructor(t,n){super(n);this.code=t}},De=class r{constructor(e){this.ws=e;this.next=1;this.waiting=new Map;e.onMessage(t=>{let n;try{n=JSON.parse(t)}catch{return}let o=typeof n.id=="number"?this.waiting.get(n.id):void 0;if(!o)return;if(this.waiting.delete(n.id),n.error===void 0||n.error===null)return o.ok(n.result??null);let s=n.error;o.no(typeof s=="string"?new J(n.code??-1,s):new J(s.code??n.code??-1,s.message??JSON.stringify(s)))}),e.onClose(()=>{for(let t of this.waiting.values())t.no(new J("closed","Baselight closed the FLAPI connection"));this.waiting.clear()})}static async connect(e,t=3e3){let n=new r(await mt(e,{maxBytes:67108864,timeoutMs:t})),o=await Er();return o&&await n.call("authenticate",{username:F("USER")??F("USERNAME")??"conform",token:o},null,t).catch(()=>null),n}call(e,t={},n=null,o=12e4){let s=this.next++;return new Promise((i,c)=>{let a=setTimeout(()=>{this.waiting.delete(s),c(new J("timeout",`${e}: no answer from Baselight within ${Math.round(o/1e3)} s`))},o);this.waiting.set(s,{ok:l=>{clearTimeout(a),i(l)},no:l=>{clearTimeout(a),c(l)}}),this.ws.send(JSON.stringify({jsonrpc:"2.0",method:e,target:n?n._id:null,params:t,id:s}))})}async forget(...e){for(let t of e)Pr(t)&&await this.call("forget",{},t).catch(()=>null)}close(){this.ws.close()}};async function Er(){let r=F("FLAPI_TOKEN");if(r)return r.trim();let e=H()==="darwin"?I(Pe(),"Library","Preferences","FilmLight","flapi-token"):I(Pe(),".filmlight","flapi-token");try{return(await et(e)).trim()||null}catch{return null}}var It=(...r)=>Object.fromEntries(r.map(e=>[e,1])),Or={[-30]:30,[-31]:30,[-32]:30,[-34]:25,[-35]:24};function be(r){if(!r||typeof r!="object")return null;let e=typeof r.fps=="string"?{TC_30DF:-30,TC_60HDF:-31}[r.fps]??Number(r.fps):r.fps,t=e>0?e:Or[e]??30,n=((r.h*60+r.m)*60+r.s)*t+r.f;if(e!==-30&&e!==-31)return n;let o=r.h*60+r.m;return n-2*(o-Math.floor(o/10))}function Mr(r,e,t){let n=Math.round(e),o=r;if(t&&n===30){let l=Math.floor(o/17982),u=o%17982;o+=18*l+(u>2?2*Math.floor((u-2)/1798):0)}let s=o%n,i=Math.floor(o/n)%60,c=Math.floor(o/n/60)%60;return{_type:"timecode",h:Math.floor(o/n/3600)%24,m:c,s:i,f:s,phase:0,fps:t&&n===30?-30:n,wrap:24}}function Dt(r){let e=Math.round(r);return Math.abs(r-e)<.005?e:Math.abs(r-e*1e3/1001)<.01?e*1e3/1001:r}var j=class extends Error{constructor(t,n){super(`baselight: ${n}`);this.why=t}},$r={darwin:"/Applications/Baselight",linux:"/usr/fl/baselight"},Se=class{constructor(e){this.url=e;this.host="baselight";this.jobs=new Map}async conn(e=3e3){let t=this.url??F("CONFORM_BASELIGHT_URL")??Tr;try{return await De.connect(t,e)}catch(n){let o=await ce($r[H()]??"/nonexistent");throw new j(o?"not_running":"not_installed",o?`Baselight is not answering FLAPI at ${t} (${n.message})`:"Baselight is not installed on this machine")}}async with(e){let t=await this.conn();try{return await e(t)}catch(n){throw n instanceof j?n:new j("flapi",n.message)}finally{t.close()}}async support(){let e;try{let t=await this.with(n=>n.call("Application.get_application_info"));e=/baselight|daylight/i.test(t.Product??"")?{ok:!0}:{ok:!1,reason:`the FLAPI server is ${t.Product??"unknown"}, not the Baselight app (port 1984 is the headless flapid)`,setup:"Point CONFORM_BASELIGHT_URL at the running Baselight (ws://localhost:1985)."}}catch(t){let n=t instanceof j?t.why:"flapi";e={ok:!1,reason:t.message.replace(/^baselight: /,""),setup:n==="not_installed"?"Install FilmLight Baselight (FLAPI ships with it; nothing else to install).":"Start Baselight. Its API server listens on port 1985 by default (Preferences > Advanced > API Server)."}}return{export:e,open:e,render:e,markers:{ok:!1,reason:"not wired for Baselight yet (FLAPI has marks: Scene.add_mark)"}}}async scenePath(e,t,n){if(t?.includes(":")){let i=await e.call("Scene.parse_path",{str:t});return{host:i.Host,job:i.Job,scene:i.Scene}}let o=await this.current(e),s=n??o?.job;if(t&&s)return{host:o?.host??Ct,job:s,scene:t};if(!o)throw new j("no_scene",t?`no job to find scene "${t}" in: pass project (the job) or "host:job:scene"`:'no scene is open in Baselight: open one, or name it ("host:job:scene")');return o}async current(e){let t=await e.call("Application.get").catch(()=>null);if(!t)return null;try{let n=await e.call("Application.get_current_scene",{},t);if(!n)return null;try{let o=await e.call("Scene.get_scene_pathname",{},n),[s,i,...c]=o.split(":");return c.length?{host:s,job:i,scene:c.join(":")}:null}finally{await e.forget(n)}}finally{await e.forget(t)}}async export(e){if(!e.out_path)throw new j("usage","export needs out_path");return await this.with(async t=>{let n=await this.scenePath(t,e.timeline),o=await t.call("Scene.open_scene",{scenepath:{Host:n.host,Job:n.job,Scene:n.scene},flags:It("OPENFLAG_READ_ONLY")});try{let s=await Lr(t,o,n.scene);await Y(fe(e.out_path)),await pe(e.out_path,JSON.stringify(s,null,1))}finally{await t.call("Scene.close_scene",{},o).catch(()=>null),await t.forget(o)}return{path:e.out_path,format:"otio",project:n.job,timeline:n.scene}})}async open(e){let{readTimeline:t}=await import("./timeline-HTG23FEH.js"),{session:n}=await t(e.path),o=n.timelines.find(u=>u.kind!=="compound")??n.timelines[0];if(!o)throw new j("usage",`no timeline in ${e.path}`);let s=new Map((n.media_references??[]).map(u=>[u.id,u])),i=o.fps_num/o.fps_den,c=o.tracks.filter(u=>u.kind==="Video").sort((u,d)=>u.track_index-d.track_index),a=[];c.length>1&&a.push(`placed V1 only: Baselight builds layers above a shot, which FLAPI cannot place in time; ${c.slice(1).reduce((u,d)=>u+d.items.filter(f=>f.kind==="clip").length,0)} clip(s) on V2+ not placed`);let l=(c[0]?.items??[]).filter(u=>u.kind==="clip"||u.kind==="gap").sort((u,d)=>u.timeline_range.start.value-d.timeline_range.start.value);return await this.with(async u=>{let d=e.into==="scratch"?null:await this.current(u);e.into!=="scratch"&&!d&&a.push(`no scene open in Baselight, so it went into our job ${Lt}`);let f=d?.job??Lt,h=d?.host??Ct;await u.call("JobManager.job_exists",{host:h,jobname:f})||await u.call("JobManager.create_job",{host:h,jobname:f});let p=(e.name??o.name??"conform.tools").replace(/[:/\\]+/g,"_"),m=p;for(let w=2;await u.call("JobManager.scene_exists",{host:h,jobname:f,scenename:m});w++)m=`${p} ${w}`;let g=await u.call("FormatSet.factory_formats"),S=o.resolution_w&&o.resolution_h?await u.call("FormatSet.get_basic_format_name",{width:o.resolution_w,height:o.resolution_h},g):null;await u.forget(g);let _=await u.call("Scene.new_scene",{scenepath:{Host:h,Job:f,Scene:m},options:{format:S,colourspace:Ft,frame_rate:i}},null,3e5),v=0,R=0,k=0,b=0;try{await u.call("Scene.start_delta",{name:"conform.tools open"},_);try{let w=0;for(let P of l){let E=P.timeline_range.start.value,N=P.timeline_range.duration.value;if(E>w&&(await Fe(u,_,E-w),k++),w=Math.max(w,E+N),P.kind==="gap"){await Fe(u,_,N),k++;continue}let M=(P.media_reference_id?s.get(P.media_reference_id):void 0)?.target_url?.replace(/^file:\/\//,""),y=P.source_range,x=M&&y?await Cr(u,M,Math.round(y.start.value),Math.round(y.start.value)+N-1):null;if(!x){await Fe(u,_,N),R++;continue}y&&Math.abs(y.duration.value-N)>.5&&b++;let L=await u.call("Scene.insert_sequence",{sequence:x,where:"INSERT_END",relativeTo:null,colourSpace:null,format:null,frameRate:i},_);await u.forget(x,L),v++}let T=await u.call("Scene.get_scene_settings",{},_);await u.call("SceneSettings.set",{values:{StartTimecode:Mr(o.start_frame??0,i,!!o.is_drop_frame)}},T),await u.forget(T),await u.call("Scene.end_delta",{},_)}catch(w){throw await u.call("Scene.cancel_delta",{},_).catch(()=>null),w}await u.call("Scene.save_scene",{},_,3e5)}catch(w){throw await u.call("Scene.close_scene",{},_).catch(()=>null),await u.forget(_),await u.call("JobManager.delete_scene",{host:h,jobname:f,scenename:m}).catch(()=>null),w}return await u.call("Scene.close_scene",{},_),await u.forget(_),a.unshift(`new scene ${h}:${f}:${m}: ${v} shot(s)${k?`, ${k} gap(s) as black`:""}`),R&&a.push(`${R} clip(s) had no media on disk at their path: placed as black of the same length (relink in Baselight's Conform view)`),b&&a.push(`${b} retimed clip(s) placed at normal speed: FLAPI has no retime setter`),m!==p&&a.push(`"${p}" was taken in ${f}: named "${m}"`),e.media_dirs?.length&&a.push("media_dirs not used: Baselight places each clip from its own path"),e.stay&&a.push("stay: FLAPI cannot switch the scene the app shows; open it from the Scenes browser"),{project:f,timeline:m,notes:a,restored:!0}})}async renderStart(e){if(e.disable_tracks?.length)throw new j("usage","disable_tracks: a Baselight render takes every layer or one (RenderTrack); leave the tracks out in the scene");if(e.audio_tracks?.length)throw new j("usage","audio_tracks is a DaVinci Resolve option");return await this.with(async t=>{let n=await this.scenePath(t,e.timeline,e.project),o=await t.call("Scene.open_scene",{scenepath:{Host:n.host,Job:n.job,Scene:n.scene},flags:It("OPENFLAG_READ_ONLY")}),s=null,i=null;try{s=await t.call("RenderSetup.create_from_scene",{scene:o});let c=await t.call("RenderSetup.get_num_deliverables",{},s),a=0;if(e.preset){let p=await t.call("RenderSetup.get_deliverable_names",{},s);if(a=p.indexOf(e.preset),a<0)throw new j("usage",`no deliverable "${e.preset}" in ${n.scene} (it has: ${p.join(", ")||"none"})`)}let l=await t.call("RenderSetup.get_deliverable",{index:a},s),u=e.name??n.scene.replace(/[^\w.-]+/g,"_");Object.assign(l,{Disabled:0,Container:"",OutputDirectory:e.target_dir,FileNamePrefix:u}),e.preset||Object.assign(l,{Name:"conform.tools",IsMovie:1,FileType:"lqtmov",MovieCodec:"apch",ImageOptions:{},FileNameExtension:".mov",RenderColourSpace:Ft,HandleEmptyFrames:"GMREB_BLACK",HandleIncompleteStacks:"GMREB_BLACK",HandleError:"BLACK",EmbedTimecode:1}),e.audio||(l.AudioCodec=""),await Y(e.target_dir),await t.call("RenderSetup.set_deliverable",{index:a,deliverable:l},s);for(let p=0;p<c;p++)p!==a&&await t.call("RenderSetup.set_deliverable_enabled",{index:p,enabled:0},s);if(e.range){let p=await t.call("Scene.get_scene_settings",{},o),m=be(await t.call("SceneSettings.get_single",{key:"StartTimecode"},p))??0;await t.forget(p);let g=e.range.in>=m?m:0;await t.call("RenderSetup.set_frames",{frames:[{Start:e.range.in-g,End:e.range.out-g}]},s)}else await t.call("RenderSetup.select_all",{},s);let d=await t.call("RenderSetup.get_output_filename_for_deliverable",{index:a},s);i=await t.call("QueueManager.create_local");let f=await t.call("RenderSetup.submit_to_queue",{queue:i,opname:`${jt}${u}`},s),h=String(f.ID);return this.jobs.set(h,{op:f.ID,out:d,notes:f.Warning?[`Baselight: ${f.Warning}`]:[]}),{job_id:h,state:"queued",percent:0}}finally{await t.forget(s,i),await t.call("Scene.close_scene",{},o).catch(()=>null),await t.forget(o)}})}async ours(e,t,n){let o=Number(n),s=await e.call("QueueManager.get_operation",{id:o},t).catch(()=>null),i=String(s?.Description??s?.Name??"");if(!this.jobs.has(n)&&!i.startsWith(jt))throw new j("not_ours",`queue operation ${n} is not a conform.tools render: left alone`);return o}async renderStatus(e){return await this.with(async t=>{let n=await t.call("QueueManager.create_local");try{let o=await this.ours(t,n,e),s=await t.call("QueueManager.get_operation_status",{id:o},n),i=Nr(s.Status),c=Number(s.Progress??0),a={job_id:e,state:i,percent:i==="complete"?100:Math.round(c<=1?c*100:c)};if(i==="failed"||i==="complete"&&s.Errors){let u=(await t.call("QueueManager.get_operation_log",{id:o},n).catch(()=>[])).filter(d=>/fail|error|warn/i.test(d.Type)).slice(-6).map(d=>`${d.Message}${d.Detail?`: ${d.Detail}`:""}`);a.error=[s.ProgressText,...u].filter(Boolean).join("; ")||"Baselight reported a failed render",i==="complete"&&(a.state="failed")}if(a.state==="complete"||a.state==="failed"||a.state==="cancelled"){let l=this.jobs.get(e);a.state==="complete"&&l&&(a.outputs=[l.out]),l?.notes.length&&(a.notes=l.notes),await t.call("QueueManager.delete_operation",{id:o},n).catch(()=>null),this.jobs.delete(e)}return a}finally{await t.forget(n)}})}async renderCancel(e){return await this.with(async t=>{let n=await t.call("QueueManager.create_local");try{let o=await this.ours(t,n,e);return await t.call("QueueManager.delete_operation",{id:o},n),this.jobs.delete(e),{job_id:e,state:"cancelled",percent:0}}finally{await t.forget(n)}})}};function Nr(r){let e=String(r).replace(/^OPSTATUS_/i,"").toLowerCase();return e==="done"?"complete":e==="active"?"rendering":e==="stopped"?"cancelled":e==="failed"||e==="crashed"||e==="toonew"?"failed":"queued"}async function Fe(r,e,t){let n=await r.call("Scene.insert_blank",{red:0,green:0,blue:0,duration:t,where:"INSERT_END",relativeTo:null,colourSpace:null},e);await r.forget(n)}async function Cr(r,e,t,n){let o=await r.call("SequenceDescriptor.get_for_template",{template:e,start:null,end:null}).catch(()=>[]);if(!o?.length)return null;let s=await r.call("SequenceDescriptor.get_start_handle",{},o[0]);await r.forget(...o);let i=await r.call("SequenceDescriptor.get_for_template",{template:e,start:s+t,end:s+n});return i?.length?(await r.forget(...i.slice(1)),i[0]):null}var Ue=(r,e)=>({OTIO_SCHEMA:"RationalTime.1",rate:e,value:r}),Ie=(r,e,t)=>({OTIO_SCHEMA:"TimeRange.1",start_time:Ue(r,t),duration:Ue(e,t)});async function Lr(r,e,t){let n=Dt(await r.call("Scene.get_working_frame_rate",{},e)),o=await r.call("Scene.get_scene_settings",{},e),s=be(await r.call("SceneSettings.get_single",{key:"StartTimecode"},o))??0;await r.forget(o);let i=await r.call("Scene.get_num_shots",{},e),c=i?await r.call("Scene.get_shot_ids",{firstIndex:0,lastIndex:i-1},e):[],a=[];for(let d of c){let f=Math.round(d.StartFrame),h=Math.round(d.EndFrame),p=await r.call("Scene.get_shot",{shot_id:d.ShotId},e);try{let m=await r.call("Shot.get_sequence_descriptor",{},p).catch(()=>null);if(!m){a.push({start:f,end:h,name:`shot ${d.ShotId}`});continue}try{let g=Dt(await r.call("Shot.get_frame_rate",{},p))||n,S=be(await r.call("Shot.get_src_start_timecode",{},p)),_=await r.call("Shot.get_src_start_frame",{},p),v=await r.call("Shot.get_src_end_frame",{},p),k=await r.call("SequenceDescriptor.is_movie",{},m)?Xe(await r.call("SequenceDescriptor.get_path",{},m),await r.call("SequenceDescriptor.get_name",{},m)):await r.call("SequenceDescriptor.get_full_filename_with_d",{},m),b=await r.call("SequenceDescriptor.get_name",{},m),w=await r.call("SequenceDescriptor.get_tape",{index:0},m).catch(()=>""),T=await r.call("SequenceDescriptor.get_start_frame",{},m),P=await r.call("SequenceDescriptor.get_start_handle",{},m),E=await r.call("SequenceDescriptor.get_end_handle",{},m),C=(be(await r.call("SequenceDescriptor.get_start_timecode",{index:0},m))??0)-(T-P),M=Math.round(v-_),y=h-f,x={OTIO_SCHEMA:"Clip.2",name:b,enabled:!0,source_range:Ie(S??C+(_-P),y,g),media_references:{DEFAULT_MEDIA:{OTIO_SCHEMA:"ExternalReference.1",target_url:k,available_range:Ie(C,E-P+1,g),available_image_bounds:null,name:b,metadata:{}}},active_media_reference_key:"DEFAULT_MEDIA",effects:M&&M!==y?[{OTIO_SCHEMA:"LinearTimeWarp.1",name:"",effect_name:"LinearTimeWarp",time_scalar:M/y,metadata:{}}]:[],markers:[],metadata:w?{baselight:{tape:w}}:{}};a.push({start:f,end:h,name:b,clip:x})}finally{await r.forget(m)}}finally{await r.forget(p)}}let l=[];for(let d of[...a].sort((f,h)=>f.start-h.start)){if(!d.clip)continue;let f=l.find(h=>h[h.length-1].end<=d.start);f?f.push(d):l.push([d])}let u=l.map((d,f)=>{let h=[],p=0;for(let m of d)m.start>p&&h.push({OTIO_SCHEMA:"Gap.1",name:"",enabled:!0,source_range:Ie(0,m.start-p,n),effects:[],markers:[],metadata:{}}),h.push(m.clip),p=m.end;return{OTIO_SCHEMA:"Track.1",name:`V${f+1}`,kind:"Video",enabled:!0,children:h,source_range:null,effects:[],markers:[],metadata:{}}});return{OTIO_SCHEMA:"Timeline.1",name:t,metadata:{baselight:{shots:c.length}},global_start_time:Ue(s,n),tracks:{OTIO_SCHEMA:"Stack.1",name:"tracks",enabled:!0,children:u,source_range:null,effects:[],markers:[],metadata:{}}}}var jr="127.0.0.1:31416",Fr="/ptsl.PTSL/SendGrpcRequest",Ir="CONFORM.TOOLS",Dr="CONFORM.TOOLS Desktop",He=[2025,6,0],re=[2025,6],qe=1e4,Ut=5e3,Ur="ConformTools",Hr="Start Pro Tools 2025.6 or newer with a session open (PTSL, its scripting door, listens on 127.0.0.1:31416).",Be={GetTrackList:3,HostReadyCheck:13,ExportSessionInfoAsText:30,GetSessionSampleRate:35,GetSessionTimeCodeRate:38,GetSessionFeetFramesRate:39,GetSessionName:42,GetSessionPath:43,GetSessionStartTime:44,GetSessionLength:45,GetPTSLVersion:55,GetTransportState:59,ClearMemoryLocation:61,EditMemoryLocation:68,GetMemoryLocations:69,RegisterConnection:70,CreateMemoryLocation:71,SetTimelineSelection:81,GetTimelineSelection:82,GetSessionIDs:97,GetMainCounterFormat:102},Br=[3,6],Vr=[4,7],Ht=106,Gr=new TextEncoder,qr=new TextDecoder;function ve(r,e){for(;r>127;)e.push(r&127|128),r=Math.floor(r/128);e.push(r)}function Bt(r){let e=[];for(let[t,n]of r){if(typeof n=="number"){n&&(ve(t<<3,e),ve(n,e));continue}let o=typeof n=="string"?Gr.encode(n):n;if(o.length){ve(t<<3|2,e),ve(o.length,e);for(let s of o)e.push(s)}}return new Uint8Array(e)}function Vt(r){let e=new Map,t=0,n=()=>{let o=0,s=1,i;do i=r[t++],o+=(i&127)*s,s*=128;while(i&128&&t<r.length);return o};for(;t<r.length;){let o=n(),s=Math.floor(o/8),i=o&7;if(i===0)e.set(s,n());else if(i===2){let c=n();e.set(s,r.subarray(t,t+c)),t+=c}else if(i===1)t+=8;else if(i===5)t+=4;else throw new A("bad_answer",`Pro Tools sent a reply that is not protobuf (wire type ${i})`)}return e}var Gt=r=>r instanceof Uint8Array?qr.decode(r):"",zr=r=>typeof r=="number"?r:0;function Jr(r,e,t){let n=Bt([[2,r],[3,He[0]],[4,e],[5,He[1]],[6,He[2]]]);return Bt([[1,n],[2,t]])}function Wr(r){let e=Vt(r),t=e.get(1);return{status:t instanceof Uint8Array?zr(Vt(t).get(3)):0,body:Gt(e.get(2)),error:Gt(e.get(3))}}var A=class extends Error{constructor(t,n,o){super(n);this.code=t;this.errors=o}};function Kr(r){let e=null;try{e=JSON.parse(r)}catch{}let t=Array.isArray(e)?e:e&&typeof e=="object"?Array.isArray(e.errors)?e.errors:[e]:[],n=t.find(a=>!a.is_warning)??t[0],o=String(n?.command_error_message||r.trim()||"Pro Tools refused the command"),s=n?.command_error_type,c=s===Ht||s==="PT_NoOpenedSession"||s==="CEType_PT_NoOpenedSession"||s===String(Ht)?"no_session":/session id|not registered|register/i.test(o)?"not_registered":"command_failed";return new A(c,o,t.length?t:void 0)}var ze=class{constructor(e=jr){this.sessionId="";this.version=null;this.queue=Promise.resolve();let t=/^(127\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})$/.exec(e)??/^\[(::1)\]:(\d{1,5})$/.exec(e);if(!t)throw new A("refused",`${e} is not a loopback IP address and port; PTSL is loopback only`);this.host=t[1],this.port=Number(t[2])}async send(e,t,n){let o;try{o=await it(this.host,this.port,Fr,Jr(e,this.sessionId,t),n)}catch(i){throw this.sessionId="",this.version=null,i instanceof st?i.code==="unavailable"?new A("not_running",`Pro Tools is not running (nothing answered on ${this.host}:${this.port})`):i.code==="deadline"?new A("timeout",`Pro Tools did not answer in ${n} ms (a modal dialog or a long command?)`):i.grpcStatus===12?new A("not_ptsl",`the program on ${this.host}:${this.port} is not Pro Tools`):new A("transport",`PTSL transport error: ${i.message}`):i}let s=Wr(o);if(Br.includes(s.status)){if(!s.body.trim())return null;try{return JSON.parse(s.body)}catch{throw new A("bad_answer","Pro Tools sent a body that is not JSON")}}throw Vr.includes(s.status)?Kr(s.error):new A("bad_status",`Pro Tools answered with task status ${s.status}`)}async handshake(){if(!this.sessionId){let e=await this.send(Be.RegisterConnection,JSON.stringify({company_name:Ir,application_name:Dr}),Ut);if(!e?.session_id)throw new A("not_registered","Pro Tools did not give conform.tools a session id");this.sessionId=e.session_id}if(!this.version){let e=await this.send(Be.GetPTSLVersion,"",Ut),t=o=>Number(e?.[o]??0)||0,n=[t("version"),t("version_minor"),t("version_revision")];if(n[0]<re[0]||n[0]===re[0]&&n[1]<re[1])throw this.sessionId="",new A("host_too_old",`Pro Tools ${n[0]}.${n[1]} is too old; conform.tools needs Pro Tools ${re[0]}.${re[1]} or newer`);this.version=n}}call(e,t,n=qe){let o=async()=>{if(e==="RegisterConnection")throw new A("refused","RegisterConnection is sent by the client itself");let i=Be[e];if(i===void 0)throw new A("unknown_command",`${e} is not a PTSL command conform.tools sends`);let c=t==null?"":typeof t=="string"?t:JSON.stringify(t);for(let a=0;;a++){if(await this.handshake(),e==="GetPTSLVersion"){let[l,u,d]=this.version;return{version:l,version_minor:u,version_revision:d}}try{return await this.send(i,c,n)}catch(l){if(l instanceof A&&l.code==="not_registered"&&a===0){this.sessionId="";continue}throw l}}},s=this.queue.then(o,o);return this.queue=s.catch(()=>{}),s}},Ve={23976:24e3/1001,24:24,25:25,2997:3e4/1001,30:30,47952:48e3/1001,48:48,50:50,5994:6e4/1001,60:60,100:100,11988:12e4/1001,120:120},Qr={1:["23976",!1],2:["24",!1],3:["25",!1],4:["2997",!1],5:["2997",!0],6:["30",!1],7:["30",!0],8:["47952",!1],9:["48",!1],10:["50",!1],11:["5994",!1],12:["5994",!0],13:["60",!1],14:["60",!0],15:["100",!1],16:["11988",!1],17:["11988",!0],18:["120",!1],19:["120",!0]};function Yr(r){if(typeof r=="number"||typeof r=="string"&&/^\d+$/.test(r.trim())){let t=Qr[Number(r)];return t?{fps:Ve[t[0]],drop:t[1]}:null}let e=/Fps(\d+)(Drop)?/i.exec(String(r??""));return e&&Ve[e[1]]?{fps:Ve[e[1]],drop:!!e[2]}:null}var Xr=/^-?\d{1,2}[:;.]\d{2}[:;.]\d{2}[:;.,]\d{2,3}(\.\d+)?$/,Zr=/^(?:(\d+):)?(\d+):(\d{2}(?:\.\d+)?)$/;function Ge(r,e){let t=String(r??"").trim();if(Xr.test(t))return ut(t.replace(/\.\d+$/,""),e.rate.fps,e.rate.drop);if(/^-?\d+$/.test(t))return e.start+Math.floor(Number(t)*e.rate.fps/e.sampleRate+1e-9);let n=Zr.exec(t);return n?e.start+Math.floor((Number(n[1]??0)*3600+Number(n[2])*60+Number(n[3]))*e.rate.fps+1e-9):null}var xe=["Blue","Cyan","Green","Yellow","Red","Pink","Purple","Fuchsia","Rose","Lavender","Sky","Mint","Lemon","Sand","Cocoa","Cream"],qt=r=>{let e=Number(r);return e>=1?xe[(e-1)%xe.length]:xe[0]},en=r=>Math.max(0,xe.findIndex(e=>e.toLowerCase()===String(r??"").toLowerCase()))+1,zt=/(?:^| )\[ct:((?:[^[\]\\]|\\.)*)\]$/s;function tn(r,e){return!e&&!zt.test(r)?r:`${r}${r?" ":""}[ct:${e.replace(/[\\[\]]/g,t=>`\\${t}`)}]`}function rn(r){let e=zt.exec(r);return e?{note:r.slice(0,e.index),data:e[1].replace(/\\(.)/gs,"$1")}:{note:r,data:""}}function nn(r){return!r.includes(":")||r.includes("/")||r.includes("\\")?r:`/Volumes/${r.split(":").filter(Boolean).join("/")}`}var ke=class{constructor(e=new ze){this.ptsl=e;this.host="protools"}async sessionName(e=qe){try{return String((await this.ptsl.call("GetSessionName",null,e)).session_name??"")}catch(t){if(t instanceof A&&t.code==="no_session")return"";throw t}}async sessionPath(e=qe){let t=await this.ptsl.call("GetSessionPath",null,e),n=typeof t.session_path=="string"?t.session_path:t.session_path?.path??"";return n?nn(n):""}async current(e=2e3){try{let t=await this.sessionName(e);return t?{project:t,project_path:await this.sessionPath(e).catch(()=>"")}:null}catch{return null}}async facts(){let e=await this.sessionName();if(!e)throw new A("no_session","protools: no session is open");let t=(await this.ptsl.call("GetSessionTimeCodeRate")).current_setting,n=Yr(t);if(!n)throw new A("bad_answer",`protools: a timecode rate conform.tools does not know (${t})`);let o=/(\d{4,6})/.exec(String((await this.ptsl.call("GetSessionSampleRate")).sample_rate??""));if(!o)throw new A("bad_answer","protools: Pro Tools reported a sample rate conform.tools does not know");let s=(await this.ptsl.call("GetSessionStartTime")).session_start_time,i={name:e,rate:n,sampleRate:Number(o[1]),start:0},c=Ge(s,i);if(c==null)throw new A("bad_answer",`protools: a session start conform.tools cannot read (${s})`);return{...i,start:c}}async support(){let e={ok:!1,reason:"Pro Tools holds one session at a time, and importing a timeline changes it; write a .ptx or AAF with timeline_write and open that in Pro Tools"},t={ok:!1,reason:"bouncing from Pro Tools (ExportMix) is not wired"},n;try{n=await this.sessionName(3e3)?{ok:!0}:{ok:!1,reason:"Pro Tools is running with no session open"}}catch(o){n={ok:!1,reason:o instanceof Error?o.message:String(o),setup:Hr}}return{export:n,open:e,render:t,markers:n}}async export(e){let t=await this.sessionName();if(!t)throw new A("no_session","protools: no session is open");if(e.timeline&&e.timeline!==t)throw new A("not_found",`protools: the open session is "${t}"; Pro Tools has one timeline per session`);let n=await this.sessionPath();if(!n||!await le(n))throw new A("no_file",`protools: session "${t}" has no saved .ptx on disk${n?` (${n})`:""}; save it in Pro Tools first`);let o=e.out_path??I(await q("conform-protools-"),at(n));return await Y(fe(o)),await rt(n,o),{path:o,format:"ptx",project:t,timeline:t}}open(){return Promise.reject(new A("unsupported","protools: open is not supported: Pro Tools holds one session, and importing a timeline into it changes it"))}renderStart(){return Promise.reject(new A("unsupported","protools: rendering (a bounce) is not wired"))}renderStatus(){return this.renderStart()}renderCancel(){return this.renderStart()}async project(){let e=await this.facts(),t=await this.sessionPath().catch(()=>""),n=[],o=[];try{let i=await this.ptsl.call("GetTrackList",{page_limit:1e3,track_filter_list:[{filter:"All",is_inverted:!1}]}),c={video:0,audio:0};for(let a of i.track_list??[]){let l=/video/i.test(String(a.type))?"video":"audio",u=a.track_attributes??{},d=u.is_inactive===!0||/^(true|.*_?(set|on|inactive))$/i.test(String(u.is_inactive??""));n.push({kind:l,index:++c[l],name:String(a.name??""),enabled:!d})}}catch(i){o.push(`tracks not read: ${i instanceof Error?i.message:String(i)}`)}let s=(await this.locations(e).catch(()=>({locs:[]}))).locs.length;return{project:e.name,timeline:e.name,timelines:[e.name],session_path:t,fps:e.rate.fps,drop_frame:e.rate.drop,sample_rate:e.sampleRate,start_tc:Ee(e.start,e.rate.fps,e.rate.drop),ptsl_version:this.ptsl.version?.join("."),markers:s,notes:o,tracks:n,jobs:[],found:{},pool:{path:"",clips:0,folders:[]}}}async locations(e){let t=[];for(let o=0;;){let s=await this.ptsl.call("GetMemoryLocations",{pagination_request:{limit:1e3,offset:o}}),i=(s.memory_locations??[]).filter(c=>c&&typeof c=="object");if(t.push(...i),o+=i.length,!i.length||o>=Number((s.pagination_response??s.stats)?.total??0))break}let n=[];for(let o of t){let s=o.time_properties,i=typeof s=="number"||/^\d+$/.test(String(s))?{1:"Marker",2:"Selection"}[Number(s)]:String(s??"").split("_").pop();if(i!=="Marker"&&i!=="Selection")continue;let c=Ge(o.start_time,e);if(c==null)continue;let a=i==="Selection"?Ge(o.end_time,e):null,{note:l,data:u}=rn(String(o.comments??""));n.push({number:Number(o.number)||0,frame:c-e.start,duration:a==null?1:Math.max(1,a-c),name:String(o.name??""),note:l,data:u,color:qt(o.color_index),raw:o})}return n.sort((o,s)=>o.frame-s.frame||o.number-s.number),{locs:n.filter((o,s)=>s===0||n[s-1].frame!==o.frame),numbers:t.map(o=>Number(o.number)||0)}}async writeFormat(){let e=await this.ptsl.call("GetMainCounterFormat"),t=e.current_setting??e.current_type,n=typeof t=="number"||/^\d+$/.test(String(t))?{3:"TimeCode",5:"Samples"}[Number(t)]:String(t??"").split("_").pop();if(n==="TimeCode")return"timecode";if(n==="Samples")return"samples";throw new A("counter_format","protools: set Pro Tools' main counter to Timecode or Samples to edit markers from conform.tools")}async apply(e){let t=await this.facts();if(e.timeline&&e.timeline!==t.name)throw new A("not_found",`protools: the open session is "${t.name}"`);let{locs:n,numbers:o}=await this.locations(t),s=new Map(n.map(p=>[p.frame,p])),i=null,c=p=>i==="samples"?String(Math.round(p*t.sampleRate/t.rate.fps)):Ee(t.start+p,t.rate.fps,t.rate.drop),a=async(p,m)=>{let g=Math.max(1,Math.round(p.duration??1)),S=m?.number??Math.max(0,...o)+1,_=m?.raw??{},v={number:S,name:p.name??"",start_time:c(p.frame),end_time:c(p.frame+(g>1?g:0)),time_properties:g>1?"TP_Selection":"TP_Marker",reference:_.reference||"MLR_Absolute",general_properties:_.general_properties||{zoom_settings:!1,pre_post_roll_times:!1,track_visibility:!1,track_heights:!1,group_enables:!1,window_configuration:!1},comments:tn(p.note??"",p.data??""),color_index:en(p.color),location:_.location||"MLC_MainRuler",..._.track_name?{track_name:_.track_name}:{}};await this.ptsl.call("CreateMemoryLocation",v),o.push(S),s.set(p.frame,{number:S,frame:p.frame,duration:g,name:p.name??"",note:p.note??"",data:p.data??"",color:qt(v.color_index),raw:v})},l=async p=>{await this.ptsl.call("ClearMemoryLocation",{location_list:[p.number]}),s.delete(p.frame),o.splice(o.indexOf(p.number),1)},u=p=>({op:"marker_add",frame:p.frame,color:p.color,name:p.name,note:p.note,duration:p.duration,...p.data?{data:p.data}:{}}),d=[],f=[];for(let p of e.ops){let m=Number(p.frame);try{if(!p.op.startsWith("marker_")||p.item){d.push({op:p.op,ok:!1,detail:`protools: '${p.op}' is not reachable over PTSL (timeline markers only)`});continue}if(!Number.isInteger(m)){d.push({op:p.op,ok:!1,detail:"frame must be a whole number"});continue}i??=await this.writeFormat();let g=s.get(m);if(p.op==="marker_add")g&&await l(g),await a({frame:m,color:p.color,name:p.name,note:p.note,duration:Number(p.duration??1),data:p.data||Ur}),d.push({op:p.op,ok:!0}),f.unshift({op:"marker_delete",frame:m},...g?[u(g)]:[]);else if(p.op==="marker_update"){if(!g){d.push({op:p.op,ok:!1,detail:`no marker at frame ${m}`});continue}let S=p.to_frame!==void 0?Number(p.to_frame):m;if(!Number.isInteger(S)){d.push({op:p.op,ok:!1,detail:"to_frame must be a whole number"});continue}if(S!==m&&s.has(S)){d.push({op:p.op,ok:!1,detail:`frame ${S} already has a marker`});continue}await l(g);let _=(v,R)=>p[v]!==void 0?p[v]:R;await a({frame:S,color:_("color",g.color),name:_("name",g.name),note:_("note",g.note),duration:Number(_("duration",g.duration)),data:_("data",g.data)},g),d.push({op:p.op,ok:!0}),f.unshift({op:"marker_update",frame:S,color:g.color,name:g.name,note:g.note,duration:g.duration,data:g.data,...S!==m?{to_frame:m}:{}})}else if(p.op==="marker_delete"){if(!g){d.push({op:p.op,ok:!1,detail:`no marker at frame ${m}`});continue}await l(g),d.push({op:p.op,ok:!0}),f.unshift(u(g))}else d.push({op:p.op,ok:!1,detail:`protools: unknown marker op '${p.op}'`})}catch(g){d.push({op:p.op,ok:!1,detail:g instanceof Error?g.message:String(g)})}}let h=d.filter(p=>p.ok).length;return{project:t.name,timeline:t.name,results:d,undo:f,applied:h,failed:d.length-h}}};var on="Install the conform.tools panel in Media Composer (mcp/hosts/avid/panel: package it, copy the .avpi into PanelSDKPlugins; an unsigned panel needs Avid's Feature Toggle Files), then open Tools > CONFORM.TOOLS. Its page loads from this engine's host bridge (port 48127) and connects by itself.",sn="Install the conform.tools hook (host_setup host=flame action=install_panel), then in Flame: Flame menu > Python > Rescan Python Hooks (or restart Flame), then Flame menu > CONFORM.TOOLS > Connect to CONFORM.TOOLS (or Connect Automatically).",Jt={resolve:new _e,premiere:new dt,avid:new Oe({host:"avid",label:"Media Composer",setup:on}),flame:new Oe({host:"flame",label:"Flame",setup:sn,items:!0}),baselight:new Se,protools:new ke};function Dn(r,e){Jt[r]=e}function Un(r){return Jt[r]??ft(r,"not wired yet")}export{bt as a,fn as b,vr as c,Rn as d,ke as e,an as f,on as g,sn as h,Dn as i,Un as j};
|
|
9
|
+
`).pop()??"";try{return JSON.parse(a)}catch{return{ok:!1,why:"bridge",detail:c.code==="ENOENT"||/Microsoft Store/.test(c.stderr)?`${o} is not installed (Resolve's scripting needs Python 3: python.org)`:Nt(c.stderr)||(typeof c.code=="string"?`the Resolve bridge could not start: ${c.code}`:`no answer from Resolve within ${Math.round(t/1e3)} s`)}}},kr=1500,Tt=Promise.resolve(),Pt=0;function Rr(r){let e=Tt.catch(()=>{}).then(async()=>{let t=Pt+kr-Date.now();t>0&&await new Promise(n=>setTimeout(n,t));try{return await r()}finally{Pt=Date.now()}});return Tt=e,e}var z=class extends Error{constructor(t,n){super(n);this.why=t}},Ar={module:"Install DaVinci Resolve (its scripting module ships with it).",no_connection:"Start Resolve and set Preferences > System > General > External scripting using: Local (Resolve Studio).",no_project:"Open a project in Resolve."},_e=class{constructor(e=vr){this.runner=e;this.host="resolve";this.restore=new Map;this.startNotes=new Map}async call(e,t={},n=6e4){let o=await this.runner(e,t,n);if(o.ok)return o;throw o.why==="resolve_error"&&/NoneType' object is not callable/.test(String(o.detail))&&!(await this.runner("version",{},1e4)).ok?new z("host_quit",`resolve: Resolve stopped responding during ${e} (it may have quit; see its log, ResolveDebug.txt). Restart Resolve and try again.`):new z(o.why??"unknown",`resolve: ${o.detail||o.why}`)}async support(){let e=await this.runner("version",{},15e3),t=e.ok?e.product==="DaVinci Resolve Studio"?{ok:!0}:{ok:!1,reason:`${e.product} has no external scripting (Resolve Studio has)`}:{ok:!1,reason:e.detail??String(e.why),setup:Ar[e.why??""]};return{export:t,open:t,render:t,markers:t}}async current(){return await this.call("current")}async project(e){return await this.call("project",e,e.export_dir||e.grades?9e5:12e4)}async clipLut(e){return await this.call("clip_lut",e,6e4)}async items(e){return e.selected?await Rr(()=>this.call("items",e,15e3)):await this.call("items",e,e.follow?15e3:12e4)}async apply(e){let t=e.ops.filter(o=>o.op==="edit_keys");if(t.length){let o=e.ops.filter(a=>a.op!=="edit_keys"),s=o.length?await this.apply({...e,ops:o}):{project:"",timeline:e.timeline??"",results:[],undo:[],applied:0,failed:0},i=await this.alignedCopy(e,t),c=i.results.filter(a=>a.ok).length;return{...s,project:s.project||i.project,timeline:s.timeline||i.timeline,results:[...s.results,...i.results],applied:s.applied+c,failed:s.failed+i.results.length-c}}let n=e.ops.filter(o=>(o.op==="grade_sizing"&&(o.target==="input"||o.target==="node")&&!o.reset||o.op==="node_structure"||o.op==="copy_nodes")&&o.item&&"track"in o.item);for(let o of n){let s=o.node_structure??o.structure_path;if(!s)continue;let i=/<Body>([0-9a-fA-F]+)<\/Body>/.exec(new TextDecoder().decode(await ue(s)))?.[1];if(!i)throw new z("usage",`${s}: not a Resolve grade still (.drx with a <Body>)`);o.structure=ye(i),o.structure_name=s}if(n.length){let{grades:o,t0:s}=await this.grades(e.timeline,e.into?{into:e.into,scratch_project:e.scratch_project}:{}),i=c=>{let a=c.item;return o.get(`${a.track}:${a.start+s}`)};for(let c of n){let a=i(c);if(a&&(c.bodies={local:a.local,remote:a.remote}),c.op==="copy_nodes"){let l=c.from;c.from_body=o.get(`${l.track}:${l.start+s}`)?.active}}}return await this.call("apply",e,6e4+e.ops.length*200)}async alignedCopy(e,t){let n=e.into?{into:e.into,scratch_project:e.scratch_project}:{},o=await q("ct-aligned-"),s=i=>({project:"",timeline:e.timeline??"",results:t.map(()=>({op:"edit_keys",ok:!1,refused:["aligned copy"],detail:`refused: ${i}; nothing changed`}))});try{let i=I(o,"export.drt"),c=await this.call("export",{timeline:e.timeline,out_path:i,...n}),a=String(c.timeline),l=Number(c.start_frame??0),{session:u}=await pt(i,"drt"),d=u.timelines[0],f=(d.fps_num??24)/(d.fps_den??1),h=d.tracks.filter(w=>String(w.kind).toLowerCase()==="video"),p=w=>Math.round(w.value*f/w.rate),m=[],g=[];for(let w of t){let T=h[w.item.track-1]?.items.find(P=>{let E=P.timeline_range?.start;return E&&[w.item.start,w.item.start+l].includes(p(E))});T?(At(T,w.keys,f),m.push(w)):g.push(`V${w.item.track}@${w.item.start}`)}let S=await lt("resolve-drt",u),_=typeof S.body=="string"?new TextEncoder().encode(S.body):S.body,v=Rt(await ue(i),_,m,l);if(!v.keyed.length)return s(`no clip could be keyed (${[...g,...v.missing].join(", ")})`);let R=I(o,`${a.replace(/[^\w.-]+/g,"_").slice(0,100)}_ALIGNED.drt`);await tt(R,v.drt);let k=await this.call("open",{path:R,name:`${a} ALIGNED`,link_existing:!0,same_as:a,...n}),b=new Map([...g.map(w=>[w,"not found in the timeline's export"]),...v.missing.map(w=>[w.split(" ")[0],w])]);return{project:String(k.project??""),timeline:String(k.timeline??""),results:t.map(w=>{let T=`V${w.item.track}@${w.item.start}`;return b.has(T)?{op:"edit_keys",ok:!1,refused:["not keyed"],detail:`refused: ${b.get(T)}; nothing changed`}:{op:"edit_keys",ok:!0,detail:`${w.keys.length} Edit-page keyframes on "${k.timeline}" (a copy of "${a}" with every grade and setting; "${a}" itself unchanged)`}})}}catch(i){return s(i instanceof Error?i.message:String(i))}finally{await me(o).catch(()=>{})}}async grades(e,t){let n=await q("ct-grades-");try{let o=I(n,"grades.drt"),s=await this.call("export",{timeline:e,out_path:o,...t});return{grades:await ue(o).then(bt).catch(()=>new Map),t0:Number(s.start_frame??0)}}finally{await me(n).catch(()=>{})}}async presets(e){return await this.call("presets",e,12e4)}async presetAuthor(e){return await this.call("preset_author",e,6e4)}async export(e){if(!e.out_path)throw new z("usage","resolve: export needs out_path");let t=await this.call("export",{timeline:e.timeline,out_path:e.out_path,...e.clip_id?{clip_id:e.clip_id}:{}});return{path:String(t.path),format:"drt",project:String(t.project),timeline:String(t.timeline)}}async open(e){let t=await this.call("open",{path:e.path,into:e.into??"current",name:e.name,media_dir:e.media_dirs?.[0],stay:e.stay??!1,folder:e.folder,create_folder:e.create_folder??!1,link_existing:e.link_existing??!1,...e.settings_from?{settings_from:e.settings_from}:{}},3e5),n=[...t.notes??[]];return(e.media_dirs?.length??0)>1&&n.push(`Resolve searches one media folder per import; used ${e.media_dirs[0]}`),{project:String(t.project),timeline:String(t.timeline),notes:n,restored:!!t.restored,...t.folder?{folder:String(t.folder)}:{},...t.settings?{settings:String(t.settings)}:{}}}async renderStart(e){let t=await this.call("render_start",{...e}),n=String(t.job_id);if(t.queued)return{job_id:n,state:"queued",percent:0,notes:["left in Resolve's render queue: start it on the Deliver page"]};this.restore.set(n,t.restore);let o=t.rejected_settings??[];return o.length&&this.startNotes.set(n,[`Resolve refused render setting(s) ${o.join(", ")} for this format; the rest were applied`]),{job_id:n,state:"queued",percent:0}}async renderStatus(e){let t=await this.call("render_status",{job_id:e},15e3),n={job_id:e,state:t.state,percent:Number(t.percent??0)};if(t.error&&(n.error=String(t.error)),n.state==="complete"||n.state==="failed"){let o=await this.call("render_finish",{job_id:e,restore:this.restore.get(e)});this.restore.delete(e),o.output&&(n.outputs=[String(o.output)]);let s=[...this.startNotes.get(e)??[],...o.tracks?[Et(o)]:[]];this.startNotes.delete(e),s.length&&(n.notes=s)}return n}async renderCancel(e){let t=await this.call("render_cancel",{job_id:e,restore:this.restore.get(e)});return this.restore.delete(e),{job_id:e,state:"cancelled",percent:0,...t.output?{outputs:[String(t.output)]}:{},...t.tracks?{notes:[Et(t)]}:{}}}},Et=r=>{let e=r.tracks.map(t=>`V${t}`).join(", ");return r.tracks_restored?`video track(s) ${e} switched back on`:`could NOT switch video track(s) ${e} back on: re-enable them on the Edit page`};async function Rn(r,e){let t=[];for await(let n of nt(r))n.isFile&&n.name.startsWith(e)&&t.push(I(r,n.name));return t.sort()}var Tr="ws://localhost:1985",Ct="localhost",Lt="conform_tools",jt="conform.tools ",Ft="Video_Full",Pr=r=>!!r&&typeof r=="object"&&"_handle"in r&&"_id"in r,J=class extends Error{constructor(t,n){super(n);this.code=t}},De=class r{constructor(e){this.ws=e;this.next=1;this.waiting=new Map;e.onMessage(t=>{let n;try{n=JSON.parse(t)}catch{return}let o=typeof n.id=="number"?this.waiting.get(n.id):void 0;if(!o)return;if(this.waiting.delete(n.id),n.error===void 0||n.error===null)return o.ok(n.result??null);let s=n.error;o.no(typeof s=="string"?new J(n.code??-1,s):new J(s.code??n.code??-1,s.message??JSON.stringify(s)))}),e.onClose(()=>{for(let t of this.waiting.values())t.no(new J("closed","Baselight closed the FLAPI connection"));this.waiting.clear()})}static async connect(e,t=3e3){let n=new r(await mt(e,{maxBytes:67108864,timeoutMs:t})),o=await Er();return o&&await n.call("authenticate",{username:F("USER")??F("USERNAME")??"conform",token:o},null,t).catch(()=>null),n}call(e,t={},n=null,o=12e4){let s=this.next++;return new Promise((i,c)=>{let a=setTimeout(()=>{this.waiting.delete(s),c(new J("timeout",`${e}: no answer from Baselight within ${Math.round(o/1e3)} s`))},o);this.waiting.set(s,{ok:l=>{clearTimeout(a),i(l)},no:l=>{clearTimeout(a),c(l)}}),this.ws.send(JSON.stringify({jsonrpc:"2.0",method:e,target:n?n._id:null,params:t,id:s}))})}async forget(...e){for(let t of e)Pr(t)&&await this.call("forget",{},t).catch(()=>null)}close(){this.ws.close()}};async function Er(){let r=F("FLAPI_TOKEN");if(r)return r.trim();let e=H()==="darwin"?I(Pe(),"Library","Preferences","FilmLight","flapi-token"):I(Pe(),".filmlight","flapi-token");try{return(await et(e)).trim()||null}catch{return null}}var It=(...r)=>Object.fromEntries(r.map(e=>[e,1])),Or={[-30]:30,[-31]:30,[-32]:30,[-34]:25,[-35]:24};function be(r){if(!r||typeof r!="object")return null;let e=typeof r.fps=="string"?{TC_30DF:-30,TC_60HDF:-31}[r.fps]??Number(r.fps):r.fps,t=e>0?e:Or[e]??30,n=((r.h*60+r.m)*60+r.s)*t+r.f;if(e!==-30&&e!==-31)return n;let o=r.h*60+r.m;return n-2*(o-Math.floor(o/10))}function Mr(r,e,t){let n=Math.round(e),o=r;if(t&&n===30){let l=Math.floor(o/17982),u=o%17982;o+=18*l+(u>2?2*Math.floor((u-2)/1798):0)}let s=o%n,i=Math.floor(o/n)%60,c=Math.floor(o/n/60)%60;return{_type:"timecode",h:Math.floor(o/n/3600)%24,m:c,s:i,f:s,phase:0,fps:t&&n===30?-30:n,wrap:24}}function Dt(r){let e=Math.round(r);return Math.abs(r-e)<.005?e:Math.abs(r-e*1e3/1001)<.01?e*1e3/1001:r}var j=class extends Error{constructor(t,n){super(`baselight: ${n}`);this.why=t}},$r={darwin:"/Applications/Baselight",linux:"/usr/fl/baselight"},Se=class{constructor(e){this.url=e;this.host="baselight";this.jobs=new Map}async conn(e=3e3){let t=this.url??F("CONFORM_BASELIGHT_URL")??Tr;try{return await De.connect(t,e)}catch(n){let o=await ce($r[H()]??"/nonexistent");throw new j(o?"not_running":"not_installed",o?`Baselight is not answering FLAPI at ${t} (${n.message})`:"Baselight is not installed on this machine")}}async with(e){let t=await this.conn();try{return await e(t)}catch(n){throw n instanceof j?n:new j("flapi",n.message)}finally{t.close()}}async support(){let e;try{let t=await this.with(n=>n.call("Application.get_application_info"));e=/baselight|daylight/i.test(t.Product??"")?{ok:!0}:{ok:!1,reason:`the FLAPI server is ${t.Product??"unknown"}, not the Baselight app (port 1984 is the headless flapid)`,setup:"Point CONFORM_BASELIGHT_URL at the running Baselight (ws://localhost:1985)."}}catch(t){let n=t instanceof j?t.why:"flapi";e={ok:!1,reason:t.message.replace(/^baselight: /,""),setup:n==="not_installed"?"Install FilmLight Baselight (FLAPI ships with it; nothing else to install).":"Start Baselight. Its API server listens on port 1985 by default (Preferences > Advanced > API Server)."}}return{export:e,open:e,render:e,markers:{ok:!1,reason:"not wired for Baselight yet (FLAPI has marks: Scene.add_mark)"}}}async scenePath(e,t,n){if(t?.includes(":")){let i=await e.call("Scene.parse_path",{str:t});return{host:i.Host,job:i.Job,scene:i.Scene}}let o=await this.current(e),s=n??o?.job;if(t&&s)return{host:o?.host??Ct,job:s,scene:t};if(!o)throw new j("no_scene",t?`no job to find scene "${t}" in: pass project (the job) or "host:job:scene"`:'no scene is open in Baselight: open one, or name it ("host:job:scene")');return o}async current(e){let t=await e.call("Application.get").catch(()=>null);if(!t)return null;try{let n=await e.call("Application.get_current_scene",{},t);if(!n)return null;try{let o=await e.call("Scene.get_scene_pathname",{},n),[s,i,...c]=o.split(":");return c.length?{host:s,job:i,scene:c.join(":")}:null}finally{await e.forget(n)}}finally{await e.forget(t)}}async export(e){if(!e.out_path)throw new j("usage","export needs out_path");return await this.with(async t=>{let n=await this.scenePath(t,e.timeline),o=await t.call("Scene.open_scene",{scenepath:{Host:n.host,Job:n.job,Scene:n.scene},flags:It("OPENFLAG_READ_ONLY")});try{let s=await Lr(t,o,n.scene);await Y(fe(e.out_path)),await pe(e.out_path,JSON.stringify(s,null,1))}finally{await t.call("Scene.close_scene",{},o).catch(()=>null),await t.forget(o)}return{path:e.out_path,format:"otio",project:n.job,timeline:n.scene}})}async open(e){let{readTimeline:t}=await import("./timeline-EXRRCS47.js"),{session:n}=await t(e.path),o=n.timelines.find(u=>u.kind!=="compound")??n.timelines[0];if(!o)throw new j("usage",`no timeline in ${e.path}`);let s=new Map((n.media_references??[]).map(u=>[u.id,u])),i=o.fps_num/o.fps_den,c=o.tracks.filter(u=>u.kind==="Video").sort((u,d)=>u.track_index-d.track_index),a=[];c.length>1&&a.push(`placed V1 only: Baselight builds layers above a shot, which FLAPI cannot place in time; ${c.slice(1).reduce((u,d)=>u+d.items.filter(f=>f.kind==="clip").length,0)} clip(s) on V2+ not placed`);let l=(c[0]?.items??[]).filter(u=>u.kind==="clip"||u.kind==="gap").sort((u,d)=>u.timeline_range.start.value-d.timeline_range.start.value);return await this.with(async u=>{let d=e.into==="scratch"?null:await this.current(u);e.into!=="scratch"&&!d&&a.push(`no scene open in Baselight, so it went into our job ${Lt}`);let f=d?.job??Lt,h=d?.host??Ct;await u.call("JobManager.job_exists",{host:h,jobname:f})||await u.call("JobManager.create_job",{host:h,jobname:f});let p=(e.name??o.name??"conform.tools").replace(/[:/\\]+/g,"_"),m=p;for(let w=2;await u.call("JobManager.scene_exists",{host:h,jobname:f,scenename:m});w++)m=`${p} ${w}`;let g=await u.call("FormatSet.factory_formats"),S=o.resolution_w&&o.resolution_h?await u.call("FormatSet.get_basic_format_name",{width:o.resolution_w,height:o.resolution_h},g):null;await u.forget(g);let _=await u.call("Scene.new_scene",{scenepath:{Host:h,Job:f,Scene:m},options:{format:S,colourspace:Ft,frame_rate:i}},null,3e5),v=0,R=0,k=0,b=0;try{await u.call("Scene.start_delta",{name:"conform.tools open"},_);try{let w=0;for(let P of l){let E=P.timeline_range.start.value,N=P.timeline_range.duration.value;if(E>w&&(await Fe(u,_,E-w),k++),w=Math.max(w,E+N),P.kind==="gap"){await Fe(u,_,N),k++;continue}let M=(P.media_reference_id?s.get(P.media_reference_id):void 0)?.target_url?.replace(/^file:\/\//,""),y=P.source_range,x=M&&y?await Cr(u,M,Math.round(y.start.value),Math.round(y.start.value)+N-1):null;if(!x){await Fe(u,_,N),R++;continue}y&&Math.abs(y.duration.value-N)>.5&&b++;let L=await u.call("Scene.insert_sequence",{sequence:x,where:"INSERT_END",relativeTo:null,colourSpace:null,format:null,frameRate:i},_);await u.forget(x,L),v++}let T=await u.call("Scene.get_scene_settings",{},_);await u.call("SceneSettings.set",{values:{StartTimecode:Mr(o.start_frame??0,i,!!o.is_drop_frame)}},T),await u.forget(T),await u.call("Scene.end_delta",{},_)}catch(w){throw await u.call("Scene.cancel_delta",{},_).catch(()=>null),w}await u.call("Scene.save_scene",{},_,3e5)}catch(w){throw await u.call("Scene.close_scene",{},_).catch(()=>null),await u.forget(_),await u.call("JobManager.delete_scene",{host:h,jobname:f,scenename:m}).catch(()=>null),w}return await u.call("Scene.close_scene",{},_),await u.forget(_),a.unshift(`new scene ${h}:${f}:${m}: ${v} shot(s)${k?`, ${k} gap(s) as black`:""}`),R&&a.push(`${R} clip(s) had no media on disk at their path: placed as black of the same length (relink in Baselight's Conform view)`),b&&a.push(`${b} retimed clip(s) placed at normal speed: FLAPI has no retime setter`),m!==p&&a.push(`"${p}" was taken in ${f}: named "${m}"`),e.media_dirs?.length&&a.push("media_dirs not used: Baselight places each clip from its own path"),e.stay&&a.push("stay: FLAPI cannot switch the scene the app shows; open it from the Scenes browser"),{project:f,timeline:m,notes:a,restored:!0}})}async renderStart(e){if(e.disable_tracks?.length)throw new j("usage","disable_tracks: a Baselight render takes every layer or one (RenderTrack); leave the tracks out in the scene");if(e.audio_tracks?.length)throw new j("usage","audio_tracks is a DaVinci Resolve option");return await this.with(async t=>{let n=await this.scenePath(t,e.timeline,e.project),o=await t.call("Scene.open_scene",{scenepath:{Host:n.host,Job:n.job,Scene:n.scene},flags:It("OPENFLAG_READ_ONLY")}),s=null,i=null;try{s=await t.call("RenderSetup.create_from_scene",{scene:o});let c=await t.call("RenderSetup.get_num_deliverables",{},s),a=0;if(e.preset){let p=await t.call("RenderSetup.get_deliverable_names",{},s);if(a=p.indexOf(e.preset),a<0)throw new j("usage",`no deliverable "${e.preset}" in ${n.scene} (it has: ${p.join(", ")||"none"})`)}let l=await t.call("RenderSetup.get_deliverable",{index:a},s),u=e.name??n.scene.replace(/[^\w.-]+/g,"_");Object.assign(l,{Disabled:0,Container:"",OutputDirectory:e.target_dir,FileNamePrefix:u}),e.preset||Object.assign(l,{Name:"conform.tools",IsMovie:1,FileType:"lqtmov",MovieCodec:"apch",ImageOptions:{},FileNameExtension:".mov",RenderColourSpace:Ft,HandleEmptyFrames:"GMREB_BLACK",HandleIncompleteStacks:"GMREB_BLACK",HandleError:"BLACK",EmbedTimecode:1}),e.audio||(l.AudioCodec=""),await Y(e.target_dir),await t.call("RenderSetup.set_deliverable",{index:a,deliverable:l},s);for(let p=0;p<c;p++)p!==a&&await t.call("RenderSetup.set_deliverable_enabled",{index:p,enabled:0},s);if(e.range){let p=await t.call("Scene.get_scene_settings",{},o),m=be(await t.call("SceneSettings.get_single",{key:"StartTimecode"},p))??0;await t.forget(p);let g=e.range.in>=m?m:0;await t.call("RenderSetup.set_frames",{frames:[{Start:e.range.in-g,End:e.range.out-g}]},s)}else await t.call("RenderSetup.select_all",{},s);let d=await t.call("RenderSetup.get_output_filename_for_deliverable",{index:a},s);i=await t.call("QueueManager.create_local");let f=await t.call("RenderSetup.submit_to_queue",{queue:i,opname:`${jt}${u}`},s),h=String(f.ID);return this.jobs.set(h,{op:f.ID,out:d,notes:f.Warning?[`Baselight: ${f.Warning}`]:[]}),{job_id:h,state:"queued",percent:0}}finally{await t.forget(s,i),await t.call("Scene.close_scene",{},o).catch(()=>null),await t.forget(o)}})}async ours(e,t,n){let o=Number(n),s=await e.call("QueueManager.get_operation",{id:o},t).catch(()=>null),i=String(s?.Description??s?.Name??"");if(!this.jobs.has(n)&&!i.startsWith(jt))throw new j("not_ours",`queue operation ${n} is not a conform.tools render: left alone`);return o}async renderStatus(e){return await this.with(async t=>{let n=await t.call("QueueManager.create_local");try{let o=await this.ours(t,n,e),s=await t.call("QueueManager.get_operation_status",{id:o},n),i=Nr(s.Status),c=Number(s.Progress??0),a={job_id:e,state:i,percent:i==="complete"?100:Math.round(c<=1?c*100:c)};if(i==="failed"||i==="complete"&&s.Errors){let u=(await t.call("QueueManager.get_operation_log",{id:o},n).catch(()=>[])).filter(d=>/fail|error|warn/i.test(d.Type)).slice(-6).map(d=>`${d.Message}${d.Detail?`: ${d.Detail}`:""}`);a.error=[s.ProgressText,...u].filter(Boolean).join("; ")||"Baselight reported a failed render",i==="complete"&&(a.state="failed")}if(a.state==="complete"||a.state==="failed"||a.state==="cancelled"){let l=this.jobs.get(e);a.state==="complete"&&l&&(a.outputs=[l.out]),l?.notes.length&&(a.notes=l.notes),await t.call("QueueManager.delete_operation",{id:o},n).catch(()=>null),this.jobs.delete(e)}return a}finally{await t.forget(n)}})}async renderCancel(e){return await this.with(async t=>{let n=await t.call("QueueManager.create_local");try{let o=await this.ours(t,n,e);return await t.call("QueueManager.delete_operation",{id:o},n),this.jobs.delete(e),{job_id:e,state:"cancelled",percent:0}}finally{await t.forget(n)}})}};function Nr(r){let e=String(r).replace(/^OPSTATUS_/i,"").toLowerCase();return e==="done"?"complete":e==="active"?"rendering":e==="stopped"?"cancelled":e==="failed"||e==="crashed"||e==="toonew"?"failed":"queued"}async function Fe(r,e,t){let n=await r.call("Scene.insert_blank",{red:0,green:0,blue:0,duration:t,where:"INSERT_END",relativeTo:null,colourSpace:null},e);await r.forget(n)}async function Cr(r,e,t,n){let o=await r.call("SequenceDescriptor.get_for_template",{template:e,start:null,end:null}).catch(()=>[]);if(!o?.length)return null;let s=await r.call("SequenceDescriptor.get_start_handle",{},o[0]);await r.forget(...o);let i=await r.call("SequenceDescriptor.get_for_template",{template:e,start:s+t,end:s+n});return i?.length?(await r.forget(...i.slice(1)),i[0]):null}var Ue=(r,e)=>({OTIO_SCHEMA:"RationalTime.1",rate:e,value:r}),Ie=(r,e,t)=>({OTIO_SCHEMA:"TimeRange.1",start_time:Ue(r,t),duration:Ue(e,t)});async function Lr(r,e,t){let n=Dt(await r.call("Scene.get_working_frame_rate",{},e)),o=await r.call("Scene.get_scene_settings",{},e),s=be(await r.call("SceneSettings.get_single",{key:"StartTimecode"},o))??0;await r.forget(o);let i=await r.call("Scene.get_num_shots",{},e),c=i?await r.call("Scene.get_shot_ids",{firstIndex:0,lastIndex:i-1},e):[],a=[];for(let d of c){let f=Math.round(d.StartFrame),h=Math.round(d.EndFrame),p=await r.call("Scene.get_shot",{shot_id:d.ShotId},e);try{let m=await r.call("Shot.get_sequence_descriptor",{},p).catch(()=>null);if(!m){a.push({start:f,end:h,name:`shot ${d.ShotId}`});continue}try{let g=Dt(await r.call("Shot.get_frame_rate",{},p))||n,S=be(await r.call("Shot.get_src_start_timecode",{},p)),_=await r.call("Shot.get_src_start_frame",{},p),v=await r.call("Shot.get_src_end_frame",{},p),k=await r.call("SequenceDescriptor.is_movie",{},m)?Xe(await r.call("SequenceDescriptor.get_path",{},m),await r.call("SequenceDescriptor.get_name",{},m)):await r.call("SequenceDescriptor.get_full_filename_with_d",{},m),b=await r.call("SequenceDescriptor.get_name",{},m),w=await r.call("SequenceDescriptor.get_tape",{index:0},m).catch(()=>""),T=await r.call("SequenceDescriptor.get_start_frame",{},m),P=await r.call("SequenceDescriptor.get_start_handle",{},m),E=await r.call("SequenceDescriptor.get_end_handle",{},m),C=(be(await r.call("SequenceDescriptor.get_start_timecode",{index:0},m))??0)-(T-P),M=Math.round(v-_),y=h-f,x={OTIO_SCHEMA:"Clip.2",name:b,enabled:!0,source_range:Ie(S??C+(_-P),y,g),media_references:{DEFAULT_MEDIA:{OTIO_SCHEMA:"ExternalReference.1",target_url:k,available_range:Ie(C,E-P+1,g),available_image_bounds:null,name:b,metadata:{}}},active_media_reference_key:"DEFAULT_MEDIA",effects:M&&M!==y?[{OTIO_SCHEMA:"LinearTimeWarp.1",name:"",effect_name:"LinearTimeWarp",time_scalar:M/y,metadata:{}}]:[],markers:[],metadata:w?{baselight:{tape:w}}:{}};a.push({start:f,end:h,name:b,clip:x})}finally{await r.forget(m)}}finally{await r.forget(p)}}let l=[];for(let d of[...a].sort((f,h)=>f.start-h.start)){if(!d.clip)continue;let f=l.find(h=>h[h.length-1].end<=d.start);f?f.push(d):l.push([d])}let u=l.map((d,f)=>{let h=[],p=0;for(let m of d)m.start>p&&h.push({OTIO_SCHEMA:"Gap.1",name:"",enabled:!0,source_range:Ie(0,m.start-p,n),effects:[],markers:[],metadata:{}}),h.push(m.clip),p=m.end;return{OTIO_SCHEMA:"Track.1",name:`V${f+1}`,kind:"Video",enabled:!0,children:h,source_range:null,effects:[],markers:[],metadata:{}}});return{OTIO_SCHEMA:"Timeline.1",name:t,metadata:{baselight:{shots:c.length}},global_start_time:Ue(s,n),tracks:{OTIO_SCHEMA:"Stack.1",name:"tracks",enabled:!0,children:u,source_range:null,effects:[],markers:[],metadata:{}}}}var jr="127.0.0.1:31416",Fr="/ptsl.PTSL/SendGrpcRequest",Ir="CONFORM.TOOLS",Dr="CONFORM.TOOLS Desktop",He=[2025,6,0],re=[2025,6],qe=1e4,Ut=5e3,Ur="ConformTools",Hr="Start Pro Tools 2025.6 or newer with a session open (PTSL, its scripting door, listens on 127.0.0.1:31416).",Be={GetTrackList:3,HostReadyCheck:13,ExportSessionInfoAsText:30,GetSessionSampleRate:35,GetSessionTimeCodeRate:38,GetSessionFeetFramesRate:39,GetSessionName:42,GetSessionPath:43,GetSessionStartTime:44,GetSessionLength:45,GetPTSLVersion:55,GetTransportState:59,ClearMemoryLocation:61,EditMemoryLocation:68,GetMemoryLocations:69,RegisterConnection:70,CreateMemoryLocation:71,SetTimelineSelection:81,GetTimelineSelection:82,GetSessionIDs:97,GetMainCounterFormat:102},Br=[3,6],Vr=[4,7],Ht=106,Gr=new TextEncoder,qr=new TextDecoder;function ve(r,e){for(;r>127;)e.push(r&127|128),r=Math.floor(r/128);e.push(r)}function Bt(r){let e=[];for(let[t,n]of r){if(typeof n=="number"){n&&(ve(t<<3,e),ve(n,e));continue}let o=typeof n=="string"?Gr.encode(n):n;if(o.length){ve(t<<3|2,e),ve(o.length,e);for(let s of o)e.push(s)}}return new Uint8Array(e)}function Vt(r){let e=new Map,t=0,n=()=>{let o=0,s=1,i;do i=r[t++],o+=(i&127)*s,s*=128;while(i&128&&t<r.length);return o};for(;t<r.length;){let o=n(),s=Math.floor(o/8),i=o&7;if(i===0)e.set(s,n());else if(i===2){let c=n();e.set(s,r.subarray(t,t+c)),t+=c}else if(i===1)t+=8;else if(i===5)t+=4;else throw new A("bad_answer",`Pro Tools sent a reply that is not protobuf (wire type ${i})`)}return e}var Gt=r=>r instanceof Uint8Array?qr.decode(r):"",zr=r=>typeof r=="number"?r:0;function Jr(r,e,t){let n=Bt([[2,r],[3,He[0]],[4,e],[5,He[1]],[6,He[2]]]);return Bt([[1,n],[2,t]])}function Wr(r){let e=Vt(r),t=e.get(1);return{status:t instanceof Uint8Array?zr(Vt(t).get(3)):0,body:Gt(e.get(2)),error:Gt(e.get(3))}}var A=class extends Error{constructor(t,n,o){super(n);this.code=t;this.errors=o}};function Kr(r){let e=null;try{e=JSON.parse(r)}catch{}let t=Array.isArray(e)?e:e&&typeof e=="object"?Array.isArray(e.errors)?e.errors:[e]:[],n=t.find(a=>!a.is_warning)??t[0],o=String(n?.command_error_message||r.trim()||"Pro Tools refused the command"),s=n?.command_error_type,c=s===Ht||s==="PT_NoOpenedSession"||s==="CEType_PT_NoOpenedSession"||s===String(Ht)?"no_session":/session id|not registered|register/i.test(o)?"not_registered":"command_failed";return new A(c,o,t.length?t:void 0)}var ze=class{constructor(e=jr){this.sessionId="";this.version=null;this.queue=Promise.resolve();let t=/^(127\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})$/.exec(e)??/^\[(::1)\]:(\d{1,5})$/.exec(e);if(!t)throw new A("refused",`${e} is not a loopback IP address and port; PTSL is loopback only`);this.host=t[1],this.port=Number(t[2])}async send(e,t,n){let o;try{o=await it(this.host,this.port,Fr,Jr(e,this.sessionId,t),n)}catch(i){throw this.sessionId="",this.version=null,i instanceof st?i.code==="unavailable"?new A("not_running",`Pro Tools is not running (nothing answered on ${this.host}:${this.port})`):i.code==="deadline"?new A("timeout",`Pro Tools did not answer in ${n} ms (a modal dialog or a long command?)`):i.grpcStatus===12?new A("not_ptsl",`the program on ${this.host}:${this.port} is not Pro Tools`):new A("transport",`PTSL transport error: ${i.message}`):i}let s=Wr(o);if(Br.includes(s.status)){if(!s.body.trim())return null;try{return JSON.parse(s.body)}catch{throw new A("bad_answer","Pro Tools sent a body that is not JSON")}}throw Vr.includes(s.status)?Kr(s.error):new A("bad_status",`Pro Tools answered with task status ${s.status}`)}async handshake(){if(!this.sessionId){let e=await this.send(Be.RegisterConnection,JSON.stringify({company_name:Ir,application_name:Dr}),Ut);if(!e?.session_id)throw new A("not_registered","Pro Tools did not give conform.tools a session id");this.sessionId=e.session_id}if(!this.version){let e=await this.send(Be.GetPTSLVersion,"",Ut),t=o=>Number(e?.[o]??0)||0,n=[t("version"),t("version_minor"),t("version_revision")];if(n[0]<re[0]||n[0]===re[0]&&n[1]<re[1])throw this.sessionId="",new A("host_too_old",`Pro Tools ${n[0]}.${n[1]} is too old; conform.tools needs Pro Tools ${re[0]}.${re[1]} or newer`);this.version=n}}call(e,t,n=qe){let o=async()=>{if(e==="RegisterConnection")throw new A("refused","RegisterConnection is sent by the client itself");let i=Be[e];if(i===void 0)throw new A("unknown_command",`${e} is not a PTSL command conform.tools sends`);let c=t==null?"":typeof t=="string"?t:JSON.stringify(t);for(let a=0;;a++){if(await this.handshake(),e==="GetPTSLVersion"){let[l,u,d]=this.version;return{version:l,version_minor:u,version_revision:d}}try{return await this.send(i,c,n)}catch(l){if(l instanceof A&&l.code==="not_registered"&&a===0){this.sessionId="";continue}throw l}}},s=this.queue.then(o,o);return this.queue=s.catch(()=>{}),s}},Ve={23976:24e3/1001,24:24,25:25,2997:3e4/1001,30:30,47952:48e3/1001,48:48,50:50,5994:6e4/1001,60:60,100:100,11988:12e4/1001,120:120},Qr={1:["23976",!1],2:["24",!1],3:["25",!1],4:["2997",!1],5:["2997",!0],6:["30",!1],7:["30",!0],8:["47952",!1],9:["48",!1],10:["50",!1],11:["5994",!1],12:["5994",!0],13:["60",!1],14:["60",!0],15:["100",!1],16:["11988",!1],17:["11988",!0],18:["120",!1],19:["120",!0]};function Yr(r){if(typeof r=="number"||typeof r=="string"&&/^\d+$/.test(r.trim())){let t=Qr[Number(r)];return t?{fps:Ve[t[0]],drop:t[1]}:null}let e=/Fps(\d+)(Drop)?/i.exec(String(r??""));return e&&Ve[e[1]]?{fps:Ve[e[1]],drop:!!e[2]}:null}var Xr=/^-?\d{1,2}[:;.]\d{2}[:;.]\d{2}[:;.,]\d{2,3}(\.\d+)?$/,Zr=/^(?:(\d+):)?(\d+):(\d{2}(?:\.\d+)?)$/;function Ge(r,e){let t=String(r??"").trim();if(Xr.test(t))return ut(t.replace(/\.\d+$/,""),e.rate.fps,e.rate.drop);if(/^-?\d+$/.test(t))return e.start+Math.floor(Number(t)*e.rate.fps/e.sampleRate+1e-9);let n=Zr.exec(t);return n?e.start+Math.floor((Number(n[1]??0)*3600+Number(n[2])*60+Number(n[3]))*e.rate.fps+1e-9):null}var xe=["Blue","Cyan","Green","Yellow","Red","Pink","Purple","Fuchsia","Rose","Lavender","Sky","Mint","Lemon","Sand","Cocoa","Cream"],qt=r=>{let e=Number(r);return e>=1?xe[(e-1)%xe.length]:xe[0]},en=r=>Math.max(0,xe.findIndex(e=>e.toLowerCase()===String(r??"").toLowerCase()))+1,zt=/(?:^| )\[ct:((?:[^[\]\\]|\\.)*)\]$/s;function tn(r,e){return!e&&!zt.test(r)?r:`${r}${r?" ":""}[ct:${e.replace(/[\\[\]]/g,t=>`\\${t}`)}]`}function rn(r){let e=zt.exec(r);return e?{note:r.slice(0,e.index),data:e[1].replace(/\\(.)/gs,"$1")}:{note:r,data:""}}function nn(r){return!r.includes(":")||r.includes("/")||r.includes("\\")?r:`/Volumes/${r.split(":").filter(Boolean).join("/")}`}var ke=class{constructor(e=new ze){this.ptsl=e;this.host="protools"}async sessionName(e=qe){try{return String((await this.ptsl.call("GetSessionName",null,e)).session_name??"")}catch(t){if(t instanceof A&&t.code==="no_session")return"";throw t}}async sessionPath(e=qe){let t=await this.ptsl.call("GetSessionPath",null,e),n=typeof t.session_path=="string"?t.session_path:t.session_path?.path??"";return n?nn(n):""}async current(e=2e3){try{let t=await this.sessionName(e);return t?{project:t,project_path:await this.sessionPath(e).catch(()=>"")}:null}catch{return null}}async facts(){let e=await this.sessionName();if(!e)throw new A("no_session","protools: no session is open");let t=(await this.ptsl.call("GetSessionTimeCodeRate")).current_setting,n=Yr(t);if(!n)throw new A("bad_answer",`protools: a timecode rate conform.tools does not know (${t})`);let o=/(\d{4,6})/.exec(String((await this.ptsl.call("GetSessionSampleRate")).sample_rate??""));if(!o)throw new A("bad_answer","protools: Pro Tools reported a sample rate conform.tools does not know");let s=(await this.ptsl.call("GetSessionStartTime")).session_start_time,i={name:e,rate:n,sampleRate:Number(o[1]),start:0},c=Ge(s,i);if(c==null)throw new A("bad_answer",`protools: a session start conform.tools cannot read (${s})`);return{...i,start:c}}async support(){let e={ok:!1,reason:"Pro Tools holds one session at a time, and importing a timeline changes it; write a .ptx or AAF with timeline_write and open that in Pro Tools"},t={ok:!1,reason:"bouncing from Pro Tools (ExportMix) is not wired"},n;try{n=await this.sessionName(3e3)?{ok:!0}:{ok:!1,reason:"Pro Tools is running with no session open"}}catch(o){n={ok:!1,reason:o instanceof Error?o.message:String(o),setup:Hr}}return{export:n,open:e,render:t,markers:n}}async export(e){let t=await this.sessionName();if(!t)throw new A("no_session","protools: no session is open");if(e.timeline&&e.timeline!==t)throw new A("not_found",`protools: the open session is "${t}"; Pro Tools has one timeline per session`);let n=await this.sessionPath();if(!n||!await le(n))throw new A("no_file",`protools: session "${t}" has no saved .ptx on disk${n?` (${n})`:""}; save it in Pro Tools first`);let o=e.out_path??I(await q("conform-protools-"),at(n));return await Y(fe(o)),await rt(n,o),{path:o,format:"ptx",project:t,timeline:t}}open(){return Promise.reject(new A("unsupported","protools: open is not supported: Pro Tools holds one session, and importing a timeline into it changes it"))}renderStart(){return Promise.reject(new A("unsupported","protools: rendering (a bounce) is not wired"))}renderStatus(){return this.renderStart()}renderCancel(){return this.renderStart()}async project(){let e=await this.facts(),t=await this.sessionPath().catch(()=>""),n=[],o=[];try{let i=await this.ptsl.call("GetTrackList",{page_limit:1e3,track_filter_list:[{filter:"All",is_inverted:!1}]}),c={video:0,audio:0};for(let a of i.track_list??[]){let l=/video/i.test(String(a.type))?"video":"audio",u=a.track_attributes??{},d=u.is_inactive===!0||/^(true|.*_?(set|on|inactive))$/i.test(String(u.is_inactive??""));n.push({kind:l,index:++c[l],name:String(a.name??""),enabled:!d})}}catch(i){o.push(`tracks not read: ${i instanceof Error?i.message:String(i)}`)}let s=(await this.locations(e).catch(()=>({locs:[]}))).locs.length;return{project:e.name,timeline:e.name,timelines:[e.name],session_path:t,fps:e.rate.fps,drop_frame:e.rate.drop,sample_rate:e.sampleRate,start_tc:Ee(e.start,e.rate.fps,e.rate.drop),ptsl_version:this.ptsl.version?.join("."),markers:s,notes:o,tracks:n,jobs:[],found:{},pool:{path:"",clips:0,folders:[]}}}async locations(e){let t=[];for(let o=0;;){let s=await this.ptsl.call("GetMemoryLocations",{pagination_request:{limit:1e3,offset:o}}),i=(s.memory_locations??[]).filter(c=>c&&typeof c=="object");if(t.push(...i),o+=i.length,!i.length||o>=Number((s.pagination_response??s.stats)?.total??0))break}let n=[];for(let o of t){let s=o.time_properties,i=typeof s=="number"||/^\d+$/.test(String(s))?{1:"Marker",2:"Selection"}[Number(s)]:String(s??"").split("_").pop();if(i!=="Marker"&&i!=="Selection")continue;let c=Ge(o.start_time,e);if(c==null)continue;let a=i==="Selection"?Ge(o.end_time,e):null,{note:l,data:u}=rn(String(o.comments??""));n.push({number:Number(o.number)||0,frame:c-e.start,duration:a==null?1:Math.max(1,a-c),name:String(o.name??""),note:l,data:u,color:qt(o.color_index),raw:o})}return n.sort((o,s)=>o.frame-s.frame||o.number-s.number),{locs:n.filter((o,s)=>s===0||n[s-1].frame!==o.frame),numbers:t.map(o=>Number(o.number)||0)}}async writeFormat(){let e=await this.ptsl.call("GetMainCounterFormat"),t=e.current_setting??e.current_type,n=typeof t=="number"||/^\d+$/.test(String(t))?{3:"TimeCode",5:"Samples"}[Number(t)]:String(t??"").split("_").pop();if(n==="TimeCode")return"timecode";if(n==="Samples")return"samples";throw new A("counter_format","protools: set Pro Tools' main counter to Timecode or Samples to edit markers from conform.tools")}async apply(e){let t=await this.facts();if(e.timeline&&e.timeline!==t.name)throw new A("not_found",`protools: the open session is "${t.name}"`);let{locs:n,numbers:o}=await this.locations(t),s=new Map(n.map(p=>[p.frame,p])),i=null,c=p=>i==="samples"?String(Math.round(p*t.sampleRate/t.rate.fps)):Ee(t.start+p,t.rate.fps,t.rate.drop),a=async(p,m)=>{let g=Math.max(1,Math.round(p.duration??1)),S=m?.number??Math.max(0,...o)+1,_=m?.raw??{},v={number:S,name:p.name??"",start_time:c(p.frame),end_time:c(p.frame+(g>1?g:0)),time_properties:g>1?"TP_Selection":"TP_Marker",reference:_.reference||"MLR_Absolute",general_properties:_.general_properties||{zoom_settings:!1,pre_post_roll_times:!1,track_visibility:!1,track_heights:!1,group_enables:!1,window_configuration:!1},comments:tn(p.note??"",p.data??""),color_index:en(p.color),location:_.location||"MLC_MainRuler",..._.track_name?{track_name:_.track_name}:{}};await this.ptsl.call("CreateMemoryLocation",v),o.push(S),s.set(p.frame,{number:S,frame:p.frame,duration:g,name:p.name??"",note:p.note??"",data:p.data??"",color:qt(v.color_index),raw:v})},l=async p=>{await this.ptsl.call("ClearMemoryLocation",{location_list:[p.number]}),s.delete(p.frame),o.splice(o.indexOf(p.number),1)},u=p=>({op:"marker_add",frame:p.frame,color:p.color,name:p.name,note:p.note,duration:p.duration,...p.data?{data:p.data}:{}}),d=[],f=[];for(let p of e.ops){let m=Number(p.frame);try{if(!p.op.startsWith("marker_")||p.item){d.push({op:p.op,ok:!1,detail:`protools: '${p.op}' is not reachable over PTSL (timeline markers only)`});continue}if(!Number.isInteger(m)){d.push({op:p.op,ok:!1,detail:"frame must be a whole number"});continue}i??=await this.writeFormat();let g=s.get(m);if(p.op==="marker_add")g&&await l(g),await a({frame:m,color:p.color,name:p.name,note:p.note,duration:Number(p.duration??1),data:p.data||Ur}),d.push({op:p.op,ok:!0}),f.unshift({op:"marker_delete",frame:m},...g?[u(g)]:[]);else if(p.op==="marker_update"){if(!g){d.push({op:p.op,ok:!1,detail:`no marker at frame ${m}`});continue}let S=p.to_frame!==void 0?Number(p.to_frame):m;if(!Number.isInteger(S)){d.push({op:p.op,ok:!1,detail:"to_frame must be a whole number"});continue}if(S!==m&&s.has(S)){d.push({op:p.op,ok:!1,detail:`frame ${S} already has a marker`});continue}await l(g);let _=(v,R)=>p[v]!==void 0?p[v]:R;await a({frame:S,color:_("color",g.color),name:_("name",g.name),note:_("note",g.note),duration:Number(_("duration",g.duration)),data:_("data",g.data)},g),d.push({op:p.op,ok:!0}),f.unshift({op:"marker_update",frame:S,color:g.color,name:g.name,note:g.note,duration:g.duration,data:g.data,...S!==m?{to_frame:m}:{}})}else if(p.op==="marker_delete"){if(!g){d.push({op:p.op,ok:!1,detail:`no marker at frame ${m}`});continue}await l(g),d.push({op:p.op,ok:!0}),f.unshift(u(g))}else d.push({op:p.op,ok:!1,detail:`protools: unknown marker op '${p.op}'`})}catch(g){d.push({op:p.op,ok:!1,detail:g instanceof Error?g.message:String(g)})}}let h=d.filter(p=>p.ok).length;return{project:t.name,timeline:t.name,results:d,undo:f,applied:h,failed:d.length-h}}};var on="Install the conform.tools panel in Media Composer (mcp/hosts/avid/panel: package it, copy the .avpi into PanelSDKPlugins; an unsigned panel needs Avid's Feature Toggle Files), then open Tools > CONFORM.TOOLS. Its page loads from this engine's host bridge (port 48127) and connects by itself.",sn="Install the conform.tools hook (host_setup host=flame action=install_panel), then in Flame: Flame menu > Python > Rescan Python Hooks (or restart Flame), then Flame menu > CONFORM.TOOLS > Connect to CONFORM.TOOLS (or Connect Automatically).",Jt={resolve:new _e,premiere:new dt,avid:new Oe({host:"avid",label:"Media Composer",setup:on}),flame:new Oe({host:"flame",label:"Flame",setup:sn,items:!0}),baselight:new Se,protools:new ke};function Dn(r,e){Jt[r]=e}function Un(r){return Jt[r]??ft(r,"not wired yet")}export{bt as a,fn as b,vr as c,Rn as d,ke as e,an as f,on as g,sn as h,Dn as i,Un as j};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
-
import{Mb as F,Nb as N,Qb as D}from"./chunk-BZE7IP6U.js";import{i as j}from"./chunk-HZBGG7HI.js";import{C as E,D as M,H as C,J as R,K as T,O as q,P as L,S as w,ba as b,da as k,ea as _,ga as I,h as y,o as O,t as S,u as A,v as x,w as P,z as H}from"./chunk-QQBDHVUU.js";var W=16e3,h=class extends Error{constructor(t,s){super(s);this.code=t}},$=class p{constructor(e,t=j,s=W){this.spec=e;this.bridge=t;this.waitMs=s;this.renders=new Map;this.host=e.host,e.items&&(this.items=n=>this.modelItems(n??{}))}async peer(){let e=await(await this.bridge()).waitFor(this.host,this.waitMs);if(!e)throw new h("not_connected",`${this.host}: the conform.tools plugin in ${this.spec.label} is not connected. ${this.spec.setup}`);return e}async needs(e){let t=await this.peer();if(!t.capabilities.includes(e))throw new h("panel_old",`${this.host}: the conform.tools plugin open in ${this.spec.label} ${t.version||""} has no ${e} (an older plugin); update it (${this.spec.setup})`);return t}async ask(e,t={},s){return await this.peer(),await(await this.bridge()).request(this.host,e,t,s)}static{this.announced=(e,t)=>e.optional_verbs.includes(t)}async support(){let e;try{e=await(await this.bridge()).waitFor(this.host,Math.min(3e3,this.waitMs))}catch(n){let o={ok:!1,reason:n instanceof Error?n.message:String(n)};return{export:o,open:o,render:o,markers:o}}if(!e){let n={ok:!1,reason:`the conform.tools plugin in ${this.spec.label} is not connected`,setup:this.spec.setup};return{export:n,open:n,render:n,markers:n}}let t=(n,o)=>n?{ok:!0}:{ok:!1,reason:`this plugin version has no ${o}`},s=e.capabilities;return{export:t(s.includes("timeline_read")||s.includes("timeline_write"),"timeline_read"),open:t(p.announced(e,"timeline_write.import_file"),"timeline_write.import_file"),render:t(s.includes("render"),"render"),markers:t(s.includes("markers"),"markers")}}async current(){let e=await this.ask("session.current_project");if(!e)return{project:"",timelines:[],timeline:""};let t=await this.ask("session.timeline_count",{project:e}),s=[];for(let o=1;o<=t;o++){let l=await this.ask("session.timeline_by_index",{project:e,index:o});l&&s.push(await this.ask("session.name",{handle:l}))}let n=await this.ask("session.current_timeline",{project:e});return{project:await this.ask("session.name",{handle:e}),timelines:s,timeline:n?await this.ask("session.name",{handle:n}):""}}async project(e={}){let t=await this.current();return{project:t.project,timeline:e.timeline??t.timeline,timelines:t.timelines,tracks:[],jobs:[],found:{},pool:{path:"",clips:0,folders:[]}}}async sequence(e){let t=await this.ask("session.current_project");if(!t)throw new h("no_project",`${this.host}: no project is open`);if(!e){let o=await this.ask("session.current_timeline",{project:t});if(!o)throw new h("no_timeline",`${this.host}: no timeline is active`);return{project:t,seq:o,name:await this.ask("session.name",{handle:o})}}let s=await this.ask("session.timeline_count",{project:t}),n=[];for(let o=1;o<=s;o++){let l=await this.ask("session.timeline_by_index",{project:t,index:o});if(!l)continue;let d=await this.ask("session.name",{handle:l});if(d===e)return{project:t,seq:l,name:d};n.push(d)}throw new h("not_found",`${this.host}: no timeline named "${e}" (have: ${n.join(", ")})`)}async model(e){let{project:t,seq:s}=await this.sequence(e);return await this.ask("timeline_read.model",{timeline:s,project:t},12e4)}async export(e){if(!e.out_path)throw new h("usage",`${this.host}: export needs out_path`);let t=await this.peer(),{project:s,seq:n,name:o}=await this.sequence(e.timeline),l=await this.ask("session.name",{handle:s}),d=r=>p.announced(t,r),m=e.out_path,c,a=[];if(d("timeline_write.export_otio")||d("timeline_write.export_xml")){let r=d("timeline_write.export_otio"),i=await this.ask(r?"timeline_write.export_otio":"timeline_write.export_xml",{project:s,timeline:n,path:e.out_path},12e4);if(c=i.format??(r?"otio":"xmeml"),i.ok===!1)throw new h("export_failed",`${this.host}: ${this.spec.label} did not write ${e.out_path}${i.errors?.length?` (${i.errors.join("; ")})`:""}`);i.path&&i.path!==e.out_path&&(m=await this.adopt(i.path,e.out_path)),a=i.warnings??[]}else if(d("timeline_read.export_file")){let r=await this.ask("timeline_read.export_file",{timeline:n,fmt:"otio",path:e.out_path},12e4);if(!r)throw new h("export_failed",`${this.host}: ${this.spec.label} exported no OTIO`);c="otio",r!==e.out_path&&(m=await this.adopt(r,e.out_path))}else{await this.needs("timeline_read");let r=await this.ask("timeline_read.model",{timeline:n,project:s},12e4),i=J(r);await E(e.out_path,JSON.stringify(i.otio)),c="otio",a=i.notes}if(!F.includes(c))throw new h("export_failed",`${this.host}: ${this.spec.label} exported ${c}, which the engine does not read (${m})`);if(!await P(m)||(await A(m)).size===0)throw new h("export_failed",`${this.host}: ${this.spec.label} did not write ${m}`);return{path:m,format:c,project:l,timeline:o,...a.length?{notes:a}:{}}}async adopt(e,t){let s=k(e)&&k(e)!==k(t)?t.slice(0,t.length-k(t).length)+k(e):t;if(await C(e,s),!N(s))throw new h("export_failed",`${this.host}: ${this.spec.label} exported ${b(e)}, which the engine does not read`);return s}async open(e){if(e.into==="scratch")throw new h("unsupported",`${this.host}: opening into a scratch project is not supported; the import lands in the open project`);let t=await this.peer();if(!p.announced(t,"timeline_write.import_file"))throw new h("unsupported",`${this.host}: this conform.tools plugin cannot import timelines (${this.spec.setup})`);let s=await this.ask("session.current_project");if(!s)throw new h("no_project",`${this.host}: no project is open`);let n=await this.ask("timeline_write.import_file",{project:s,path:e.path,sequences:null},3e5);if(!n.ok)throw new h("import_failed",`${this.host}: ${this.spec.label} did not import ${e.path}${n.issues?.length?` (${n.issues.join("; ")})`:""}`);let o=[...n.issues??[]];return n.imported.length>1&&o.push(`imported ${n.imported.length} timelines: ${n.imported.map(l=>l.name).join(", ")}`),e.name&&o.push(`${this.spec.label} names imported timelines after the file's own; name was not applied`),e.media_dirs?.length&&o.push(`${this.spec.label} links media from the paths in the file; media_dirs was not used (relink with timeline_relink before writing)`),{project:await this.ask("session.name",{handle:s}),timeline:n.imported[0]?.name??b(e.path),notes:o,restored:!e.stay,...n.bin?{folder:n.bin}:{}}}async modelItems(e){let t=await this.model(e.timeline),s=[...e.kind==="audio"?[]:t.items.map(n=>({kind:"video",track:n.track,start:n.start-t.start_frame,end:n.end-t.start_frame,id:n.handle?.$h??n.clip_id??"",name:n.name??"",color:n.color??"",flags:n.flags??[],enabled:n.enabled??!0,file:n.file_path})),...e.kind==="video"?[]:(t.audio_items??[]).map(n=>({kind:"audio",track:n.track,start:n.start-t.start_frame,end:n.end-t.start_frame,id:"",name:n.name??"",file:n.file_path??""}))].filter(n=>e.track===void 0||n.track===e.track);return{project:(await this.current()).project,timeline:t.timeline,start_frame:t.start_frame,fps:t.fps,items:s,color_groups:[],layers:1}}async apply(e){let t=e.ops.length>0&&e.ops.every(a=>a.op==="timeline_rename"&&(a.timeline||a.guid)),{project:s,seq:n,name:o}=await this.sequence(t?void 0:e.timeline),l=[],d=[],m=a=>a.op.startsWith("marker_")&&!a.item;for(let a=0;a<e.ops.length;){let r=a;for(;r<e.ops.length&&m(e.ops[r])===m(e.ops[a]);)r++;let i=e.ops.slice(a,r),u=m(i[0])?await this.markerOps(n,i):await this.clipOps(n,i,e.timeline);l.push(...u.results),d.unshift(...u.undo),a=r}let c=l.filter(a=>a.ok).length;return{project:await this.ask("session.name",{handle:s}),timeline:o,results:l,undo:d,applied:c,failed:l.length-c}}async clipOps(e,t,s){let n=await this.peer();if(n.capabilities.includes("edit"))return await this.ask("edit.apply",{timeline:e,ops:t},6e4+t.length*500);let o=(a,r)=>({op:a.op,ok:!1,detail:r});if(!n.capabilities.includes("item_meta"))return{results:t.map(a=>o(a,`${this.host}: clip edits are not reachable over this plugin`)),undo:[]};let l=await this.model(s),d=a=>a?"id"in a?{$h:a.id}:(a.kind??"video")!=="video"?null:l.items.find(r=>r.track===a.track&&r.start-l.start_frame===a.start)?.handle??null:null,m=[],c=[];for(let a of t){let r=d(a.item);try{if(!r)m.push(o(a,`no video item at ${JSON.stringify(a.item??null)}`));else if(a.op==="clip_color"){let i=await this.ask("item_meta.color",{handle:r}),u=a.color?await this.ask("item_meta.set_color",{handle:r,color:a.color}):await this.ask("item_meta.clear_color",{handle:r});m.push({op:a.op,ok:u}),u&&c.unshift({op:"clip_color",item:a.item,color:i})}else if(a.op==="enabled"&&p.announced(n,"item_meta.set_enabled")){let i=l.items.find(f=>f.handle?.$h===r.$h)?.enabled??!0,u=await this.ask("item_meta.set_enabled",{item:r,enabled:!!a.on});m.push({op:a.op,ok:u}),u&&c.unshift({op:"enabled",item:a.item,on:i})}else m.push(o(a,`${this.host}: '${a.op}' is not reachable over this plugin`))}catch(i){m.push(o(a,i instanceof Error?i.message:String(i)))}}return{results:m,undo:c}}async markerOps(e,t){let s=await this.peer(),n=r=>p.announced(s,r),o=new Map((await this.ask("markers.list",{target:e})).map(r=>[r.frame,r])),l=[],d=[],m=async r=>{let i=await this.ask("markers.add",{target:e,frame:r.frame,color:r.color??"",name:r.name??"",note:r.note??"",duration:r.duration??1,custom_data:r.custom_data??""});return i&&o.set(r.frame,{color:"",name:"",note:"",duration:1,...r}),i},c=async r=>{let i=await this.ask("markers.delete_at",{target:e,frame:r});return i&&o.delete(r),i},a=r=>({op:"marker_add",frame:r.frame,color:r.color,name:r.name,note:r.note,duration:r.duration,...r.custom_data?{data:r.custom_data}:{}});for(let r of t){let i=Number(r.frame);try{if(r.op==="marker_add"){let u=o.get(i);u&&await c(i);let f=await m({frame:i,color:r.color,name:r.name,note:r.note,duration:Number(r.duration??1),custom_data:r.data});l.push({op:r.op,ok:f}),f&&d.unshift(...u?[a(u)]:[],{op:"marker_delete",frame:i})}else if(r.op==="marker_update"){let u=o.get(i);if(!u){l.push({op:r.op,ok:!1,detail:`no marker at frame ${i}`});continue}let f=r.to_frame!==void 0?Number(r.to_frame):i,v={...u,frame:f,...r.color!==void 0?{color:String(r.color)}:{},...r.name!==void 0?{name:String(r.name)}:{},...r.note!==void 0?{note:String(r.note)}:{}},g=!0;n("markers.set_color")&&n("markers.set_text")&&n("markers.move")?(r.color!==void 0&&(g=await this.ask("markers.set_color",{target:e,frame:i,color:r.color})&&g),(r.name!==void 0||r.note!==void 0)&&(g=await this.ask("markers.set_text",{target:e,frame:i,name:r.name,note:r.note})&&g),f!==i&&(g=await this.ask("markers.move",{target:e,frame:i,to_frame:f})&&g),o.delete(i),o.set(f,v)):g=await c(i)&&await m(v),l.push({op:r.op,ok:g}),d.unshift({op:"marker_update",frame:f,color:u.color,name:u.name,note:u.note,...f!==i?{to_frame:i}:{}})}else if(r.op==="marker_delete"){let u=o.get(i),f=!!u&&await c(i);l.push({op:r.op,ok:f,...u?{}:{detail:`no marker at frame ${i}`}}),f&&u&&d.unshift(a(u))}else l.push({op:r.op,ok:!1,detail:`${this.host}: '${r.op}' is not reachable over this plugin`})}catch(u){l.push({op:r.op,ok:!1,detail:u instanceof Error?u.message:String(u)})}}return{results:l,undo:d}}async renderStart(e){if(await this.needs("render"),e.disable_tracks?.length||e.audio_tracks?.length)throw new h("unsupported",`${this.host}: disable_tracks / audio_tracks are DaVinci Resolve's; pick a preset that renders what you need`);if(!e.preset)throw new h("usage",`${this.host}: preset is required: one of ${this.spec.label}'s export presets by name`);let{seq:t,name:s}=await this.sequence(e.timeline),n=e.name??s,o={purpose:"deliver",format:"preset",preset:e.preset,target_dir:e.target_dir,name:n,...e.range?{range:[e.range.in,e.range.out]}:{}},l=await this.ask("render.submit",{timeline:t,job:o});if(!l?.id)throw new h("render_refused",`${this.host}: ${l?.error??`${this.spec.label} refused the render`}`);if(!await this.ask("render.start",{job_ids:[l.id]}))throw new h("render_refused",`${this.host}: ${this.spec.label} did not start job ${l.id}`);return this.renders.set(l.id,{dir:e.target_dir,name:n}),{job_id:l.id,state:"queued",percent:0}}async renderStatus(e){let t=await this.ask("render.status",{job_id:e});if(!t)return{job_id:e,state:"failed",percent:0,error:`${this.host}: no render job ${e}`};let s={done:"complete",rendering:"rendering",queued:"queued",failed:"failed",cancelled:"cancelled"}[t.state]??"rendering",n={job_id:e,state:s,percent:Math.round(t.progress??(s==="complete"?100:0)),...t.error?{error:t.error}:{}};if(s==="complete"||s==="failed"||s==="cancelled"){let o=this.renders.get(e);s==="complete"&&o&&(n.outputs=await V(o.dir,o.name)),await this.ask("render.remove",{job_id:e}).catch(()=>!1),this.renders.delete(e)}return n}async renderCancel(e){return await this.ask("render.cancel",{job_id:e})?{job_id:e,state:"cancelled",percent:0}:{...await this.renderStatus(e),error:`${this.spec.label}'s running export cannot be cancelled from here; stop it in ${this.spec.label}`}}};async function V(p,e){let t=[];try{for await(let s of L(p))s.isFile&&s.name.startsWith(`${e}.`)&&t.push(_(p,s.name))}catch{}return t.sort()}function J(p){let e=(c,a)=>({OTIO_SCHEMA:"RationalTime.1",value:c,rate:a}),t=(c,a,r,i=r)=>({OTIO_SCHEMA:"TimeRange.1",start_time:e(c,r),duration:e(a,i)}),s=p.fps,n=p.tracks?.length?p.tracks:[...new Set(p.items.map(c=>c.track))].sort((c,a)=>c-a).map(c=>({index:c,enabled:!0,name:"",items:p.items.filter(a=>a.track===c)})),o=c=>(c.reversed?-1:1)*(c.speed||1)/(c.fps_factor||1),l=new Map;for(let c of p.items)if(c.file_path&&c.start_tc!=null&&c.src_abs_in!=null){let a=c.src_abs_in-c.start_tc+Math.ceil((c.end-c.start)*Math.abs(o(c))*(c.fps_factor||1));l.set(c.file_path,Math.max(l.get(c.file_path)??0,a))}let d=n.map(c=>{let a=p.start_frame,r=[];for(let i of[...c.items].sort((u,f)=>u.start-f.start)){if(i.start<a)continue;i.start>a&&r.push({OTIO_SCHEMA:"Gap.1",name:"",source_range:t(0,i.start-a,s)});let u=i.src_fps||s,f=i.start_tc!=null&&l.has(i.file_path)?i.start_tc:null,v=f!=null?i.src_abs_in:i.src_in??i.src_abs_in??0,g=o(i);r.push({OTIO_SCHEMA:"Clip.2",name:i.name??b(i.file_path||""),enabled:i.enabled!==!1,source_range:t(v,i.end-i.start,u,s),media_references:{DEFAULT_MEDIA:{OTIO_SCHEMA:"ExternalReference.1",name:b(i.file_path||""),target_url:i.file_path?`file://${i.file_path}`:"",...f!=null?{available_range:t(f,l.get(i.file_path),u)}:{},metadata:{}}},active_media_reference_key:"DEFAULT_MEDIA",effects:Math.abs(g-1)>1e-6?[{OTIO_SCHEMA:"LinearTimeWarp.1",name:"",effect_name:"LinearTimeWarp",time_scalar:g}]:[],markers:[],metadata:i.reel?{cmx_3600:{reel:i.reel}}:{}}),a=i.end}return{OTIO_SCHEMA:"Track.1",name:c.name||`V${c.index}`,kind:"Video",enabled:c.enabled!==!1,children:r,effects:[],markers:[],metadata:{}}}),m=[];return p.audio_items?.length&&m.push(`${p.audio_items.length} audio clip(s) not carried: the host's plugin reports no audio source times`),p.transitions?.length&&m.push(`${p.transitions.length} transition(s) not carried (cuts in their place)`),{otio:{OTIO_SCHEMA:"Timeline.1",name:p.timeline,global_start_time:e(p.start_frame,s),metadata:{},tracks:{OTIO_SCHEMA:"Stack.1",name:"tracks",children:d,effects:[],markers:[],metadata:{}}},notes:m}}var X=16e3,G="Install the conform.tools panel (host_setup host=premiere action=install_panel), then in Premiere open Window > UXP Plugins > conform.tools. It connects by itself from then on.";var U=class extends ${constructor(t=j,s=X){super({host:"premiere",label:"Premiere Pro",setup:G},t,s);this.items=async(t={})=>{await this.needs("edit");let{seq:s}=await this.sequence(t.timeline),n=await this.ask("edit.items",{timeline:s,kind:t.kind,track:t.track},12e4),o=n.project_path?await K(n.project_path,n.timeline).catch(d=>({error:d instanceof Error?d.message:String(d)})):{error:"the project has never been saved"},l=0;if(!("error"in o))for(let d of n.items){let m=o.get(`${d.kind}:${d.track}:${d.start}:${Number(d.end)-Number(d.start)}`);m?Object.assign(d,m,{saved:!0}):(d.saved=!1,l++)}return{...n,color_groups:[],layers:1,..."error"in o?{saved_note:`saved project not read: ${o.error}`}:{unsaved_items:l}}};this.premiereRenders=new Map}async current(){let t=await this.ask("session.describe");return{project:t.project,timelines:t.timelines,timeline:t.current}}async liveMarkers(t){if(!$.announced(await this.peer(),"edit.markers"))return null;let{seq:s}=await this.sequence(t);return await this.ask("edit.markers",{timeline:s},12e4)}async model(t){return await super.model(t)}async projectClips(){return await this.needs("edit"),await this.ask("edit.project_clips",{},12e4)}async relinkClips(t){return await this.needs("edit"),await this.ask("edit.relink_clips",{items:t},6e4+t.length*2e3)}async cutIn(t,s){await this.needs("edit");let{seq:n}=await this.sequence(t);return await this.ask("edit.cut_in",{timeline:n,cuts:s},12e4+s.length*3e3)}async renderStart(t){if(t.range)throw new h("unsupported","premiere: a frame range is not supported yet; set in/out on the sequence in Premiere");if(!t.preset||!/\.epr$/i.test(t.preset))throw new h("usage","premiere: preset must be the path of a Media Encoder preset (.epr)");let{seq:s,name:n}=await this.sequence(t.timeline);await M(t.target_dir);let o=_(t.target_dir,`${t.name??n}.mov`),l=await this.ask("render.export_sequence",{timeline:s,output_path:o,preset_path:t.preset,queue:!1},6e4);if(!l.ok)throw new h("render_refused","premiere: Premiere refused the export");let d=l.job||`ppro-${Date.now()}`;return this.premiereRenders.set(d,o),{job_id:d,state:"rendering",percent:0}}async renderStatus(t){let s=await this.ask("render.progress"),n=s[t]??s.last,o=this.premiereRenders.get(t);return n?.event==="error"||n?.event==="onEncodeError"?{job_id:t,state:"failed",percent:0,error:String(n.data??"encode error")}:n?.event==="complete"||n?.event==="onEncodeComplete"||o&&await x(o)&&!n?{job_id:t,state:"complete",percent:100,...o?{outputs:[o]}:{}}:{job_id:t,state:"rendering",percent:typeof n?.data=="number"?Math.round(Number(n.data)*100):0}}async renderCancel(t){return{job_id:t,state:"cancelled",percent:0,error:"Premiere's export cannot be cancelled from here; cancel it in Premiere / Media Encoder"}}};async function K(p,e){let{session:t}=await D(p,"prproj"),s=t.timelines.find(o=>o.name===e),n=new Map;if(!s)throw new Error(`the saved project has no sequence "${e}" (saved before it was made?)`);for(let o of s.tracks)if(!(o.kind!=="Video"&&o.kind!=="Audio"))for(let l of o.items){if(l.kind==="gap"||l.kind==="transition")continue;let d=l;n.set(`${o.kind==="Video"?"video":"audio"}:${o.track_index}:${l.timeline_range.start.value}:${l.timeline_range.duration.value}`,{saved_id:l.id,...d.speed_factor!=null&&d.speed_factor!==1?{retime:d.speed_factor}:{},...d.speed_ramped?{ramped:!0}:{},...d.speed_reverse?{reversed:!0}:{},...l.kind==="nested"?{nested:!0}:{},...d.is_multicam?{multicam:!0}:{},...d.effects?.some(m=>/stabiliz/i.test(m.kind??""))?{stabilized:!0}:{},...d.effects?.length?{saved_effects:d.effects.map(m=>m.name??m.kind??"")}:{}})}return n}function z(p=y()){return p==="darwin"?"/Library/Application Support/Adobe/Adobe Desktop Common/RemoteComponents/UPI/UnifiedPluginInstallerAgent/UnifiedPluginInstallerAgent.app/Contents/MacOS/UnifiedPluginInstallerAgent":p==="win32"?"C:\\Program Files\\Common Files\\Adobe\\Adobe Desktop Common\\RemoteComponents\\UPI\\UnifiedPluginInstallerAgent\\UnifiedPluginInstallerAgent.exe":null}async function B(){for(let p of["./uxp-plugin/","./premiere-uxp/"]){let e=S(new URL(p,import.meta.url));if(await P(_(e,"manifest.json")))return e}throw new Error("premiere: the conform.tools panel is missing from this install")}async function Q(){return JSON.parse(await H(_(await B(),"manifest.json"))).version}async function oe(p=y()){let e=z(p);if(!e||!await x(e))return{installed:!1,listing:"Creative Cloud's plugin installer is not on this machine"};let t=await w(e,p==="win32"?["/list","all"]:["--list","all"],{timeoutMs:6e4}),s=t.stdout.split(`
|
|
3
|
+
import{Nb as F,Ob as N,Rb as D}from"./chunk-4QGSPWXM.js";import{i as j}from"./chunk-2XB3P2Q5.js";import{C as E,D as M,H as C,J as R,K as T,O as q,P as L,S as w,ba as b,da as k,ea as _,ga as I,h as y,o as O,t as S,u as A,v as x,w as P,z as H}from"./chunk-QQBDHVUU.js";var W=16e3,h=class extends Error{constructor(t,s){super(s);this.code=t}},$=class p{constructor(e,t=j,s=W){this.spec=e;this.bridge=t;this.waitMs=s;this.renders=new Map;this.host=e.host,e.items&&(this.items=n=>this.modelItems(n??{}))}async peer(){let e=await(await this.bridge()).waitFor(this.host,this.waitMs);if(!e)throw new h("not_connected",`${this.host}: the conform.tools plugin in ${this.spec.label} is not connected. ${this.spec.setup}`);return e}async needs(e){let t=await this.peer();if(!t.capabilities.includes(e))throw new h("panel_old",`${this.host}: the conform.tools plugin open in ${this.spec.label} ${t.version||""} has no ${e} (an older plugin); update it (${this.spec.setup})`);return t}async ask(e,t={},s){return await this.peer(),await(await this.bridge()).request(this.host,e,t,s)}static{this.announced=(e,t)=>e.optional_verbs.includes(t)}async support(){let e;try{e=await(await this.bridge()).waitFor(this.host,Math.min(3e3,this.waitMs))}catch(n){let o={ok:!1,reason:n instanceof Error?n.message:String(n)};return{export:o,open:o,render:o,markers:o}}if(!e){let n={ok:!1,reason:`the conform.tools plugin in ${this.spec.label} is not connected`,setup:this.spec.setup};return{export:n,open:n,render:n,markers:n}}let t=(n,o)=>n?{ok:!0}:{ok:!1,reason:`this plugin version has no ${o}`},s=e.capabilities;return{export:t(s.includes("timeline_read")||s.includes("timeline_write"),"timeline_read"),open:t(p.announced(e,"timeline_write.import_file"),"timeline_write.import_file"),render:t(s.includes("render"),"render"),markers:t(s.includes("markers"),"markers")}}async current(){let e=await this.ask("session.current_project");if(!e)return{project:"",timelines:[],timeline:""};let t=await this.ask("session.timeline_count",{project:e}),s=[];for(let o=1;o<=t;o++){let l=await this.ask("session.timeline_by_index",{project:e,index:o});l&&s.push(await this.ask("session.name",{handle:l}))}let n=await this.ask("session.current_timeline",{project:e});return{project:await this.ask("session.name",{handle:e}),timelines:s,timeline:n?await this.ask("session.name",{handle:n}):""}}async project(e={}){let t=await this.current();return{project:t.project,timeline:e.timeline??t.timeline,timelines:t.timelines,tracks:[],jobs:[],found:{},pool:{path:"",clips:0,folders:[]}}}async sequence(e){let t=await this.ask("session.current_project");if(!t)throw new h("no_project",`${this.host}: no project is open`);if(!e){let o=await this.ask("session.current_timeline",{project:t});if(!o)throw new h("no_timeline",`${this.host}: no timeline is active`);return{project:t,seq:o,name:await this.ask("session.name",{handle:o})}}let s=await this.ask("session.timeline_count",{project:t}),n=[];for(let o=1;o<=s;o++){let l=await this.ask("session.timeline_by_index",{project:t,index:o});if(!l)continue;let d=await this.ask("session.name",{handle:l});if(d===e)return{project:t,seq:l,name:d};n.push(d)}throw new h("not_found",`${this.host}: no timeline named "${e}" (have: ${n.join(", ")})`)}async model(e){let{project:t,seq:s}=await this.sequence(e);return await this.ask("timeline_read.model",{timeline:s,project:t},12e4)}async export(e){if(!e.out_path)throw new h("usage",`${this.host}: export needs out_path`);let t=await this.peer(),{project:s,seq:n,name:o}=await this.sequence(e.timeline),l=await this.ask("session.name",{handle:s}),d=r=>p.announced(t,r),m=e.out_path,c,a=[];if(d("timeline_write.export_otio")||d("timeline_write.export_xml")){let r=d("timeline_write.export_otio"),i=await this.ask(r?"timeline_write.export_otio":"timeline_write.export_xml",{project:s,timeline:n,path:e.out_path},12e4);if(c=i.format??(r?"otio":"xmeml"),i.ok===!1)throw new h("export_failed",`${this.host}: ${this.spec.label} did not write ${e.out_path}${i.errors?.length?` (${i.errors.join("; ")})`:""}`);i.path&&i.path!==e.out_path&&(m=await this.adopt(i.path,e.out_path)),a=i.warnings??[]}else if(d("timeline_read.export_file")){let r=await this.ask("timeline_read.export_file",{timeline:n,fmt:"otio",path:e.out_path},12e4);if(!r)throw new h("export_failed",`${this.host}: ${this.spec.label} exported no OTIO`);c="otio",r!==e.out_path&&(m=await this.adopt(r,e.out_path))}else{await this.needs("timeline_read");let r=await this.ask("timeline_read.model",{timeline:n,project:s},12e4),i=J(r);await E(e.out_path,JSON.stringify(i.otio)),c="otio",a=i.notes}if(!F.includes(c))throw new h("export_failed",`${this.host}: ${this.spec.label} exported ${c}, which the engine does not read (${m})`);if(!await P(m)||(await A(m)).size===0)throw new h("export_failed",`${this.host}: ${this.spec.label} did not write ${m}`);return{path:m,format:c,project:l,timeline:o,...a.length?{notes:a}:{}}}async adopt(e,t){let s=k(e)&&k(e)!==k(t)?t.slice(0,t.length-k(t).length)+k(e):t;if(await C(e,s),!N(s))throw new h("export_failed",`${this.host}: ${this.spec.label} exported ${b(e)}, which the engine does not read`);return s}async open(e){if(e.into==="scratch")throw new h("unsupported",`${this.host}: opening into a scratch project is not supported; the import lands in the open project`);let t=await this.peer();if(!p.announced(t,"timeline_write.import_file"))throw new h("unsupported",`${this.host}: this conform.tools plugin cannot import timelines (${this.spec.setup})`);let s=await this.ask("session.current_project");if(!s)throw new h("no_project",`${this.host}: no project is open`);let n=await this.ask("timeline_write.import_file",{project:s,path:e.path,sequences:null},3e5);if(!n.ok)throw new h("import_failed",`${this.host}: ${this.spec.label} did not import ${e.path}${n.issues?.length?` (${n.issues.join("; ")})`:""}`);let o=[...n.issues??[]];return n.imported.length>1&&o.push(`imported ${n.imported.length} timelines: ${n.imported.map(l=>l.name).join(", ")}`),e.name&&o.push(`${this.spec.label} names imported timelines after the file's own; name was not applied`),e.media_dirs?.length&&o.push(`${this.spec.label} links media from the paths in the file; media_dirs was not used (relink with timeline_relink before writing)`),{project:await this.ask("session.name",{handle:s}),timeline:n.imported[0]?.name??b(e.path),notes:o,restored:!e.stay,...n.bin?{folder:n.bin}:{}}}async modelItems(e){let t=await this.model(e.timeline),s=[...e.kind==="audio"?[]:t.items.map(n=>({kind:"video",track:n.track,start:n.start-t.start_frame,end:n.end-t.start_frame,id:n.handle?.$h??n.clip_id??"",name:n.name??"",color:n.color??"",flags:n.flags??[],enabled:n.enabled??!0,file:n.file_path})),...e.kind==="video"?[]:(t.audio_items??[]).map(n=>({kind:"audio",track:n.track,start:n.start-t.start_frame,end:n.end-t.start_frame,id:"",name:n.name??"",file:n.file_path??""}))].filter(n=>e.track===void 0||n.track===e.track);return{project:(await this.current()).project,timeline:t.timeline,start_frame:t.start_frame,fps:t.fps,items:s,color_groups:[],layers:1}}async apply(e){let t=e.ops.length>0&&e.ops.every(a=>a.op==="timeline_rename"&&(a.timeline||a.guid)),{project:s,seq:n,name:o}=await this.sequence(t?void 0:e.timeline),l=[],d=[],m=a=>a.op.startsWith("marker_")&&!a.item;for(let a=0;a<e.ops.length;){let r=a;for(;r<e.ops.length&&m(e.ops[r])===m(e.ops[a]);)r++;let i=e.ops.slice(a,r),u=m(i[0])?await this.markerOps(n,i):await this.clipOps(n,i,e.timeline);l.push(...u.results),d.unshift(...u.undo),a=r}let c=l.filter(a=>a.ok).length;return{project:await this.ask("session.name",{handle:s}),timeline:o,results:l,undo:d,applied:c,failed:l.length-c}}async clipOps(e,t,s){let n=await this.peer();if(n.capabilities.includes("edit"))return await this.ask("edit.apply",{timeline:e,ops:t},6e4+t.length*500);let o=(a,r)=>({op:a.op,ok:!1,detail:r});if(!n.capabilities.includes("item_meta"))return{results:t.map(a=>o(a,`${this.host}: clip edits are not reachable over this plugin`)),undo:[]};let l=await this.model(s),d=a=>a?"id"in a?{$h:a.id}:(a.kind??"video")!=="video"?null:l.items.find(r=>r.track===a.track&&r.start-l.start_frame===a.start)?.handle??null:null,m=[],c=[];for(let a of t){let r=d(a.item);try{if(!r)m.push(o(a,`no video item at ${JSON.stringify(a.item??null)}`));else if(a.op==="clip_color"){let i=await this.ask("item_meta.color",{handle:r}),u=a.color?await this.ask("item_meta.set_color",{handle:r,color:a.color}):await this.ask("item_meta.clear_color",{handle:r});m.push({op:a.op,ok:u}),u&&c.unshift({op:"clip_color",item:a.item,color:i})}else if(a.op==="enabled"&&p.announced(n,"item_meta.set_enabled")){let i=l.items.find(f=>f.handle?.$h===r.$h)?.enabled??!0,u=await this.ask("item_meta.set_enabled",{item:r,enabled:!!a.on});m.push({op:a.op,ok:u}),u&&c.unshift({op:"enabled",item:a.item,on:i})}else m.push(o(a,`${this.host}: '${a.op}' is not reachable over this plugin`))}catch(i){m.push(o(a,i instanceof Error?i.message:String(i)))}}return{results:m,undo:c}}async markerOps(e,t){let s=await this.peer(),n=r=>p.announced(s,r),o=new Map((await this.ask("markers.list",{target:e})).map(r=>[r.frame,r])),l=[],d=[],m=async r=>{let i=await this.ask("markers.add",{target:e,frame:r.frame,color:r.color??"",name:r.name??"",note:r.note??"",duration:r.duration??1,custom_data:r.custom_data??""});return i&&o.set(r.frame,{color:"",name:"",note:"",duration:1,...r}),i},c=async r=>{let i=await this.ask("markers.delete_at",{target:e,frame:r});return i&&o.delete(r),i},a=r=>({op:"marker_add",frame:r.frame,color:r.color,name:r.name,note:r.note,duration:r.duration,...r.custom_data?{data:r.custom_data}:{}});for(let r of t){let i=Number(r.frame);try{if(r.op==="marker_add"){let u=o.get(i);u&&await c(i);let f=await m({frame:i,color:r.color,name:r.name,note:r.note,duration:Number(r.duration??1),custom_data:r.data});l.push({op:r.op,ok:f}),f&&d.unshift(...u?[a(u)]:[],{op:"marker_delete",frame:i})}else if(r.op==="marker_update"){let u=o.get(i);if(!u){l.push({op:r.op,ok:!1,detail:`no marker at frame ${i}`});continue}let f=r.to_frame!==void 0?Number(r.to_frame):i,v={...u,frame:f,...r.color!==void 0?{color:String(r.color)}:{},...r.name!==void 0?{name:String(r.name)}:{},...r.note!==void 0?{note:String(r.note)}:{}},g=!0;n("markers.set_color")&&n("markers.set_text")&&n("markers.move")?(r.color!==void 0&&(g=await this.ask("markers.set_color",{target:e,frame:i,color:r.color})&&g),(r.name!==void 0||r.note!==void 0)&&(g=await this.ask("markers.set_text",{target:e,frame:i,name:r.name,note:r.note})&&g),f!==i&&(g=await this.ask("markers.move",{target:e,frame:i,to_frame:f})&&g),o.delete(i),o.set(f,v)):g=await c(i)&&await m(v),l.push({op:r.op,ok:g}),d.unshift({op:"marker_update",frame:f,color:u.color,name:u.name,note:u.note,...f!==i?{to_frame:i}:{}})}else if(r.op==="marker_delete"){let u=o.get(i),f=!!u&&await c(i);l.push({op:r.op,ok:f,...u?{}:{detail:`no marker at frame ${i}`}}),f&&u&&d.unshift(a(u))}else l.push({op:r.op,ok:!1,detail:`${this.host}: '${r.op}' is not reachable over this plugin`})}catch(u){l.push({op:r.op,ok:!1,detail:u instanceof Error?u.message:String(u)})}}return{results:l,undo:d}}async renderStart(e){if(await this.needs("render"),e.disable_tracks?.length||e.audio_tracks?.length)throw new h("unsupported",`${this.host}: disable_tracks / audio_tracks are DaVinci Resolve's; pick a preset that renders what you need`);if(!e.preset)throw new h("usage",`${this.host}: preset is required: one of ${this.spec.label}'s export presets by name`);let{seq:t,name:s}=await this.sequence(e.timeline),n=e.name??s,o={purpose:"deliver",format:"preset",preset:e.preset,target_dir:e.target_dir,name:n,...e.range?{range:[e.range.in,e.range.out]}:{}},l=await this.ask("render.submit",{timeline:t,job:o});if(!l?.id)throw new h("render_refused",`${this.host}: ${l?.error??`${this.spec.label} refused the render`}`);if(!await this.ask("render.start",{job_ids:[l.id]}))throw new h("render_refused",`${this.host}: ${this.spec.label} did not start job ${l.id}`);return this.renders.set(l.id,{dir:e.target_dir,name:n}),{job_id:l.id,state:"queued",percent:0}}async renderStatus(e){let t=await this.ask("render.status",{job_id:e});if(!t)return{job_id:e,state:"failed",percent:0,error:`${this.host}: no render job ${e}`};let s={done:"complete",rendering:"rendering",queued:"queued",failed:"failed",cancelled:"cancelled"}[t.state]??"rendering",n={job_id:e,state:s,percent:Math.round(t.progress??(s==="complete"?100:0)),...t.error?{error:t.error}:{}};if(s==="complete"||s==="failed"||s==="cancelled"){let o=this.renders.get(e);s==="complete"&&o&&(n.outputs=await V(o.dir,o.name)),await this.ask("render.remove",{job_id:e}).catch(()=>!1),this.renders.delete(e)}return n}async renderCancel(e){return await this.ask("render.cancel",{job_id:e})?{job_id:e,state:"cancelled",percent:0}:{...await this.renderStatus(e),error:`${this.spec.label}'s running export cannot be cancelled from here; stop it in ${this.spec.label}`}}};async function V(p,e){let t=[];try{for await(let s of L(p))s.isFile&&s.name.startsWith(`${e}.`)&&t.push(_(p,s.name))}catch{}return t.sort()}function J(p){let e=(c,a)=>({OTIO_SCHEMA:"RationalTime.1",value:c,rate:a}),t=(c,a,r,i=r)=>({OTIO_SCHEMA:"TimeRange.1",start_time:e(c,r),duration:e(a,i)}),s=p.fps,n=p.tracks?.length?p.tracks:[...new Set(p.items.map(c=>c.track))].sort((c,a)=>c-a).map(c=>({index:c,enabled:!0,name:"",items:p.items.filter(a=>a.track===c)})),o=c=>(c.reversed?-1:1)*(c.speed||1)/(c.fps_factor||1),l=new Map;for(let c of p.items)if(c.file_path&&c.start_tc!=null&&c.src_abs_in!=null){let a=c.src_abs_in-c.start_tc+Math.ceil((c.end-c.start)*Math.abs(o(c))*(c.fps_factor||1));l.set(c.file_path,Math.max(l.get(c.file_path)??0,a))}let d=n.map(c=>{let a=p.start_frame,r=[];for(let i of[...c.items].sort((u,f)=>u.start-f.start)){if(i.start<a)continue;i.start>a&&r.push({OTIO_SCHEMA:"Gap.1",name:"",source_range:t(0,i.start-a,s)});let u=i.src_fps||s,f=i.start_tc!=null&&l.has(i.file_path)?i.start_tc:null,v=f!=null?i.src_abs_in:i.src_in??i.src_abs_in??0,g=o(i);r.push({OTIO_SCHEMA:"Clip.2",name:i.name??b(i.file_path||""),enabled:i.enabled!==!1,source_range:t(v,i.end-i.start,u,s),media_references:{DEFAULT_MEDIA:{OTIO_SCHEMA:"ExternalReference.1",name:b(i.file_path||""),target_url:i.file_path?`file://${i.file_path}`:"",...f!=null?{available_range:t(f,l.get(i.file_path),u)}:{},metadata:{}}},active_media_reference_key:"DEFAULT_MEDIA",effects:Math.abs(g-1)>1e-6?[{OTIO_SCHEMA:"LinearTimeWarp.1",name:"",effect_name:"LinearTimeWarp",time_scalar:g}]:[],markers:[],metadata:i.reel?{cmx_3600:{reel:i.reel}}:{}}),a=i.end}return{OTIO_SCHEMA:"Track.1",name:c.name||`V${c.index}`,kind:"Video",enabled:c.enabled!==!1,children:r,effects:[],markers:[],metadata:{}}}),m=[];return p.audio_items?.length&&m.push(`${p.audio_items.length} audio clip(s) not carried: the host's plugin reports no audio source times`),p.transitions?.length&&m.push(`${p.transitions.length} transition(s) not carried (cuts in their place)`),{otio:{OTIO_SCHEMA:"Timeline.1",name:p.timeline,global_start_time:e(p.start_frame,s),metadata:{},tracks:{OTIO_SCHEMA:"Stack.1",name:"tracks",children:d,effects:[],markers:[],metadata:{}}},notes:m}}var X=16e3,G="Install the conform.tools panel (host_setup host=premiere action=install_panel), then in Premiere open Window > UXP Plugins > conform.tools. It connects by itself from then on.";var U=class extends ${constructor(t=j,s=X){super({host:"premiere",label:"Premiere Pro",setup:G},t,s);this.items=async(t={})=>{await this.needs("edit");let{seq:s}=await this.sequence(t.timeline),n=await this.ask("edit.items",{timeline:s,kind:t.kind,track:t.track},12e4),o=n.project_path?await K(n.project_path,n.timeline).catch(d=>({error:d instanceof Error?d.message:String(d)})):{error:"the project has never been saved"},l=0;if(!("error"in o))for(let d of n.items){let m=o.get(`${d.kind}:${d.track}:${d.start}:${Number(d.end)-Number(d.start)}`);m?Object.assign(d,m,{saved:!0}):(d.saved=!1,l++)}return{...n,color_groups:[],layers:1,..."error"in o?{saved_note:`saved project not read: ${o.error}`}:{unsaved_items:l}}};this.premiereRenders=new Map}async current(){let t=await this.ask("session.describe");return{project:t.project,timelines:t.timelines,timeline:t.current}}async liveMarkers(t){if(!$.announced(await this.peer(),"edit.markers"))return null;let{seq:s}=await this.sequence(t);return await this.ask("edit.markers",{timeline:s},12e4)}async model(t){return await super.model(t)}async projectClips(){return await this.needs("edit"),await this.ask("edit.project_clips",{},12e4)}async relinkClips(t){return await this.needs("edit"),await this.ask("edit.relink_clips",{items:t},6e4+t.length*2e3)}async cutIn(t,s){await this.needs("edit");let{seq:n}=await this.sequence(t);return await this.ask("edit.cut_in",{timeline:n,cuts:s},12e4+s.length*3e3)}async renderStart(t){if(t.range)throw new h("unsupported","premiere: a frame range is not supported yet; set in/out on the sequence in Premiere");if(!t.preset||!/\.epr$/i.test(t.preset))throw new h("usage","premiere: preset must be the path of a Media Encoder preset (.epr)");let{seq:s,name:n}=await this.sequence(t.timeline);await M(t.target_dir);let o=_(t.target_dir,`${t.name??n}.mov`),l=await this.ask("render.export_sequence",{timeline:s,output_path:o,preset_path:t.preset,queue:!1},6e4);if(!l.ok)throw new h("render_refused","premiere: Premiere refused the export");let d=l.job||`ppro-${Date.now()}`;return this.premiereRenders.set(d,o),{job_id:d,state:"rendering",percent:0}}async renderStatus(t){let s=await this.ask("render.progress"),n=s[t]??s.last,o=this.premiereRenders.get(t);return n?.event==="error"||n?.event==="onEncodeError"?{job_id:t,state:"failed",percent:0,error:String(n.data??"encode error")}:n?.event==="complete"||n?.event==="onEncodeComplete"||o&&await x(o)&&!n?{job_id:t,state:"complete",percent:100,...o?{outputs:[o]}:{}}:{job_id:t,state:"rendering",percent:typeof n?.data=="number"?Math.round(Number(n.data)*100):0}}async renderCancel(t){return{job_id:t,state:"cancelled",percent:0,error:"Premiere's export cannot be cancelled from here; cancel it in Premiere / Media Encoder"}}};async function K(p,e){let{session:t}=await D(p,"prproj"),s=t.timelines.find(o=>o.name===e),n=new Map;if(!s)throw new Error(`the saved project has no sequence "${e}" (saved before it was made?)`);for(let o of s.tracks)if(!(o.kind!=="Video"&&o.kind!=="Audio"))for(let l of o.items){if(l.kind==="gap"||l.kind==="transition")continue;let d=l;n.set(`${o.kind==="Video"?"video":"audio"}:${o.track_index}:${l.timeline_range.start.value}:${l.timeline_range.duration.value}`,{saved_id:l.id,...d.speed_factor!=null&&d.speed_factor!==1?{retime:d.speed_factor}:{},...d.speed_ramped?{ramped:!0}:{},...d.speed_reverse?{reversed:!0}:{},...l.kind==="nested"?{nested:!0}:{},...d.is_multicam?{multicam:!0}:{},...d.effects?.some(m=>/stabiliz/i.test(m.kind??""))?{stabilized:!0}:{},...d.effects?.length?{saved_effects:d.effects.map(m=>m.name??m.kind??"")}:{}})}return n}function z(p=y()){return p==="darwin"?"/Library/Application Support/Adobe/Adobe Desktop Common/RemoteComponents/UPI/UnifiedPluginInstallerAgent/UnifiedPluginInstallerAgent.app/Contents/MacOS/UnifiedPluginInstallerAgent":p==="win32"?"C:\\Program Files\\Common Files\\Adobe\\Adobe Desktop Common\\RemoteComponents\\UPI\\UnifiedPluginInstallerAgent\\UnifiedPluginInstallerAgent.exe":null}async function B(){for(let p of["./uxp-plugin/","./premiere-uxp/"]){let e=S(new URL(p,import.meta.url));if(await P(_(e,"manifest.json")))return e}throw new Error("premiere: the conform.tools panel is missing from this install")}async function Q(){return JSON.parse(await H(_(await B(),"manifest.json"))).version}async function oe(p=y()){let e=z(p);if(!e||!await x(e))return{installed:!1,listing:"Creative Cloud's plugin installer is not on this machine"};let t=await w(e,p==="win32"?["/list","all"]:["--list","all"],{timeoutMs:6e4}),s=t.stdout.split(`
|
|
4
4
|
`).find(n=>/CONFORM\.TOOLS|conformtools/i.test(n));return{installed:!!s&&/enabled|installed/i.test(s),version:s?.match(/(\d+\.\d+\.\d+)\s*$/)?.[1],listing:t.stdout.trim()}}async function ae(p=y()){let e=z(p);if(!e||!await x(e))throw new Error("premiere: Creative Cloud's plugin installer (UnifiedPluginInstallerAgent) is not on this machine; install Creative Cloud");let t=await B(),s=await Q(),n=await q("conform-ccx-");for(let a of["manifest.json","index.html","index.js","lib","icons"])await T(_(t,a),_(n,a));let o=_(O(),"premiere");await M(o);let l=I(_(o,`conformtools-premiere-${s}.ccx`));await R(l);let d=p==="darwin"?await w("sh",["-c",`cd '${n.replace(/'/g,"'\\''")}' && zip -r -q -X '${l.replace(/'/g,"'\\''")}' manifest.json index.html index.js lib icons`]):await w("powershell",["-NoProfile","-Command",`Compress-Archive -Path '${n}\\*' -DestinationPath '${l.replace(/\.ccx$/,".zip")}' -Force; Move-Item -Force '${l.replace(/\.ccx$/,".zip")}' '${l}'`]);if(await R(n),!d.success)throw new Error(`premiere: could not package the panel: ${d.stderr.trim()}`);await w(e,p==="win32"?["/remove","conform.tools"]:["--remove","conform.tools"],{timeoutMs:12e4});let m=await w(e,p==="win32"?["/install",l]:["--install",l],{timeoutMs:18e4}),c=`${m.stdout}
|
|
5
5
|
${m.stderr}`.trim();if(!m.success||!/Installation Successful/i.test(c))throw new Error(`premiere: Adobe's installer refused the panel: ${c.split(`
|
|
6
6
|
`).pop()}`);return{version:s,ccx:l,output:c}}export{$ as a,U as b,K as c,Q as d,oe as e,ae as f};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
-
import{c as le,d as ue,g as pe,h as fe,i as de}from"./chunk-VZ3XYHK4.js";import{a as me}from"./chunk-YJREJ2MH.js";import{a as s}from"./chunk-E75BCWXY.js";import{C as T,D as R,E as re,F as O,G as oe,P as ie,S as ae,W as se,X as ce,b as c,ea as l,h as y,i as te,o as h,p as b,v as ne,z as _}from"./chunk-QQBDHVUU.js";var Be=["pro","studio","enterprise"],gt=e=>Be.includes((e??"").toLowerCase()),ge=["align","reconform","conform-reference"],he=["autobalance","p2p","p2p-send","receive"],Fe={transferGB:2e3},g={payg:{id:"payg",name:"Pay As You Go",includes:{web:!0,mcp:!1,app:!1,studio_tools:!1}},web:{id:"web",name:"Indie",unlisted:!0,includes:{web:!0,mcp:!1,app:!1,studio_tools:!1},allowance:{transferGB:50}},indie:{id:"indie",name:"Pro",popular:!0,includes:{web:!0,mcp:!0,app:!0,studio_tools:!1},allowance:{transferGB:250}},pro:{id:"pro",name:"Studio",includes:{web:!0,mcp:!0,app:!0,studio_tools:!0},allowance:{transferGB:1e3}},studio:{id:"studio",name:"Enterprise",includes:{web:!0,mcp:!0,app:!0,studio_tools:!0},allowance:Fe}},_e={web:!0,mcp:!0,app:!0,studio_tools:!0};import{AsyncLocalStorage as xe}from"node:async_hooks";var M=()=>{throw new Error("this build has no local engine \u2014 timelines are read and written on conform.tools")};function we(e,t){return M()}function ye(e,t){return M()}function be(e){return M()}var Ge=new xe;function B(e){let t=Ge.getStore();if(!t||t.declared.includes(e))return;let n=`verb '${t.verb}' reached the protected stage '${e}' without declaring it in protectedStages (core/verbs.ts)`;if(c("CONFORM_STRICT_STAGES")==="1")throw new s("internal",n);console.error(`[conform] warning: ${n}`)}var F=!1,ze=new xe;function J(){let e=ze.getStore();if(e==="hosted")return"hosted";if(e==="local"){if(!!1)throw new s("unsupported","offline conversion needs the app's own engine (this build converts on conform.tools)");return"local"}return c("CONFORM_ENGINE")==="hosted"||!!1?"hosted":"local"}async function vt(e){return B("canonicalize"),J()==="local"?await we(e.fmt,e.data):await ve(e.fmt,e.file)}async function St(e,t){return B("write"),J()==="local"?await ye(e,t):await Se(e,t)}async function xt(e){if(J()!=="local")return null;B("canonicalize");let t=JSON.parse(await be(JSON.stringify(e)));return{session:t.session,issues:t.issues??[]}}import{createPrivateKey as Et,createPublicKey as Ke,sign as At,verify as We}from"node:crypto";import{Buffer as v}from"node:buffer";var He="CONFORMTOOLS_LICENSE_V1",ke=/^[0-9A-F]{8}(-[0-9A-F]{8}){3}$/,Oe=e=>JSON.stringify({dev_mode:e.dev_mode??!1,email:e.email,expires_at:e.expires_at,features:e.features,issued_at:e.issued_at,machine_fingerprint:e.machine_fingerprint,tier:e.tier});function Ee(e){let t=e.split(/\r?\n/).map(r=>r.trim()).filter(r=>r&&!r.startsWith("#")&&!r.startsWith("-----")).join(""),n=JSON.parse(v.from(t,"base64").toString("utf8"));if(n?.magic!==He||!n.payload?.data)throw new Error("not a conform.tools licence");return n.payload}function Ae(e,t){let n=v.from(e.signature,"base64"),r=v.from(Oe(e.data));return n.length!==64?!1:t.some(o=>We(null,r,Ke({key:v.concat([v.from("302a300506032b6570032100","hex"),v.from(o)]),format:"der",type:"spki"}),n))}var Ye=["cMwVBrEYKMzlG6pC7FF2lNKIoEqGz2xB5yph6clNnTg=","qnheqkkDU09l1oI6h2CFh4uQ97bY/hkTA5niGKH0+X8="],qe=Ye.map(e=>Uint8Array.from(atob(e),t=>t.charCodeAt(0)));function N(){let e=c("CONFORM_RECORDS_DIR");if(e)return e;let t=b(),n=y()==="darwin"?l(t,"Library/Application Support"):y()==="win32"?c("LOCALAPPDATA")??l(t,"AppData/Local"):c("XDG_DATA_HOME")??l(t,".local/share");return l(n,"conform.tools")}var Ve=()=>c("CONFORM_LICENSE_PATH")??l(N(),"license.lic"),$=()=>l(N(),"grant.lic"),Xe=null;function I(){return Xe??=(async()=>{let e=await me();if(!e)return[];let t=await ae(e,["machine"],{timeoutMs:15e3}).catch(()=>null);try{return JSON.parse(t?.stdout??"").machines.filter(n=>ke.test(n))}catch{return[]}})()}function Ze(e,t,n=Date.now()){if(!Ae(e,qe))return{ok:!1,reason:"invalid licence signature"};let r=Date.parse(e.data.expires_at);return!Number.isFinite(r)||r<n?{ok:!1,reason:`licence expired ${e.data.expires_at}`}:[t??[]].flat().includes(e.data.machine_fingerprint)?{ok:!0,data:e.data}:{ok:!1,reason:"licence is for another machine"}}async function Pe(){let e;try{e=await _(Ve())}catch{return null}try{return Ze(Ee(e),await I())}catch(t){return{ok:!1,reason:t.message}}}var Qe={production:{supabaseUrl:"https://sttpwvjbpsetzbhrkohl.supabase.co",anonKey:"sb_publishable_cyuIPsrQa5Ye7lqFxjnknQ_ozDuwwzp",appBase:"https://conform.tools"},staging:{supabaseUrl:"https://slxggvbvgzkiwojcgykx.supabase.co",anonKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InNseGdndmJ2Z3praXdvamNneWt4Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzEyODUzMTksImV4cCI6MjA4Njg2MTMxOX0.b18iDsWftny0k9VmOCcbN6kLlyZsZ7GULn_jRH9CE9I",appBase:"https://beta.conform.tools"}};function a(){let e=c("CONFORM_ENV")==="staging"?"staging":"production",t=Qe[e];return{env:e,supabaseUrl:c("CONFORM_SUPABASE_URL")??t.supabaseUrl,anonKey:c("CONFORM_SUPABASE_ANON_KEY")??t.anonKey,appBase:c("CONFORM_APP_BASE")??t.appBase}}var et=600*1e3,Te=72*3600*1e3,tt=300*1e3,S=()=>l(h(),a().env==="production"?"auth.json":`auth-${a().env}.json`);async function x(){for(let e of new Set([S(),l(h(),"auth.json")]))try{let t=JSON.parse(await _(e));if(t.env===a().env&&t.access_token)return t}catch{}return await rt()}var nt=()=>{let e=y()==="win32"?c("APPDATA")??l(b(),"AppData","Roaming"):y()==="darwin"?l(b(),"Library","Application Support"):c("XDG_CONFIG_HOME")??l(b(),".config");return l(e,"conform-tools","kv-store.json")};async function rt(){let e=nt();try{let t=JSON.parse(await _(e)),n=JSON.parse(t["ct-supabase-auth"]??"null");if(!n?.access_token||!n.refresh_token)return null;let r=n.access_token.split(".")[1].replace(/-/g,"+").replace(/_/g,"/");if(JSON.parse(atob(r+"=".repeat(-r.length&3))).iss!==`${a().supabaseUrl}/auth/v1`)return null;let i={env:a().env,access_token:n.access_token,refresh_token:n.refresh_token,expires_at:n.expires_at??0};return await L(i),delete t["ct-supabase-auth"],await T(e,JSON.stringify(t)),i}catch{return null}}async function ot(){try{for await(let e of ie(h())){if(!/^auth(?:-(\w+))?\.json$/.exec(e.name))continue;let n=JSON.parse(await _(l(h(),e.name)));if(n.access_token&&n.env&&n.env!==a().env)return{other_env:n.env}}}catch{}return{}}async function L(e){await R(h()),await T(S(),JSON.stringify(e)),await oe(S(),384)}var z=6e3,P=0,K=()=>Date.now()<P,$e=()=>{P=Date.now()+6e4};function Bt(){P=0}var Ie=e=>e.expires_at-60>Date.now()/1e3;async function G(e){let t=await x();return t&&t.refresh_token!==e.refresh_token&&Object.assign(e,t),Ie(e)}async function W(e){if(Ie(e))return e.access_token;if(K())return null;if(await G(e))return e.access_token;let t=await re(`${S()}.lock`);try{if(await G(e))return e.access_token;let n=a(),r=await fetch(`${n.supabaseUrl}/auth/v1/token?grant_type=refresh_token`,{method:"POST",headers:{apikey:n.anonKey,"content-type":"application/json"},body:JSON.stringify({refresh_token:e.refresh_token}),signal:AbortSignal.timeout(z)}).catch(i=>{throw $e(),i});if(!r.ok)return r.status!==400&&r.status!==401?null:await G(e)?e.access_token:"";let o=await r.json();return e.access_token=o.access_token,o.refresh_token&&(e.refresh_token=o.refresh_token),e.expires_at=o.expires_at??Math.floor(Date.now()/1e3)+(o.expires_in??3600),await L(e),e.access_token}catch{return null}finally{await t()}}async function Ft(){return(await x().catch(()=>null))?.last_entitlement?.model_key??null}async function Jt(){return(await H()).token}async function H(e="conform.tools"){let t=await x();if(!t)return m=null,{token:null,error:new s("not_signed_in",`${e}: not signed in to conform.tools \u2014 run account_login`)};let n=await W(t);return n?{token:n,error:null}:n===""?(m=null,{token:null,error:new s("not_signed_in",`${e}: the sign-in expired or was revoked \u2014 sign in again (account_login)`)}):{token:null,error:new s("offline",`${e}: couldn't reach conform.tools to renew the sign-in (no answer, or the server was busy). You are still signed in; it retries by itself \u2014 check the network if it keeps happening.`)}}var m=null;function Ne(e,t){return{signed_in:!0,entitled:e.entitled,env:a().env,email:e.email,access:e.access,tier:e.tier,trial_days_remaining:e.trial_days_remaining,source:t,...e.entitled?{}:{reason:"not_entitled"},...e.invite_only?{invite_only:!0}:{},...e.dev?{dev:!0}:{}}}async function Y(e={}){let t=await Pe();if(t?.ok)return{signed_in:!!await x().catch(()=>null),entitled:!0,env:a().env,email:t.data.email,access:"licence",tier:t.data.tier,source:"licence"};let n=await it(e);return t&&!n.entitled?{...n,licence_error:t.reason}:n}async function it(e){if(!e.force&&m&&Date.now()-m.at<et)return{...m.status,source:"cache"};let t=a(),n=await x();if(!n)return{signed_in:!1,entitled:!1,env:t.env,reason:"not_signed_in",...await ot()};let r=await W(n);if(r==="")return{signed_in:!0,entitled:!1,env:t.env,reason:"auth_rejected"};if(r&&!K())try{let o=(await I())[0],i=await fetch(`${t.supabaseUrl}/functions/v1/v1-billing/v1/billing/entitlement${o?`?machine=${o}`:""}`,{headers:{authorization:`Bearer ${r}`,apikey:t.anonKey},signal:AbortSignal.timeout(z)}).catch(u=>{throw $e(),u});if(i.status===401||i.status===403)return{signed_in:!0,entitled:!1,env:t.env,reason:"auth_rejected"};if(i.ok){let{grant:u,...p}=(await i.json()).data;o&&await at(u),n.last_entitlement=p,n.last_entitlement_at=Date.now(),await L(n);let f=Ne(p,"live");return m={at:Date.now(),status:f},f}}catch{}if(n.last_entitlement&&n.last_entitlement_at&&Date.now()-n.last_entitlement_at<Te){let o=Te-(Date.now()-n.last_entitlement_at);return{...Ne(n.last_entitlement,"grace"),grace_remaining_h:Math.round(o/36e4)/10}}return{signed_in:!0,entitled:!1,env:t.env,reason:"offline_grace_expired"}}async function at(e){try{if(!e)return await O($());await R(N()),await T($(),e)}catch{}}function st(e){return e.source==="licence"?`${e.email} \xB7 machine licence (${e.tier}) \u2014 runs offline, no account check`:ct(e)+(e.licence_error?`
|
|
3
|
+
import{c as le,d as ue,g as pe,h as fe,i as de}from"./chunk-VZ3XYHK4.js";import{a as me}from"./chunk-YJREJ2MH.js";import{a as s}from"./chunk-E75BCWXY.js";import{C as T,D as R,E as re,F as O,G as oe,P as ie,S as ae,W as se,X as ce,b as c,ea as l,h as y,i as te,o as h,p as b,v as ne,z as _}from"./chunk-QQBDHVUU.js";var Be=["pro","studio","enterprise"],gt=e=>Be.includes((e??"").toLowerCase()),ge=["align","reconform","conform-reference"],he=["autobalance","p2p","p2p-send","receive"],Fe={transferGB:2e3},g={payg:{id:"payg",name:"Pay As You Go",includes:{web:!0,mcp:!1,app:!1,studio_tools:!1}},web:{id:"web",name:"Indie",unlisted:!0,includes:{web:!0,mcp:!1,app:!1,studio_tools:!1},allowance:{transferGB:50}},indie:{id:"indie",name:"Pro",popular:!0,includes:{web:!0,mcp:!0,app:!0,studio_tools:!1},allowance:{transferGB:250}},pro:{id:"pro",name:"Studio",includes:{web:!0,mcp:!0,app:!0,studio_tools:!0},allowance:{transferGB:1e3}},studio:{id:"studio",name:"Enterprise",includes:{web:!0,mcp:!0,app:!0,studio_tools:!0},allowance:Fe}},_e={web:!0,mcp:!0,app:!0,studio_tools:!0};import{AsyncLocalStorage as xe}from"node:async_hooks";var M=()=>{throw new Error("this build has no local engine \u2014 timelines are read and written on conform.tools")};function we(e,t){return M()}function ye(e,t){return M()}function be(e){return M()}var Ge=new xe;function B(e){let t=Ge.getStore();if(!t||t.declared.includes(e))return;let n=`verb '${t.verb}' reached the protected stage '${e}' without declaring it in protectedStages (core/verbs.ts)`;if(c("CONFORM_STRICT_STAGES")==="1")throw new s("internal",n);console.error(`[conform] warning: ${n}`)}var F=!1,ze=new xe;function J(){let e=ze.getStore();if(e==="hosted")return"hosted";if(e==="local"){if(!!1)throw new s("unsupported","offline conversion needs the app's own engine (this build converts on conform.tools)");return"local"}return c("CONFORM_ENGINE")==="hosted"||!!1?"hosted":"local"}async function vt(e){return B("canonicalize"),J()==="local"?await we(e.fmt,e.data):await ve(e.fmt,e.file)}async function St(e,t){return B("write"),J()==="local"?await ye(e,t):await Se(e,t)}async function xt(e){if(J()!=="local")return null;B("canonicalize");let t=JSON.parse(await be(JSON.stringify(e)));return{session:t.session,issues:t.issues??[]}}import{createPrivateKey as Et,createPublicKey as Ke,sign as At,verify as We}from"node:crypto";import{Buffer as v}from"node:buffer";var He="CONFORMTOOLS_LICENSE_V1",ke=/^[0-9A-F]{8}(-[0-9A-F]{8}){3}$/,Oe=e=>JSON.stringify({dev_mode:e.dev_mode??!1,email:e.email,expires_at:e.expires_at,features:e.features,issued_at:e.issued_at,machine_fingerprint:e.machine_fingerprint,tier:e.tier});function Ee(e){let t=e.split(/\r?\n/).map(r=>r.trim()).filter(r=>r&&!r.startsWith("#")&&!r.startsWith("-----")).join(""),n=JSON.parse(v.from(t,"base64").toString("utf8"));if(n?.magic!==He||!n.payload?.data)throw new Error("not a conform.tools licence");return n.payload}function Ae(e,t){let n=v.from(e.signature,"base64"),r=v.from(Oe(e.data));return n.length!==64?!1:t.some(o=>We(null,r,Ke({key:v.concat([v.from("302a300506032b6570032100","hex"),v.from(o)]),format:"der",type:"spki"}),n))}var Ye=["cMwVBrEYKMzlG6pC7FF2lNKIoEqGz2xB5yph6clNnTg=","qnheqkkDU09l1oI6h2CFh4uQ97bY/hkTA5niGKH0+X8="],qe=Ye.map(e=>Uint8Array.from(atob(e),t=>t.charCodeAt(0)));function I(){let e=c("CONFORM_RECORDS_DIR");if(e)return e;let t=b(),n=y()==="darwin"?l(t,"Library/Application Support"):y()==="win32"?c("LOCALAPPDATA")??l(t,"AppData/Local"):c("XDG_DATA_HOME")??l(t,".local/share");return l(n,"conform.tools")}var Ve=()=>c("CONFORM_LICENSE_PATH")??l(I(),"license.lic"),N=()=>l(I(),"grant.lic"),Xe=null;function $(){return Xe??=(async()=>{let e=await me();if(!e)return[];let t=await ae(e,["machine"],{timeoutMs:15e3}).catch(()=>null);try{return JSON.parse(t?.stdout??"").machines.filter(n=>ke.test(n))}catch{return[]}})()}function Ze(e,t,n=Date.now()){if(!Ae(e,qe))return{ok:!1,reason:"invalid licence signature"};let r=Date.parse(e.data.expires_at);if(!Number.isFinite(r)||r<n)return{ok:!1,reason:`licence expired ${e.data.expires_at}`};let o=[t??[]].flat().filter(Boolean);return o.length?o.includes(e.data.machine_fingerprint)?{ok:!0,data:e.data}:{ok:!1,reason:"licence is for another machine"}:{ok:!1,reason:"this machine's ID could not be read (the conform.tools engine is not installed here)"}}async function Pe(){let e;try{e=await _(Ve())}catch{return null}try{return Ze(Ee(e),await $())}catch(t){return{ok:!1,reason:t.message}}}var Qe={production:{supabaseUrl:"https://sttpwvjbpsetzbhrkohl.supabase.co",anonKey:"sb_publishable_cyuIPsrQa5Ye7lqFxjnknQ_ozDuwwzp",appBase:"https://conform.tools"},staging:{supabaseUrl:"https://slxggvbvgzkiwojcgykx.supabase.co",anonKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InNseGdndmJ2Z3praXdvamNneWt4Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzEyODUzMTksImV4cCI6MjA4Njg2MTMxOX0.b18iDsWftny0k9VmOCcbN6kLlyZsZ7GULn_jRH9CE9I",appBase:"https://beta.conform.tools"}};function a(){let e=c("CONFORM_ENV")==="staging"?"staging":"production",t=Qe[e];return{env:e,supabaseUrl:c("CONFORM_SUPABASE_URL")??t.supabaseUrl,anonKey:c("CONFORM_SUPABASE_ANON_KEY")??t.anonKey,appBase:c("CONFORM_APP_BASE")??t.appBase}}var et=600*1e3,Te=72*3600*1e3,tt=300*1e3,S=()=>l(h(),a().env==="production"?"auth.json":`auth-${a().env}.json`);async function x(){for(let e of new Set([S(),l(h(),"auth.json")]))try{let t=JSON.parse(await _(e));if(t.env===a().env&&t.access_token)return t}catch{}return await rt()}var nt=()=>{let e=y()==="win32"?c("APPDATA")??l(b(),"AppData","Roaming"):y()==="darwin"?l(b(),"Library","Application Support"):c("XDG_CONFIG_HOME")??l(b(),".config");return l(e,"conform-tools","kv-store.json")};async function rt(){let e=nt();try{let t=JSON.parse(await _(e)),n=JSON.parse(t["ct-supabase-auth"]??"null");if(!n?.access_token||!n.refresh_token)return null;let r=n.access_token.split(".")[1].replace(/-/g,"+").replace(/_/g,"/");if(JSON.parse(atob(r+"=".repeat(-r.length&3))).iss!==`${a().supabaseUrl}/auth/v1`)return null;let i={env:a().env,access_token:n.access_token,refresh_token:n.refresh_token,expires_at:n.expires_at??0};return await L(i),delete t["ct-supabase-auth"],await T(e,JSON.stringify(t)),i}catch{return null}}async function ot(){try{for await(let e of ie(h())){if(!/^auth(?:-(\w+))?\.json$/.exec(e.name))continue;let n=JSON.parse(await _(l(h(),e.name)));if(n.access_token&&n.env&&n.env!==a().env)return{other_env:n.env}}}catch{}return{}}async function L(e){await R(h()),await T(S(),JSON.stringify(e)),await oe(S(),384)}var z=6e3,P=0,K=()=>Date.now()<P,Ne=()=>{P=Date.now()+6e4};function Bt(){P=0}var $e=e=>e.expires_at-60>Date.now()/1e3;async function G(e){let t=await x();return t&&t.refresh_token!==e.refresh_token&&Object.assign(e,t),$e(e)}async function W(e){if($e(e))return e.access_token;if(K())return null;if(await G(e))return e.access_token;let t=await re(`${S()}.lock`);try{if(await G(e))return e.access_token;let n=a(),r=await fetch(`${n.supabaseUrl}/auth/v1/token?grant_type=refresh_token`,{method:"POST",headers:{apikey:n.anonKey,"content-type":"application/json"},body:JSON.stringify({refresh_token:e.refresh_token}),signal:AbortSignal.timeout(z)}).catch(i=>{throw Ne(),i});if(!r.ok)return r.status!==400&&r.status!==401?null:await G(e)?e.access_token:"";let o=await r.json();return e.access_token=o.access_token,o.refresh_token&&(e.refresh_token=o.refresh_token),e.expires_at=o.expires_at??Math.floor(Date.now()/1e3)+(o.expires_in??3600),await L(e),e.access_token}catch{return null}finally{await t()}}async function Ft(){return(await x().catch(()=>null))?.last_entitlement?.model_key??null}async function Jt(){return(await H()).token}async function H(e="conform.tools"){let t=await x();if(!t)return m=null,{token:null,error:new s("not_signed_in",`${e}: not signed in to conform.tools \u2014 run account_login`)};let n=await W(t);return n?{token:n,error:null}:n===""?(m=null,{token:null,error:new s("not_signed_in",`${e}: the sign-in expired or was revoked \u2014 sign in again (account_login)`)}):{token:null,error:new s("offline",`${e}: couldn't reach conform.tools to renew the sign-in (no answer, or the server was busy). You are still signed in; it retries by itself \u2014 check the network if it keeps happening.`)}}var m=null;function Ie(e,t){return{signed_in:!0,entitled:e.entitled,env:a().env,email:e.email,access:e.access,tier:e.tier,trial_days_remaining:e.trial_days_remaining,source:t,...e.entitled?{}:{reason:"not_entitled"},...e.invite_only?{invite_only:!0}:{},...e.dev?{dev:!0}:{}}}async function Y(e={}){let t=await Pe();if(t?.ok)return{signed_in:!!await x().catch(()=>null),entitled:!0,env:a().env,email:t.data.email,access:"licence",tier:t.data.tier,source:"licence"};let n=await it(e);return t&&!n.entitled?{...n,licence_error:t.reason}:n}async function it(e){if(!e.force&&m&&Date.now()-m.at<et)return{...m.status,source:"cache"};let t=a(),n=await x();if(!n)return{signed_in:!1,entitled:!1,env:t.env,reason:"not_signed_in",...await ot()};let r=await W(n);if(r==="")return{signed_in:!0,entitled:!1,env:t.env,reason:"auth_rejected"};if(r&&!K())try{let o=(await $())[0],i=await fetch(`${t.supabaseUrl}/functions/v1/v1-billing/v1/billing/entitlement${o?`?machine=${o}`:""}`,{headers:{authorization:`Bearer ${r}`,apikey:t.anonKey},signal:AbortSignal.timeout(z)}).catch(u=>{throw Ne(),u});if(i.status===401||i.status===403)return{signed_in:!0,entitled:!1,env:t.env,reason:"auth_rejected"};if(i.ok){let{grant:u,...p}=(await i.json()).data;o&&await at(u),n.last_entitlement=p,n.last_entitlement_at=Date.now(),await L(n);let f=Ie(p,"live");return m={at:Date.now(),status:f},f}}catch{}if(n.last_entitlement&&n.last_entitlement_at&&Date.now()-n.last_entitlement_at<Te){let o=Te-(Date.now()-n.last_entitlement_at);return{...Ie(n.last_entitlement,"grace"),grace_remaining_h:Math.round(o/36e4)/10}}return{signed_in:!0,entitled:!1,env:t.env,reason:"offline_grace_expired"}}async function at(e){try{if(!e)return await O(N());await R(I()),await T(N(),e)}catch{}}function st(e){return e.source==="licence"?`${e.email} \xB7 machine licence (${e.tier}) \u2014 runs offline, no account check`:ct(e)+(e.licence_error?`
|
|
4
4
|
(the machine licence was not used: ${e.licence_error})`:"")}function ct(e){let t=a();if(!e.signed_in)return`not signed in (${t.env})${e.other_env?`; you are signed in to ${e.other_env} only (each server keeps its own sign-in)`:""}. Run the account_login tool, or \`npx -y conformtools@latest login\` in a terminal.`;if(e.reason==="auth_rejected")return"signed-in session was rejected (expired or revoked) \u2014 sign in again with account_login.";if(e.reason==="offline_grace_expired")return"offline for more than 72 h since the last account check \u2014 reconnect and run account_status.";let n=`${e.email??"(unknown email)"} \xB7 ${t.env}`;if(!e.entitled&&e.invite_only)return`${n}
|
|
5
5
|
the conform.tools engine (the MCP and the app) is invite-only for now, and ${e.email??"this account"} is not on the list. If that is the wrong Google account, run account_logout, then account_login with the invited one.`;if(!e.entitled)return`${n}
|
|
6
6
|
no active plan on ${e.email??"this account"}: the MCP is in the ${g.indie.name} plan and up. If that is the wrong Google account, run account_logout, then account_login and pick the account with the plan; otherwise choose a plan at ${t.appBase}/pricing, then run account_status.`;let r=e.access==="trial"?`trial, ${e.trial_days_remaining??"?"} day(s) left`:e.access==="allowlist"?"invited (early access)":`subscribed${e.tier?` (${q(e.tier)})`:""}`,o=D(e),i=o?` \xB7 includes ${[o.web&&"the web tools",o.mcp&&"the MCP",o.app&&"the app"].filter(Boolean).join(", ")||"the web tools"}`:"";return`${n}
|
|
7
|
-
${r}${i}${e.source==="grace"?` \u2014 offline, using the last check (${e.grace_remaining_h} h of grace left)`:""}`}function q(e){return g[e.toLowerCase()]?.name??e}function D(e){if(e.access==="trial")return _e;let t=(e.tier??"").toLowerCase();return(t==="enterprise"?g.studio:g[t])?.includes??null}var Le=()=>Y();function Gt(e){Le=e}async function De(){let e=await Le();if(e.entitled)return e;let t=e.signed_in&&e.reason==="not_entitled"?"not_entitled":"not_signed_in";throw new s(t,st(e),{account:e})}async function zt(){let e=await De();if(e.source==="licence"||D(e)?.mcp!==!1)return e;throw new s("not_entitled",`The conform.tools MCP is in the ${g.indie.name} plan and up. ${e.access==="trial"?"Your trial":`Your plan${e.tier?` (${q(e.tier)})`:""}`} includes Timeline Exchange on ${a().appBase}, but not the engine on this machine. Upgrade at ${a().appBase}/pricing, then run account_status.`,{account:e,needs:"mcp"})}async function lt(){let e=await De();if(e.source==="licence")return e;if(!D(e)?.app)throw new s("not_entitled",`The conform.tools app is in the ${g.indie.name} plan and up. ${e.access==="trial"?"Your trial":`Your plan${e.tier?` (${q(e.tier)})`:""}`} does not include the app. Upgrade at ${a().appBase}/pricing, then reopen the app.`,{account:e,needs:"app"});let t=await ft();if(t)throw new s("seat_in_use",`This seat is in use on ${t}. Each seat runs the app on one computer at a time: quit the app there (or sign out), or wait 15 minutes after it last ran, then reopen it here.`,{account:e,needs:"seat",in_use_by:t});return e}var Ce=()=>c("CONFORM_DEV")==="0",Kt=()=>!Ce()&&(F||m?.status.dev===!0);async function ut(){return!Ce()&&(F||(await Y().catch(()=>null))?.dev===!0)}async function Wt(e){if(!(!he.includes(e)||await ut()))throw new s("not_found",`no tool "${e}"`)}async function Ht(e){if(!ge.includes(e))return;let t=await lt();if(!(t.source==="licence"||D(t)?.studio_tools!==!1))throw new s("not_entitled",`This tool is in the ${g.pro.name} plan. Upgrade at ${a().appBase}/pricing.`,{account:t,needs:"studio_tools"})}var pt=240*1e3,A=null;async function ft(){if(A&&Date.now()-A.at<pt)return A.busy;let e=await Ue("POST").catch(()=>null);return A={at:Date.now(),busy:e},e}async function Ue(e){let t=a(),n=await x(),r=(await
|
|
7
|
+
${r}${i}${e.source==="grace"?` \u2014 offline, using the last check (${e.grace_remaining_h} h of grace left)`:""}`}function q(e){return g[e.toLowerCase()]?.name??e}function D(e){if(e.access==="trial")return _e;let t=(e.tier??"").toLowerCase();return(t==="enterprise"?g.studio:g[t])?.includes??null}var Le=()=>Y();function Gt(e){Le=e}async function De(){let e=await Le();if(e.entitled)return e;let t=e.signed_in&&e.reason==="not_entitled"?"not_entitled":"not_signed_in";throw new s(t,st(e),{account:e})}async function zt(){let e=await De();if(e.source==="licence"||D(e)?.mcp!==!1)return e;throw new s("not_entitled",`The conform.tools MCP is in the ${g.indie.name} plan and up. ${e.access==="trial"?"Your trial":`Your plan${e.tier?` (${q(e.tier)})`:""}`} includes Timeline Exchange on ${a().appBase}, but not the engine on this machine. Upgrade at ${a().appBase}/pricing, then run account_status.`,{account:e,needs:"mcp"})}async function lt(){let e=await De();if(e.source==="licence")return e;if(!D(e)?.app)throw new s("not_entitled",`The conform.tools app is in the ${g.indie.name} plan and up. ${e.access==="trial"?"Your trial":`Your plan${e.tier?` (${q(e.tier)})`:""}`} does not include the app. Upgrade at ${a().appBase}/pricing, then reopen the app.`,{account:e,needs:"app"});let t=await ft();if(t)throw new s("seat_in_use",`This seat is in use on ${t}. Each seat runs the app on one computer at a time: quit the app there (or sign out), or wait 15 minutes after it last ran, then reopen it here.`,{account:e,needs:"seat",in_use_by:t});return e}var Ce=()=>c("CONFORM_DEV")==="0",Kt=()=>!Ce()&&(F||m?.status.dev===!0);async function ut(){return!Ce()&&(F||(await Y().catch(()=>null))?.dev===!0)}async function Wt(e){if(!(!he.includes(e)||await ut()))throw new s("not_found",`no tool "${e}"`)}async function Ht(e){if(!ge.includes(e))return;let t=await lt();if(!(t.source==="licence"||D(t)?.studio_tools!==!1))throw new s("not_entitled",`This tool is in the ${g.pro.name} plan. Upgrade at ${a().appBase}/pricing.`,{account:t,needs:"studio_tools"})}var pt=240*1e3,A=null;async function ft(){if(A&&Date.now()-A.at<pt)return A.busy;let e=await Ue("POST").catch(()=>null);return A={at:Date.now(),busy:e},e}async function Ue(e){let t=a(),n=await x(),r=(await $())[0],o=n&&await W(n);if(!o||!r||K())return null;let i=await fetch(`${t.supabaseUrl}/functions/v1/v1-billing/v1/billing/seat`,{method:e,headers:{authorization:`Bearer ${o}`,apikey:t.anonKey,"content-type":"application/json"},body:JSON.stringify({machine:r,name:te()}),signal:AbortSignal.timeout(z)});return i.status===409?(await i.json()).in_use_by??"another computer":null}var E=null;function Yt(e={}){if(E)return E;let t=a(),n=crypto.randomUUID().replaceAll("-","");return E=new Promise((r,o)=>{let i=!1,u=d=>{i||(i=!0,clearTimeout(f),setTimeout(()=>p.close(),250),E=null,d())},p=ce({hostname:"127.0.0.1",port:0,onListen:async d=>{let k=`${t.appBase}/plugin-auth?client=engine&port=${d}&state=${n}`,w=await se(k);e.onUrl?.(k,w)}},async d=>{let k=new URL(d.url);if(k.pathname!=="/callback")return new Response("not found",{status:404});let w=k.searchParams,Z=w.get("access_token")??"",Q=w.get("refresh_token")??"",C=!!Z&&!!Q&&w.get("state")===n;if(C){let ee=Number(w.get("expires_at"));await L({env:t.env,access_token:Z,refresh_token:Q,expires_at:ee>0?ee:Math.floor(Date.now()/1e3)+3600}),m=null,P=0,Y({force:!0}).then(U=>u(()=>r(U)),U=>u(()=>o(U)))}return new Response(dt(C),{status:C?200:400,headers:{"content-type":"text/html; charset=utf-8"}})}),f=setTimeout(()=>u(()=>o(new s("not_signed_in","sign-in was not completed within 5 minutes"))),e.timeoutMs??tt)}),E}async function qt(){await Ue("DELETE").catch(()=>{}),A=null,m=null,P=0,await ne(S())&&await O(S()),await O(N()).catch(()=>{});let e=l(h(),"auth.json");try{JSON.parse(await _(e)).env===a().env&&await O(e)}catch{}}function dt(e){let[t,n]=e?["Connected","You're signed in \u2014 you can close this tab."]:["Sign-in failed","Please try again."];return`<!doctype html><meta charset=utf-8><title>conform.tools</title><body style='font:16px -apple-system,Helvetica,Arial,sans-serif;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;background:#f5f5f7;color:#1d1d1f'><div style='text-align:center'><div style='font-size:22px;font-weight:700'>conform<span style='color:#ff3c00'>.tools</span></div><div style='margin-top:14px;font-size:20px;font-weight:600'>${t}</div><div style='margin-top:6px;color:#6e6e73'>${n}</div></div></body>`}le(!0);var Re={aaf:"aaf",avb:"avb",prproj:"prproj",drt:"resolve-drt",otio:"otio",capcut:"capcut",flame:"flame-archive",fcpxml:"resolve-fcpxml",xmeml:"fcp-xml",blscene:"baselight-blscene"},rn=Object.keys(Re),mt=new Set([502,503,504,529,546]),V=(e,t)=>`${a().supabaseUrl}/functions/v1/${e}${t}`;async function X(){let{token:e,error:t}=await H("reading and writing timelines runs on conform.tools");if(!e&&c("CONFORM_ANONYMOUS_READ")==="1")return a().anonKey;if(!e)throw t;return e}async function Me(e,t){let n;for(let r=0;r<3;r++){try{let o=await fetch(e,t);if(!mt.has(o.status)||r===2)return o;n=new Error(`status ${o.status}`)}catch(o){if(n=o,r===2)break}await new Promise(o=>setTimeout(o,1500*(r+1)))}throw new s("offline",`conform.tools is unreachable (${n instanceof Error?n.message:String(n)}) \u2014 reading and writing timelines need the network`)}async function je(e,t){let r=(await e.json().catch(()=>({})))?.error?.message??`${t} failed (${e.status})`;throw e.status===401?new s("not_signed_in",`${r} \u2014 sign in again (account_login)`):e.status===402||e.status===403?new s("not_entitled",r):new s(e.status>=500?"engine":"refused",r)}async function ve(e,t){let n=Re[e];if(!n)throw new s("unsupported",`'${e}' timelines are not read by conform.tools yet`);let{fmt:r,extract:o}=await ue(t,n),i=JSON.stringify({format:r,source_filename:t.name,persist:!1}),{contentType:u,body:p}=await pe(i,typeof o=="string"?o:JSON.stringify(o)),f=await Me(V("v1-timeline-canonicalize","/v1/timeline-canonicalize"),{method:"POST",headers:{"content-type":u,authorization:`Bearer ${await X()}`,apikey:a().anonKey},body:p});f.ok||await je(f,"read");let d=await f.json();return JSON.stringify(d.session)}async function Se(e,t){let n=await Me(V("v1-write","/v1/write"),{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${await X()}`,apikey:a().anonKey,"x-engine-accept-delivery":"cdn"},body:JSON.stringify({target_format:e,session:t})});n.ok||await je(n,"write");let r=de(n.headers.get(fe))??[];if(n.headers.get("x-engine-delivery")==="cdn"){let i=await n.json(),u=await fetch(i.download_url);if(!u.ok)throw new s("engine",`download failed (${u.status})`);let p=new Uint8Array(await u.arrayBuffer());if(p.byteLength!==i.size)throw new s("engine",`download incomplete: ${p.byteLength} of ${i.size} bytes`);return{body:p,contentType:i.content_type,filenameSuggestion:i.filename,issues:r,serverSession:i.session_id??void 0}}let o=n.headers.get("content-disposition")?.match(/filename="([^"]+)"/)?.[1];return{body:new Uint8Array(await n.arrayBuffer()),contentType:n.headers.get("content-type")??"application/octet-stream",filenameSuggestion:o??`timeline.${e}`,issues:r,serverSession:n.headers.get("x-session-id")??void 0}}async function on(e,t,n){try{let r={"content-type":"application/json",authorization:`Bearer ${await X()}`,apikey:a().anonKey},o=d=>V("v1-sessions",`/v1/sessions/${encodeURIComponent(e)}/original${d}`),i=await fetch(o(""),{method:"POST",headers:r,body:JSON.stringify({filename:t,content_type:"application/octet-stream"})});if(!i.ok)return!1;let{key:u,upload:p}=await i.json();return(await fetch(p.url,{method:p.method??"PUT",headers:p.headers??{"content-type":"application/octet-stream"},body:n})).ok?(await fetch(o("/complete"),{method:"POST",headers:r,body:JSON.stringify({key:u})})).ok:!1}catch{return!1}}export{gt as a,he as b,g as c,rn as d,ve as e,Se as f,on as g,Ge as h,F as i,ze as j,J as k,vt as l,St as m,xt as n,$ as o,a as p,nt as q,z as r,Bt as s,Ft as t,Jt as u,H as v,Y as w,st as x,D as y,Gt as z,De as A,zt as B,lt as C,Kt as D,ut as E,Wt as F,Ht as G,Yt as H,qt as I};
|