conformtools 0.6.18 → 0.6.20
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/README.md +3 -2
- package/dist/{account-O3J732QJ.js → account-VD3EE5UT.js} +1 -1
- package/dist/{agent-hook-setup-HBT2LTVR.js → agent-hook-setup-D2QNHA3V.js} +1 -1
- package/dist/{analysis-engine-BZUEBW55.js → analysis-engine-VNGF3DE4.js} +1 -1
- package/dist/{bridge-25FGN67G.js → bridge-MLBUD6XW.js} +1 -1
- package/dist/browser/timeline_core_bg.wasm +0 -0
- package/dist/{chunk-ND2YUUUH.js → chunk-2S2ZPQQD.js} +1 -1
- package/dist/{chunk-S5AOIOTT.js → chunk-2WNNDPVR.js} +1 -1
- package/dist/chunk-2XQ42O7E.js +7 -0
- package/dist/{chunk-34JO3JNC.js → chunk-3WJSWOCS.js} +1 -1
- package/dist/{chunk-AYUKWSCR.js → chunk-4UT55WZA.js} +1 -1
- package/dist/{chunk-TD3ZHREE.js → chunk-4V3KLFCJ.js} +1 -1
- package/dist/chunk-6IL7M3VP.js +162 -0
- package/dist/chunk-A7AYMSY7.js +9 -0
- package/dist/chunk-COALWMI7.js +4 -0
- package/dist/chunk-GBNPOZ32.js +10 -0
- package/dist/{chunk-PIM3PV5N.js → chunk-GHP6HDLM.js} +1 -1
- package/dist/{chunk-3DYCTUSQ.js → chunk-HCT34NDA.js} +1 -1
- package/dist/{chunk-DIW5X4GI.js → chunk-HROU7LLU.js} +1 -1
- package/dist/{chunk-ANQZKVDD.js → chunk-IPQLKAF2.js} +1 -1
- package/dist/chunk-JVJUJKUP.js +5 -0
- package/dist/chunk-M545OKDZ.js +6 -0
- package/dist/chunk-MU5AGXSH.js +3 -0
- package/dist/chunk-OSPDH2RK.js +6 -0
- package/dist/{chunk-MHBNMYZP.js → chunk-V2FVIZT7.js} +1 -1
- package/dist/chunk-WYI4LL4P.js +535 -0
- package/dist/chunk-Y7PFSVRX.js +3 -0
- package/dist/chunk-ZAL7Y5VZ.js +7 -0
- package/dist/{claude-setup-W27DLJIO.js → claude-setup-AI4WXN2V.js} +1 -1
- package/dist/cli.js +2 -2
- package/dist/demo-engine-MOHHYVGV.js +3 -0
- package/dist/engine-WMOJ3HRU.js +5 -0
- package/dist/framing-U46POZQG.js +3 -0
- package/dist/gfx-worker.js +1 -1
- package/dist/{h264-YX5KP63E.js → h264-4ETGWMKR.js} +1 -1
- package/dist/{h264-mxf-VAHIJCA7.js → h264-mxf-EFHHQL7X.js} +1 -1
- package/dist/hook.js +3 -2
- package/dist/host-relink-MVHI3YQI.js +10 -0
- package/dist/hosted-6BLHLZXM.js +3 -0
- package/dist/hosts-7UO4QETB.js +3 -0
- package/dist/http.js +4 -3
- package/dist/{inspect-7XEE32P5.js → inspect-5TMUYGAL.js} +17 -17
- package/dist/{isobmff-RHP3N5K2.js → isobmff-55TPOVCK.js} +1 -1
- package/dist/{mc-video-CHBOYPI5.js → mc-video-GKWEWCEQ.js} +1 -1
- package/dist/mcp.js +8 -8
- package/dist/media-HCKSVARE.js +3 -0
- package/dist/{mxf-R2ONKSYU.js → mxf-AJTCMKTX.js} +1 -1
- package/dist/{ops-MKDFWWPG.js → ops-UGZODMYE.js} +1 -1
- package/dist/{probe-YDOFGCGD.js → probe-YOYK7HR5.js} +1 -1
- package/dist/{r3d-F4OWLQE2.js → r3d-XHSJUARW.js} +1 -1
- package/dist/resolve-bridge.py +173 -27
- package/dist/{sequence-patch-2S7IPE52.js → sequence-patch-5MFTY52Q.js} +1 -1
- package/dist/{store-A5AKWOSX.js → store-6XN5Q6UG.js} +1 -1
- package/dist/{timeline-ZHDJXDZJ.js → timeline-TFF3L7JP.js} +1 -1
- package/dist/timeline_core-6BRZG4LP.js +3 -0
- package/package.json +5 -5
- package/dist/chunk-2V5PY4P5.js +0 -5
- package/dist/chunk-6B3IELRW.js +0 -6
- package/dist/chunk-AAJRTGEP.js +0 -10
- package/dist/chunk-GTPTZRO6.js +0 -3
- package/dist/chunk-IDEKLW7C.js +0 -3
- package/dist/chunk-LP2MR4ZH.js +0 -516
- package/dist/chunk-NN444GPH.js +0 -6
- package/dist/chunk-QBQJDV2F.js +0 -161
- package/dist/chunk-ROGMKTND.js +0 -4
- package/dist/chunk-RXRBRR3E.js +0 -10
- package/dist/chunk-T7S2UBNN.js +0 -7
- package/dist/chunk-UIX3TT72.js +0 -7
- package/dist/demo-engine-JAQPM4EV.js +0 -3
- package/dist/engine-ZGBF3SQN.js +0 -5
- package/dist/framing-PGFJZIBU.js +0 -3
- package/dist/host-relink-M2VWUZW5.js +0 -10
- package/dist/hosted-4CNQYNX5.js +0 -3
- package/dist/hosts-R4BHIZJS.js +0 -3
- package/dist/media-4VUWQJLQ.js +0 -3
- package/dist/timeline_core-ZKQQHUA2.js +0 -3
|
@@ -0,0 +1,535 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
+
import{a as Zb}from"./chunk-JVJUJKUP.js";import{a as Ub,b as Gb,c as Ou,d as Hb,e as zb,f as Wb,j as an}from"./chunk-A7AYMSY7.js";import{d as Kb,e as Vb,f as Jb}from"./chunk-OSPDH2RK.js";import{c as Xb,d as Qb,e as Yb}from"./chunk-2WNNDPVR.js";import{$ as Fa,$a as jg,$b as Ba,$c as Pu,Aa as fg,Ab as Eo,Ba as La,Bb as Ru,Ca as hg,Cb as Da,Da as gg,Db as ob,Ea as bg,Eb as sb,Fa as xu,G as m,Ga as yg,Gc as Eu,H as Eh,Ha as wg,Hc as Mu,I as pu,Ia as kg,Ic as Rb,Ja as Na,Jc as Cb,K as t1,Ka as _g,Kc as gi,L as n1,La as vg,M as r1,Ma as Tg,Mc as Ua,N as a1,Na as xg,Nc as Ab,O as xa,Oa as Sg,Oc as Eb,P as l1,Pa as $g,Pc as Iu,Qa as Rg,Qc as Mb,R as c1,Ra as Cg,Rb as ib,Rc as Ib,S as u1,Sa as Ag,Sc as Pb,T as mu,Ta as Eg,U as mi,Ua as Mg,V as Co,Va as Ig,Vb as ds,Vc as Fb,W as V1,Wa as Pg,Wb as Cr,Wc as Ob,X as J1,Xa as Fg,Xb as ab,Xc as Lb,Y as X1,Ya as Og,Yb as lb,Z as Q1,Za as Lg,Zb as cb,Zc as Ga,_ as yu,_a as Ng,_b as ub,aa as Y1,ab as Dg,ad as Ha,ba as Z1,bb as Bg,bc as db,ca as eg,cb as qg,cc as qa,cd as Nb,da as tg,db as Ug,dc as Cu,dd as jb,ea as fi,eb as Gg,ec as pb,ed as Db,fa as ng,fb as ja,fc as mb,ga as hi,gb as Hg,gc as fb,gd as Fu,ha as rg,hb as zg,hc as hb,hd as Bb,ia as wu,ib as Wg,ic as gb,id as qb,ja as og,jb as Ao,jc as Au,ka as ku,kb as Su,kd as za,la as Pt,lb as Zt,ma as us,mb as Kg,na as _u,nb as Vg,oa as Oa,ob as $u,pa as sg,pb as Jg,pc as bb,qa as ig,qb as Xg,ra as ag,rb as Qg,rc as yb,sa as lg,sb as Sn,sc as wb,ta as cg,tc as kb,ua as ug,ub as Yg,uc as _b,va as dg,vb as Zg,vc as vb,wa as pg,wb as eb,wc as Tb,xa as mg,xb as tb,xc as xb,ya as vu,yb as nb,yc as ps,za as Tu,zb as rb,zc as $b}from"./chunk-6IL7M3VP.js";import{a as Ro,b as or,c as di,d as U1,e as bu,g as Ea,h as pi,k as Ma,l as st,m as G1,n as H1,q as Ia,t as z1,u as Pa,v as W1,w as K1}from"./chunk-GBNPOZ32.js";import{a as Hr,b as rr,c as B1}from"./chunk-3PVQ5QP4.js";import{b as L1,e as N1,f as Ca}from"./chunk-VFXMP7IF.js";import{a as ka,c as Ch,e as Ah}from"./chunk-GHP6HDLM.js";import{c as P1}from"./chunk-JV7TZDKJ.js";import{b as F1,c as O1}from"./chunk-BBCQMZQN.js";import{a as E1,b as M1,d as I1,e as Ra}from"./chunk-2DEUYEQD.js";import{d as j1,e as D1,f as So,i as $o}from"./chunk-2S2ZPQQD.js";import{e as s1,f as i1}from"./chunk-Y7PFSVRX.js";import{M as o1,S as cs}from"./chunk-C2ESM27Z.js";import{c as ey,d as Lu,e as Nu,f as ju,g as ty,h as ny,i as ry,k as oy,m as sy,n as iy}from"./chunk-HROU7LLU.js";import{l as Sb}from"./chunk-N34DQ6MH.js";import{a as q1,b as He,d as At,e as Aa,f as yr}from"./chunk-NU3X7P4N.js";import{A as b1,E as y1,Ea as C1,F as w1,Fa as A1,G as hu,Ha as Gr,L as k1,N as _1,P as v1,Q as T1,S as x1,T as S1,V as gu,c as Sa,d as d1,f as p1,h as m1,i as $a,l as f1,m as h1,ma as $1,v as fu,z as g1,za as R1}from"./chunk-L2RTMZCN.js";import{A as Kn,B as Yh,C as ft,D as Yt,E as Zh,F as Ta,G as e1,a as ci,b as Bh,c as qh,d as Uh,e as lu,f as zn,g as Gh,h as Wn,i as Hh,j as zh,k as Wh,l as cu,m as Kh,n as uu,o as Vh,p as Qt,q as ui,r as du,s as Jh,u as va,v as Xh,w as xo,x as Qh}from"./chunk-3WJSWOCS.js";import{a as iu,b as Mh,c as Ph,d as li,h as Fh,i as Oh,j as ls,k as au,o as Lh,q as Nh,r as jh,s as Dh}from"./chunk-2XQ42O7E.js";import{b as _a,c as qt,d as Ih}from"./chunk-M545OKDZ.js";import{a as P,b as Q,c as St,d as ee}from"./chunk-COALWMI7.js";import{$ as To,A as Gn,B as Ke,C as Ve,E as Wt,G as wa,H as vo,I as dn,K as Th,M as xh,N as It,O as Ct,P as ou,R as sn,S as Sh,T as br,U as $h,Z as su,_ as Rh,aa as fe,b as zt,ba as xn,ca as Hn,d as nu,da as re,h as Xt,k as ru,l as wh,m as kh,o as tt,p as ai,q as mt,s as _h,t as _o,u as Bt,v as Ye,w as On,x as vh,y as Ut,z as ct}from"./chunk-MU5AGXSH.js";import{c as Ie,f as H$}from"./chunk-PSANHDZM.js";var rn=Ie(id=>{"use strict";Object.defineProperty(id,"__esModule",{value:!0});var i0;(function(e){e[e.NONE=0]="NONE";let n=1;e[e._abstract=n]="_abstract";let r=n+1;e[e._accessor=r]="_accessor";let o=r+1;e[e._as=o]="_as";let s=o+1;e[e._assert=s]="_assert";let i=s+1;e[e._asserts=i]="_asserts";let a=i+1;e[e._async=a]="_async";let l=a+1;e[e._await=l]="_await";let c=l+1;e[e._checks=c]="_checks";let u=c+1;e[e._constructor=u]="_constructor";let d=u+1;e[e._declare=d]="_declare";let p=d+1;e[e._enum=p]="_enum";let f=p+1;e[e._exports=f]="_exports";let h=f+1;e[e._from=h]="_from";let g=h+1;e[e._get=g]="_get";let b=g+1;e[e._global=b]="_global";let k=b+1;e[e._implements=k]="_implements";let w=k+1;e[e._infer=w]="_infer";let y=w+1;e[e._interface=y]="_interface";let _=y+1;e[e._is=_]="_is";let v=_+1;e[e._keyof=v]="_keyof";let T=v+1;e[e._mixins=T]="_mixins";let $=T+1;e[e._module=$]="_module";let x=$+1;e[e._namespace=x]="_namespace";let R=x+1;e[e._of=R]="_of";let C=R+1;e[e._opaque=C]="_opaque";let B=C+1;e[e._out=B]="_out";let L=B+1;e[e._override=L]="_override";let Z=L+1;e[e._private=Z]="_private";let X=Z+1;e[e._protected=X]="_protected";let O=X+1;e[e._proto=O]="_proto";let ae=O+1;e[e._public=ae]="_public";let W=ae+1;e[e._readonly=W]="_readonly";let ne=W+1;e[e._require=ne]="_require";let z=ne+1;e[e._satisfies=z]="_satisfies";let q=z+1;e[e._set=q]="_set";let j=q+1;e[e._static=j]="_static";let I=j+1;e[e._symbol=I]="_symbol";let S=I+1;e[e._type=S]="_type";let A=S+1;e[e._unique=A]="_unique";let U=A+1;e[e._using=U]="_using"})(i0||(id.ContextualKeyword=i0={}))});var et=Ie(ll=>{"use strict";Object.defineProperty(ll,"__esModule",{value:!0});var he;(function(e){e[e.PRECEDENCE_MASK=15]="PRECEDENCE_MASK";let n=16;e[e.IS_KEYWORD=n]="IS_KEYWORD";let r=32;e[e.IS_ASSIGN=r]="IS_ASSIGN";let o=64;e[e.IS_RIGHT_ASSOCIATIVE=o]="IS_RIGHT_ASSOCIATIVE";let s=128;e[e.IS_PREFIX=s]="IS_PREFIX";let i=256;e[e.IS_POSTFIX=i]="IS_POSTFIX";let a=512;e[e.IS_EXPRESSION_START=a]="IS_EXPRESSION_START";let l=512;e[e.num=l]="num";let c=1536;e[e.bigint=c]="bigint";let u=2560;e[e.decimal=u]="decimal";let d=3584;e[e.regexp=d]="regexp";let p=4608;e[e.string=p]="string";let f=5632;e[e.name=f]="name";let h=6144;e[e.eof=h]="eof";let g=7680;e[e.bracketL=g]="bracketL";let b=8192;e[e.bracketR=b]="bracketR";let k=9728;e[e.braceL=k]="braceL";let w=10752;e[e.braceBarL=w]="braceBarL";let y=11264;e[e.braceR=y]="braceR";let _=12288;e[e.braceBarR=_]="braceBarR";let v=13824;e[e.parenL=v]="parenL";let T=14336;e[e.parenR=T]="parenR";let $=15360;e[e.comma=$]="comma";let x=16384;e[e.semi=x]="semi";let R=17408;e[e.colon=R]="colon";let C=18432;e[e.doubleColon=C]="doubleColon";let B=19456;e[e.dot=B]="dot";let L=20480;e[e.question=L]="question";let Z=21504;e[e.questionDot=Z]="questionDot";let X=22528;e[e.arrow=X]="arrow";let O=23552;e[e.template=O]="template";let ae=24576;e[e.ellipsis=ae]="ellipsis";let W=25600;e[e.backQuote=W]="backQuote";let ne=27136;e[e.dollarBraceL=ne]="dollarBraceL";let z=27648;e[e.at=z]="at";let q=29184;e[e.hash=q]="hash";let j=29728;e[e.eq=j]="eq";let I=30752;e[e.assign=I]="assign";let S=32640;e[e.preIncDec=S]="preIncDec";let A=33664;e[e.postIncDec=A]="postIncDec";let U=34432;e[e.bang=U]="bang";let de=35456;e[e.tilde=de]="tilde";let te=35841;e[e.pipeline=te]="pipeline";let _e=36866;e[e.nullishCoalescing=_e]="nullishCoalescing";let Se=37890;e[e.logicalOR=Se]="logicalOR";let H=38915;e[e.logicalAND=H]="logicalAND";let le=39940;e[e.bitwiseOR=le]="bitwiseOR";let pe=40965;e[e.bitwiseXOR=pe]="bitwiseXOR";let xe=41990;e[e.bitwiseAND=xe]="bitwiseAND";let ve=43015;e[e.equality=ve]="equality";let Oe=44040;e[e.lessThan=Oe]="lessThan";let ue=45064;e[e.greaterThan=ue]="greaterThan";let me=46088;e[e.relationalOrEqual=me]="relationalOrEqual";let ge=47113;e[e.bitShiftL=ge]="bitShiftL";let Re=48137;e[e.bitShiftR=Re]="bitShiftR";let Le=49802;e[e.plus=Le]="plus";let Ne=50826;e[e.minus=Ne]="minus";let We=51723;e[e.modulo=We]="modulo";let pt=52235;e[e.star=pt]="star";let Nt=53259;e[e.slash=Nt]="slash";let yn=54348;e[e.exponent=yn]="exponent";let En=55296;e[e.jsxName=En]="jsxName";let Mn=56320;e[e.jsxText=Mn]="jsxText";let hr=57344;e[e.jsxEmptyText=hr]="jsxEmptyText";let In=58880;e[e.jsxTagStart=In]="jsxTagStart";let Pn=59392;e[e.jsxTagEnd=Pn]="jsxTagEnd";let wn=60928;e[e.typeParameterStart=wn]="typeParameterStart";let tr=61440;e[e.nonNullAssertion=tr]="nonNullAssertion";let si=62480;e[e._break=si]="_break";let ns=63504;e[e._case=ns]="_case";let V=64528;e[e._catch=V]="_catch";let be=65552;e[e._continue=be]="_continue";let we=66576;e[e._debugger=we]="_debugger";let $e=67600;e[e._default=$e]="_default";let De=68624;e[e._do=De]="_do";let Pe=69648;e[e._else=Pe]="_else";let Xe=70672;e[e._finally=Xe]="_finally";let yt=71696;e[e._for=yt]="_for";let Je=73232;e[e._function=Je]="_function";let Mt=73744;e[e._if=Mt]="_if";let jt=74768;e[e._return=jt]="_return";let Dt=75792;e[e._switch=Dt]="_switch";let on=77456;e[e._throw=on]="_throw";let cn=77840;e[e._try=cn]="_try";let vn=78864;e[e._var=vn]="_var";let Tn=79888;e[e._let=Tn]="_let";let Fn=80912;e[e._const=Fn]="_const";let gr=81936;e[e._while=gr]="_while";let yo=82960;e[e._with=yo]="_with";let un=84496;e[e._new=un]="_new";let wo=85520;e[e._this=wo]="_this";let rs=86544;e[e._super=rs]="_super";let ii=87568;e[e._class=ii]="_class";let os=88080;e[e._extends=os]="_extends";let ko=89104;e[e._export=ko]="_export";let nr=90640;e[e._import=nr]="_import";let Ur=91664;e[e._yield=Ur]="_yield";let ss=92688;e[e._null=ss]="_null";let is=93712;e[e._true=is]="_true";let as=94736;e[e._false=as]="_false";let Yc=95256;e[e._in=Yc]="_in";let Zc=96280;e[e._instanceof=Zc]="_instanceof";let eu=97936;e[e._typeof=eu]="_typeof";let tu=98960;e[e._void=tu]="_void";let C$=99984;e[e._delete=C$]="_delete";let A$=100880;e[e._async=A$]="_async";let E$=101904;e[e._get=E$]="_get";let M$=102928;e[e._set=M$]="_set";let I$=103952;e[e._declare=I$]="_declare";let P$=104976;e[e._readonly=P$]="_readonly";let F$=106e3;e[e._abstract=F$]="_abstract";let O$=107024;e[e._static=O$]="_static";let L$=107536;e[e._public=L$]="_public";let N$=108560;e[e._private=N$]="_private";let j$=109584;e[e._protected=j$]="_protected";let D$=110608;e[e._override=D$]="_override";let B$=112144;e[e._as=B$]="_as";let q$=113168;e[e._enum=q$]="_enum";let U$=114192;e[e._type=U$]="_type";let G$=115216;e[e._implements=G$]="_implements"})(he||(ll.TokenType=he={}));function oC(e){switch(e){case he.num:return"num";case he.bigint:return"bigint";case he.decimal:return"decimal";case he.regexp:return"regexp";case he.string:return"string";case he.name:return"name";case he.eof:return"eof";case he.bracketL:return"[";case he.bracketR:return"]";case he.braceL:return"{";case he.braceBarL:return"{|";case he.braceR:return"}";case he.braceBarR:return"|}";case he.parenL:return"(";case he.parenR:return")";case he.comma:return",";case he.semi:return";";case he.colon:return":";case he.doubleColon:return"::";case he.dot:return".";case he.question:return"?";case he.questionDot:return"?.";case he.arrow:return"=>";case he.template:return"template";case he.ellipsis:return"...";case he.backQuote:return"`";case he.dollarBraceL:return"${";case he.at:return"@";case he.hash:return"#";case he.eq:return"=";case he.assign:return"_=";case he.preIncDec:return"++/--";case he.postIncDec:return"++/--";case he.bang:return"!";case he.tilde:return"~";case he.pipeline:return"|>";case he.nullishCoalescing:return"??";case he.logicalOR:return"||";case he.logicalAND:return"&&";case he.bitwiseOR:return"|";case he.bitwiseXOR:return"^";case he.bitwiseAND:return"&";case he.equality:return"==/!=";case he.lessThan:return"<";case he.greaterThan:return">";case he.relationalOrEqual:return"<=/>=";case he.bitShiftL:return"<<";case he.bitShiftR:return">>/>>>";case he.plus:return"+";case he.minus:return"-";case he.modulo:return"%";case he.star:return"*";case he.slash:return"/";case he.exponent:return"**";case he.jsxName:return"jsxName";case he.jsxText:return"jsxText";case he.jsxEmptyText:return"jsxEmptyText";case he.jsxTagStart:return"jsxTagStart";case he.jsxTagEnd:return"jsxTagEnd";case he.typeParameterStart:return"typeParameterStart";case he.nonNullAssertion:return"nonNullAssertion";case he._break:return"break";case he._case:return"case";case he._catch:return"catch";case he._continue:return"continue";case he._debugger:return"debugger";case he._default:return"default";case he._do:return"do";case he._else:return"else";case he._finally:return"finally";case he._for:return"for";case he._function:return"function";case he._if:return"if";case he._return:return"return";case he._switch:return"switch";case he._throw:return"throw";case he._try:return"try";case he._var:return"var";case he._let:return"let";case he._const:return"const";case he._while:return"while";case he._with:return"with";case he._new:return"new";case he._this:return"this";case he._super:return"super";case he._class:return"class";case he._extends:return"extends";case he._export:return"export";case he._import:return"import";case he._yield:return"yield";case he._null:return"null";case he._true:return"true";case he._false:return"false";case he._in:return"in";case he._instanceof:return"instanceof";case he._typeof:return"typeof";case he._void:return"void";case he._delete:return"delete";case he._async:return"async";case he._get:return"get";case he._set:return"set";case he._declare:return"declare";case he._readonly:return"readonly";case he._abstract:return"abstract";case he._static:return"static";case he._public:return"public";case he._private:return"private";case he._protected:return"protected";case he._override:return"override";case he._as:return"as";case he._enum:return"enum";case he._type:return"type";case he._implements:return"implements";default:return""}}ll.formatTokenType=oC});var ul=Ie(Ci=>{"use strict";Object.defineProperty(Ci,"__esModule",{value:!0});var sC=rn(),iC=et(),ad=class{constructor(t,n,r){this.startTokenIndex=t,this.endTokenIndex=n,this.isFunctionScope=r}};Ci.Scope=ad;var cl=class{constructor(t,n,r,o,s,i,a,l,c,u,d,p,f){this.potentialArrowAt=t,this.noAnonFunctionType=n,this.inDisallowConditionalTypesContext=r,this.tokensLength=o,this.scopesLength=s,this.pos=i,this.type=a,this.contextualKeyword=l,this.start=c,this.end=u,this.isType=d,this.scopeDepth=p,this.error=f}};Ci.StateSnapshot=cl;var ld=class e{constructor(){e.prototype.__init.call(this),e.prototype.__init2.call(this),e.prototype.__init3.call(this),e.prototype.__init4.call(this),e.prototype.__init5.call(this),e.prototype.__init6.call(this),e.prototype.__init7.call(this),e.prototype.__init8.call(this),e.prototype.__init9.call(this),e.prototype.__init10.call(this),e.prototype.__init11.call(this),e.prototype.__init12.call(this),e.prototype.__init13.call(this)}__init(){this.potentialArrowAt=-1}__init2(){this.noAnonFunctionType=!1}__init3(){this.inDisallowConditionalTypesContext=!1}__init4(){this.tokens=[]}__init5(){this.scopes=[]}__init6(){this.pos=0}__init7(){this.type=iC.TokenType.eof}__init8(){this.contextualKeyword=sC.ContextualKeyword.NONE}__init9(){this.start=0}__init10(){this.end=0}__init11(){this.isType=!1}__init12(){this.scopeDepth=0}__init13(){this.error=null}snapshot(){return new cl(this.potentialArrowAt,this.noAnonFunctionType,this.inDisallowConditionalTypesContext,this.tokens.length,this.scopes.length,this.pos,this.type,this.contextualKeyword,this.start,this.end,this.isType,this.scopeDepth,this.error)}restoreFromSnapshot(t){this.potentialArrowAt=t.potentialArrowAt,this.noAnonFunctionType=t.noAnonFunctionType,this.inDisallowConditionalTypesContext=t.inDisallowConditionalTypesContext,this.tokens.length=t.tokensLength,this.scopes.length=t.scopesLength,this.pos=t.pos,this.type=t.type,this.contextualKeyword=t.contextualKeyword,this.start=t.start,this.end=t.end,this.isType=t.isType,this.scopeDepth=t.scopeDepth,this.error=t.error}};Ci.default=ld});var Nn=Ie(dl=>{"use strict";Object.defineProperty(dl,"__esModule",{value:!0});var Vr;(function(e){e[e.backSpace=8]="backSpace";let n=10;e[e.lineFeed=n]="lineFeed";let r=9;e[e.tab=r]="tab";let o=13;e[e.carriageReturn=o]="carriageReturn";let s=14;e[e.shiftOut=s]="shiftOut";let i=32;e[e.space=i]="space";let a=33;e[e.exclamationMark=a]="exclamationMark";let l=34;e[e.quotationMark=l]="quotationMark";let c=35;e[e.numberSign=c]="numberSign";let u=36;e[e.dollarSign=u]="dollarSign";let d=37;e[e.percentSign=d]="percentSign";let p=38;e[e.ampersand=p]="ampersand";let f=39;e[e.apostrophe=f]="apostrophe";let h=40;e[e.leftParenthesis=h]="leftParenthesis";let g=41;e[e.rightParenthesis=g]="rightParenthesis";let b=42;e[e.asterisk=b]="asterisk";let k=43;e[e.plusSign=k]="plusSign";let w=44;e[e.comma=w]="comma";let y=45;e[e.dash=y]="dash";let _=46;e[e.dot=_]="dot";let v=47;e[e.slash=v]="slash";let T=48;e[e.digit0=T]="digit0";let $=49;e[e.digit1=$]="digit1";let x=50;e[e.digit2=x]="digit2";let R=51;e[e.digit3=R]="digit3";let C=52;e[e.digit4=C]="digit4";let B=53;e[e.digit5=B]="digit5";let L=54;e[e.digit6=L]="digit6";let Z=55;e[e.digit7=Z]="digit7";let X=56;e[e.digit8=X]="digit8";let O=57;e[e.digit9=O]="digit9";let ae=58;e[e.colon=ae]="colon";let W=59;e[e.semicolon=W]="semicolon";let ne=60;e[e.lessThan=ne]="lessThan";let z=61;e[e.equalsTo=z]="equalsTo";let q=62;e[e.greaterThan=q]="greaterThan";let j=63;e[e.questionMark=j]="questionMark";let I=64;e[e.atSign=I]="atSign";let S=65;e[e.uppercaseA=S]="uppercaseA";let A=66;e[e.uppercaseB=A]="uppercaseB";let U=67;e[e.uppercaseC=U]="uppercaseC";let de=68;e[e.uppercaseD=de]="uppercaseD";let te=69;e[e.uppercaseE=te]="uppercaseE";let _e=70;e[e.uppercaseF=_e]="uppercaseF";let Se=71;e[e.uppercaseG=Se]="uppercaseG";let H=72;e[e.uppercaseH=H]="uppercaseH";let le=73;e[e.uppercaseI=le]="uppercaseI";let pe=74;e[e.uppercaseJ=pe]="uppercaseJ";let xe=75;e[e.uppercaseK=xe]="uppercaseK";let ve=76;e[e.uppercaseL=ve]="uppercaseL";let Oe=77;e[e.uppercaseM=Oe]="uppercaseM";let ue=78;e[e.uppercaseN=ue]="uppercaseN";let me=79;e[e.uppercaseO=me]="uppercaseO";let ge=80;e[e.uppercaseP=ge]="uppercaseP";let Re=81;e[e.uppercaseQ=Re]="uppercaseQ";let Le=82;e[e.uppercaseR=Le]="uppercaseR";let Ne=83;e[e.uppercaseS=Ne]="uppercaseS";let We=84;e[e.uppercaseT=We]="uppercaseT";let pt=85;e[e.uppercaseU=pt]="uppercaseU";let Nt=86;e[e.uppercaseV=Nt]="uppercaseV";let yn=87;e[e.uppercaseW=yn]="uppercaseW";let En=88;e[e.uppercaseX=En]="uppercaseX";let Mn=89;e[e.uppercaseY=Mn]="uppercaseY";let hr=90;e[e.uppercaseZ=hr]="uppercaseZ";let In=91;e[e.leftSquareBracket=In]="leftSquareBracket";let Pn=92;e[e.backslash=Pn]="backslash";let wn=93;e[e.rightSquareBracket=wn]="rightSquareBracket";let tr=94;e[e.caret=tr]="caret";let si=95;e[e.underscore=si]="underscore";let ns=96;e[e.graveAccent=ns]="graveAccent";let V=97;e[e.lowercaseA=V]="lowercaseA";let be=98;e[e.lowercaseB=be]="lowercaseB";let we=99;e[e.lowercaseC=we]="lowercaseC";let $e=100;e[e.lowercaseD=$e]="lowercaseD";let De=101;e[e.lowercaseE=De]="lowercaseE";let Pe=102;e[e.lowercaseF=Pe]="lowercaseF";let Xe=103;e[e.lowercaseG=Xe]="lowercaseG";let yt=104;e[e.lowercaseH=yt]="lowercaseH";let Je=105;e[e.lowercaseI=Je]="lowercaseI";let Mt=106;e[e.lowercaseJ=Mt]="lowercaseJ";let jt=107;e[e.lowercaseK=jt]="lowercaseK";let Dt=108;e[e.lowercaseL=Dt]="lowercaseL";let on=109;e[e.lowercaseM=on]="lowercaseM";let cn=110;e[e.lowercaseN=cn]="lowercaseN";let vn=111;e[e.lowercaseO=vn]="lowercaseO";let Tn=112;e[e.lowercaseP=Tn]="lowercaseP";let Fn=113;e[e.lowercaseQ=Fn]="lowercaseQ";let gr=114;e[e.lowercaseR=gr]="lowercaseR";let yo=115;e[e.lowercaseS=yo]="lowercaseS";let un=116;e[e.lowercaseT=un]="lowercaseT";let wo=117;e[e.lowercaseU=wo]="lowercaseU";let rs=118;e[e.lowercaseV=rs]="lowercaseV";let ii=119;e[e.lowercaseW=ii]="lowercaseW";let os=120;e[e.lowercaseX=os]="lowercaseX";let ko=121;e[e.lowercaseY=ko]="lowercaseY";let nr=122;e[e.lowercaseZ=nr]="lowercaseZ";let Ur=123;e[e.leftCurlyBrace=Ur]="leftCurlyBrace";let ss=124;e[e.verticalBar=ss]="verticalBar";let is=125;e[e.rightCurlyBrace=is]="rightCurlyBrace";let as=126;e[e.tilde=as]="tilde";let Yc=160;e[e.nonBreakingSpace=Yc]="nonBreakingSpace";let Zc=5760;e[e.oghamSpaceMark=Zc]="oghamSpaceMark";let eu=8232;e[e.lineSeparator=eu]="lineSeparator";let tu=8233;e[e.paragraphSeparator=tu]="paragraphSeparator"})(Vr||(dl.charCodes=Vr={}));function aC(e){return e>=Vr.digit0&&e<=Vr.digit9||e>=Vr.lowercaseA&&e<=Vr.lowercaseF||e>=Vr.uppercaseA&&e<=Vr.uppercaseF}dl.isDigit=aC});var jn=Ie(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});function lC(e){return e&&e.__esModule?e:{default:e}}var cC=ul(),uC=lC(cC),dC=Nn();Kt.isJSXEnabled;Kt.isTypeScriptEnabled;Kt.isFlowEnabled;Kt.state;Kt.input;Kt.nextContextId;function pC(){return Kt.nextContextId++}Kt.getNextContextId=pC;function mC(e){if("pos"in e){let t=a0(e.pos);e.message+=` (${t.line}:${t.column})`,e.loc=t}return e}Kt.augmentError=mC;var pl=class{constructor(t,n){this.line=t,this.column=n}};Kt.Loc=pl;function a0(e){let t=1,n=1;for(let r=0;r<e;r++)Kt.input.charCodeAt(r)===dC.charCodes.lineFeed?(t++,n=1):n++;return new pl(t,n)}Kt.locationForIndex=a0;function fC(e,t,n,r){Kt.input=e,Kt.state=new uC.default,Kt.nextContextId=1,Kt.isJSXEnabled=t,Kt.isTypeScriptEnabled=n,Kt.isFlowEnabled=r}Kt.initParser=fC});var Xr=Ie(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});var Jr=en(),Fo=et(),ml=Nn(),Dn=jn();function hC(e){return Dn.state.contextualKeyword===e}Bn.isContextual=hC;function gC(e){let t=Jr.lookaheadTypeAndKeyword.call(void 0);return t.type===Fo.TokenType.name&&t.contextualKeyword===e}Bn.isLookaheadContextual=gC;function l0(e){return Dn.state.contextualKeyword===e&&Jr.eat.call(void 0,Fo.TokenType.name)}Bn.eatContextual=l0;function bC(e){l0(e)||fl()}Bn.expectContextual=bC;function c0(){return Jr.match.call(void 0,Fo.TokenType.eof)||Jr.match.call(void 0,Fo.TokenType.braceR)||u0()}Bn.canInsertSemicolon=c0;function u0(){let e=Dn.state.tokens[Dn.state.tokens.length-1],t=e?e.end:0;for(let n=t;n<Dn.state.start;n++){let r=Dn.input.charCodeAt(n);if(r===ml.charCodes.lineFeed||r===ml.charCodes.carriageReturn||r===8232||r===8233)return!0}return!1}Bn.hasPrecedingLineBreak=u0;function yC(){let e=Jr.nextTokenStart.call(void 0);for(let t=Dn.state.end;t<e;t++){let n=Dn.input.charCodeAt(t);if(n===ml.charCodes.lineFeed||n===ml.charCodes.carriageReturn||n===8232||n===8233)return!0}return!1}Bn.hasFollowingLineBreak=yC;function d0(){return Jr.eat.call(void 0,Fo.TokenType.semi)||c0()}Bn.isLineTerminator=d0;function wC(){d0()||fl('Unexpected token, expected ";"')}Bn.semicolon=wC;function kC(e){Jr.eat.call(void 0,e)||fl(`Unexpected token, expected "${Fo.formatTokenType.call(void 0,e)}"`)}Bn.expect=kC;function fl(e="Unexpected token",t=Dn.state.start){if(Dn.state.error)return;let n=new SyntaxError(e);n.pos=t,Dn.state.error=n,Dn.state.pos=Dn.input.length,Jr.finishToken.call(void 0,Fo.TokenType.eof)}Bn.unexpected=fl});var ud=Ie(Oo=>{"use strict";Object.defineProperty(Oo,"__esModule",{value:!0});var cd=Nn(),_C=[9,11,12,cd.charCodes.space,cd.charCodes.nonBreakingSpace,cd.charCodes.oghamSpaceMark,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279];Oo.WHITESPACE_CHARS=_C;var vC=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;Oo.skipWhiteSpace=vC;var TC=new Uint8Array(65536);Oo.IS_WHITESPACE=TC;for(let e of Oo.WHITESPACE_CHARS)Oo.IS_WHITESPACE[e]=1});var xs=Ie(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});var p0=Nn(),xC=ud();function SC(e){if(e<48)return e===36;if(e<58)return!0;if(e<65)return!1;if(e<91)return!0;if(e<97)return e===95;if(e<123)return!0;if(e<128)return!1;throw new Error("Should not be called with non-ASCII char code.")}var $C=new Uint8Array(65536);ir.IS_IDENTIFIER_CHAR=$C;for(let e=0;e<128;e++)ir.IS_IDENTIFIER_CHAR[e]=SC(e)?1:0;for(let e=128;e<65536;e++)ir.IS_IDENTIFIER_CHAR[e]=1;for(let e of xC.WHITESPACE_CHARS)ir.IS_IDENTIFIER_CHAR[e]=0;ir.IS_IDENTIFIER_CHAR[8232]=0;ir.IS_IDENTIFIER_CHAR[8233]=0;var RC=ir.IS_IDENTIFIER_CHAR.slice();ir.IS_IDENTIFIER_START=RC;for(let e=p0.charCodes.digit0;e<=p0.charCodes.digit9;e++)ir.IS_IDENTIFIER_START[e]=0});var m0=Ie(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0});var Qe=rn(),nt=et(),CC=new Int32Array([-1,27,783,918,1755,2376,2862,3483,-1,3699,-1,4617,4752,4833,5130,5508,5940,-1,6480,6939,7749,8181,8451,8613,-1,8829,-1,-1,-1,54,243,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,432,-1,-1,-1,675,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,81,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,108,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,135,-1,-1,-1,-1,-1,-1,-1,-1,-1,162,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,189,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,216,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._abstract<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,270,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,297,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,324,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,351,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,378,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,405,-1,-1,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._accessor<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._as<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,459,-1,-1,-1,-1,-1,594,-1,-1,-1,-1,-1,-1,486,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,513,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,540,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._assert<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,567,-1,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._asserts<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,621,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,648,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._async<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,702,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,729,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,756,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._await<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,810,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,837,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,864,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,891,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(nt.TokenType._break<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,945,-1,-1,-1,-1,-1,-1,1107,-1,-1,-1,1242,-1,-1,1350,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,972,1026,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,999,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(nt.TokenType._case<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1053,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1080,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(nt.TokenType._catch<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1134,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1161,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1188,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1215,-1,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._checks<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1269,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1296,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1323,-1,-1,-1,-1,-1,-1,-1,(nt.TokenType._class<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1377,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1404,1620,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1431,-1,-1,-1,-1,-1,-1,(nt.TokenType._const<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1458,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1485,-1,-1,-1,-1,-1,-1,-1,-1,1512,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1539,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1566,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1593,-1,-1,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._constructor<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1647,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1674,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1701,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1728,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(nt.TokenType._continue<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1782,-1,-1,-1,-1,-1,-1,-1,-1,-1,2349,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1809,1971,-1,-1,2106,-1,-1,-1,-1,-1,2241,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1836,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1863,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1890,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1917,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1944,-1,-1,-1,-1,-1,-1,-1,-1,(nt.TokenType._debugger<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1998,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2025,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2052,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2079,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._declare<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2133,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2160,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2187,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2214,-1,-1,-1,-1,-1,-1,(nt.TokenType._default<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2268,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2295,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2322,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(nt.TokenType._delete<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(nt.TokenType._do<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2403,-1,2484,-1,-1,-1,-1,-1,-1,-1,-1,-1,2565,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2430,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2457,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(nt.TokenType._else<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2511,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2538,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._enum<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2592,-1,-1,-1,2727,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2619,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2646,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2673,-1,-1,-1,-1,-1,-1,(nt.TokenType._export<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2700,-1,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._exports<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2754,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2781,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2808,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2835,-1,-1,-1,-1,-1,-1,-1,(nt.TokenType._extends<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2889,-1,-1,-1,-1,-1,-1,-1,2997,-1,-1,-1,-1,-1,3159,-1,-1,3213,-1,-1,3294,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2916,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2943,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2970,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(nt.TokenType._false<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3024,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3051,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3078,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3105,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3132,-1,(nt.TokenType._finally<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3186,-1,-1,-1,-1,-1,-1,-1,-1,(nt.TokenType._for<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3240,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3267,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._from<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3321,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3348,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3375,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3402,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3429,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3456,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(nt.TokenType._function<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3510,-1,-1,-1,-1,-1,-1,3564,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3537,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._get<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3591,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3618,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3645,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3672,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._global<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3726,-1,-1,-1,-1,-1,-1,3753,4077,-1,-1,-1,-1,4590,-1,-1,-1,-1,-1,-1,-1,(nt.TokenType._if<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3780,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3807,-1,-1,3996,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3834,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3861,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3888,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3915,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3942,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3969,-1,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._implements<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4023,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4050,-1,-1,-1,-1,-1,-1,(nt.TokenType._import<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(nt.TokenType._in<<1)+1,-1,-1,-1,-1,-1,4104,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4185,4401,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4131,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4158,-1,-1,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._infer<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4212,-1,-1,-1,-1,-1,-1,-1,4239,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4266,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4293,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4320,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4347,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4374,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(nt.TokenType._instanceof<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4428,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4455,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4482,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4509,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4536,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4563,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._interface<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._is<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4644,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4671,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4698,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4725,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._keyof<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4779,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4806,-1,-1,-1,-1,-1,-1,(nt.TokenType._let<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4860,-1,-1,-1,-1,-1,4995,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4887,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4914,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4941,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4968,-1,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._mixins<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5022,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5049,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5076,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5103,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._module<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5157,-1,-1,-1,5373,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5427,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5184,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5211,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5238,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5265,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5292,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5319,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5346,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._namespace<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5400,-1,-1,-1,(nt.TokenType._new<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5454,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5481,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(nt.TokenType._null<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5535,-1,-1,-1,-1,-1,-1,-1,-1,-1,5562,-1,-1,-1,-1,5697,5751,-1,-1,-1,-1,Qe.ContextualKeyword._of<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5589,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5616,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5643,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5670,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._opaque<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5724,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._out<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5778,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5805,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5832,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5859,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5886,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5913,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._override<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5967,-1,-1,6345,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5994,-1,-1,-1,-1,-1,6129,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6021,-1,-1,-1,-1,-1,6048,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6075,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6102,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._private<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6156,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6183,-1,-1,-1,-1,-1,-1,-1,-1,-1,6318,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6210,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6237,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6264,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6291,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._protected<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._proto<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6372,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6399,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6426,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6453,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._public<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6507,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6534,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6696,-1,-1,6831,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6561,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6588,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6615,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6642,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6669,-1,Qe.ContextualKeyword._readonly<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6723,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6750,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6777,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6804,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._require<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6858,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6885,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6912,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(nt.TokenType._return<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6966,-1,-1,-1,7182,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7236,7371,-1,7479,-1,7614,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6993,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7020,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7047,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7074,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7101,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7128,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7155,-1,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._satisfies<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7209,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._set<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7263,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7290,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7317,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7344,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._static<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7398,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7425,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7452,-1,-1,-1,-1,-1,-1,-1,-1,(nt.TokenType._super<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7506,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7533,-1,-1,-1,-1,-1,-1,-1,-1,-1,7560,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7587,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(nt.TokenType._switch<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7641,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7668,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7695,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7722,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._symbol<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7776,-1,-1,-1,-1,-1,-1,-1,-1,-1,7938,-1,-1,-1,-1,-1,-1,8046,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7803,-1,-1,-1,-1,-1,-1,-1,-1,7857,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7830,-1,-1,-1,-1,-1,-1,-1,(nt.TokenType._this<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7884,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7911,-1,-1,-1,(nt.TokenType._throw<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7965,-1,-1,-1,8019,-1,-1,-1,-1,-1,-1,7992,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(nt.TokenType._true<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(nt.TokenType._try<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8073,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8100,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._type<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8127,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8154,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(nt.TokenType._typeof<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8208,-1,-1,-1,-1,8343,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8235,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8262,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8289,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8316,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._unique<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8370,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8397,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8424,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,Qe.ContextualKeyword._using<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8478,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8532,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8505,-1,-1,-1,-1,-1,-1,-1,-1,(nt.TokenType._var<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8559,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8586,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(nt.TokenType._void<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8640,8748,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8667,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8694,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8721,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(nt.TokenType._while<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8775,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8802,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(nt.TokenType._with<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8856,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8883,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8910,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8937,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(nt.TokenType._yield<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1]);dd.READ_WORD_TREE=CC});var b0=Ie(md=>{"use strict";Object.defineProperty(md,"__esModule",{value:!0});var ar=jn(),Qr=Nn(),f0=xs(),pd=en(),h0=m0(),g0=et();function AC(){let e=0,t=0,n=ar.state.pos;for(;n<ar.input.length&&(t=ar.input.charCodeAt(n),!(t<Qr.charCodes.lowercaseA||t>Qr.charCodes.lowercaseZ));){let o=h0.READ_WORD_TREE[e+(t-Qr.charCodes.lowercaseA)+1];if(o===-1)break;e=o,n++}let r=h0.READ_WORD_TREE[e];if(r>-1&&!f0.IS_IDENTIFIER_CHAR[t]){ar.state.pos=n,r&1?pd.finishToken.call(void 0,r>>>1):pd.finishToken.call(void 0,g0.TokenType.name,r>>>1);return}for(;n<ar.input.length;){let o=ar.input.charCodeAt(n);if(f0.IS_IDENTIFIER_CHAR[o])n++;else if(o===Qr.charCodes.backslash){if(n+=2,ar.input.charCodeAt(n)===Qr.charCodes.leftCurlyBrace){for(;n<ar.input.length&&ar.input.charCodeAt(n)!==Qr.charCodes.rightCurlyBrace;)n++;n++}}else if(o===Qr.charCodes.atSign&&ar.input.charCodeAt(n+1)===Qr.charCodes.atSign)n+=2;else break}ar.state.pos=n,pd.finishToken.call(void 0,g0.TokenType.name)}md.default=AC});var en=Ie(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});function EC(e){return e&&e.__esModule?e:{default:e}}var N=jn(),Ss=Xr(),oe=Nn(),w0=xs(),hd=ud(),MC=rn(),IC=b0(),PC=EC(IC),Ae=et(),Ot;(function(e){e[e.Access=0]="Access";let n=1;e[e.ExportAccess=n]="ExportAccess";let r=n+1;e[e.TopLevelDeclaration=r]="TopLevelDeclaration";let o=r+1;e[e.FunctionScopedDeclaration=o]="FunctionScopedDeclaration";let s=o+1;e[e.BlockScopedDeclaration=s]="BlockScopedDeclaration";let i=s+1;e[e.ObjectShorthandTopLevelDeclaration=i]="ObjectShorthandTopLevelDeclaration";let a=i+1;e[e.ObjectShorthandFunctionScopedDeclaration=a]="ObjectShorthandFunctionScopedDeclaration";let l=a+1;e[e.ObjectShorthandBlockScopedDeclaration=l]="ObjectShorthandBlockScopedDeclaration";let c=l+1;e[e.ObjectShorthand=c]="ObjectShorthand";let u=c+1;e[e.ImportDeclaration=u]="ImportDeclaration";let d=u+1;e[e.ObjectKey=d]="ObjectKey";let p=d+1;e[e.ImportAccess=p]="ImportAccess"})(Ot||(bt.IdentifierRole=Ot={}));var y0;(function(e){e[e.NoChildren=0]="NoChildren";let n=1;e[e.OneChild=n]="OneChild";let r=n+1;e[e.StaticChildren=r]="StaticChildren";let o=r+1;e[e.KeyAfterPropSpread=o]="KeyAfterPropSpread"})(y0||(bt.JSXRole=y0={}));function FC(e){let t=e.identifierRole;return t===Ot.TopLevelDeclaration||t===Ot.FunctionScopedDeclaration||t===Ot.BlockScopedDeclaration||t===Ot.ObjectShorthandTopLevelDeclaration||t===Ot.ObjectShorthandFunctionScopedDeclaration||t===Ot.ObjectShorthandBlockScopedDeclaration}bt.isDeclaration=FC;function OC(e){let t=e.identifierRole;return t===Ot.FunctionScopedDeclaration||t===Ot.BlockScopedDeclaration||t===Ot.ObjectShorthandFunctionScopedDeclaration||t===Ot.ObjectShorthandBlockScopedDeclaration}bt.isNonTopLevelDeclaration=OC;function LC(e){let t=e.identifierRole;return t===Ot.TopLevelDeclaration||t===Ot.ObjectShorthandTopLevelDeclaration||t===Ot.ImportDeclaration}bt.isTopLevelDeclaration=LC;function NC(e){let t=e.identifierRole;return t===Ot.TopLevelDeclaration||t===Ot.BlockScopedDeclaration||t===Ot.ObjectShorthandTopLevelDeclaration||t===Ot.ObjectShorthandBlockScopedDeclaration}bt.isBlockScopedDeclaration=NC;function jC(e){let t=e.identifierRole;return t===Ot.FunctionScopedDeclaration||t===Ot.ObjectShorthandFunctionScopedDeclaration}bt.isFunctionScopedDeclaration=jC;function DC(e){return e.identifierRole===Ot.ObjectShorthandTopLevelDeclaration||e.identifierRole===Ot.ObjectShorthandBlockScopedDeclaration||e.identifierRole===Ot.ObjectShorthandFunctionScopedDeclaration}bt.isObjectShorthandDeclaration=DC;var Ai=class{constructor(){this.type=N.state.type,this.contextualKeyword=N.state.contextualKeyword,this.start=N.state.start,this.end=N.state.end,this.scopeDepth=N.state.scopeDepth,this.isType=N.state.isType,this.identifierRole=null,this.jsxRole=null,this.shadowsGlobal=!1,this.isAsyncOperation=!1,this.contextId=null,this.rhsEndIndex=null,this.isExpression=!1,this.numNullishCoalesceStarts=0,this.numNullishCoalesceEnds=0,this.isOptionalChainStart=!1,this.isOptionalChainEnd=!1,this.subscriptStartIndex=null,this.nullishStartIndex=null}};bt.Token=Ai;function gl(){N.state.tokens.push(new Ai),T0()}bt.next=gl;function BC(){N.state.tokens.push(new Ai),N.state.start=N.state.pos,cA()}bt.nextTemplateToken=BC;function qC(){N.state.type===Ae.TokenType.assign&&--N.state.pos,iA()}bt.retokenizeSlashAsRegex=qC;function UC(e){for(let n=N.state.tokens.length-e;n<N.state.tokens.length;n++)N.state.tokens[n].isType=!0;let t=N.state.isType;return N.state.isType=!0,t}bt.pushTypeContext=UC;function GC(e){N.state.isType=e}bt.popTypeContext=GC;function k0(e){return gd(e)?(gl(),!0):!1}bt.eat=k0;function HC(e){let t=N.state.isType;N.state.isType=!0,k0(e),N.state.isType=t}bt.eatTypeToken=HC;function gd(e){return N.state.type===e}bt.match=gd;function zC(){let e=N.state.snapshot();gl();let t=N.state.type;return N.state.restoreFromSnapshot(e),t}bt.lookaheadType=zC;var hl=class{constructor(t,n){this.type=t,this.contextualKeyword=n}};bt.TypeAndKeyword=hl;function WC(){let e=N.state.snapshot();gl();let t=N.state.type,n=N.state.contextualKeyword;return N.state.restoreFromSnapshot(e),new hl(t,n)}bt.lookaheadTypeAndKeyword=WC;function _0(){return v0(N.state.pos)}bt.nextTokenStart=_0;function v0(e){hd.skipWhiteSpace.lastIndex=e;let t=hd.skipWhiteSpace.exec(N.input);return e+t[0].length}bt.nextTokenStartSince=v0;function KC(){return N.input.charCodeAt(_0())}bt.lookaheadCharCode=KC;function T0(){if(S0(),N.state.start=N.state.pos,N.state.pos>=N.input.length){let e=N.state.tokens;e.length>=2&&e[e.length-1].start>=N.input.length&&e[e.length-2].start>=N.input.length&&Ss.unexpected.call(void 0,"Unexpectedly reached the end of input."),wt(Ae.TokenType.eof);return}VC(N.input.charCodeAt(N.state.pos))}bt.nextToken=T0;function VC(e){w0.IS_IDENTIFIER_START[e]||e===oe.charCodes.backslash||e===oe.charCodes.atSign&&N.input.charCodeAt(N.state.pos+1)===oe.charCodes.atSign?PC.default.call(void 0):R0(e)}function JC(){for(;N.input.charCodeAt(N.state.pos)!==oe.charCodes.asterisk||N.input.charCodeAt(N.state.pos+1)!==oe.charCodes.slash;)if(N.state.pos++,N.state.pos>N.input.length){Ss.unexpected.call(void 0,"Unterminated comment",N.state.pos-2);return}N.state.pos+=2}function x0(e){let t=N.input.charCodeAt(N.state.pos+=e);if(N.state.pos<N.input.length)for(;t!==oe.charCodes.lineFeed&&t!==oe.charCodes.carriageReturn&&t!==oe.charCodes.lineSeparator&&t!==oe.charCodes.paragraphSeparator&&++N.state.pos<N.input.length;)t=N.input.charCodeAt(N.state.pos)}bt.skipLineComment=x0;function S0(){for(;N.state.pos<N.input.length;){let e=N.input.charCodeAt(N.state.pos);switch(e){case oe.charCodes.carriageReturn:N.input.charCodeAt(N.state.pos+1)===oe.charCodes.lineFeed&&++N.state.pos;case oe.charCodes.lineFeed:case oe.charCodes.lineSeparator:case oe.charCodes.paragraphSeparator:++N.state.pos;break;case oe.charCodes.slash:switch(N.input.charCodeAt(N.state.pos+1)){case oe.charCodes.asterisk:N.state.pos+=2,JC();break;case oe.charCodes.slash:x0(2);break;default:return}break;default:if(hd.IS_WHITESPACE[e])++N.state.pos;else return}}}bt.skipSpace=S0;function wt(e,t=MC.ContextualKeyword.NONE){N.state.end=N.state.pos,N.state.type=e,N.state.contextualKeyword=t}bt.finishToken=wt;function XC(){let e=N.input.charCodeAt(N.state.pos+1);if(e>=oe.charCodes.digit0&&e<=oe.charCodes.digit9){C0(!0);return}e===oe.charCodes.dot&&N.input.charCodeAt(N.state.pos+2)===oe.charCodes.dot?(N.state.pos+=3,wt(Ae.TokenType.ellipsis)):(++N.state.pos,wt(Ae.TokenType.dot))}function QC(){N.input.charCodeAt(N.state.pos+1)===oe.charCodes.equalsTo?gt(Ae.TokenType.assign,2):gt(Ae.TokenType.slash,1)}function YC(e){let t=e===oe.charCodes.asterisk?Ae.TokenType.star:Ae.TokenType.modulo,n=1,r=N.input.charCodeAt(N.state.pos+1);e===oe.charCodes.asterisk&&r===oe.charCodes.asterisk&&(n++,r=N.input.charCodeAt(N.state.pos+2),t=Ae.TokenType.exponent),r===oe.charCodes.equalsTo&&N.input.charCodeAt(N.state.pos+2)!==oe.charCodes.greaterThan&&(n++,t=Ae.TokenType.assign),gt(t,n)}function ZC(e){let t=N.input.charCodeAt(N.state.pos+1);if(t===e){N.input.charCodeAt(N.state.pos+2)===oe.charCodes.equalsTo?gt(Ae.TokenType.assign,3):gt(e===oe.charCodes.verticalBar?Ae.TokenType.logicalOR:Ae.TokenType.logicalAND,2);return}if(e===oe.charCodes.verticalBar){if(t===oe.charCodes.greaterThan){gt(Ae.TokenType.pipeline,2);return}else if(t===oe.charCodes.rightCurlyBrace&&N.isFlowEnabled){gt(Ae.TokenType.braceBarR,2);return}}if(t===oe.charCodes.equalsTo){gt(Ae.TokenType.assign,2);return}gt(e===oe.charCodes.verticalBar?Ae.TokenType.bitwiseOR:Ae.TokenType.bitwiseAND,1)}function eA(){N.input.charCodeAt(N.state.pos+1)===oe.charCodes.equalsTo?gt(Ae.TokenType.assign,2):gt(Ae.TokenType.bitwiseXOR,1)}function tA(e){let t=N.input.charCodeAt(N.state.pos+1);if(t===e){gt(Ae.TokenType.preIncDec,2);return}t===oe.charCodes.equalsTo?gt(Ae.TokenType.assign,2):e===oe.charCodes.plusSign?gt(Ae.TokenType.plus,1):gt(Ae.TokenType.minus,1)}function nA(){let e=N.input.charCodeAt(N.state.pos+1);if(e===oe.charCodes.lessThan){if(N.input.charCodeAt(N.state.pos+2)===oe.charCodes.equalsTo){gt(Ae.TokenType.assign,3);return}N.state.isType?gt(Ae.TokenType.lessThan,1):gt(Ae.TokenType.bitShiftL,2);return}e===oe.charCodes.equalsTo?gt(Ae.TokenType.relationalOrEqual,2):gt(Ae.TokenType.lessThan,1)}function $0(){if(N.state.isType){gt(Ae.TokenType.greaterThan,1);return}let e=N.input.charCodeAt(N.state.pos+1);if(e===oe.charCodes.greaterThan){let t=N.input.charCodeAt(N.state.pos+2)===oe.charCodes.greaterThan?3:2;if(N.input.charCodeAt(N.state.pos+t)===oe.charCodes.equalsTo){gt(Ae.TokenType.assign,t+1);return}gt(Ae.TokenType.bitShiftR,t);return}e===oe.charCodes.equalsTo?gt(Ae.TokenType.relationalOrEqual,2):gt(Ae.TokenType.greaterThan,1)}function rA(){N.state.type===Ae.TokenType.greaterThan&&(N.state.pos-=1,$0())}bt.rescan_gt=rA;function oA(e){let t=N.input.charCodeAt(N.state.pos+1);if(t===oe.charCodes.equalsTo){gt(Ae.TokenType.equality,N.input.charCodeAt(N.state.pos+2)===oe.charCodes.equalsTo?3:2);return}if(e===oe.charCodes.equalsTo&&t===oe.charCodes.greaterThan){N.state.pos+=2,wt(Ae.TokenType.arrow);return}gt(e===oe.charCodes.equalsTo?Ae.TokenType.eq:Ae.TokenType.bang,1)}function sA(){let e=N.input.charCodeAt(N.state.pos+1),t=N.input.charCodeAt(N.state.pos+2);e===oe.charCodes.questionMark&&!(N.isFlowEnabled&&N.state.isType)?t===oe.charCodes.equalsTo?gt(Ae.TokenType.assign,3):gt(Ae.TokenType.nullishCoalescing,2):e===oe.charCodes.dot&&!(t>=oe.charCodes.digit0&&t<=oe.charCodes.digit9)?(N.state.pos+=2,wt(Ae.TokenType.questionDot)):(++N.state.pos,wt(Ae.TokenType.question))}function R0(e){switch(e){case oe.charCodes.numberSign:++N.state.pos,wt(Ae.TokenType.hash);return;case oe.charCodes.dot:XC();return;case oe.charCodes.leftParenthesis:++N.state.pos,wt(Ae.TokenType.parenL);return;case oe.charCodes.rightParenthesis:++N.state.pos,wt(Ae.TokenType.parenR);return;case oe.charCodes.semicolon:++N.state.pos,wt(Ae.TokenType.semi);return;case oe.charCodes.comma:++N.state.pos,wt(Ae.TokenType.comma);return;case oe.charCodes.leftSquareBracket:++N.state.pos,wt(Ae.TokenType.bracketL);return;case oe.charCodes.rightSquareBracket:++N.state.pos,wt(Ae.TokenType.bracketR);return;case oe.charCodes.leftCurlyBrace:N.isFlowEnabled&&N.input.charCodeAt(N.state.pos+1)===oe.charCodes.verticalBar?gt(Ae.TokenType.braceBarL,2):(++N.state.pos,wt(Ae.TokenType.braceL));return;case oe.charCodes.rightCurlyBrace:++N.state.pos,wt(Ae.TokenType.braceR);return;case oe.charCodes.colon:N.input.charCodeAt(N.state.pos+1)===oe.charCodes.colon?gt(Ae.TokenType.doubleColon,2):(++N.state.pos,wt(Ae.TokenType.colon));return;case oe.charCodes.questionMark:sA();return;case oe.charCodes.atSign:++N.state.pos,wt(Ae.TokenType.at);return;case oe.charCodes.graveAccent:++N.state.pos,wt(Ae.TokenType.backQuote);return;case oe.charCodes.digit0:{let t=N.input.charCodeAt(N.state.pos+1);if(t===oe.charCodes.lowercaseX||t===oe.charCodes.uppercaseX||t===oe.charCodes.lowercaseO||t===oe.charCodes.uppercaseO||t===oe.charCodes.lowercaseB||t===oe.charCodes.uppercaseB){aA();return}}case oe.charCodes.digit1:case oe.charCodes.digit2:case oe.charCodes.digit3:case oe.charCodes.digit4:case oe.charCodes.digit5:case oe.charCodes.digit6:case oe.charCodes.digit7:case oe.charCodes.digit8:case oe.charCodes.digit9:C0(!1);return;case oe.charCodes.quotationMark:case oe.charCodes.apostrophe:lA(e);return;case oe.charCodes.slash:QC();return;case oe.charCodes.percentSign:case oe.charCodes.asterisk:YC(e);return;case oe.charCodes.verticalBar:case oe.charCodes.ampersand:ZC(e);return;case oe.charCodes.caret:eA();return;case oe.charCodes.plusSign:case oe.charCodes.dash:tA(e);return;case oe.charCodes.lessThan:nA();return;case oe.charCodes.greaterThan:$0();return;case oe.charCodes.equalsTo:case oe.charCodes.exclamationMark:oA(e);return;case oe.charCodes.tilde:gt(Ae.TokenType.tilde,1);return;default:break}Ss.unexpected.call(void 0,`Unexpected character '${String.fromCharCode(e)}'`,N.state.pos)}bt.getTokenFromCode=R0;function gt(e,t){N.state.pos+=t,wt(e)}function iA(){let e=N.state.pos,t=!1,n=!1;for(;;){if(N.state.pos>=N.input.length){Ss.unexpected.call(void 0,"Unterminated regular expression",e);return}let r=N.input.charCodeAt(N.state.pos);if(t)t=!1;else{if(r===oe.charCodes.leftSquareBracket)n=!0;else if(r===oe.charCodes.rightSquareBracket&&n)n=!1;else if(r===oe.charCodes.slash&&!n)break;t=r===oe.charCodes.backslash}++N.state.pos}++N.state.pos,A0(),wt(Ae.TokenType.regexp)}function fd(){for(;;){let e=N.input.charCodeAt(N.state.pos);if(e>=oe.charCodes.digit0&&e<=oe.charCodes.digit9||e===oe.charCodes.underscore)N.state.pos++;else break}}function aA(){for(N.state.pos+=2;;){let t=N.input.charCodeAt(N.state.pos);if(t>=oe.charCodes.digit0&&t<=oe.charCodes.digit9||t>=oe.charCodes.lowercaseA&&t<=oe.charCodes.lowercaseF||t>=oe.charCodes.uppercaseA&&t<=oe.charCodes.uppercaseF||t===oe.charCodes.underscore)N.state.pos++;else break}N.input.charCodeAt(N.state.pos)===oe.charCodes.lowercaseN?(++N.state.pos,wt(Ae.TokenType.bigint)):wt(Ae.TokenType.num)}function C0(e){let t=!1,n=!1;e||fd();let r=N.input.charCodeAt(N.state.pos);if(r===oe.charCodes.dot&&(++N.state.pos,fd(),r=N.input.charCodeAt(N.state.pos)),(r===oe.charCodes.uppercaseE||r===oe.charCodes.lowercaseE)&&(r=N.input.charCodeAt(++N.state.pos),(r===oe.charCodes.plusSign||r===oe.charCodes.dash)&&++N.state.pos,fd(),r=N.input.charCodeAt(N.state.pos)),r===oe.charCodes.lowercaseN?(++N.state.pos,t=!0):r===oe.charCodes.lowercaseM&&(++N.state.pos,n=!0),t){wt(Ae.TokenType.bigint);return}if(n){wt(Ae.TokenType.decimal);return}wt(Ae.TokenType.num)}function lA(e){for(N.state.pos++;;){if(N.state.pos>=N.input.length){Ss.unexpected.call(void 0,"Unterminated string constant");return}let t=N.input.charCodeAt(N.state.pos);if(t===oe.charCodes.backslash)N.state.pos++;else if(t===e)break;N.state.pos++}N.state.pos++,wt(Ae.TokenType.string)}function cA(){for(;;){if(N.state.pos>=N.input.length){Ss.unexpected.call(void 0,"Unterminated template");return}let e=N.input.charCodeAt(N.state.pos);if(e===oe.charCodes.graveAccent||e===oe.charCodes.dollarSign&&N.input.charCodeAt(N.state.pos+1)===oe.charCodes.leftCurlyBrace){if(N.state.pos===N.state.start&&gd(Ae.TokenType.template))if(e===oe.charCodes.dollarSign){N.state.pos+=2,wt(Ae.TokenType.dollarBraceL);return}else{++N.state.pos,wt(Ae.TokenType.backQuote);return}wt(Ae.TokenType.template);return}e===oe.charCodes.backslash&&N.state.pos++,N.state.pos++}}function A0(){for(;N.state.pos<N.input.length;){let e=N.input.charCodeAt(N.state.pos);if(w0.IS_IDENTIFIER_CHAR[e])N.state.pos++;else if(e===oe.charCodes.backslash){if(N.state.pos+=2,N.input.charCodeAt(N.state.pos)===oe.charCodes.leftCurlyBrace){for(;N.state.pos<N.input.length&&N.input.charCodeAt(N.state.pos)!==oe.charCodes.rightCurlyBrace;)N.state.pos++;N.state.pos++}}else break}}bt.skipWord=A0});var Ei=Ie(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var E0=et();function uA(e,t=e.currentIndex()){let n=t+1;if(bl(e,n)){let r=e.identifierNameAtIndex(t);return{isType:!1,leftName:r,rightName:r,endIndex:n}}if(n++,bl(e,n))return{isType:!0,leftName:null,rightName:null,endIndex:n};if(n++,bl(e,n))return{isType:!1,leftName:e.identifierNameAtIndex(t),rightName:e.identifierNameAtIndex(t+2),endIndex:n};if(n++,bl(e,n))return{isType:!0,leftName:null,rightName:null,endIndex:n};throw new Error(`Unexpected import/export specifier at ${t}`)}bd.default=uA;function bl(e,t){let n=e.tokens[t];return n.type===E0.TokenType.braceR||n.type===E0.TokenType.comma}});var M0=Ie(yd=>{"use strict";Object.defineProperty(yd,"__esModule",{value:!0});yd.default=new Map([["quot",'"'],["amp","&"],["apos","'"],["lt","<"],["gt",">"],["nbsp","\xA0"],["iexcl","\xA1"],["cent","\xA2"],["pound","\xA3"],["curren","\xA4"],["yen","\xA5"],["brvbar","\xA6"],["sect","\xA7"],["uml","\xA8"],["copy","\xA9"],["ordf","\xAA"],["laquo","\xAB"],["not","\xAC"],["shy","\xAD"],["reg","\xAE"],["macr","\xAF"],["deg","\xB0"],["plusmn","\xB1"],["sup2","\xB2"],["sup3","\xB3"],["acute","\xB4"],["micro","\xB5"],["para","\xB6"],["middot","\xB7"],["cedil","\xB8"],["sup1","\xB9"],["ordm","\xBA"],["raquo","\xBB"],["frac14","\xBC"],["frac12","\xBD"],["frac34","\xBE"],["iquest","\xBF"],["Agrave","\xC0"],["Aacute","\xC1"],["Acirc","\xC2"],["Atilde","\xC3"],["Auml","\xC4"],["Aring","\xC5"],["AElig","\xC6"],["Ccedil","\xC7"],["Egrave","\xC8"],["Eacute","\xC9"],["Ecirc","\xCA"],["Euml","\xCB"],["Igrave","\xCC"],["Iacute","\xCD"],["Icirc","\xCE"],["Iuml","\xCF"],["ETH","\xD0"],["Ntilde","\xD1"],["Ograve","\xD2"],["Oacute","\xD3"],["Ocirc","\xD4"],["Otilde","\xD5"],["Ouml","\xD6"],["times","\xD7"],["Oslash","\xD8"],["Ugrave","\xD9"],["Uacute","\xDA"],["Ucirc","\xDB"],["Uuml","\xDC"],["Yacute","\xDD"],["THORN","\xDE"],["szlig","\xDF"],["agrave","\xE0"],["aacute","\xE1"],["acirc","\xE2"],["atilde","\xE3"],["auml","\xE4"],["aring","\xE5"],["aelig","\xE6"],["ccedil","\xE7"],["egrave","\xE8"],["eacute","\xE9"],["ecirc","\xEA"],["euml","\xEB"],["igrave","\xEC"],["iacute","\xED"],["icirc","\xEE"],["iuml","\xEF"],["eth","\xF0"],["ntilde","\xF1"],["ograve","\xF2"],["oacute","\xF3"],["ocirc","\xF4"],["otilde","\xF5"],["ouml","\xF6"],["divide","\xF7"],["oslash","\xF8"],["ugrave","\xF9"],["uacute","\xFA"],["ucirc","\xFB"],["uuml","\xFC"],["yacute","\xFD"],["thorn","\xFE"],["yuml","\xFF"],["OElig","\u0152"],["oelig","\u0153"],["Scaron","\u0160"],["scaron","\u0161"],["Yuml","\u0178"],["fnof","\u0192"],["circ","\u02C6"],["tilde","\u02DC"],["Alpha","\u0391"],["Beta","\u0392"],["Gamma","\u0393"],["Delta","\u0394"],["Epsilon","\u0395"],["Zeta","\u0396"],["Eta","\u0397"],["Theta","\u0398"],["Iota","\u0399"],["Kappa","\u039A"],["Lambda","\u039B"],["Mu","\u039C"],["Nu","\u039D"],["Xi","\u039E"],["Omicron","\u039F"],["Pi","\u03A0"],["Rho","\u03A1"],["Sigma","\u03A3"],["Tau","\u03A4"],["Upsilon","\u03A5"],["Phi","\u03A6"],["Chi","\u03A7"],["Psi","\u03A8"],["Omega","\u03A9"],["alpha","\u03B1"],["beta","\u03B2"],["gamma","\u03B3"],["delta","\u03B4"],["epsilon","\u03B5"],["zeta","\u03B6"],["eta","\u03B7"],["theta","\u03B8"],["iota","\u03B9"],["kappa","\u03BA"],["lambda","\u03BB"],["mu","\u03BC"],["nu","\u03BD"],["xi","\u03BE"],["omicron","\u03BF"],["pi","\u03C0"],["rho","\u03C1"],["sigmaf","\u03C2"],["sigma","\u03C3"],["tau","\u03C4"],["upsilon","\u03C5"],["phi","\u03C6"],["chi","\u03C7"],["psi","\u03C8"],["omega","\u03C9"],["thetasym","\u03D1"],["upsih","\u03D2"],["piv","\u03D6"],["ensp","\u2002"],["emsp","\u2003"],["thinsp","\u2009"],["zwnj","\u200C"],["zwj","\u200D"],["lrm","\u200E"],["rlm","\u200F"],["ndash","\u2013"],["mdash","\u2014"],["lsquo","\u2018"],["rsquo","\u2019"],["sbquo","\u201A"],["ldquo","\u201C"],["rdquo","\u201D"],["bdquo","\u201E"],["dagger","\u2020"],["Dagger","\u2021"],["bull","\u2022"],["hellip","\u2026"],["permil","\u2030"],["prime","\u2032"],["Prime","\u2033"],["lsaquo","\u2039"],["rsaquo","\u203A"],["oline","\u203E"],["frasl","\u2044"],["euro","\u20AC"],["image","\u2111"],["weierp","\u2118"],["real","\u211C"],["trade","\u2122"],["alefsym","\u2135"],["larr","\u2190"],["uarr","\u2191"],["rarr","\u2192"],["darr","\u2193"],["harr","\u2194"],["crarr","\u21B5"],["lArr","\u21D0"],["uArr","\u21D1"],["rArr","\u21D2"],["dArr","\u21D3"],["hArr","\u21D4"],["forall","\u2200"],["part","\u2202"],["exist","\u2203"],["empty","\u2205"],["nabla","\u2207"],["isin","\u2208"],["notin","\u2209"],["ni","\u220B"],["prod","\u220F"],["sum","\u2211"],["minus","\u2212"],["lowast","\u2217"],["radic","\u221A"],["prop","\u221D"],["infin","\u221E"],["ang","\u2220"],["and","\u2227"],["or","\u2228"],["cap","\u2229"],["cup","\u222A"],["int","\u222B"],["there4","\u2234"],["sim","\u223C"],["cong","\u2245"],["asymp","\u2248"],["ne","\u2260"],["equiv","\u2261"],["le","\u2264"],["ge","\u2265"],["sub","\u2282"],["sup","\u2283"],["nsub","\u2284"],["sube","\u2286"],["supe","\u2287"],["oplus","\u2295"],["otimes","\u2297"],["perp","\u22A5"],["sdot","\u22C5"],["lceil","\u2308"],["rceil","\u2309"],["lfloor","\u230A"],["rfloor","\u230B"],["lang","\u2329"],["rang","\u232A"],["loz","\u25CA"],["spades","\u2660"],["clubs","\u2663"],["hearts","\u2665"],["diams","\u2666"]])});var kd=Ie(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});function dA(e){let[t,n]=I0(e.jsxPragma||"React.createElement"),[r,o]=I0(e.jsxFragmentPragma||"React.Fragment");return{base:t,suffix:n,fragmentBase:r,fragmentSuffix:o}}wd.default=dA;function I0(e){let t=e.indexOf(".");return t===-1&&(t=e.length),[e.slice(0,t),e.slice(t)]}});var Vn=Ie(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});var _d=class{getPrefixCode(){return""}getHoistedCode(){return""}getSuffixCode(){return""}};vd.default=_d});var Sd=Ie(wl=>{"use strict";Object.defineProperty(wl,"__esModule",{value:!0});function xd(e){return e&&e.__esModule?e:{default:e}}var pA=M0(),mA=xd(pA),yl=en(),lt=et(),kr=Nn(),fA=kd(),hA=xd(fA),gA=Vn(),bA=xd(gA),Td=class e extends bA.default{__init(){this.lastLineNumber=1}__init2(){this.lastIndex=0}__init3(){this.filenameVarName=null}__init4(){this.esmAutomaticImportNameResolutions={}}__init5(){this.cjsAutomaticModuleNameResolutions={}}constructor(t,n,r,o,s){super(),this.rootTransformer=t,this.tokens=n,this.importProcessor=r,this.nameManager=o,this.options=s,e.prototype.__init.call(this),e.prototype.__init2.call(this),e.prototype.__init3.call(this),e.prototype.__init4.call(this),e.prototype.__init5.call(this),this.jsxPragmaInfo=hA.default.call(void 0,s),this.isAutomaticRuntime=s.jsxRuntime==="automatic",this.jsxImportSource=s.jsxImportSource||"react"}process(){return this.tokens.matches1(lt.TokenType.jsxTagStart)?(this.processJSXTag(),!0):!1}getPrefixCode(){let t="";if(this.filenameVarName&&(t+=`const ${this.filenameVarName} = ${JSON.stringify(this.options.filePath||"")};`),this.isAutomaticRuntime)if(this.importProcessor)for(let[n,r]of Object.entries(this.cjsAutomaticModuleNameResolutions))t+=`var ${r} = require("${n}");`;else{let{createElement:n,...r}=this.esmAutomaticImportNameResolutions;n&&(t+=`import {createElement as ${n}} from "${this.jsxImportSource}";`);let o=Object.entries(r).map(([s,i])=>`${s} as ${i}`).join(", ");if(o){let s=this.jsxImportSource+(this.options.production?"/jsx-runtime":"/jsx-dev-runtime");t+=`import {${o}} from "${s}";`}}return t}processJSXTag(){let{jsxRole:t,start:n}=this.tokens.currentToken(),r=this.options.production?null:this.getElementLocationCode(n);this.isAutomaticRuntime&&t!==yl.JSXRole.KeyAfterPropSpread?this.transformTagToJSXFunc(r,t):this.transformTagToCreateElement(r)}getElementLocationCode(t){return`lineNumber: ${this.getLineNumberForIndex(t)}`}getLineNumberForIndex(t){let n=this.tokens.code;for(;this.lastIndex<t&&this.lastIndex<n.length;)n[this.lastIndex]===`
|
|
4
|
+
`&&this.lastLineNumber++,this.lastIndex++;return this.lastLineNumber}transformTagToJSXFunc(t,n){let r=n===yl.JSXRole.StaticChildren;this.tokens.replaceToken(this.getJSXFuncInvocationCode(r));let o=null;if(this.tokens.matches1(lt.TokenType.jsxTagEnd))this.tokens.replaceToken(`${this.getFragmentCode()}, {`),this.processAutomaticChildrenAndEndProps(n);else{if(this.processTagIntro(),this.tokens.appendCode(", {"),o=this.processProps(!0),this.tokens.matches2(lt.TokenType.slash,lt.TokenType.jsxTagEnd))this.tokens.appendCode("}");else if(this.tokens.matches1(lt.TokenType.jsxTagEnd))this.tokens.removeToken(),this.processAutomaticChildrenAndEndProps(n);else throw new Error("Expected either /> or > at the end of the tag.");o&&this.tokens.appendCode(`, ${o}`)}for(this.options.production||(o===null&&this.tokens.appendCode(", void 0"),this.tokens.appendCode(`, ${r}, ${this.getDevSource(t)}, this`)),this.tokens.removeInitialToken();!this.tokens.matches1(lt.TokenType.jsxTagEnd);)this.tokens.removeToken();this.tokens.replaceToken(")")}transformTagToCreateElement(t){if(this.tokens.replaceToken(this.getCreateElementInvocationCode()),this.tokens.matches1(lt.TokenType.jsxTagEnd))this.tokens.replaceToken(`${this.getFragmentCode()}, null`),this.processChildren(!0);else if(this.processTagIntro(),this.processPropsObjectWithDevInfo(t),!this.tokens.matches2(lt.TokenType.slash,lt.TokenType.jsxTagEnd))if(this.tokens.matches1(lt.TokenType.jsxTagEnd))this.tokens.removeToken(),this.processChildren(!0);else throw new Error("Expected either /> or > at the end of the tag.");for(this.tokens.removeInitialToken();!this.tokens.matches1(lt.TokenType.jsxTagEnd);)this.tokens.removeToken();this.tokens.replaceToken(")")}getJSXFuncInvocationCode(t){return this.options.production?t?this.claimAutoImportedFuncInvocation("jsxs","/jsx-runtime"):this.claimAutoImportedFuncInvocation("jsx","/jsx-runtime"):this.claimAutoImportedFuncInvocation("jsxDEV","/jsx-dev-runtime")}getCreateElementInvocationCode(){if(this.isAutomaticRuntime)return this.claimAutoImportedFuncInvocation("createElement","");{let{jsxPragmaInfo:t}=this;return`${this.importProcessor&&this.importProcessor.getIdentifierReplacement(t.base)||t.base}${t.suffix}(`}}getFragmentCode(){if(this.isAutomaticRuntime)return this.claimAutoImportedName("Fragment",this.options.production?"/jsx-runtime":"/jsx-dev-runtime");{let{jsxPragmaInfo:t}=this;return(this.importProcessor&&this.importProcessor.getIdentifierReplacement(t.fragmentBase)||t.fragmentBase)+t.fragmentSuffix}}claimAutoImportedFuncInvocation(t,n){let r=this.claimAutoImportedName(t,n);return this.importProcessor?`${r}.call(void 0, `:`${r}(`}claimAutoImportedName(t,n){if(this.importProcessor){let r=this.jsxImportSource+n;return this.cjsAutomaticModuleNameResolutions[r]||(this.cjsAutomaticModuleNameResolutions[r]=this.importProcessor.getFreeIdentifierForPath(r)),`${this.cjsAutomaticModuleNameResolutions[r]}.${t}`}else return this.esmAutomaticImportNameResolutions[t]||(this.esmAutomaticImportNameResolutions[t]=this.nameManager.claimFreeName(`_${t}`)),this.esmAutomaticImportNameResolutions[t]}processTagIntro(){let t=this.tokens.currentIndex()+1;for(;this.tokens.tokens[t].isType||!this.tokens.matches2AtIndex(t-1,lt.TokenType.jsxName,lt.TokenType.jsxName)&&!this.tokens.matches2AtIndex(t-1,lt.TokenType.greaterThan,lt.TokenType.jsxName)&&!this.tokens.matches1AtIndex(t,lt.TokenType.braceL)&&!this.tokens.matches1AtIndex(t,lt.TokenType.jsxTagEnd)&&!this.tokens.matches2AtIndex(t,lt.TokenType.slash,lt.TokenType.jsxTagEnd);)t++;if(t===this.tokens.currentIndex()+1){let n=this.tokens.identifierName();F0(n)&&this.tokens.replaceToken(`'${n}'`)}for(;this.tokens.currentIndex()<t;)this.rootTransformer.processToken()}processPropsObjectWithDevInfo(t){let n=this.options.production?"":`__self: this, __source: ${this.getDevSource(t)}`;if(!this.tokens.matches1(lt.TokenType.jsxName)&&!this.tokens.matches1(lt.TokenType.braceL)){n?this.tokens.appendCode(`, {${n}}`):this.tokens.appendCode(", null");return}this.tokens.appendCode(", {"),this.processProps(!1),n?this.tokens.appendCode(` ${n}}`):this.tokens.appendCode("}")}processProps(t){let n=null;for(;;){if(this.tokens.matches2(lt.TokenType.jsxName,lt.TokenType.eq)){let r=this.tokens.identifierName();if(t&&r==="key"){n!==null&&this.tokens.appendCode(n.replace(/[^\n]/g,"")),this.tokens.removeToken(),this.tokens.removeToken();let o=this.tokens.snapshot();this.processPropValue(),n=this.tokens.dangerouslyGetAndRemoveCodeSinceSnapshot(o);continue}else this.processPropName(r),this.tokens.replaceToken(": "),this.processPropValue()}else if(this.tokens.matches1(lt.TokenType.jsxName)){let r=this.tokens.identifierName();this.processPropName(r),this.tokens.appendCode(": true")}else if(this.tokens.matches1(lt.TokenType.braceL))this.tokens.replaceToken(""),this.rootTransformer.processBalancedCode(),this.tokens.replaceToken("");else break;this.tokens.appendCode(",")}return n}processPropName(t){t.includes("-")?this.tokens.replaceToken(`'${t}'`):this.tokens.copyToken()}processPropValue(){this.tokens.matches1(lt.TokenType.braceL)?(this.tokens.replaceToken(""),this.rootTransformer.processBalancedCode(),this.tokens.replaceToken("")):this.tokens.matches1(lt.TokenType.jsxTagStart)?this.processJSXTag():this.processStringPropValue()}processStringPropValue(){let t=this.tokens.currentToken(),n=this.tokens.code.slice(t.start+1,t.end-1),r=P0(n),o=wA(n);this.tokens.replaceToken(o+r)}processAutomaticChildrenAndEndProps(t){t===yl.JSXRole.StaticChildren?(this.tokens.appendCode(" children: ["),this.processChildren(!1),this.tokens.appendCode("]}")):(t===yl.JSXRole.OneChild&&this.tokens.appendCode(" children: "),this.processChildren(!1),this.tokens.appendCode("}"))}processChildren(t){let n=t;for(;;){if(this.tokens.matches2(lt.TokenType.jsxTagStart,lt.TokenType.slash))return;let r=!1;if(this.tokens.matches1(lt.TokenType.braceL))this.tokens.matches2(lt.TokenType.braceL,lt.TokenType.braceR)?(this.tokens.replaceToken(""),this.tokens.replaceToken("")):(this.tokens.replaceToken(n?", ":""),this.rootTransformer.processBalancedCode(),this.tokens.replaceToken(""),r=!0);else if(this.tokens.matches1(lt.TokenType.jsxTagStart))this.tokens.appendCode(n?", ":""),this.processJSXTag(),r=!0;else if(this.tokens.matches1(lt.TokenType.jsxText)||this.tokens.matches1(lt.TokenType.jsxEmptyText))r=this.processChildTextElement(n);else throw new Error("Unexpected token when processing JSX children.");r&&(n=!0)}}processChildTextElement(t){let n=this.tokens.currentToken(),r=this.tokens.code.slice(n.start,n.end),o=P0(r),s=yA(r);return s==='""'?(this.tokens.replaceToken(o),!1):(this.tokens.replaceToken(`${t?", ":""}${s}${o}`),!0)}getDevSource(t){return`{fileName: ${this.getFilenameVarName()}, ${t}}`}getFilenameVarName(){return this.filenameVarName||(this.filenameVarName=this.nameManager.claimFreeName("_jsxFileName")),this.filenameVarName}};wl.default=Td;function F0(e){let t=e.charCodeAt(0);return t>=kr.charCodes.lowercaseA&&t<=kr.charCodes.lowercaseZ}wl.startsWithLowerCase=F0;function yA(e){let t="",n="",r=!1,o=!1;for(let s=0;s<e.length;s++){let i=e[s];if(i===" "||i===" "||i==="\r")r||(n+=i);else if(i===`
|
|
5
|
+
`)n="",r=!0;else{if(o&&r&&(t+=" "),t+=n,n="",i==="&"){let{entity:a,newI:l}=O0(e,s+1);s=l-1,t+=a}else t+=i;o=!0,r=!1}}return r||(t+=n),JSON.stringify(t)}function P0(e){let t=0,n=0;for(let r of e)r===`
|
|
6
|
+
`?(t++,n=0):r===" "&&n++;return`
|
|
7
|
+
`.repeat(t)+" ".repeat(n)}function wA(e){let t="";for(let n=0;n<e.length;n++){let r=e[n];if(r===`
|
|
8
|
+
`)if(/\s/.test(e[n+1]))for(t+=" ";n<e.length&&/\s/.test(e[n+1]);)n++;else t+=`
|
|
9
|
+
`;else if(r==="&"){let{entity:o,newI:s}=O0(e,n+1);t+=o,n=s-1}else t+=r}return JSON.stringify(t)}function O0(e,t){let n="",r=0,o,s=t;if(e[s]==="#"){let i=10;s++;let a;if(e[s]==="x")for(i=16,s++,a=s;s<e.length&&_A(e.charCodeAt(s));)s++;else for(a=s;s<e.length&&kA(e.charCodeAt(s));)s++;if(e[s]===";"){let l=e.slice(a,s);l&&(s++,o=String.fromCodePoint(parseInt(l,i)))}}else for(;s<e.length&&r++<10;){let i=e[s];if(s++,i===";"){o=mA.default.get(n);break}n+=i}return o?{entity:o,newI:s}:{entity:"&",newI:t}}function kA(e){return e>=kr.charCodes.digit0&&e<=kr.charCodes.digit9}function _A(e){return e>=kr.charCodes.digit0&&e<=kr.charCodes.digit9||e>=kr.charCodes.lowercaseA&&e<=kr.charCodes.lowercaseF||e>=kr.charCodes.uppercaseA&&e<=kr.charCodes.uppercaseF}});var Rd=Ie($d=>{"use strict";Object.defineProperty($d,"__esModule",{value:!0});function vA(e){return e&&e.__esModule?e:{default:e}}var kl=en(),$s=et(),TA=Sd(),xA=kd(),SA=vA(xA);function $A(e,t){let n=SA.default.call(void 0,t),r=new Set;for(let o=0;o<e.tokens.length;o++){let s=e.tokens[o];if(s.type===$s.TokenType.name&&!s.isType&&(s.identifierRole===kl.IdentifierRole.Access||s.identifierRole===kl.IdentifierRole.ObjectShorthand||s.identifierRole===kl.IdentifierRole.ExportAccess)&&!s.shadowsGlobal&&r.add(e.identifierNameForToken(s)),s.type===$s.TokenType.jsxTagStart&&r.add(n.base),s.type===$s.TokenType.jsxTagStart&&o+1<e.tokens.length&&e.tokens[o+1].type===$s.TokenType.jsxTagEnd&&(r.add(n.base),r.add(n.fragmentBase)),s.type===$s.TokenType.jsxName&&s.identifierRole===kl.IdentifierRole.Access){let i=e.identifierNameForToken(s);(!TA.startsWithLowerCase.call(void 0,i)||e.tokens[o+1].type===$s.TokenType.dot)&&r.add(e.identifierNameForToken(s))}}return r}$d.getNonTypeIdentifiers=$A});var L0=Ie(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});function RA(e){return e&&e.__esModule?e:{default:e}}var CA=en(),_l=rn(),Ue=et(),AA=Ei(),EA=RA(AA),MA=Rd(),Cd=class e{__init(){this.nonTypeIdentifiers=new Set}__init2(){this.importInfoByPath=new Map}__init3(){this.importsToReplace=new Map}__init4(){this.identifierReplacements=new Map}__init5(){this.exportBindingsByLocalName=new Map}constructor(t,n,r,o,s,i,a){this.nameManager=t,this.tokens=n,this.enableLegacyTypeScriptModuleInterop=r,this.options=o,this.isTypeScriptTransformEnabled=s,this.keepUnusedImports=i,this.helperManager=a,e.prototype.__init.call(this),e.prototype.__init2.call(this),e.prototype.__init3.call(this),e.prototype.__init4.call(this),e.prototype.__init5.call(this)}preprocessTokens(){for(let t=0;t<this.tokens.tokens.length;t++)this.tokens.matches1AtIndex(t,Ue.TokenType._import)&&!this.tokens.matches3AtIndex(t,Ue.TokenType._import,Ue.TokenType.name,Ue.TokenType.eq)&&this.preprocessImportAtIndex(t),this.tokens.matches1AtIndex(t,Ue.TokenType._export)&&!this.tokens.matches2AtIndex(t,Ue.TokenType._export,Ue.TokenType.eq)&&this.preprocessExportAtIndex(t);this.generateImportReplacements()}pruneTypeOnlyImports(){this.nonTypeIdentifiers=MA.getNonTypeIdentifiers.call(void 0,this.tokens,this.options);for(let[t,n]of this.importInfoByPath.entries()){if(n.hasBareImport||n.hasStarExport||n.exportStarNames.length>0||n.namedExports.length>0)continue;[...n.defaultNames,...n.wildcardNames,...n.namedImports.map(({localName:o})=>o)].every(o=>this.shouldAutomaticallyElideImportedName(o))&&this.importsToReplace.set(t,"")}}shouldAutomaticallyElideImportedName(t){return this.isTypeScriptTransformEnabled&&!this.keepUnusedImports&&!this.nonTypeIdentifiers.has(t)}generateImportReplacements(){for(let[t,n]of this.importInfoByPath.entries()){let{defaultNames:r,wildcardNames:o,namedImports:s,namedExports:i,exportStarNames:a,hasStarExport:l}=n;if(r.length===0&&o.length===0&&s.length===0&&i.length===0&&a.length===0&&!l){this.importsToReplace.set(t,`require('${t}');`);continue}let c=this.getFreeIdentifierForPath(t),u;this.enableLegacyTypeScriptModuleInterop?u=c:u=o.length>0?o[0]:this.getFreeIdentifierForPath(t);let d=`var ${c} = require('${t}');`;if(o.length>0)for(let p of o){let f=this.enableLegacyTypeScriptModuleInterop?c:`${this.helperManager.getHelperName("interopRequireWildcard")}(${c})`;d+=` var ${p} = ${f};`}else a.length>0&&u!==c?d+=` var ${u} = ${this.helperManager.getHelperName("interopRequireWildcard")}(${c});`:r.length>0&&u!==c&&(d+=` var ${u} = ${this.helperManager.getHelperName("interopRequireDefault")}(${c});`);for(let{importedName:p,localName:f}of i)d+=` ${this.helperManager.getHelperName("createNamedExportFrom")}(${c}, '${f}', '${p}');`;for(let p of a)d+=` exports.${p} = ${u};`;l&&(d+=` ${this.helperManager.getHelperName("createStarExport")}(${c});`),this.importsToReplace.set(t,d);for(let p of r)this.identifierReplacements.set(p,`${u}.default`);for(let{importedName:p,localName:f}of s)this.identifierReplacements.set(f,`${c}.${p}`)}}getFreeIdentifierForPath(t){let n=t.split("/"),o=n[n.length-1].replace(/\W/g,"");return this.nameManager.claimFreeName(`_${o}`)}preprocessImportAtIndex(t){let n=[],r=[],o=[];if(t++,(this.tokens.matchesContextualAtIndex(t,_l.ContextualKeyword._type)||this.tokens.matches1AtIndex(t,Ue.TokenType._typeof))&&!this.tokens.matches1AtIndex(t+1,Ue.TokenType.comma)&&!this.tokens.matchesContextualAtIndex(t+1,_l.ContextualKeyword._from)||this.tokens.matches1AtIndex(t,Ue.TokenType.parenL))return;if(this.tokens.matches1AtIndex(t,Ue.TokenType.name)&&(n.push(this.tokens.identifierNameAtIndex(t)),t++,this.tokens.matches1AtIndex(t,Ue.TokenType.comma)&&t++),this.tokens.matches1AtIndex(t,Ue.TokenType.star)&&(t+=2,r.push(this.tokens.identifierNameAtIndex(t)),t++),this.tokens.matches1AtIndex(t,Ue.TokenType.braceL)){let a=this.getNamedImports(t+1);t=a.newIndex;for(let l of a.namedImports)l.importedName==="default"?n.push(l.localName):o.push(l)}if(this.tokens.matchesContextualAtIndex(t,_l.ContextualKeyword._from)&&t++,!this.tokens.matches1AtIndex(t,Ue.TokenType.string))throw new Error("Expected string token at the end of import statement.");let s=this.tokens.stringValueAtIndex(t),i=this.getImportInfo(s);i.defaultNames.push(...n),i.wildcardNames.push(...r),i.namedImports.push(...o),n.length===0&&r.length===0&&o.length===0&&(i.hasBareImport=!0)}preprocessExportAtIndex(t){if(this.tokens.matches2AtIndex(t,Ue.TokenType._export,Ue.TokenType._var)||this.tokens.matches2AtIndex(t,Ue.TokenType._export,Ue.TokenType._let)||this.tokens.matches2AtIndex(t,Ue.TokenType._export,Ue.TokenType._const))this.preprocessVarExportAtIndex(t);else if(this.tokens.matches2AtIndex(t,Ue.TokenType._export,Ue.TokenType._function)||this.tokens.matches2AtIndex(t,Ue.TokenType._export,Ue.TokenType._class)){let n=this.tokens.identifierNameAtIndex(t+2);this.addExportBinding(n,n)}else if(this.tokens.matches3AtIndex(t,Ue.TokenType._export,Ue.TokenType.name,Ue.TokenType._function)){let n=this.tokens.identifierNameAtIndex(t+3);this.addExportBinding(n,n)}else this.tokens.matches2AtIndex(t,Ue.TokenType._export,Ue.TokenType.braceL)?this.preprocessNamedExportAtIndex(t):this.tokens.matches2AtIndex(t,Ue.TokenType._export,Ue.TokenType.star)&&this.preprocessExportStarAtIndex(t)}preprocessVarExportAtIndex(t){let n=0;for(let r=t+2;;r++)if(this.tokens.matches1AtIndex(r,Ue.TokenType.braceL)||this.tokens.matches1AtIndex(r,Ue.TokenType.dollarBraceL)||this.tokens.matches1AtIndex(r,Ue.TokenType.bracketL))n++;else if(this.tokens.matches1AtIndex(r,Ue.TokenType.braceR)||this.tokens.matches1AtIndex(r,Ue.TokenType.bracketR))n--;else{if(n===0&&!this.tokens.matches1AtIndex(r,Ue.TokenType.name))break;if(this.tokens.matches1AtIndex(1,Ue.TokenType.eq)){let o=this.tokens.currentToken().rhsEndIndex;if(o==null)throw new Error("Expected = token with an end index.");r=o-1}else{let o=this.tokens.tokens[r];if(CA.isDeclaration.call(void 0,o)){let s=this.tokens.identifierNameAtIndex(r);this.identifierReplacements.set(s,`exports.${s}`)}}}}preprocessNamedExportAtIndex(t){t+=2;let{newIndex:n,namedImports:r}=this.getNamedImports(t);if(t=n,this.tokens.matchesContextualAtIndex(t,_l.ContextualKeyword._from))t++;else{for(let{importedName:i,localName:a}of r)this.addExportBinding(i,a);return}if(!this.tokens.matches1AtIndex(t,Ue.TokenType.string))throw new Error("Expected string token at the end of import statement.");let o=this.tokens.stringValueAtIndex(t);this.getImportInfo(o).namedExports.push(...r)}preprocessExportStarAtIndex(t){let n=null;if(this.tokens.matches3AtIndex(t,Ue.TokenType._export,Ue.TokenType.star,Ue.TokenType._as)?(t+=3,n=this.tokens.identifierNameAtIndex(t),t+=2):t+=3,!this.tokens.matches1AtIndex(t,Ue.TokenType.string))throw new Error("Expected string token at the end of star export statement.");let r=this.tokens.stringValueAtIndex(t),o=this.getImportInfo(r);n!==null?o.exportStarNames.push(n):o.hasStarExport=!0}getNamedImports(t){let n=[];for(;;){if(this.tokens.matches1AtIndex(t,Ue.TokenType.braceR)){t++;break}let r=EA.default.call(void 0,this.tokens,t);if(t=r.endIndex,r.isType||n.push({importedName:r.leftName,localName:r.rightName}),this.tokens.matches2AtIndex(t,Ue.TokenType.comma,Ue.TokenType.braceR)){t+=2;break}else if(this.tokens.matches1AtIndex(t,Ue.TokenType.braceR)){t++;break}else if(this.tokens.matches1AtIndex(t,Ue.TokenType.comma))t++;else throw new Error(`Unexpected token: ${JSON.stringify(this.tokens.tokens[t])}`)}return{newIndex:t,namedImports:n}}getImportInfo(t){let n=this.importInfoByPath.get(t);if(n)return n;let r={defaultNames:[],wildcardNames:[],namedImports:[],namedExports:[],hasBareImport:!1,exportStarNames:[],hasStarExport:!1};return this.importInfoByPath.set(t,r),r}addExportBinding(t,n){this.exportBindingsByLocalName.has(t)||this.exportBindingsByLocalName.set(t,[]),this.exportBindingsByLocalName.get(t).push(n)}claimImportCode(t){let n=this.importsToReplace.get(t);return this.importsToReplace.set(t,""),n||""}getIdentifierReplacement(t){return this.identifierReplacements.get(t)||null}resolveExportBinding(t){let n=this.exportBindingsByLocalName.get(t);return!n||n.length===0?null:n.map(r=>`exports.${r}`).join(" = ")}getGlobalNames(){return new Set([...this.identifierReplacements.keys(),...this.exportBindingsByLocalName.keys()])}};Ad.default=Cd});var Md=Ie((Ed,Mi)=>{(function(e,t){if(typeof Ed=="object"&&typeof Mi<"u")t(Mi),Mi.exports=n(Mi);else if(typeof define=="function"&&define.amd)define(["module"],function(r){t.apply(this,arguments),r.exports=n(r)});else{let r={exports:{}};t(r),e=typeof globalThis<"u"?globalThis:e||self,e.sourcemapCodec=n(r)}function n(r){return"default"in r.exports?r.exports.default:r.exports}})(Ed,(function(e){"use strict";var t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,s=(j,I)=>{for(var S in I)t(j,S,{get:I[S],enumerable:!0})},i=(j,I,S,A)=>{if(I&&typeof I=="object"||typeof I=="function")for(let U of r(I))!o.call(j,U)&&U!==S&&t(j,U,{get:()=>I[U],enumerable:!(A=n(I,U))||A.enumerable});return j},a=j=>i(t({},"__esModule",{value:!0}),j),l={};s(l,{decode:()=>W,decodeGeneratedRanges:()=>B,decodeOriginalScopes:()=>x,decodeRangeMappings:()=>O,encode:()=>q,encodeGeneratedRanges:()=>L,encodeOriginalScopes:()=>R,encodeRangeMappings:()=>ae}),e.exports=a(l);var c=44,u=59,d="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",p=new Uint8Array(64),f=new Uint8Array(128);for(let j=0;j<d.length;j++){let I=d.charCodeAt(j);p[j]=I,f[I]=j}function h(j){let I=0,S=0,A=0;do{let U=j.next();A=f[U],I|=(A&31)<<S,S+=5}while(A&32);return I}function g(j){return j&1?-2147483648|-(j>>>1):j>>>1}function b(j,I){do{let S=I&31;I>>>=5,I>0&&(S|=32),j.write(p[S])}while(I>0)}function k(j){return j<0?-j<<1|1:j<<1}function w(j,I){return j.pos>=I?!1:j.peek()!==c}var y=1024*16,_=typeof TextDecoder<"u"?new TextDecoder:typeof Buffer<"u"?{decode(j){return Buffer.from(j.buffer,j.byteOffset,j.byteLength).toString()}}:{decode(j){let I="";for(let S=0;S<j.length;S++)I+=String.fromCharCode(j[S]);return I}},v=class{constructor(){this.pos=0,this.out="",this.buffer=new Uint8Array(y)}write(j){let{buffer:I}=this;I[this.pos++]=j,this.pos===y&&(this.out+=_.decode(I),this.pos=0)}flush(){let{buffer:j,out:I,pos:S}=this;return S>0?I+_.decode(j.subarray(0,S)):I}},T=class{constructor(j){this.pos=0,this.buffer=j}next(){return this.buffer.charCodeAt(this.pos++)}peek(){return this.buffer.charCodeAt(this.pos)}indexOf(j){let{buffer:I,pos:S}=this,A=I.indexOf(j,S);return A===-1?I.length:A}},$=[];function x(j){let{length:I}=j,S=new T(j),A=[],U=[],de=0;for(;S.pos<I;S.pos++){de+=g(h(S));let te=g(h(S));if(!w(S,I)){let xe=U.pop();xe[2]=de,xe[3]=te;continue}let _e=g(h(S)),le=g(h(S))&1?[de,te,0,0,_e,g(h(S))]:[de,te,0,0,_e],pe=$;if(w(S,I)){pe=[];do{let xe=g(h(S));pe.push(xe)}while(w(S,I))}le.vars=pe,A.push(le),U.push(le)}return A}function R(j){let I=new v;for(let S=0;S<j.length;)S=C(j,S,I,[0]);return I.flush()}function C(j,I,S,A){let U=j[I],{0:de,1:te,2:_e,3:Se,4:H,vars:le}=U;I>0&&S.write(c),b(S,k(de-A[0])),A[0]=de,b(S,k(te)),b(S,k(H));let pe=U.length===6?1:0;b(S,k(pe)),U.length===6&&b(S,k(U[5]));for(let xe of le)b(S,k(xe));for(I++;I<j.length;){let xe=j[I],{0:ve,1:Oe}=xe;if(ve>_e||ve===_e&&Oe>=Se)break;I=C(j,I,S,A)}return S.write(c),b(S,k(_e-A[0])),A[0]=_e,b(S,k(Se)),I}function B(j){let{length:I}=j,S=new T(j),A=[],U=[],de=0,te=0,_e=0,Se=0,H=0,le=0,pe=0,xe=0;do{let ve=S.indexOf(";"),Oe=0;for(;S.pos<ve;S.pos++){if(Oe+=g(h(S)),!w(S,ve)){let pt=U.pop();pt[2]=de,pt[3]=Oe;continue}let ue=g(h(S)),me=ue&1,ge=ue&2,Re=ue&4,Le=null,Ne=$,We;if(me){let pt=te+g(h(S));_e=g(h(S))+(te===pt?_e:0),te=pt,We=[de,Oe,0,0,pt,_e]}else We=[de,Oe,0,0];if(We.isScope=!!Re,ge){let pt=Se,Nt=H;Se+=g(h(S));let yn=pt===Se;H=(yn?H:0)+g(h(S)),le=(yn&&Nt===H?le:0)+g(h(S)),Le=[Se,H,le]}if(We.callsite=Le,w(S,ve)){Ne=[];do{pe=de,xe=Oe;let pt=g(h(S)),Nt;if(pt<-1){Nt=[[g(h(S))]];for(let yn=-1;yn>pt;yn--){let En=pe;pe+=g(h(S)),xe=(pe===En?xe:0)+g(h(S));let Mn=g(h(S));Nt.push([Mn,pe,xe])}}else Nt=[[pt]];Ne.push(Nt)}while(w(S,ve))}We.bindings=Ne,A.push(We),U.push(We)}de++,S.pos=ve+1}while(S.pos<I);return A}function L(j){if(j.length===0)return"";let I=new v;for(let S=0;S<j.length;)S=Z(j,S,I,[0,0,0,0,0,0,0]);return I.flush()}function Z(j,I,S,A){let U=j[I],{0:de,1:te,2:_e,3:Se,isScope:H,callsite:le,bindings:pe}=U;A[0]<de?(X(S,A[0],de),A[0]=de,A[1]=0):I>0&&S.write(c),b(S,k(U[1]-A[1])),A[1]=U[1];let xe=(U.length===6?1:0)|(le?2:0)|(H?4:0);if(b(S,k(xe)),U.length===6){let{4:ve,5:Oe}=U;ve!==A[2]&&(A[3]=0),b(S,k(ve-A[2])),A[2]=ve,b(S,k(Oe-A[3])),A[3]=Oe}if(le){let{0:ve,1:Oe,2:ue}=U.callsite;ve!==A[4]?(A[5]=0,A[6]=0):Oe!==A[5]&&(A[6]=0),b(S,k(ve-A[4])),A[4]=ve,b(S,k(Oe-A[5])),A[5]=Oe,b(S,k(ue-A[6])),A[6]=ue}if(pe)for(let ve of pe){ve.length>1&&b(S,k(-ve.length));let Oe=ve[0][0];b(S,k(Oe));let ue=de,me=te;for(let ge=1;ge<ve.length;ge++){let Re=ve[ge];b(S,k(Re[1]-ue)),ue=Re[1],b(S,k(Re[2]-me)),me=Re[2],b(S,k(Re[0]))}}for(I++;I<j.length;){let ve=j[I],{0:Oe,1:ue}=ve;if(Oe>_e||Oe===_e&&ue>=Se)break;I=Z(j,I,S,A)}return A[0]<_e?(X(S,A[0],_e),A[0]=_e,A[1]=0):S.write(c),b(S,k(Se-A[1])),A[1]=Se,I}function X(j,I,S){do j.write(u);while(++I<S)}function O(j){let{length:I}=j,S=new T(j),A=[];do{let U=S.indexOf(";"),de=[],te=0;for(;S.pos<U;)te+=h(S),de.push(te);A.push(de),S.pos=U+1}while(S.pos<=I);return A}function ae(j){if(j.length===0)return"";let I=new v;for(let S=0;S<j.length;S++){let A=j[S];S>0&&I.write(u);let U=0;for(let de=0;de<A.length;de++){let te=A[de];b(I,te-U),U=te}}return I.flush()}function W(j){let{length:I}=j,S=new T(j),A=[],U=0,de=0,te=0,_e=0,Se=0;do{let H=S.indexOf(";"),le=[],pe=!0,xe=0;for(U=0;S.pos<H;){let ve;U+=g(h(S)),U<xe&&(pe=!1),xe=U,w(S,H)?(de+=g(h(S)),te+=g(h(S)),_e+=g(h(S)),w(S,H)?(Se+=g(h(S)),ve=[U,de,te,_e,Se]):ve=[U,de,te,_e]):ve=[U],le.push(ve),S.pos++}pe||ne(le),A.push(le),S.pos=H+1}while(S.pos<=I);return A}function ne(j){j.sort(z)}function z(j,I){return j[0]-I[0]}function q(j){let I=new v,S=0,A=0,U=0,de=0;for(let te=0;te<j.length;te++){let _e=j[te];if(te>0&&I.write(u),_e.length===0)continue;let Se=0;for(let H=0;H<_e.length;H++){let le=_e[H];H>0&&I.write(c),b(I,k(le[0]-Se)),Se=le[0],le.length!==1&&(b(I,k(le[1]-S)),b(I,k(le[2]-A)),b(I,k(le[3]-U)),S=le[1],A=le[2],U=le[3],le.length!==4&&(b(I,k(le[4]-de)),de=le[4]))}}return I.flush()}}))});var N0=Ie((Id,Pd)=>{(function(e,t){typeof Id=="object"&&typeof Pd<"u"?Pd.exports=t():typeof define=="function"&&define.amd?define(t):(e=typeof globalThis<"u"?globalThis:e||self,e.resolveURI=t())})(Id,(function(){"use strict";let e=/^[\w+.-]+:\/\//,t=/^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/,n=/^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;function r(b){return e.test(b)}function o(b){return b.startsWith("//")}function s(b){return b.startsWith("/")}function i(b){return b.startsWith("file:")}function a(b){return/^[.?#]/.test(b)}function l(b){let k=t.exec(b);return u(k[1],k[2]||"",k[3],k[4]||"",k[5]||"/",k[6]||"",k[7]||"")}function c(b){let k=n.exec(b),w=k[2];return u("file:","",k[1]||"","",s(w)?w:"/"+w,k[3]||"",k[4]||"")}function u(b,k,w,y,_,v,T){return{scheme:b,user:k,host:w,port:y,path:_,query:v,hash:T,type:7}}function d(b){if(o(b)){let w=l("http:"+b);return w.scheme="",w.type=6,w}if(s(b)){let w=l("http://foo.com"+b);return w.scheme="",w.host="",w.type=5,w}if(i(b))return c(b);if(r(b))return l(b);let k=l("http://foo.com/"+b);return k.scheme="",k.host="",k.type=b?b.startsWith("?")?3:b.startsWith("#")?2:4:1,k}function p(b){if(b.endsWith("/.."))return b;let k=b.lastIndexOf("/");return b.slice(0,k+1)}function f(b,k){h(k,k.type),b.path==="/"?b.path=k.path:b.path=p(k.path)+b.path}function h(b,k){let w=k<=4,y=b.path.split("/"),_=1,v=0,T=!1;for(let x=1;x<y.length;x++){let R=y[x];if(!R){T=!0;continue}if(T=!1,R!=="."){if(R===".."){v?(T=!0,v--,_--):w&&(y[_++]=R);continue}y[_++]=R,v++}}let $="";for(let x=1;x<_;x++)$+="/"+y[x];(!$||T&&!$.endsWith("/.."))&&($+="/"),b.path=$}function g(b,k){if(!b&&!k)return"";let w=d(b),y=w.type;if(k&&y!==7){let v=d(k),T=v.type;switch(y){case 1:w.hash=v.hash;case 2:w.query=v.query;case 3:case 4:f(w,v);case 5:w.user=v.user,w.host=v.host,w.port=v.port;case 6:w.scheme=v.scheme}T>y&&(y=T)}h(w,y);let _=w.query+w.hash;switch(y){case 2:case 3:return _;case 4:{let v=w.path.slice(1);return v?a(k||b)&&!a(v)?"./"+v+_:v+_:_||"."}case 5:return w.path+_;default:return w.scheme+"//"+w.user+w.host+w.port+w.path+_}}return g}))});var j0=Ie((Fd,Ii)=>{(function(e,t){if(typeof Fd=="object"&&typeof Ii<"u")t(Ii,N0(),Md()),Ii.exports=n(Ii);else if(typeof define=="function"&&define.amd)define(["module","@jridgewell/resolve-uri","@jridgewell/sourcemap-codec"],function(r){t.apply(this,arguments),r.exports=n(r)});else{let r={exports:{}};t(r,e.resolveURI,e.sourcemapCodec),e=typeof globalThis<"u"?globalThis:e||self,e.traceMapping=n(r)}function n(r){return"default"in r.exports?r.exports.default:r.exports}})(Fd,(function(e,t,n){"use strict";var r=Object.create,o=Object.defineProperty,s=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.getPrototypeOf,l=Object.prototype.hasOwnProperty,c=(V,be)=>function(){return be||(0,V[i(V)[0]])((be={exports:{}}).exports,be),be.exports},u=(V,be)=>{for(var we in be)o(V,we,{get:be[we],enumerable:!0})},d=(V,be,we,$e)=>{if(be&&typeof be=="object"||typeof be=="function")for(let De of i(be))!l.call(V,De)&&De!==we&&o(V,De,{get:()=>be[De],enumerable:!($e=s(be,De))||$e.enumerable});return V},p=(V,be,we)=>(we=V!=null?r(a(V)):{},d(be||!V||!V.__esModule?o(we,"default",{value:V,enumerable:!0}):we,V)),f=V=>d(o({},"__esModule",{value:!0}),V),h=c({"umd:@jridgewell/sourcemap-codec"(V,be){be.exports=n}}),g=c({"umd:@jridgewell/resolve-uri"(V,be){be.exports=t}}),b={};u(b,{AnyMap:()=>U,FlattenMap:()=>U,GREATEST_LOWER_BOUND:()=>xe,LEAST_UPPER_BOUND:()=>pe,TraceMap:()=>ve,allGeneratedPositionsFor:()=>Ne,decodedMap:()=>Mn,decodedMappings:()=>me,eachMapping:()=>We,encodedMap:()=>hr,encodedMappings:()=>ue,generatedPositionFor:()=>Le,isIgnored:()=>yn,originalPositionFor:()=>Re,presortedDecodedMap:()=>En,sourceContentFor:()=>Nt,traceSegment:()=>ge}),e.exports=f(b);var k=p(h()),w=p(g());function y(V){if(!V)return"";let be=V.lastIndexOf("/");return V.slice(0,be+1)}function _(V,be){let we=y(V),$e=be?be+"/":"";return De=>(0,w.default)($e+(De||""),we)}var v=0,T=1,$=2,x=3,R=4,C=1,B=2;function L(V,be){let we=Z(V,0);if(we===V.length)return V;be||(V=V.slice());for(let $e=we;$e<V.length;$e=Z(V,$e+1))V[$e]=O(V[$e],be);return V}function Z(V,be){for(let we=be;we<V.length;we++)if(!X(V[we]))return we;return V.length}function X(V){for(let be=1;be<V.length;be++)if(V[be][v]<V[be-1][v])return!1;return!0}function O(V,be){return be||(V=V.slice()),V.sort(ae)}function ae(V,be){return V[v]-be[v]}function W(V,be){let we=be.map(()=>[]);for(let $e=0;$e<V.length;$e++){let De=V[$e];for(let Pe=0;Pe<De.length;Pe++){let Xe=De[Pe];if(Xe.length===1)continue;let yt=Xe[T],Je=Xe[$],Mt=Xe[x],jt=we[yt];(jt[Je]||(jt[Je]=[])).push([Mt,$e,Xe[v]])}}for(let $e=0;$e<we.length;$e++){let De=we[$e];for(let Pe=0;Pe<De.length;Pe++){let Xe=De[Pe];Xe&&Xe.sort(ae)}}return we}var ne=!1;function z(V,be,we,$e){for(;we<=$e;){let De=we+($e-we>>1),Pe=V[De][v]-be;if(Pe===0)return ne=!0,De;Pe<0?we=De+1:$e=De-1}return ne=!1,we-1}function q(V,be,we){for(let $e=we+1;$e<V.length&&V[$e][v]===be;we=$e++);return we}function j(V,be,we){for(let $e=we-1;$e>=0&&V[$e][v]===be;we=$e--);return we}function I(){return{lastKey:-1,lastNeedle:-1,lastIndex:-1}}function S(V,be,we,$e){let{lastKey:De,lastNeedle:Pe,lastIndex:Xe}=we,yt=0,Je=V.length-1;if($e===De){if(be===Pe)return ne=Xe!==-1&&V[Xe][v]===be,Xe;be>=Pe?yt=Xe===-1?0:Xe:Je=Xe}return we.lastKey=$e,we.lastNeedle=be,we.lastIndex=z(V,be,yt,Je)}function A(V){return typeof V=="string"?JSON.parse(V):V}var U=function(V,be){let we=A(V);if(!("sections"in we))return new ve(we,be);let $e=[],De=[],Pe=[],Xe=[],yt=[];de(we,be,$e,De,Pe,Xe,yt,0,0,1/0,1/0);let Je={version:3,file:we.file,names:Xe,sources:De,sourcesContent:Pe,mappings:$e,ignoreList:yt};return En(Je)};function de(V,be,we,$e,De,Pe,Xe,yt,Je,Mt,jt){let{sections:Dt}=V;for(let on=0;on<Dt.length;on++){let{map:cn,offset:vn}=Dt[on],Tn=Mt,Fn=jt;if(on+1<Dt.length){let gr=Dt[on+1].offset;Tn=Math.min(Mt,yt+gr.line),Tn===Mt?Fn=Math.min(jt,Je+gr.column):Tn<Mt&&(Fn=Je+gr.column)}te(cn,be,we,$e,De,Pe,Xe,yt+vn.line,Je+vn.column,Tn,Fn)}}function te(V,be,we,$e,De,Pe,Xe,yt,Je,Mt,jt){let Dt=A(V);if("sections"in Dt)return de(...arguments);let on=new ve(Dt,be),cn=$e.length,vn=Pe.length,Tn=me(on),{resolvedSources:Fn,sourcesContent:gr,ignoreList:yo}=on;if(_e($e,Fn),_e(Pe,on.names),gr)_e(De,gr);else for(let un=0;un<Fn.length;un++)De.push(null);if(yo)for(let un=0;un<yo.length;un++)Xe.push(yo[un]+cn);for(let un=0;un<Tn.length;un++){let wo=yt+un;if(wo>Mt)return;let rs=Se(we,wo),ii=un===0?Je:0,os=Tn[un];for(let ko=0;ko<os.length;ko++){let nr=os[ko],Ur=ii+nr[v];if(wo===Mt&&Ur>=jt)return;if(nr.length===1){rs.push([Ur]);continue}let ss=cn+nr[T],is=nr[$],as=nr[x];rs.push(nr.length===4?[Ur,ss,is,as]:[Ur,ss,is,as,vn+nr[R]])}}}function _e(V,be){for(let we=0;we<be.length;we++)V.push(be[we])}function Se(V,be){for(let we=V.length;we<=be;we++)V[we]=[];return V[be]}var H="`line` must be greater than 0 (lines start at line 1)",le="`column` must be greater than or equal to 0 (columns start at column 0)",pe=-1,xe=1,ve=class{constructor(V,be){let we=typeof V=="string";if(!we&&V._decodedMemo)return V;let $e=A(V),{version:De,file:Pe,names:Xe,sourceRoot:yt,sources:Je,sourcesContent:Mt}=$e;this.version=De,this.file=Pe,this.names=Xe||[],this.sourceRoot=yt,this.sources=Je,this.sourcesContent=Mt,this.ignoreList=$e.ignoreList||$e.x_google_ignoreList||void 0;let jt=_(be,yt);this.resolvedSources=Je.map(jt);let{mappings:Dt}=$e;if(typeof Dt=="string")this._encoded=Dt,this._decoded=void 0;else if(Array.isArray(Dt))this._encoded=void 0,this._decoded=L(Dt,we);else throw $e.sections?new Error("TraceMap passed sectioned source map, please use FlattenMap export instead"):new Error(`invalid source map: ${JSON.stringify($e)}`);this._decodedMemo=I(),this._bySources=void 0,this._bySourceMemos=void 0}};function Oe(V){return V}function ue(V){var be,we;return(we=(be=V)._encoded)!=null?we:be._encoded=(0,k.encode)(V._decoded)}function me(V){var be;return(be=V)._decoded||(be._decoded=(0,k.decode)(V._encoded))}function ge(V,be,we){let $e=me(V);if(be>=$e.length)return null;let De=$e[be],Pe=tr(De,V._decodedMemo,be,we,xe);return Pe===-1?null:De[Pe]}function Re(V,be){let{line:we,column:$e,bias:De}=be;if(we--,we<0)throw new Error(H);if($e<0)throw new Error(le);let Pe=me(V);if(we>=Pe.length)return Pn(null,null,null,null);let Xe=Pe[we],yt=tr(Xe,V._decodedMemo,we,$e,De||xe);if(yt===-1)return Pn(null,null,null,null);let Je=Xe[yt];if(Je.length===1)return Pn(null,null,null,null);let{names:Mt,resolvedSources:jt}=V;return Pn(jt[Je[T]],Je[$]+1,Je[x],Je.length===5?Mt[Je[R]]:null)}function Le(V,be){let{source:we,line:$e,column:De,bias:Pe}=be;return ns(V,we,$e,De,Pe||xe,!1)}function Ne(V,be){let{source:we,line:$e,column:De,bias:Pe}=be;return ns(V,we,$e,De,Pe||pe,!0)}function We(V,be){let we=me(V),{names:$e,resolvedSources:De}=V;for(let Pe=0;Pe<we.length;Pe++){let Xe=we[Pe];for(let yt=0;yt<Xe.length;yt++){let Je=Xe[yt],Mt=Pe+1,jt=Je[0],Dt=null,on=null,cn=null,vn=null;Je.length!==1&&(Dt=De[Je[1]],on=Je[2]+1,cn=Je[3]),Je.length===5&&(vn=$e[Je[4]]),be({generatedLine:Mt,generatedColumn:jt,source:Dt,originalLine:on,originalColumn:cn,name:vn})}}}function pt(V,be){let{sources:we,resolvedSources:$e}=V,De=we.indexOf(be);return De===-1&&(De=$e.indexOf(be)),De}function Nt(V,be){let{sourcesContent:we}=V;if(we==null)return null;let $e=pt(V,be);return $e===-1?null:we[$e]}function yn(V,be){let{ignoreList:we}=V;if(we==null)return!1;let $e=pt(V,be);return $e===-1?!1:we.includes($e)}function En(V,be){let we=new ve(In(V,[]),be);return we._decoded=V.mappings,we}function Mn(V){return In(V,me(V))}function hr(V){return In(V,ue(V))}function In(V,be){return{version:V.version,file:V.file,names:V.names,sourceRoot:V.sourceRoot,sources:V.sources,sourcesContent:V.sourcesContent,mappings:be,ignoreList:V.ignoreList||V.x_google_ignoreList}}function Pn(V,be,we,$e){return{source:V,line:be,column:we,name:$e}}function wn(V,be){return{line:V,column:be}}function tr(V,be,we,$e,De){let Pe=S(V,$e,be,we);return ne?Pe=(De===pe?q:j)(V,$e,Pe):De===pe&&Pe++,Pe===-1||Pe===V.length?-1:Pe}function si(V,be,we,$e,De){let Pe=tr(V,be,we,$e,xe);if(!ne&&De===pe&&Pe++,Pe===-1||Pe===V.length)return[];let Xe=ne?$e:V[Pe][v];ne||(Pe=j(V,Xe,Pe));let yt=q(V,Xe,Pe),Je=[];for(;Pe<=yt;Pe++){let Mt=V[Pe];Je.push(wn(Mt[C]+1,Mt[B]))}return Je}function ns(V,be,we,$e,De,Pe){var Xe,yt;if(we--,we<0)throw new Error(H);if($e<0)throw new Error(le);let{sources:Je,resolvedSources:Mt}=V,jt=Je.indexOf(be);if(jt===-1&&(jt=Mt.indexOf(be)),jt===-1)return Pe?[]:wn(null,null);let Dt=(Xe=V)._bySourceMemos||(Xe._bySourceMemos=Je.map(I)),cn=((yt=V)._bySources||(yt._bySources=W(me(V),Dt)))[jt][we];if(cn==null)return Pe?[]:wn(null,null);let vn=Dt[jt];if(Pe)return si(cn,vn,we,$e,De);let Tn=tr(cn,vn,we,$e,De);if(Tn===-1)return wn(null,null);let Fn=cn[Tn];return wn(Fn[C]+1,Fn[B])}}))});var D0=Ie((Od,Pi)=>{(function(e,t){if(typeof Od=="object"&&typeof Pi<"u")t(Pi,Md(),j0()),Pi.exports=n(Pi);else if(typeof define=="function"&&define.amd)define(["module","@jridgewell/sourcemap-codec","@jridgewell/trace-mapping"],function(r){t.apply(this,arguments),r.exports=n(r)});else{let r={exports:{}};t(r,e.sourcemapCodec,e.traceMapping),e=typeof globalThis<"u"?globalThis:e||self,e.genMapping=n(r)}function n(r){return"default"in r.exports?r.exports.default:r.exports}})(Od,(function(e,t,n){"use strict";var r=Object.create,o=Object.defineProperty,s=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.getPrototypeOf,l=Object.prototype.hasOwnProperty,c=(ue,me)=>function(){return me||(0,ue[i(ue)[0]])((me={exports:{}}).exports,me),me.exports},u=(ue,me)=>{for(var ge in me)o(ue,ge,{get:me[ge],enumerable:!0})},d=(ue,me,ge,Re)=>{if(me&&typeof me=="object"||typeof me=="function")for(let Le of i(me))!l.call(ue,Le)&&Le!==ge&&o(ue,Le,{get:()=>me[Le],enumerable:!(Re=s(me,Le))||Re.enumerable});return ue},p=(ue,me,ge)=>(ge=ue!=null?r(a(ue)):{},d(me||!ue||!ue.__esModule?o(ge,"default",{value:ue,enumerable:!0}):ge,ue)),f=ue=>d(o({},"__esModule",{value:!0}),ue),h=c({"umd:@jridgewell/sourcemap-codec"(ue,me){me.exports=t}}),g=c({"umd:@jridgewell/trace-mapping"(ue,me){me.exports=n}}),b={};u(b,{GenMapping:()=>X,addMapping:()=>W,addSegment:()=>ae,allMappings:()=>U,fromMap:()=>A,maybeAddMapping:()=>z,maybeAddSegment:()=>ne,setIgnore:()=>j,setSourceContent:()=>q,toDecodedMap:()=>I,toEncodedMap:()=>S}),e.exports=f(b);var k=class{constructor(){this._indexes={__proto__:null},this.array=[]}};function w(ue){return ue}function y(ue,me){return ue._indexes[me]}function _(ue,me){let ge=y(ue,me);if(ge!==void 0)return ge;let{array:Re,_indexes:Le}=ue,Ne=Re.push(me);return Le[me]=Ne-1}function v(ue,me){let ge=y(ue,me);if(ge===void 0)return;let{array:Re,_indexes:Le}=ue;for(let Ne=ge+1;Ne<Re.length;Ne++){let We=Re[Ne];Re[Ne-1]=We,Le[We]--}Le[me]=void 0,Re.pop()}var T=p(h()),$=p(g()),x=0,R=1,C=2,B=3,L=4,Z=-1,X=class{constructor({file:ue,sourceRoot:me}={}){this._names=new k,this._sources=new k,this._sourcesContent=[],this._mappings=[],this.file=ue,this.sourceRoot=me,this._ignoreList=new k}};function O(ue){return ue}function ae(ue,me,ge,Re,Le,Ne,We,pt){return de(!1,ue,me,ge,Re,Le,Ne,We,pt)}function W(ue,me){return Oe(!1,ue,me)}var ne=(ue,me,ge,Re,Le,Ne,We,pt)=>de(!0,ue,me,ge,Re,Le,Ne,We,pt),z=(ue,me)=>Oe(!0,ue,me);function q(ue,me,ge){let{_sources:Re,_sourcesContent:Le}=ue,Ne=_(Re,me);Le[Ne]=ge}function j(ue,me,ge=!0){let{_sources:Re,_sourcesContent:Le,_ignoreList:Ne}=ue,We=_(Re,me);We===Le.length&&(Le[We]=null),ge?_(Ne,We):v(Ne,We)}function I(ue){let{_mappings:me,_sources:ge,_sourcesContent:Re,_names:Le,_ignoreList:Ne}=ue;return le(me),{version:3,file:ue.file||void 0,names:Le.array,sourceRoot:ue.sourceRoot||void 0,sources:ge.array,sourcesContent:Re,mappings:me,ignoreList:Ne.array}}function S(ue){let me=I(ue);return Object.assign({},me,{mappings:(0,T.encode)(me.mappings)})}function A(ue){let me=new $.TraceMap(ue),ge=new X({file:me.file,sourceRoot:me.sourceRoot});return pe(ge._names,me.names),pe(ge._sources,me.sources),ge._sourcesContent=me.sourcesContent||me.sources.map(()=>null),ge._mappings=(0,$.decodedMappings)(me),me.ignoreList&&pe(ge._ignoreList,me.ignoreList),ge}function U(ue){let me=[],{_mappings:ge,_sources:Re,_names:Le}=ue;for(let Ne=0;Ne<ge.length;Ne++){let We=ge[Ne];for(let pt=0;pt<We.length;pt++){let Nt=We[pt],yn={line:Ne+1,column:Nt[x]},En,Mn,hr;Nt.length!==1&&(En=Re.array[Nt[R]],Mn={line:Nt[C]+1,column:Nt[B]},Nt.length===5&&(hr=Le.array[Nt[L]])),me.push({generated:yn,source:En,original:Mn,name:hr})}}return me}function de(ue,me,ge,Re,Le,Ne,We,pt,Nt){let{_mappings:yn,_sources:En,_sourcesContent:Mn,_names:hr}=me,In=_e(yn,ge),Pn=Se(In,Re);if(!Le)return ue&&xe(In,Pn)?void 0:H(In,Pn,[Re]);let wn=_(En,Le),tr=pt?_(hr,pt):Z;if(wn===Mn.length&&(Mn[wn]=Nt??null),!(ue&&ve(In,Pn,wn,Ne,We,tr)))return H(In,Pn,pt?[Re,wn,Ne,We,tr]:[Re,wn,Ne,We])}function te(ue){}function _e(ue,me){for(let ge=ue.length;ge<=me;ge++)ue[ge]=[];return ue[me]}function Se(ue,me){let ge=ue.length;for(let Re=ge-1;Re>=0;ge=Re--){let Le=ue[Re];if(me>=Le[x])break}return ge}function H(ue,me,ge){for(let Re=ue.length;Re>me;Re--)ue[Re]=ue[Re-1];ue[me]=ge}function le(ue){let{length:me}=ue,ge=me;for(let Re=ge-1;Re>=0&&!(ue[Re].length>0);ge=Re,Re--);ge<me&&(ue.length=ge)}function pe(ue,me){for(let ge=0;ge<me.length;ge++)_(ue,me[ge])}function xe(ue,me){return me===0?!0:ue[me-1].length===1}function ve(ue,me,ge,Re,Le,Ne){if(me===0)return!1;let We=ue[me-1];return We.length===1?!1:ge===We[R]&&Re===We[C]&&Le===We[B]&&Ne===(We.length===5?We[L]:Z)}function Oe(ue,me,ge){let{generated:Re,source:Le,original:Ne,name:We,content:pt}=ge;return Le?de(ue,me,Re.line-1,Re.column,Le,Ne.line-1,Ne.column,We,pt):de(ue,me,Re.line-1,Re.column,null,null,null,null,null)}}))});var q0=Ie(Ld=>{"use strict";Object.defineProperty(Ld,"__esModule",{value:!0});var Fi=D0(),B0=Nn();function IA({code:e,mappings:t},n,r,o,s){let i=PA(o,s),a=new Fi.GenMapping({file:r.compiledFilename}),l=0,c=t[0];for(;c===void 0&&l<t.length-1;)l++,c=t[l];let u=0,d=0;c!==d&&Fi.maybeAddSegment.call(void 0,a,u,0,n,u,0);for(let g=0;g<e.length;g++){if(g===c){let b=c-d,k=i[l];for(Fi.maybeAddSegment.call(void 0,a,u,b,n,u,k);(c===g||c===void 0)&&l<t.length-1;)l++,c=t[l]}e.charCodeAt(g)===B0.charCodes.lineFeed&&(u++,d=g+1,c!==d&&Fi.maybeAddSegment.call(void 0,a,u,0,n,u,0))}let{sourceRoot:p,sourcesContent:f,...h}=Fi.toEncodedMap.call(void 0,a);return h}Ld.default=IA;function PA(e,t){let n=new Array(t.length),r=0,o=t[r].start,s=0;for(let i=0;i<e.length;i++)i===o&&(n[r]=o-s,r++,o=t[r].start),e.charCodeAt(i)===B0.charCodes.lineFeed&&(s=i+1);return n}});var U0=Ie(jd=>{"use strict";Object.defineProperty(jd,"__esModule",{value:!0});var FA={require:`
|
|
10
|
+
import {createRequire as CREATE_REQUIRE_NAME} from "module";
|
|
11
|
+
const require = CREATE_REQUIRE_NAME(import.meta.url);
|
|
12
|
+
`,interopRequireWildcard:`
|
|
13
|
+
function interopRequireWildcard(obj) {
|
|
14
|
+
if (obj && obj.__esModule) {
|
|
15
|
+
return obj;
|
|
16
|
+
} else {
|
|
17
|
+
var newObj = {};
|
|
18
|
+
if (obj != null) {
|
|
19
|
+
for (var key in obj) {
|
|
20
|
+
if (Object.prototype.hasOwnProperty.call(obj, key)) {
|
|
21
|
+
newObj[key] = obj[key];
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
newObj.default = obj;
|
|
26
|
+
return newObj;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
`,interopRequireDefault:`
|
|
30
|
+
function interopRequireDefault(obj) {
|
|
31
|
+
return obj && obj.__esModule ? obj : { default: obj };
|
|
32
|
+
}
|
|
33
|
+
`,createNamedExportFrom:`
|
|
34
|
+
function createNamedExportFrom(obj, localName, importedName) {
|
|
35
|
+
Object.defineProperty(exports, localName, {enumerable: true, configurable: true, get: () => obj[importedName]});
|
|
36
|
+
}
|
|
37
|
+
`,createStarExport:`
|
|
38
|
+
function createStarExport(obj) {
|
|
39
|
+
Object.keys(obj)
|
|
40
|
+
.filter((key) => key !== "default" && key !== "__esModule")
|
|
41
|
+
.forEach((key) => {
|
|
42
|
+
if (exports.hasOwnProperty(key)) {
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
Object.defineProperty(exports, key, {enumerable: true, configurable: true, get: () => obj[key]});
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
`,nullishCoalesce:`
|
|
49
|
+
function nullishCoalesce(lhs, rhsFn) {
|
|
50
|
+
if (lhs != null) {
|
|
51
|
+
return lhs;
|
|
52
|
+
} else {
|
|
53
|
+
return rhsFn();
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
`,asyncNullishCoalesce:`
|
|
57
|
+
async function asyncNullishCoalesce(lhs, rhsFn) {
|
|
58
|
+
if (lhs != null) {
|
|
59
|
+
return lhs;
|
|
60
|
+
} else {
|
|
61
|
+
return await rhsFn();
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
`,optionalChain:`
|
|
65
|
+
function optionalChain(ops) {
|
|
66
|
+
let lastAccessLHS = undefined;
|
|
67
|
+
let value = ops[0];
|
|
68
|
+
let i = 1;
|
|
69
|
+
while (i < ops.length) {
|
|
70
|
+
const op = ops[i];
|
|
71
|
+
const fn = ops[i + 1];
|
|
72
|
+
i += 2;
|
|
73
|
+
if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {
|
|
74
|
+
return undefined;
|
|
75
|
+
}
|
|
76
|
+
if (op === 'access' || op === 'optionalAccess') {
|
|
77
|
+
lastAccessLHS = value;
|
|
78
|
+
value = fn(value);
|
|
79
|
+
} else if (op === 'call' || op === 'optionalCall') {
|
|
80
|
+
value = fn((...args) => value.call(lastAccessLHS, ...args));
|
|
81
|
+
lastAccessLHS = undefined;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return value;
|
|
85
|
+
}
|
|
86
|
+
`,asyncOptionalChain:`
|
|
87
|
+
async function asyncOptionalChain(ops) {
|
|
88
|
+
let lastAccessLHS = undefined;
|
|
89
|
+
let value = ops[0];
|
|
90
|
+
let i = 1;
|
|
91
|
+
while (i < ops.length) {
|
|
92
|
+
const op = ops[i];
|
|
93
|
+
const fn = ops[i + 1];
|
|
94
|
+
i += 2;
|
|
95
|
+
if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {
|
|
96
|
+
return undefined;
|
|
97
|
+
}
|
|
98
|
+
if (op === 'access' || op === 'optionalAccess') {
|
|
99
|
+
lastAccessLHS = value;
|
|
100
|
+
value = await fn(value);
|
|
101
|
+
} else if (op === 'call' || op === 'optionalCall') {
|
|
102
|
+
value = await fn((...args) => value.call(lastAccessLHS, ...args));
|
|
103
|
+
lastAccessLHS = undefined;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return value;
|
|
107
|
+
}
|
|
108
|
+
`,optionalChainDelete:`
|
|
109
|
+
function optionalChainDelete(ops) {
|
|
110
|
+
const result = OPTIONAL_CHAIN_NAME(ops);
|
|
111
|
+
return result == null ? true : result;
|
|
112
|
+
}
|
|
113
|
+
`,asyncOptionalChainDelete:`
|
|
114
|
+
async function asyncOptionalChainDelete(ops) {
|
|
115
|
+
const result = await ASYNC_OPTIONAL_CHAIN_NAME(ops);
|
|
116
|
+
return result == null ? true : result;
|
|
117
|
+
}
|
|
118
|
+
`},Nd=class e{__init(){this.helperNames={}}__init2(){this.createRequireName=null}constructor(t){this.nameManager=t,e.prototype.__init.call(this),e.prototype.__init2.call(this)}getHelperName(t){let n=this.helperNames[t];return n||(n=this.nameManager.claimFreeName(`_${t}`),this.helperNames[t]=n,n)}emitHelpers(){let t="";this.helperNames.optionalChainDelete&&this.getHelperName("optionalChain"),this.helperNames.asyncOptionalChainDelete&&this.getHelperName("asyncOptionalChain");for(let[n,r]of Object.entries(FA)){let o=this.helperNames[n],s=r;n==="optionalChainDelete"?s=s.replace("OPTIONAL_CHAIN_NAME",this.helperNames.optionalChain):n==="asyncOptionalChainDelete"?s=s.replace("ASYNC_OPTIONAL_CHAIN_NAME",this.helperNames.asyncOptionalChain):n==="require"&&(this.createRequireName===null&&(this.createRequireName=this.nameManager.claimFreeName("_createRequire")),s=s.replace(/CREATE_REQUIRE_NAME/g,this.createRequireName)),o&&(t+=" ",t+=s.replace(n,o).replace(/\s+/g," ").trim())}return t}};jd.HelperManager=Nd});var z0=Ie(Tl=>{"use strict";Object.defineProperty(Tl,"__esModule",{value:!0});var Dd=en(),vl=et();function OA(e,t,n){H0(e,n)&&LA(e,t,n)}Tl.default=OA;function H0(e,t){for(let n of e.tokens)if(n.type===vl.TokenType.name&&!n.isType&&Dd.isNonTopLevelDeclaration.call(void 0,n)&&t.has(e.identifierNameForToken(n)))return!0;return!1}Tl.hasShadowedGlobals=H0;function LA(e,t,n){let r=[],o=t.length-1;for(let s=e.tokens.length-1;;s--){for(;r.length>0&&r[r.length-1].startTokenIndex===s+1;)r.pop();for(;o>=0&&t[o].endTokenIndex===s+1;)r.push(t[o]),o--;if(s<0)break;let i=e.tokens[s],a=e.identifierNameForToken(i);if(r.length>1&&!i.isType&&i.type===vl.TokenType.name&&n.has(a)){if(Dd.isBlockScopedDeclaration.call(void 0,i))G0(r[r.length-1],e,a);else if(Dd.isFunctionScopedDeclaration.call(void 0,i)){let l=r.length-1;for(;l>0&&!r[l].isFunctionScope;)l--;if(l<0)throw new Error("Did not find parent function scope.");G0(r[l],e,a)}}}if(r.length>0)throw new Error("Expected empty scope stack after processing file.")}function G0(e,t,n){for(let r=e.startTokenIndex;r<e.endTokenIndex;r++){let o=t.tokens[r];(o.type===vl.TokenType.name||o.type===vl.TokenType.jsxName)&&t.identifierNameForToken(o)===n&&(o.shadowsGlobal=!0)}}});var W0=Ie(Bd=>{"use strict";Object.defineProperty(Bd,"__esModule",{value:!0});var NA=et();function jA(e,t){let n=[];for(let r of t)r.type===NA.TokenType.name&&n.push(e.slice(r.start,r.end));return n}Bd.default=jA});var K0=Ie(Ud=>{"use strict";Object.defineProperty(Ud,"__esModule",{value:!0});function DA(e){return e&&e.__esModule?e:{default:e}}var BA=W0(),qA=DA(BA),qd=class e{__init(){this.usedNames=new Set}constructor(t,n){e.prototype.__init.call(this),this.usedNames=new Set(qA.default.call(void 0,t,n))}claimFreeName(t){let n=this.findFreeName(t);return this.usedNames.add(n),n}findFreeName(t){if(!this.usedNames.has(t))return t;let n=2;for(;this.usedNames.has(t+String(n));)n++;return t+String(n)}};Ud.default=qd});var xl=Ie(_r=>{"use strict";var UA=_r&&_r.__extends||(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,o){r.__proto__=o}||function(r,o){for(var s in o)o.hasOwnProperty(s)&&(r[s]=o[s])},e(t,n)};return function(t,n){e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})();Object.defineProperty(_r,"__esModule",{value:!0});_r.DetailContext=_r.NoopContext=_r.VError=void 0;var V0=(function(e){UA(t,e);function t(n,r){var o=e.call(this,r)||this;return o.path=n,Object.setPrototypeOf(o,t.prototype),o}return t})(Error);_r.VError=V0;var GA=(function(){function e(){}return e.prototype.fail=function(t,n,r){return!1},e.prototype.unionResolver=function(){return this},e.prototype.createContext=function(){return this},e.prototype.resolveUnion=function(t){},e})();_r.NoopContext=GA;var J0=(function(){function e(){this._propNames=[""],this._messages=[null],this._score=0}return e.prototype.fail=function(t,n,r){return this._propNames.push(t),this._messages.push(n),this._score+=r,!1},e.prototype.unionResolver=function(){return new HA},e.prototype.resolveUnion=function(t){for(var n,r,o=t,s=null,i=0,a=o.contexts;i<a.length;i++){var l=a[i];(!s||l._score>=s._score)&&(s=l)}s&&s._score>0&&((n=this._propNames).push.apply(n,s._propNames),(r=this._messages).push.apply(r,s._messages))},e.prototype.getError=function(t){for(var n=[],r=this._propNames.length-1;r>=0;r--){var o=this._propNames[r];t+=typeof o=="number"?"["+o+"]":o?"."+o:"";var s=this._messages[r];s&&n.push(t+" "+s)}return new V0(t,n.join("; "))},e.prototype.getErrorDetail=function(t){for(var n=[],r=this._propNames.length-1;r>=0;r--){var o=this._propNames[r];t+=typeof o=="number"?"["+o+"]":o?"."+o:"";var s=this._messages[r];s&&n.push({path:t,message:s})}for(var i=null,r=n.length-1;r>=0;r--)i&&(n[r].nested=[i]),i=n[r];return i},e})();_r.DetailContext=J0;var HA=(function(){function e(){this.contexts=[]}return e.prototype.createContext=function(){var t=new J0;return this.contexts.push(t),t},e})()});var Xd=Ie(Fe=>{"use strict";var qn=Fe&&Fe.__extends||(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,o){r.__proto__=o}||function(r,o){for(var s in o)o.hasOwnProperty(s)&&(r[s]=o[s])},e(t,n)};return function(t,n){e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})();Object.defineProperty(Fe,"__esModule",{value:!0});Fe.basicTypes=Fe.BasicType=Fe.TParamList=Fe.TParam=Fe.param=Fe.TFunc=Fe.func=Fe.TProp=Fe.TOptional=Fe.opt=Fe.TIface=Fe.iface=Fe.TEnumLiteral=Fe.enumlit=Fe.TEnumType=Fe.enumtype=Fe.TIntersection=Fe.intersection=Fe.TUnion=Fe.union=Fe.TTuple=Fe.tuple=Fe.TArray=Fe.array=Fe.TLiteral=Fe.lit=Fe.TName=Fe.name=Fe.TType=void 0;var Y0=xl(),$n=(function(){function e(){}return e})();Fe.TType=$n;function Yr(e){return typeof e=="string"?Z0(e):e}function zd(e,t){var n=e[t];if(!n)throw new Error("Unknown type "+t);return n}function Z0(e){return new Wd(e)}Fe.name=Z0;var Wd=(function(e){qn(t,e);function t(n){var r=e.call(this)||this;return r.name=n,r._failMsg="is not a "+n,r}return t.prototype.getChecker=function(n,r,o){var s=this,i=zd(n,this.name),a=i.getChecker(n,r,o);return i instanceof pn||i instanceof t?a:function(l,c){return a(l,c)?!0:c.fail(null,s._failMsg,0)}},t})($n);Fe.TName=Wd;function zA(e){return new Kd(e)}Fe.lit=zA;var Kd=(function(e){qn(t,e);function t(n){var r=e.call(this)||this;return r.value=n,r.name=JSON.stringify(n),r._failMsg="is not "+r.name,r}return t.prototype.getChecker=function(n,r){var o=this;return function(s,i){return s===o.value?!0:i.fail(null,o._failMsg,-1)}},t})($n);Fe.TLiteral=Kd;function WA(e){return new ew(Yr(e))}Fe.array=WA;var ew=(function(e){qn(t,e);function t(n){var r=e.call(this)||this;return r.ttype=n,r}return t.prototype.getChecker=function(n,r){var o=this.ttype.getChecker(n,r);return function(s,i){if(!Array.isArray(s))return i.fail(null,"is not an array",0);for(var a=0;a<s.length;a++){var l=o(s[a],i);if(!l)return i.fail(a,null,1)}return!0}},t})($n);Fe.TArray=ew;function KA(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return new tw(e.map(function(n){return Yr(n)}))}Fe.tuple=KA;var tw=(function(e){qn(t,e);function t(n){var r=e.call(this)||this;return r.ttypes=n,r}return t.prototype.getChecker=function(n,r){var o=this.ttypes.map(function(i){return i.getChecker(n,r)}),s=function(i,a){if(!Array.isArray(i))return a.fail(null,"is not an array",0);for(var l=0;l<o.length;l++){var c=o[l](i[l],a);if(!c)return a.fail(l,null,1)}return!0};return r?function(i,a){return s(i,a)?i.length<=o.length?!0:a.fail(o.length,"is extraneous",2):!1}:s},t})($n);Fe.TTuple=tw;function VA(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return new nw(e.map(function(n){return Yr(n)}))}Fe.union=VA;var nw=(function(e){qn(t,e);function t(n){var r=e.call(this)||this;r.ttypes=n;var o=n.map(function(i){return i instanceof Wd||i instanceof Kd?i.name:null}).filter(function(i){return i}),s=n.length-o.length;return o.length?(s>0&&o.push(s+" more"),r._failMsg="is none of "+o.join(", ")):r._failMsg="is none of "+s+" types",r}return t.prototype.getChecker=function(n,r){var o=this,s=this.ttypes.map(function(i){return i.getChecker(n,r)});return function(i,a){for(var l=a.unionResolver(),c=0;c<s.length;c++){var u=s[c](i,l.createContext());if(u)return!0}return a.resolveUnion(l),a.fail(null,o._failMsg,0)}},t})($n);Fe.TUnion=nw;function JA(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return new rw(e.map(function(n){return Yr(n)}))}Fe.intersection=JA;var rw=(function(e){qn(t,e);function t(n){var r=e.call(this)||this;return r.ttypes=n,r}return t.prototype.getChecker=function(n,r){var o=new Set,s=this.ttypes.map(function(i){return i.getChecker(n,r,o)});return function(i,a){var l=s.every(function(c){return c(i,a)});return l?!0:a.fail(null,null,0)}},t})($n);Fe.TIntersection=rw;function XA(e){return new Vd(e)}Fe.enumtype=XA;var Vd=(function(e){qn(t,e);function t(n){var r=e.call(this)||this;return r.members=n,r.validValues=new Set,r._failMsg="is not a valid enum value",r.validValues=new Set(Object.keys(n).map(function(o){return n[o]})),r}return t.prototype.getChecker=function(n,r){var o=this;return function(s,i){return o.validValues.has(s)?!0:i.fail(null,o._failMsg,0)}},t})($n);Fe.TEnumType=Vd;function QA(e,t){return new ow(e,t)}Fe.enumlit=QA;var ow=(function(e){qn(t,e);function t(n,r){var o=e.call(this)||this;return o.enumName=n,o.prop=r,o._failMsg="is not "+n+"."+r,o}return t.prototype.getChecker=function(n,r){var o=this,s=zd(n,this.enumName);if(!(s instanceof Vd))throw new Error("Type "+this.enumName+" used in enumlit is not an enum type");var i=s.members[this.prop];if(!s.members.hasOwnProperty(this.prop))throw new Error("Unknown value "+this.enumName+"."+this.prop+" used in enumlit");return function(a,l){return a===i?!0:l.fail(null,o._failMsg,-1)}},t})($n);Fe.TEnumLiteral=ow;function YA(e){return Object.keys(e).map(function(t){return ZA(t,e[t])})}function ZA(e,t){return t instanceof Jd?new Hd(e,t.ttype,!0):new Hd(e,Yr(t),!1)}function eE(e,t){return new sw(e,YA(t))}Fe.iface=eE;var sw=(function(e){qn(t,e);function t(n,r){var o=e.call(this)||this;return o.bases=n,o.props=r,o.propSet=new Set(r.map(function(s){return s.name})),o}return t.prototype.getChecker=function(n,r,o){var s=this,i=this.bases.map(function(p){return zd(n,p).getChecker(n,r)}),a=this.props.map(function(p){return p.ttype.getChecker(n,r)}),l=new Y0.NoopContext,c=this.props.map(function(p,f){return!p.isOpt&&!a[f](void 0,l)}),u=function(p,f){if(typeof p!="object"||p===null)return f.fail(null,"is not an object",0);for(var h=0;h<i.length;h++)if(!i[h](p,f))return!1;for(var h=0;h<a.length;h++){var g=s.props[h].name,b=p[g];if(b===void 0){if(c[h])return f.fail(g,"is missing",1)}else{var k=a[h](b,f);if(!k)return f.fail(g,null,1)}}return!0};if(!r)return u;var d=this.propSet;return o&&(this.propSet.forEach(function(p){return o.add(p)}),d=o),function(p,f){if(!u(p,f))return!1;for(var h in p)if(!d.has(h))return f.fail(h,"is extraneous",2);return!0}},t})($n);Fe.TIface=sw;function tE(e){return new Jd(Yr(e))}Fe.opt=tE;var Jd=(function(e){qn(t,e);function t(n){var r=e.call(this)||this;return r.ttype=n,r}return t.prototype.getChecker=function(n,r){var o=this.ttype.getChecker(n,r);return function(s,i){return s===void 0||o(s,i)}},t})($n);Fe.TOptional=Jd;var Hd=(function(){function e(t,n,r){this.name=t,this.ttype=n,this.isOpt=r}return e})();Fe.TProp=Hd;function nE(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];return new iw(new lw(t),Yr(e))}Fe.func=nE;var iw=(function(e){qn(t,e);function t(n,r){var o=e.call(this)||this;return o.paramList=n,o.result=r,o}return t.prototype.getChecker=function(n,r){return function(o,s){return typeof o=="function"?!0:s.fail(null,"is not a function",0)}},t})($n);Fe.TFunc=iw;function rE(e,t,n){return new aw(e,Yr(t),!!n)}Fe.param=rE;var aw=(function(){function e(t,n,r){this.name=t,this.ttype=n,this.isOpt=r}return e})();Fe.TParam=aw;var lw=(function(e){qn(t,e);function t(n){var r=e.call(this)||this;return r.params=n,r}return t.prototype.getChecker=function(n,r){var o=this,s=this.params.map(function(c){return c.ttype.getChecker(n,r)}),i=new Y0.NoopContext,a=this.params.map(function(c,u){return!c.isOpt&&!s[u](void 0,i)}),l=function(c,u){if(!Array.isArray(c))return u.fail(null,"is not an array",0);for(var d=0;d<s.length;d++){var p=o.params[d];if(c[d]===void 0){if(a[d])return u.fail(p.name,"is missing",1)}else{var f=s[d](c[d],u);if(!f)return u.fail(p.name,null,1)}}return!0};return r?function(c,u){return l(c,u)?c.length<=s.length?!0:u.fail(s.length,"is extraneous",2):!1}:l},t})($n);Fe.TParamList=lw;var pn=(function(e){qn(t,e);function t(n,r){var o=e.call(this)||this;return o.validator=n,o.message=r,o}return t.prototype.getChecker=function(n,r){var o=this;return function(s,i){return o.validator(s)?!0:i.fail(null,o.message,0)}},t})($n);Fe.BasicType=pn;Fe.basicTypes={any:new pn(function(e){return!0},"is invalid"),number:new pn(function(e){return typeof e=="number"},"is not a number"),object:new pn(function(e){return typeof e=="object"&&e},"is not an object"),boolean:new pn(function(e){return typeof e=="boolean"},"is not a boolean"),string:new pn(function(e){return typeof e=="string"},"is not a string"),symbol:new pn(function(e){return typeof e=="symbol"},"is not a symbol"),void:new pn(function(e){return e==null},"is not void"),undefined:new pn(function(e){return e===void 0},"is not undefined"),null:new pn(function(e){return e===null},"is not null"),never:new pn(function(e){return!1},"is unexpected"),Date:new pn(X0("[object Date]"),"is not a Date"),RegExp:new pn(X0("[object RegExp]"),"is not a RegExp")};var oE=Object.prototype.toString;function X0(e){return function(t){return typeof t=="object"&&t&&oE.call(t)===e}}typeof Buffer<"u"&&(Fe.basicTypes.Buffer=new pn(function(e){return Buffer.isBuffer(e)},"is not a Buffer"));var sE=function(e){Fe.basicTypes[e.name]=new pn(function(t){return t instanceof e},"is not a "+e.name)};for(Sl=0,Gd=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,ArrayBuffer];Sl<Gd.length;Sl++)Q0=Gd[Sl],sE(Q0);var Q0,Sl,Gd});var Qd=Ie(rt=>{"use strict";var iE=rt&&rt.__spreadArrays||function(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;for(var r=Array(e),o=0,t=0;t<n;t++)for(var s=arguments[t],i=0,a=s.length;i<a;i++,o++)r[o]=s[i];return r};Object.defineProperty(rt,"__esModule",{value:!0});rt.Checker=rt.createCheckers=void 0;var Oi=Xd(),Rs=xl(),Tt=Xd();Object.defineProperty(rt,"TArray",{enumerable:!0,get:function(){return Tt.TArray}});Object.defineProperty(rt,"TEnumType",{enumerable:!0,get:function(){return Tt.TEnumType}});Object.defineProperty(rt,"TEnumLiteral",{enumerable:!0,get:function(){return Tt.TEnumLiteral}});Object.defineProperty(rt,"TFunc",{enumerable:!0,get:function(){return Tt.TFunc}});Object.defineProperty(rt,"TIface",{enumerable:!0,get:function(){return Tt.TIface}});Object.defineProperty(rt,"TLiteral",{enumerable:!0,get:function(){return Tt.TLiteral}});Object.defineProperty(rt,"TName",{enumerable:!0,get:function(){return Tt.TName}});Object.defineProperty(rt,"TOptional",{enumerable:!0,get:function(){return Tt.TOptional}});Object.defineProperty(rt,"TParam",{enumerable:!0,get:function(){return Tt.TParam}});Object.defineProperty(rt,"TParamList",{enumerable:!0,get:function(){return Tt.TParamList}});Object.defineProperty(rt,"TProp",{enumerable:!0,get:function(){return Tt.TProp}});Object.defineProperty(rt,"TTuple",{enumerable:!0,get:function(){return Tt.TTuple}});Object.defineProperty(rt,"TType",{enumerable:!0,get:function(){return Tt.TType}});Object.defineProperty(rt,"TUnion",{enumerable:!0,get:function(){return Tt.TUnion}});Object.defineProperty(rt,"TIntersection",{enumerable:!0,get:function(){return Tt.TIntersection}});Object.defineProperty(rt,"array",{enumerable:!0,get:function(){return Tt.array}});Object.defineProperty(rt,"enumlit",{enumerable:!0,get:function(){return Tt.enumlit}});Object.defineProperty(rt,"enumtype",{enumerable:!0,get:function(){return Tt.enumtype}});Object.defineProperty(rt,"func",{enumerable:!0,get:function(){return Tt.func}});Object.defineProperty(rt,"iface",{enumerable:!0,get:function(){return Tt.iface}});Object.defineProperty(rt,"lit",{enumerable:!0,get:function(){return Tt.lit}});Object.defineProperty(rt,"name",{enumerable:!0,get:function(){return Tt.name}});Object.defineProperty(rt,"opt",{enumerable:!0,get:function(){return Tt.opt}});Object.defineProperty(rt,"param",{enumerable:!0,get:function(){return Tt.param}});Object.defineProperty(rt,"tuple",{enumerable:!0,get:function(){return Tt.tuple}});Object.defineProperty(rt,"union",{enumerable:!0,get:function(){return Tt.union}});Object.defineProperty(rt,"intersection",{enumerable:!0,get:function(){return Tt.intersection}});Object.defineProperty(rt,"BasicType",{enumerable:!0,get:function(){return Tt.BasicType}});var aE=xl();Object.defineProperty(rt,"VError",{enumerable:!0,get:function(){return aE.VError}});function lE(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var n=Object.assign.apply(Object,iE([{},Oi.basicTypes],e)),r={},o=0,s=e;o<s.length;o++)for(var i=s[o],a=0,l=Object.keys(i);a<l.length;a++){var c=l[a];r[c]=new cw(n,i[c])}return r}rt.createCheckers=lE;var cw=(function(){function e(t,n,r){if(r===void 0&&(r="value"),this.suite=t,this.ttype=n,this._path=r,this.props=new Map,n instanceof Oi.TIface)for(var o=0,s=n.props;o<s.length;o++){var i=s[o];this.props.set(i.name,i.ttype)}this.checkerPlain=this.ttype.getChecker(t,!1),this.checkerStrict=this.ttype.getChecker(t,!0)}return e.prototype.setReportedPath=function(t){this._path=t},e.prototype.check=function(t){return this._doCheck(this.checkerPlain,t)},e.prototype.test=function(t){return this.checkerPlain(t,new Rs.NoopContext)},e.prototype.validate=function(t){return this._doValidate(this.checkerPlain,t)},e.prototype.strictCheck=function(t){return this._doCheck(this.checkerStrict,t)},e.prototype.strictTest=function(t){return this.checkerStrict(t,new Rs.NoopContext)},e.prototype.strictValidate=function(t){return this._doValidate(this.checkerStrict,t)},e.prototype.getProp=function(t){var n=this.props.get(t);if(!n)throw new Error("Type has no property "+t);return new e(this.suite,n,this._path+"."+t)},e.prototype.methodArgs=function(t){var n=this._getMethod(t);return new e(this.suite,n.paramList)},e.prototype.methodResult=function(t){var n=this._getMethod(t);return new e(this.suite,n.result)},e.prototype.getArgs=function(){if(!(this.ttype instanceof Oi.TFunc))throw new Error("getArgs() applied to non-function");return new e(this.suite,this.ttype.paramList)},e.prototype.getResult=function(){if(!(this.ttype instanceof Oi.TFunc))throw new Error("getResult() applied to non-function");return new e(this.suite,this.ttype.result)},e.prototype.getType=function(){return this.ttype},e.prototype._doCheck=function(t,n){var r=new Rs.NoopContext;if(!t(n,r)){var o=new Rs.DetailContext;throw t(n,o),o.getError(this._path)}},e.prototype._doValidate=function(t,n){var r=new Rs.NoopContext;if(t(n,r))return null;var o=new Rs.DetailContext;return t(n,o),o.getErrorDetail(this._path)},e.prototype._getMethod=function(t){var n=this.props.get(t);if(!n)throw new Error("Type has no property "+t);if(!(n instanceof Oi.TFunc))throw new Error("Property "+t+" is not a method");return n},e})();rt.Checker=cw});var uw=Ie(Mr=>{"use strict";Object.defineProperty(Mr,"__esModule",{value:!0});function cE(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}var uE=Qd(),$t=cE(uE),dE=$t.union($t.lit("jsx"),$t.lit("typescript"),$t.lit("flow"),$t.lit("imports"),$t.lit("react-hot-loader"),$t.lit("jest"));Mr.Transform=dE;var pE=$t.iface([],{compiledFilename:"string"});Mr.SourceMapOptions=pE;var mE=$t.iface([],{transforms:$t.array("Transform"),disableESTransforms:$t.opt("boolean"),jsxRuntime:$t.opt($t.union($t.lit("classic"),$t.lit("automatic"),$t.lit("preserve"))),production:$t.opt("boolean"),jsxImportSource:$t.opt("string"),jsxPragma:$t.opt("string"),jsxFragmentPragma:$t.opt("string"),keepUnusedImports:$t.opt("boolean"),preserveDynamicImport:$t.opt("boolean"),injectCreateRequireForImportRequire:$t.opt("boolean"),enableLegacyTypeScriptModuleInterop:$t.opt("boolean"),enableLegacyBabel5ModuleInterop:$t.opt("boolean"),sourceMapOptions:$t.opt("SourceMapOptions"),filePath:$t.opt("string")});Mr.Options=mE;var fE={Transform:Mr.Transform,SourceMapOptions:Mr.SourceMapOptions,Options:Mr.Options};Mr.default=fE});var dw=Ie(Yd=>{"use strict";Object.defineProperty(Yd,"__esModule",{value:!0});function hE(e){return e&&e.__esModule?e:{default:e}}var gE=Qd(),bE=uw(),yE=hE(bE),{Options:wE}=gE.createCheckers.call(void 0,yE.default);function kE(e){wE.strictCheck(e)}Yd.validateOptions=kE});var $l=Ie(vr=>{"use strict";Object.defineProperty(vr,"__esModule",{value:!0});var _E=ji(),pw=Cs(),mn=en(),Li=rn(),Jn=et(),tn=jn(),Ni=Lo(),Zd=Xr();function vE(){mn.next.call(void 0),Ni.parseMaybeAssign.call(void 0,!1)}vr.parseSpread=vE;function mw(e){mn.next.call(void 0),tp(e)}vr.parseRest=mw;function fw(e){Ni.parseIdentifier.call(void 0),hw(e)}vr.parseBindingIdentifier=fw;function TE(){Ni.parseIdentifier.call(void 0),tn.state.tokens[tn.state.tokens.length-1].identifierRole=mn.IdentifierRole.ImportDeclaration}vr.parseImportedIdentifier=TE;function hw(e){let t;tn.state.scopeDepth===0?t=mn.IdentifierRole.TopLevelDeclaration:e?t=mn.IdentifierRole.BlockScopedDeclaration:t=mn.IdentifierRole.FunctionScopedDeclaration,tn.state.tokens[tn.state.tokens.length-1].identifierRole=t}vr.markPriorBindingIdentifier=hw;function tp(e){switch(tn.state.type){case Jn.TokenType._this:{let t=mn.pushTypeContext.call(void 0,0);mn.next.call(void 0),mn.popTypeContext.call(void 0,t);return}case Jn.TokenType._yield:case Jn.TokenType.name:{tn.state.type=Jn.TokenType.name,fw(e);return}case Jn.TokenType.bracketL:{mn.next.call(void 0),gw(Jn.TokenType.bracketR,e,!0);return}case Jn.TokenType.braceL:Ni.parseObj.call(void 0,!0,e);return;default:Zd.unexpected.call(void 0)}}vr.parseBindingAtom=tp;function gw(e,t,n=!1,r=!1,o=0){let s=!0,i=!1,a=tn.state.tokens.length;for(;!mn.eat.call(void 0,e)&&!tn.state.error;)if(s?s=!1:(Zd.expect.call(void 0,Jn.TokenType.comma),tn.state.tokens[tn.state.tokens.length-1].contextId=o,!i&&tn.state.tokens[a].isType&&(tn.state.tokens[tn.state.tokens.length-1].isType=!0,i=!0)),!(n&&mn.match.call(void 0,Jn.TokenType.comma))){if(mn.eat.call(void 0,e))break;if(mn.match.call(void 0,Jn.TokenType.ellipsis)){mw(t),bw(),mn.eat.call(void 0,Jn.TokenType.comma),Zd.expect.call(void 0,e);break}else xE(r,t)}}vr.parseBindingList=gw;function xE(e,t){e&&pw.tsParseModifiers.call(void 0,[Li.ContextualKeyword._public,Li.ContextualKeyword._protected,Li.ContextualKeyword._private,Li.ContextualKeyword._readonly,Li.ContextualKeyword._override]),ep(t),bw(),ep(t,!0)}function bw(){tn.isFlowEnabled?_E.flowParseAssignableListItemTypes.call(void 0):tn.isTypeScriptEnabled&&pw.tsParseAssignableListItemTypes.call(void 0)}function ep(e,t=!1){if(t||tp(e),!mn.eat.call(void 0,Jn.TokenType.eq))return;let n=tn.state.tokens.length-1;Ni.parseMaybeAssign.call(void 0),tn.state.tokens[n].rhsEndIndex=tn.state.tokens.length}vr.parseMaybeDefault=ep});var Cs=Ie(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});var M=en(),Me=rn(),E=et(),G=jn(),Ze=Lo(),Es=$l(),Tr=Gi(),ke=Xr(),SE=pp();function rp(){return M.match.call(void 0,E.TokenType.name)}function $E(){return M.match.call(void 0,E.TokenType.name)||!!(G.state.type&E.TokenType.IS_KEYWORD)||M.match.call(void 0,E.TokenType.string)||M.match.call(void 0,E.TokenType.num)||M.match.call(void 0,E.TokenType.bigint)||M.match.call(void 0,E.TokenType.decimal)}function vw(){let e=G.state.snapshot();return M.next.call(void 0),(M.match.call(void 0,E.TokenType.bracketL)||M.match.call(void 0,E.TokenType.braceL)||M.match.call(void 0,E.TokenType.star)||M.match.call(void 0,E.TokenType.ellipsis)||M.match.call(void 0,E.TokenType.hash)||$E())&&!ke.hasPrecedingLineBreak.call(void 0)?!0:(G.state.restoreFromSnapshot(e),!1)}function Tw(e){for(;ap(e)!==null;);}ut.tsParseModifiers=Tw;function ap(e){if(!M.match.call(void 0,E.TokenType.name))return null;let t=G.state.contextualKeyword;if(e.indexOf(t)!==-1&&vw()){switch(t){case Me.ContextualKeyword._readonly:G.state.tokens[G.state.tokens.length-1].type=E.TokenType._readonly;break;case Me.ContextualKeyword._abstract:G.state.tokens[G.state.tokens.length-1].type=E.TokenType._abstract;break;case Me.ContextualKeyword._static:G.state.tokens[G.state.tokens.length-1].type=E.TokenType._static;break;case Me.ContextualKeyword._public:G.state.tokens[G.state.tokens.length-1].type=E.TokenType._public;break;case Me.ContextualKeyword._private:G.state.tokens[G.state.tokens.length-1].type=E.TokenType._private;break;case Me.ContextualKeyword._protected:G.state.tokens[G.state.tokens.length-1].type=E.TokenType._protected;break;case Me.ContextualKeyword._override:G.state.tokens[G.state.tokens.length-1].type=E.TokenType._override;break;case Me.ContextualKeyword._declare:G.state.tokens[G.state.tokens.length-1].type=E.TokenType._declare;break;default:break}return t}return null}ut.tsParseModifier=ap;function Bi(){for(Ze.parseIdentifier.call(void 0);M.eat.call(void 0,E.TokenType.dot);)Ze.parseIdentifier.call(void 0)}function RE(){Bi(),!ke.hasPrecedingLineBreak.call(void 0)&&M.match.call(void 0,E.TokenType.lessThan)&&Is()}function CE(){M.next.call(void 0),Ui()}function AE(){M.next.call(void 0)}function EE(){ke.expect.call(void 0,E.TokenType._typeof),M.match.call(void 0,E.TokenType._import)?xw():Bi(),!ke.hasPrecedingLineBreak.call(void 0)&&M.match.call(void 0,E.TokenType.lessThan)&&Is()}function xw(){ke.expect.call(void 0,E.TokenType._import),ke.expect.call(void 0,E.TokenType.parenL),ke.expect.call(void 0,E.TokenType.string),ke.expect.call(void 0,E.TokenType.parenR),M.eat.call(void 0,E.TokenType.dot)&&Bi(),M.match.call(void 0,E.TokenType.lessThan)&&Is()}function ME(){M.eat.call(void 0,E.TokenType._const);let e=M.eat.call(void 0,E.TokenType._in),t=ke.eatContextual.call(void 0,Me.ContextualKeyword._out);M.eat.call(void 0,E.TokenType._const),(e||t)&&!M.match.call(void 0,E.TokenType.name)?G.state.tokens[G.state.tokens.length-1].type=E.TokenType.name:Ze.parseIdentifier.call(void 0),M.eat.call(void 0,E.TokenType._extends)&&Lt(),M.eat.call(void 0,E.TokenType.eq)&&Lt()}function Ms(){M.match.call(void 0,E.TokenType.lessThan)&&Cl()}ut.tsTryParseTypeParameters=Ms;function Cl(){let e=M.pushTypeContext.call(void 0,0);for(M.match.call(void 0,E.TokenType.lessThan)||M.match.call(void 0,E.TokenType.typeParameterStart)?M.next.call(void 0):ke.unexpected.call(void 0);!M.eat.call(void 0,E.TokenType.greaterThan)&&!G.state.error;)ME(),M.eat.call(void 0,E.TokenType.comma);M.popTypeContext.call(void 0,e)}function lp(e){let t=e===E.TokenType.arrow;Ms(),ke.expect.call(void 0,E.TokenType.parenL),G.state.scopeDepth++,IE(!1),G.state.scopeDepth--,(t||M.match.call(void 0,e))&&Di(e)}function IE(e){Es.parseBindingList.call(void 0,E.TokenType.parenR,e)}function Rl(){M.eat.call(void 0,E.TokenType.comma)||ke.semicolon.call(void 0)}function yw(){lp(E.TokenType.colon),Rl()}function PE(){let e=G.state.snapshot();M.next.call(void 0);let t=M.eat.call(void 0,E.TokenType.name)&&M.match.call(void 0,E.TokenType.colon);return G.state.restoreFromSnapshot(e),t}function Sw(){if(!(M.match.call(void 0,E.TokenType.bracketL)&&PE()))return!1;let e=M.pushTypeContext.call(void 0,0);return ke.expect.call(void 0,E.TokenType.bracketL),Ze.parseIdentifier.call(void 0),Ui(),ke.expect.call(void 0,E.TokenType.bracketR),qi(),Rl(),M.popTypeContext.call(void 0,e),!0}function ww(e){M.eat.call(void 0,E.TokenType.question),!e&&(M.match.call(void 0,E.TokenType.parenL)||M.match.call(void 0,E.TokenType.lessThan))?(lp(E.TokenType.colon),Rl()):(qi(),Rl())}function FE(){if(M.match.call(void 0,E.TokenType.parenL)||M.match.call(void 0,E.TokenType.lessThan)){yw();return}if(M.match.call(void 0,E.TokenType._new)){M.next.call(void 0),M.match.call(void 0,E.TokenType.parenL)||M.match.call(void 0,E.TokenType.lessThan)?yw():ww(!1);return}let e=!!ap([Me.ContextualKeyword._readonly]);Sw()||((ke.isContextual.call(void 0,Me.ContextualKeyword._get)||ke.isContextual.call(void 0,Me.ContextualKeyword._set))&&vw(),Ze.parsePropertyName.call(void 0,-1),ww(e))}function OE(){$w()}function $w(){for(ke.expect.call(void 0,E.TokenType.braceL);!M.eat.call(void 0,E.TokenType.braceR)&&!G.state.error;)FE()}function LE(){let e=G.state.snapshot(),t=NE();return G.state.restoreFromSnapshot(e),t}function NE(){return M.next.call(void 0),M.eat.call(void 0,E.TokenType.plus)||M.eat.call(void 0,E.TokenType.minus)?ke.isContextual.call(void 0,Me.ContextualKeyword._readonly):(ke.isContextual.call(void 0,Me.ContextualKeyword._readonly)&&M.next.call(void 0),!M.match.call(void 0,E.TokenType.bracketL)||(M.next.call(void 0),!rp())?!1:(M.next.call(void 0),M.match.call(void 0,E.TokenType._in)))}function jE(){Ze.parseIdentifier.call(void 0),ke.expect.call(void 0,E.TokenType._in),Lt()}function DE(){ke.expect.call(void 0,E.TokenType.braceL),M.match.call(void 0,E.TokenType.plus)||M.match.call(void 0,E.TokenType.minus)?(M.next.call(void 0),ke.expectContextual.call(void 0,Me.ContextualKeyword._readonly)):ke.eatContextual.call(void 0,Me.ContextualKeyword._readonly),ke.expect.call(void 0,E.TokenType.bracketL),jE(),ke.eatContextual.call(void 0,Me.ContextualKeyword._as)&&Lt(),ke.expect.call(void 0,E.TokenType.bracketR),M.match.call(void 0,E.TokenType.plus)||M.match.call(void 0,E.TokenType.minus)?(M.next.call(void 0),ke.expect.call(void 0,E.TokenType.question)):M.eat.call(void 0,E.TokenType.question),ZE(),ke.semicolon.call(void 0),ke.expect.call(void 0,E.TokenType.braceR)}function BE(){for(ke.expect.call(void 0,E.TokenType.bracketL);!M.eat.call(void 0,E.TokenType.bracketR)&&!G.state.error;)qE(),M.eat.call(void 0,E.TokenType.comma)}function qE(){M.eat.call(void 0,E.TokenType.ellipsis)?Lt():(Lt(),M.eat.call(void 0,E.TokenType.question)),M.eat.call(void 0,E.TokenType.colon)&&Lt()}function UE(){ke.expect.call(void 0,E.TokenType.parenL),Lt(),ke.expect.call(void 0,E.TokenType.parenR)}function GE(){for(M.nextTemplateToken.call(void 0),M.nextTemplateToken.call(void 0);!M.match.call(void 0,E.TokenType.backQuote)&&!G.state.error;)ke.expect.call(void 0,E.TokenType.dollarBraceL),Lt(),M.nextTemplateToken.call(void 0),M.nextTemplateToken.call(void 0);M.next.call(void 0)}var Zr;(function(e){e[e.TSFunctionType=0]="TSFunctionType";let n=1;e[e.TSConstructorType=n]="TSConstructorType";let r=n+1;e[e.TSAbstractConstructorType=r]="TSAbstractConstructorType"})(Zr||(Zr={}));function np(e){e===Zr.TSAbstractConstructorType&&ke.expectContextual.call(void 0,Me.ContextualKeyword._abstract),(e===Zr.TSConstructorType||e===Zr.TSAbstractConstructorType)&&ke.expect.call(void 0,E.TokenType._new);let t=G.state.inDisallowConditionalTypesContext;G.state.inDisallowConditionalTypesContext=!1,lp(E.TokenType.arrow),G.state.inDisallowConditionalTypesContext=t}function HE(){switch(G.state.type){case E.TokenType.name:RE();return;case E.TokenType._void:case E.TokenType._null:M.next.call(void 0);return;case E.TokenType.string:case E.TokenType.num:case E.TokenType.bigint:case E.TokenType.decimal:case E.TokenType._true:case E.TokenType._false:Ze.parseLiteral.call(void 0);return;case E.TokenType.minus:M.next.call(void 0),Ze.parseLiteral.call(void 0);return;case E.TokenType._this:{AE(),ke.isContextual.call(void 0,Me.ContextualKeyword._is)&&!ke.hasPrecedingLineBreak.call(void 0)&&CE();return}case E.TokenType._typeof:EE();return;case E.TokenType._import:xw();return;case E.TokenType.braceL:LE()?DE():OE();return;case E.TokenType.bracketL:BE();return;case E.TokenType.parenL:UE();return;case E.TokenType.backQuote:GE();return;default:if(G.state.type&E.TokenType.IS_KEYWORD){M.next.call(void 0),G.state.tokens[G.state.tokens.length-1].type=E.TokenType.name;return}break}ke.unexpected.call(void 0)}function zE(){for(HE();!ke.hasPrecedingLineBreak.call(void 0)&&M.eat.call(void 0,E.TokenType.bracketL);)M.eat.call(void 0,E.TokenType.bracketR)||(Lt(),ke.expect.call(void 0,E.TokenType.bracketR))}function WE(){if(ke.expectContextual.call(void 0,Me.ContextualKeyword._infer),Ze.parseIdentifier.call(void 0),M.match.call(void 0,E.TokenType._extends)){let e=G.state.snapshot();ke.expect.call(void 0,E.TokenType._extends);let t=G.state.inDisallowConditionalTypesContext;G.state.inDisallowConditionalTypesContext=!0,Lt(),G.state.inDisallowConditionalTypesContext=t,(G.state.error||!G.state.inDisallowConditionalTypesContext&&M.match.call(void 0,E.TokenType.question))&&G.state.restoreFromSnapshot(e)}}function op(){if(ke.isContextual.call(void 0,Me.ContextualKeyword._keyof)||ke.isContextual.call(void 0,Me.ContextualKeyword._unique)||ke.isContextual.call(void 0,Me.ContextualKeyword._readonly))M.next.call(void 0),op();else if(ke.isContextual.call(void 0,Me.ContextualKeyword._infer))WE();else{let e=G.state.inDisallowConditionalTypesContext;G.state.inDisallowConditionalTypesContext=!1,zE(),G.state.inDisallowConditionalTypesContext=e}}function kw(){if(M.eat.call(void 0,E.TokenType.bitwiseAND),op(),M.match.call(void 0,E.TokenType.bitwiseAND))for(;M.eat.call(void 0,E.TokenType.bitwiseAND);)op()}function KE(){if(M.eat.call(void 0,E.TokenType.bitwiseOR),kw(),M.match.call(void 0,E.TokenType.bitwiseOR))for(;M.eat.call(void 0,E.TokenType.bitwiseOR);)kw()}function VE(){return M.match.call(void 0,E.TokenType.lessThan)?!0:M.match.call(void 0,E.TokenType.parenL)&&XE()}function JE(){if(M.match.call(void 0,E.TokenType.name)||M.match.call(void 0,E.TokenType._this))return M.next.call(void 0),!0;if(M.match.call(void 0,E.TokenType.braceL)||M.match.call(void 0,E.TokenType.bracketL)){let e=1;for(M.next.call(void 0);e>0&&!G.state.error;)M.match.call(void 0,E.TokenType.braceL)||M.match.call(void 0,E.TokenType.bracketL)?e++:(M.match.call(void 0,E.TokenType.braceR)||M.match.call(void 0,E.TokenType.bracketR))&&e--,M.next.call(void 0);return!0}return!1}function XE(){let e=G.state.snapshot(),t=QE();return G.state.restoreFromSnapshot(e),t}function QE(){return M.next.call(void 0),!!(M.match.call(void 0,E.TokenType.parenR)||M.match.call(void 0,E.TokenType.ellipsis)||JE()&&(M.match.call(void 0,E.TokenType.colon)||M.match.call(void 0,E.TokenType.comma)||M.match.call(void 0,E.TokenType.question)||M.match.call(void 0,E.TokenType.eq)||M.match.call(void 0,E.TokenType.parenR)&&(M.next.call(void 0),M.match.call(void 0,E.TokenType.arrow))))}function Di(e){let t=M.pushTypeContext.call(void 0,0);ke.expect.call(void 0,e),eM()||Lt(),M.popTypeContext.call(void 0,t)}function YE(){M.match.call(void 0,E.TokenType.colon)&&Di(E.TokenType.colon)}function qi(){M.match.call(void 0,E.TokenType.colon)&&Ui()}ut.tsTryParseTypeAnnotation=qi;function ZE(){M.eat.call(void 0,E.TokenType.colon)&&Lt()}function eM(){let e=G.state.snapshot();return ke.isContextual.call(void 0,Me.ContextualKeyword._asserts)?(M.next.call(void 0),ke.eatContextual.call(void 0,Me.ContextualKeyword._is)?(Lt(),!0):rp()||M.match.call(void 0,E.TokenType._this)?(M.next.call(void 0),ke.eatContextual.call(void 0,Me.ContextualKeyword._is)&&Lt(),!0):(G.state.restoreFromSnapshot(e),!1)):rp()||M.match.call(void 0,E.TokenType._this)?(M.next.call(void 0),ke.isContextual.call(void 0,Me.ContextualKeyword._is)&&!ke.hasPrecedingLineBreak.call(void 0)?(M.next.call(void 0),Lt(),!0):(G.state.restoreFromSnapshot(e),!1)):!1}function Ui(){let e=M.pushTypeContext.call(void 0,0);ke.expect.call(void 0,E.TokenType.colon),Lt(),M.popTypeContext.call(void 0,e)}ut.tsParseTypeAnnotation=Ui;function Lt(){if(sp(),G.state.inDisallowConditionalTypesContext||ke.hasPrecedingLineBreak.call(void 0)||!M.eat.call(void 0,E.TokenType._extends))return;let e=G.state.inDisallowConditionalTypesContext;G.state.inDisallowConditionalTypesContext=!0,sp(),G.state.inDisallowConditionalTypesContext=e,ke.expect.call(void 0,E.TokenType.question),Lt(),ke.expect.call(void 0,E.TokenType.colon),Lt()}ut.tsParseType=Lt;function tM(){return ke.isContextual.call(void 0,Me.ContextualKeyword._abstract)&&M.lookaheadType.call(void 0)===E.TokenType._new}function sp(){if(VE()){np(Zr.TSFunctionType);return}if(M.match.call(void 0,E.TokenType._new)){np(Zr.TSConstructorType);return}else if(tM()){np(Zr.TSAbstractConstructorType);return}KE()}ut.tsParseNonConditionalType=sp;function nM(){let e=M.pushTypeContext.call(void 0,1);Lt(),ke.expect.call(void 0,E.TokenType.greaterThan),M.popTypeContext.call(void 0,e),Ze.parseMaybeUnary.call(void 0)}ut.tsParseTypeAssertion=nM;function rM(){if(M.eat.call(void 0,E.TokenType.jsxTagStart)){G.state.tokens[G.state.tokens.length-1].type=E.TokenType.typeParameterStart;let e=M.pushTypeContext.call(void 0,1);for(;!M.match.call(void 0,E.TokenType.greaterThan)&&!G.state.error;)Lt(),M.eat.call(void 0,E.TokenType.comma);SE.nextJSXTagToken.call(void 0),M.popTypeContext.call(void 0,e)}}ut.tsTryParseJSXTypeArgument=rM;function Rw(){for(;!M.match.call(void 0,E.TokenType.braceL)&&!G.state.error;)oM(),M.eat.call(void 0,E.TokenType.comma)}function oM(){Bi(),M.match.call(void 0,E.TokenType.lessThan)&&Is()}function sM(){Es.parseBindingIdentifier.call(void 0,!1),Ms(),M.eat.call(void 0,E.TokenType._extends)&&Rw(),$w()}function iM(){Es.parseBindingIdentifier.call(void 0,!1),Ms(),ke.expect.call(void 0,E.TokenType.eq),Lt(),ke.semicolon.call(void 0)}function aM(){if(M.match.call(void 0,E.TokenType.string)?Ze.parseLiteral.call(void 0):Ze.parseIdentifier.call(void 0),M.eat.call(void 0,E.TokenType.eq)){let e=G.state.tokens.length-1;Ze.parseMaybeAssign.call(void 0),G.state.tokens[e].rhsEndIndex=G.state.tokens.length}}function cp(){for(Es.parseBindingIdentifier.call(void 0,!1),ke.expect.call(void 0,E.TokenType.braceL);!M.eat.call(void 0,E.TokenType.braceR)&&!G.state.error;)aM(),M.eat.call(void 0,E.TokenType.comma)}function up(){ke.expect.call(void 0,E.TokenType.braceL),Tr.parseBlockBody.call(void 0,E.TokenType.braceR)}function ip(){Es.parseBindingIdentifier.call(void 0,!1),M.eat.call(void 0,E.TokenType.dot)?ip():up()}function Cw(){ke.isContextual.call(void 0,Me.ContextualKeyword._global)?Ze.parseIdentifier.call(void 0):M.match.call(void 0,E.TokenType.string)?Ze.parseExprAtom.call(void 0):ke.unexpected.call(void 0),M.match.call(void 0,E.TokenType.braceL)?up():ke.semicolon.call(void 0)}function Aw(){Es.parseImportedIdentifier.call(void 0),ke.expect.call(void 0,E.TokenType.eq),cM(),ke.semicolon.call(void 0)}ut.tsParseImportEqualsDeclaration=Aw;function lM(){return ke.isContextual.call(void 0,Me.ContextualKeyword._require)&&M.lookaheadType.call(void 0)===E.TokenType.parenL}function cM(){lM()?uM():Bi()}function uM(){ke.expectContextual.call(void 0,Me.ContextualKeyword._require),ke.expect.call(void 0,E.TokenType.parenL),M.match.call(void 0,E.TokenType.string)||ke.unexpected.call(void 0),Ze.parseLiteral.call(void 0),ke.expect.call(void 0,E.TokenType.parenR)}function dM(){if(ke.isLineTerminator.call(void 0))return!1;switch(G.state.type){case E.TokenType._function:{let e=M.pushTypeContext.call(void 0,1);M.next.call(void 0);let t=G.state.start;return Tr.parseFunction.call(void 0,t,!0),M.popTypeContext.call(void 0,e),!0}case E.TokenType._class:{let e=M.pushTypeContext.call(void 0,1);return Tr.parseClass.call(void 0,!0,!1),M.popTypeContext.call(void 0,e),!0}case E.TokenType._const:if(M.match.call(void 0,E.TokenType._const)&&ke.isLookaheadContextual.call(void 0,Me.ContextualKeyword._enum)){let e=M.pushTypeContext.call(void 0,1);return ke.expect.call(void 0,E.TokenType._const),ke.expectContextual.call(void 0,Me.ContextualKeyword._enum),G.state.tokens[G.state.tokens.length-1].type=E.TokenType._enum,cp(),M.popTypeContext.call(void 0,e),!0}case E.TokenType._var:case E.TokenType._let:{let e=M.pushTypeContext.call(void 0,1);return Tr.parseVarStatement.call(void 0,G.state.type!==E.TokenType._var),M.popTypeContext.call(void 0,e),!0}case E.TokenType.name:{let e=M.pushTypeContext.call(void 0,1),t=G.state.contextualKeyword,n=!1;return t===Me.ContextualKeyword._global?(Cw(),n=!0):n=Al(t,!0),M.popTypeContext.call(void 0,e),n}default:return!1}}function _w(){return Al(G.state.contextualKeyword,!0)}function pM(e){switch(e){case Me.ContextualKeyword._declare:{let t=G.state.tokens.length-1;if(dM())return G.state.tokens[t].type=E.TokenType._declare,!0;break}case Me.ContextualKeyword._global:if(M.match.call(void 0,E.TokenType.braceL))return up(),!0;break;default:return Al(e,!1)}return!1}function Al(e,t){switch(e){case Me.ContextualKeyword._abstract:if(As(t)&&M.match.call(void 0,E.TokenType._class))return G.state.tokens[G.state.tokens.length-1].type=E.TokenType._abstract,Tr.parseClass.call(void 0,!0,!1),!0;break;case Me.ContextualKeyword._enum:if(As(t)&&M.match.call(void 0,E.TokenType.name))return G.state.tokens[G.state.tokens.length-1].type=E.TokenType._enum,cp(),!0;break;case Me.ContextualKeyword._interface:if(As(t)&&M.match.call(void 0,E.TokenType.name)){let n=M.pushTypeContext.call(void 0,t?2:1);return sM(),M.popTypeContext.call(void 0,n),!0}break;case Me.ContextualKeyword._module:if(As(t)){if(M.match.call(void 0,E.TokenType.string)){let n=M.pushTypeContext.call(void 0,t?2:1);return Cw(),M.popTypeContext.call(void 0,n),!0}else if(M.match.call(void 0,E.TokenType.name)){let n=M.pushTypeContext.call(void 0,t?2:1);return ip(),M.popTypeContext.call(void 0,n),!0}}break;case Me.ContextualKeyword._namespace:if(As(t)&&M.match.call(void 0,E.TokenType.name)){let n=M.pushTypeContext.call(void 0,t?2:1);return ip(),M.popTypeContext.call(void 0,n),!0}break;case Me.ContextualKeyword._type:if(As(t)&&M.match.call(void 0,E.TokenType.name)){let n=M.pushTypeContext.call(void 0,t?2:1);return iM(),M.popTypeContext.call(void 0,n),!0}break;default:break}return!1}function As(e){return e?(M.next.call(void 0),!0):!ke.isLineTerminator.call(void 0)}function mM(){let e=G.state.snapshot();return Cl(),Tr.parseFunctionParams.call(void 0),YE(),ke.expect.call(void 0,E.TokenType.arrow),G.state.error?(G.state.restoreFromSnapshot(e),!1):(Ze.parseFunctionBody.call(void 0,!0),!0)}function dp(){G.state.type===E.TokenType.bitShiftL&&(G.state.pos-=1,M.finishToken.call(void 0,E.TokenType.lessThan)),Is()}function Is(){let e=M.pushTypeContext.call(void 0,0);for(ke.expect.call(void 0,E.TokenType.lessThan);!M.match.call(void 0,E.TokenType.greaterThan)&&!G.state.error;)Lt(),M.eat.call(void 0,E.TokenType.comma);e?(ke.expect.call(void 0,E.TokenType.greaterThan),M.popTypeContext.call(void 0,e)):(M.popTypeContext.call(void 0,e),M.rescan_gt.call(void 0),ke.expect.call(void 0,E.TokenType.greaterThan),G.state.tokens[G.state.tokens.length-1].isType=!0)}function fM(){if(M.match.call(void 0,E.TokenType.name))switch(G.state.contextualKeyword){case Me.ContextualKeyword._abstract:case Me.ContextualKeyword._declare:case Me.ContextualKeyword._enum:case Me.ContextualKeyword._interface:case Me.ContextualKeyword._module:case Me.ContextualKeyword._namespace:case Me.ContextualKeyword._type:return!0;default:break}return!1}ut.tsIsDeclarationStart=fM;function hM(e,t){if(M.match.call(void 0,E.TokenType.colon)&&Di(E.TokenType.colon),!M.match.call(void 0,E.TokenType.braceL)&&ke.isLineTerminator.call(void 0)){let n=G.state.tokens.length-1;for(;n>=0&&(G.state.tokens[n].start>=e||G.state.tokens[n].type===E.TokenType._default||G.state.tokens[n].type===E.TokenType._export);)G.state.tokens[n].isType=!0,n--;return}Ze.parseFunctionBody.call(void 0,!1,t)}ut.tsParseFunctionBodyAndFinish=hM;function gM(e,t,n){if(!ke.hasPrecedingLineBreak.call(void 0)&&M.eat.call(void 0,E.TokenType.bang)){G.state.tokens[G.state.tokens.length-1].type=E.TokenType.nonNullAssertion;return}if(M.match.call(void 0,E.TokenType.lessThan)||M.match.call(void 0,E.TokenType.bitShiftL)){let r=G.state.snapshot();if(!t&&Ze.atPossibleAsync.call(void 0)&&mM())return;if(dp(),!t&&M.eat.call(void 0,E.TokenType.parenL)?(G.state.tokens[G.state.tokens.length-1].subscriptStartIndex=e,Ze.parseCallExpressionArguments.call(void 0)):M.match.call(void 0,E.TokenType.backQuote)?Ze.parseTemplate.call(void 0):(G.state.type===E.TokenType.greaterThan||G.state.type!==E.TokenType.parenL&&G.state.type&E.TokenType.IS_EXPRESSION_START&&!ke.hasPrecedingLineBreak.call(void 0))&&ke.unexpected.call(void 0),G.state.error)G.state.restoreFromSnapshot(r);else return}else!t&&M.match.call(void 0,E.TokenType.questionDot)&&M.lookaheadType.call(void 0)===E.TokenType.lessThan&&(M.next.call(void 0),G.state.tokens[e].isOptionalChainStart=!0,G.state.tokens[G.state.tokens.length-1].subscriptStartIndex=e,Is(),ke.expect.call(void 0,E.TokenType.parenL),Ze.parseCallExpressionArguments.call(void 0));Ze.baseParseSubscript.call(void 0,e,t,n)}ut.tsParseSubscript=gM;function bM(){if(M.eat.call(void 0,E.TokenType._import))return ke.isContextual.call(void 0,Me.ContextualKeyword._type)&&M.lookaheadType.call(void 0)!==E.TokenType.eq&&ke.expectContextual.call(void 0,Me.ContextualKeyword._type),Aw(),!0;if(M.eat.call(void 0,E.TokenType.eq))return Ze.parseExpression.call(void 0),ke.semicolon.call(void 0),!0;if(ke.eatContextual.call(void 0,Me.ContextualKeyword._as))return ke.expectContextual.call(void 0,Me.ContextualKeyword._namespace),Ze.parseIdentifier.call(void 0),ke.semicolon.call(void 0),!0;if(ke.isContextual.call(void 0,Me.ContextualKeyword._type)){let e=M.lookaheadType.call(void 0);(e===E.TokenType.braceL||e===E.TokenType.star)&&M.next.call(void 0)}return!1}ut.tsTryParseExport=bM;function yM(){if(Ze.parseIdentifier.call(void 0),M.match.call(void 0,E.TokenType.comma)||M.match.call(void 0,E.TokenType.braceR)){G.state.tokens[G.state.tokens.length-1].identifierRole=M.IdentifierRole.ImportDeclaration;return}if(Ze.parseIdentifier.call(void 0),M.match.call(void 0,E.TokenType.comma)||M.match.call(void 0,E.TokenType.braceR)){G.state.tokens[G.state.tokens.length-1].identifierRole=M.IdentifierRole.ImportDeclaration,G.state.tokens[G.state.tokens.length-2].isType=!0,G.state.tokens[G.state.tokens.length-1].isType=!0;return}if(Ze.parseIdentifier.call(void 0),M.match.call(void 0,E.TokenType.comma)||M.match.call(void 0,E.TokenType.braceR)){G.state.tokens[G.state.tokens.length-3].identifierRole=M.IdentifierRole.ImportAccess,G.state.tokens[G.state.tokens.length-1].identifierRole=M.IdentifierRole.ImportDeclaration;return}Ze.parseIdentifier.call(void 0),G.state.tokens[G.state.tokens.length-3].identifierRole=M.IdentifierRole.ImportAccess,G.state.tokens[G.state.tokens.length-1].identifierRole=M.IdentifierRole.ImportDeclaration,G.state.tokens[G.state.tokens.length-4].isType=!0,G.state.tokens[G.state.tokens.length-3].isType=!0,G.state.tokens[G.state.tokens.length-2].isType=!0,G.state.tokens[G.state.tokens.length-1].isType=!0}ut.tsParseImportSpecifier=yM;function wM(){if(Ze.parseIdentifier.call(void 0),M.match.call(void 0,E.TokenType.comma)||M.match.call(void 0,E.TokenType.braceR)){G.state.tokens[G.state.tokens.length-1].identifierRole=M.IdentifierRole.ExportAccess;return}if(Ze.parseIdentifier.call(void 0),M.match.call(void 0,E.TokenType.comma)||M.match.call(void 0,E.TokenType.braceR)){G.state.tokens[G.state.tokens.length-1].identifierRole=M.IdentifierRole.ExportAccess,G.state.tokens[G.state.tokens.length-2].isType=!0,G.state.tokens[G.state.tokens.length-1].isType=!0;return}if(Ze.parseIdentifier.call(void 0),M.match.call(void 0,E.TokenType.comma)||M.match.call(void 0,E.TokenType.braceR)){G.state.tokens[G.state.tokens.length-3].identifierRole=M.IdentifierRole.ExportAccess;return}Ze.parseIdentifier.call(void 0),G.state.tokens[G.state.tokens.length-3].identifierRole=M.IdentifierRole.ExportAccess,G.state.tokens[G.state.tokens.length-4].isType=!0,G.state.tokens[G.state.tokens.length-3].isType=!0,G.state.tokens[G.state.tokens.length-2].isType=!0,G.state.tokens[G.state.tokens.length-1].isType=!0}ut.tsParseExportSpecifier=wM;function kM(){if(ke.isContextual.call(void 0,Me.ContextualKeyword._abstract)&&M.lookaheadType.call(void 0)===E.TokenType._class)return G.state.type=E.TokenType._abstract,M.next.call(void 0),Tr.parseClass.call(void 0,!0,!0),!0;if(ke.isContextual.call(void 0,Me.ContextualKeyword._interface)){let e=M.pushTypeContext.call(void 0,2);return Al(Me.ContextualKeyword._interface,!0),M.popTypeContext.call(void 0,e),!0}return!1}ut.tsTryParseExportDefaultExpression=kM;function _M(){if(G.state.type===E.TokenType._const){let e=M.lookaheadTypeAndKeyword.call(void 0);if(e.type===E.TokenType.name&&e.contextualKeyword===Me.ContextualKeyword._enum)return ke.expect.call(void 0,E.TokenType._const),ke.expectContextual.call(void 0,Me.ContextualKeyword._enum),G.state.tokens[G.state.tokens.length-1].type=E.TokenType._enum,cp(),!0}return!1}ut.tsTryParseStatementContent=_M;function vM(e){let t=G.state.tokens.length;Tw([Me.ContextualKeyword._abstract,Me.ContextualKeyword._readonly,Me.ContextualKeyword._declare,Me.ContextualKeyword._static,Me.ContextualKeyword._override]);let n=G.state.tokens.length;if(Sw()){let o=e?t-1:t;for(let s=o;s<n;s++)G.state.tokens[s].isType=!0;return!0}return!1}ut.tsTryParseClassMemberWithIsStatic=vM;function TM(e){pM(e)||ke.semicolon.call(void 0)}ut.tsParseIdentifierStatement=TM;function xM(){let e=ke.eatContextual.call(void 0,Me.ContextualKeyword._declare);e&&(G.state.tokens[G.state.tokens.length-1].type=E.TokenType._declare);let t=!1;if(M.match.call(void 0,E.TokenType.name))if(e){let n=M.pushTypeContext.call(void 0,2);t=_w(),M.popTypeContext.call(void 0,n)}else t=_w();if(!t)if(e){let n=M.pushTypeContext.call(void 0,2);Tr.parseStatement.call(void 0,!0),M.popTypeContext.call(void 0,n)}else Tr.parseStatement.call(void 0,!0)}ut.tsParseExportDeclaration=xM;function SM(e){if(e&&(M.match.call(void 0,E.TokenType.lessThan)||M.match.call(void 0,E.TokenType.bitShiftL))&&dp(),ke.eatContextual.call(void 0,Me.ContextualKeyword._implements)){G.state.tokens[G.state.tokens.length-1].type=E.TokenType._implements;let t=M.pushTypeContext.call(void 0,1);Rw(),M.popTypeContext.call(void 0,t)}}ut.tsAfterParseClassSuper=SM;function $M(){Ms()}ut.tsStartParseObjPropValue=$M;function RM(){Ms()}ut.tsStartParseFunctionParams=RM;function CM(){let e=M.pushTypeContext.call(void 0,0);ke.hasPrecedingLineBreak.call(void 0)||M.eat.call(void 0,E.TokenType.bang),qi(),M.popTypeContext.call(void 0,e)}ut.tsAfterParseVarHead=CM;function AM(){M.match.call(void 0,E.TokenType.colon)&&Ui()}ut.tsStartParseAsyncArrowFromCallExpression=AM;function EM(e,t){return G.isJSXEnabled?Ew(e,t):Mw(e,t)}ut.tsParseMaybeAssign=EM;function Ew(e,t){if(!M.match.call(void 0,E.TokenType.lessThan))return Ze.baseParseMaybeAssign.call(void 0,e,t);let n=G.state.snapshot(),r=Ze.baseParseMaybeAssign.call(void 0,e,t);if(G.state.error)G.state.restoreFromSnapshot(n);else return r;return G.state.type=E.TokenType.typeParameterStart,Cl(),r=Ze.baseParseMaybeAssign.call(void 0,e,t),r||ke.unexpected.call(void 0),r}ut.tsParseMaybeAssignWithJSX=Ew;function Mw(e,t){if(!M.match.call(void 0,E.TokenType.lessThan))return Ze.baseParseMaybeAssign.call(void 0,e,t);let n=G.state.snapshot();Cl();let r=Ze.baseParseMaybeAssign.call(void 0,e,t);if(r||ke.unexpected.call(void 0),G.state.error)G.state.restoreFromSnapshot(n);else return r;return Ze.baseParseMaybeAssign.call(void 0,e,t)}ut.tsParseMaybeAssignWithoutJSX=Mw;function MM(){if(M.match.call(void 0,E.TokenType.colon)){let e=G.state.snapshot();Di(E.TokenType.colon),ke.canInsertSemicolon.call(void 0)&&ke.unexpected.call(void 0),M.match.call(void 0,E.TokenType.arrow)||ke.unexpected.call(void 0),G.state.error&&G.state.restoreFromSnapshot(e)}return M.eat.call(void 0,E.TokenType.arrow)}ut.tsParseArrow=MM;function IM(){let e=M.pushTypeContext.call(void 0,0);M.eat.call(void 0,E.TokenType.question),qi(),M.popTypeContext.call(void 0,e)}ut.tsParseAssignableListItemTypes=IM;function PM(){(M.match.call(void 0,E.TokenType.lessThan)||M.match.call(void 0,E.TokenType.bitShiftL))&&dp(),Tr.baseParseMaybeDecoratorArguments.call(void 0)}ut.tsParseMaybeDecoratorArguments=PM});var pp=Ie(Ml=>{"use strict";Object.defineProperty(Ml,"__esModule",{value:!0});var ot=en(),ht=et(),Be=jn(),El=Lo(),eo=Xr(),Gt=Nn(),Iw=xs(),FM=Cs();function OM(){let e=!1,t=!1;for(;;){if(Be.state.pos>=Be.input.length){eo.unexpected.call(void 0,"Unterminated JSX contents");return}let n=Be.input.charCodeAt(Be.state.pos);if(n===Gt.charCodes.lessThan||n===Gt.charCodes.leftCurlyBrace){if(Be.state.pos===Be.state.start){if(n===Gt.charCodes.lessThan){Be.state.pos++,ot.finishToken.call(void 0,ht.TokenType.jsxTagStart);return}ot.getTokenFromCode.call(void 0,n);return}e&&!t?ot.finishToken.call(void 0,ht.TokenType.jsxEmptyText):ot.finishToken.call(void 0,ht.TokenType.jsxText);return}n===Gt.charCodes.lineFeed?e=!0:n!==Gt.charCodes.space&&n!==Gt.charCodes.carriageReturn&&n!==Gt.charCodes.tab&&(t=!0),Be.state.pos++}}function LM(e){for(Be.state.pos++;;){if(Be.state.pos>=Be.input.length){eo.unexpected.call(void 0,"Unterminated string constant");return}if(Be.input.charCodeAt(Be.state.pos)===e){Be.state.pos++;break}Be.state.pos++}ot.finishToken.call(void 0,ht.TokenType.string)}function NM(){let e;do{if(Be.state.pos>Be.input.length){eo.unexpected.call(void 0,"Unexpectedly reached the end of input.");return}e=Be.input.charCodeAt(++Be.state.pos)}while(Iw.IS_IDENTIFIER_CHAR[e]||e===Gt.charCodes.dash);ot.finishToken.call(void 0,ht.TokenType.jsxName)}function mp(){Xn()}function Pw(e){if(mp(),!ot.eat.call(void 0,ht.TokenType.colon)){Be.state.tokens[Be.state.tokens.length-1].identifierRole=e;return}mp()}function Fw(){let e=Be.state.tokens.length;Pw(ot.IdentifierRole.Access);let t=!1;for(;ot.match.call(void 0,ht.TokenType.dot);)t=!0,Xn(),mp();if(!t){let n=Be.state.tokens[e],r=Be.input.charCodeAt(n.start);r>=Gt.charCodes.lowercaseA&&r<=Gt.charCodes.lowercaseZ&&(n.identifierRole=null)}}function jM(){switch(Be.state.type){case ht.TokenType.braceL:ot.next.call(void 0),El.parseExpression.call(void 0),Xn();return;case ht.TokenType.jsxTagStart:Lw(),Xn();return;case ht.TokenType.string:Xn();return;default:eo.unexpected.call(void 0,"JSX value should be either an expression or a quoted JSX text")}}function DM(){eo.expect.call(void 0,ht.TokenType.ellipsis),El.parseExpression.call(void 0)}function BM(e){if(ot.match.call(void 0,ht.TokenType.jsxTagEnd))return!1;Fw(),Be.isTypeScriptEnabled&&FM.tsTryParseJSXTypeArgument.call(void 0);let t=!1;for(;!ot.match.call(void 0,ht.TokenType.slash)&&!ot.match.call(void 0,ht.TokenType.jsxTagEnd)&&!Be.state.error;){if(ot.eat.call(void 0,ht.TokenType.braceL)){t=!0,eo.expect.call(void 0,ht.TokenType.ellipsis),El.parseMaybeAssign.call(void 0),Xn();continue}t&&Be.state.end-Be.state.start===3&&Be.input.charCodeAt(Be.state.start)===Gt.charCodes.lowercaseK&&Be.input.charCodeAt(Be.state.start+1)===Gt.charCodes.lowercaseE&&Be.input.charCodeAt(Be.state.start+2)===Gt.charCodes.lowercaseY&&(Be.state.tokens[e].jsxRole=ot.JSXRole.KeyAfterPropSpread),Pw(ot.IdentifierRole.ObjectKey),ot.match.call(void 0,ht.TokenType.eq)&&(Xn(),jM())}let n=ot.match.call(void 0,ht.TokenType.slash);return n&&Xn(),n}function qM(){ot.match.call(void 0,ht.TokenType.jsxTagEnd)||Fw()}function Ow(){let e=Be.state.tokens.length-1;Be.state.tokens[e].jsxRole=ot.JSXRole.NoChildren;let t=0;if(!BM(e))for(Ps();;)switch(Be.state.type){case ht.TokenType.jsxTagStart:if(Xn(),ot.match.call(void 0,ht.TokenType.slash)){Xn(),qM(),Be.state.tokens[e].jsxRole!==ot.JSXRole.KeyAfterPropSpread&&(t===1?Be.state.tokens[e].jsxRole=ot.JSXRole.OneChild:t>1&&(Be.state.tokens[e].jsxRole=ot.JSXRole.StaticChildren));return}t++,Ow(),Ps();break;case ht.TokenType.jsxText:t++,Ps();break;case ht.TokenType.jsxEmptyText:Ps();break;case ht.TokenType.braceL:ot.next.call(void 0),ot.match.call(void 0,ht.TokenType.ellipsis)?(DM(),Ps(),t+=2):(ot.match.call(void 0,ht.TokenType.braceR)||(t++,El.parseExpression.call(void 0)),Ps());break;default:eo.unexpected.call(void 0);return}}function Lw(){Xn(),Ow()}Ml.jsxParseElement=Lw;function Xn(){Be.state.tokens.push(new ot.Token),ot.skipSpace.call(void 0),Be.state.start=Be.state.pos;let e=Be.input.charCodeAt(Be.state.pos);if(Iw.IS_IDENTIFIER_START[e])NM();else if(e===Gt.charCodes.quotationMark||e===Gt.charCodes.apostrophe)LM(e);else switch(++Be.state.pos,e){case Gt.charCodes.greaterThan:ot.finishToken.call(void 0,ht.TokenType.jsxTagEnd);break;case Gt.charCodes.lessThan:ot.finishToken.call(void 0,ht.TokenType.jsxTagStart);break;case Gt.charCodes.slash:ot.finishToken.call(void 0,ht.TokenType.slash);break;case Gt.charCodes.equalsTo:ot.finishToken.call(void 0,ht.TokenType.eq);break;case Gt.charCodes.leftCurlyBrace:ot.finishToken.call(void 0,ht.TokenType.braceL);break;case Gt.charCodes.dot:ot.finishToken.call(void 0,ht.TokenType.dot);break;case Gt.charCodes.colon:ot.finishToken.call(void 0,ht.TokenType.colon);break;default:eo.unexpected.call(void 0)}}Ml.nextJSXTagToken=Xn;function Ps(){Be.state.tokens.push(new ot.Token),Be.state.start=Be.state.pos,OM()}});var jw=Ie(Pl=>{"use strict";Object.defineProperty(Pl,"__esModule",{value:!0});var Il=en(),Fs=et(),Nw=jn(),UM=Lo(),GM=ji(),HM=Cs();function zM(e){if(Il.match.call(void 0,Fs.TokenType.question)){let t=Il.lookaheadType.call(void 0);if(t===Fs.TokenType.colon||t===Fs.TokenType.comma||t===Fs.TokenType.parenR)return}UM.baseParseConditional.call(void 0,e)}Pl.typedParseConditional=zM;function WM(){Il.eatTypeToken.call(void 0,Fs.TokenType.question),Il.match.call(void 0,Fs.TokenType.colon)&&(Nw.isTypeScriptEnabled?HM.tsParseTypeAnnotation.call(void 0):Nw.isFlowEnabled&&GM.flowParseTypeAnnotation.call(void 0))}Pl.typedParseParenItem=WM});var Lo=Ie(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});var Fr=ji(),KM=pp(),Dw=jw(),no=Cs(),ye=en(),Ir=rn(),Bw=ul(),se=et(),qw=Nn(),VM=xs(),ie=jn(),to=$l(),lr=Gi(),it=Xr(),Ll=class{constructor(t){this.stop=t}};Et.StopState=Ll;function Hi(e=!1){if(Qn(e),ye.match.call(void 0,se.TokenType.comma))for(;ye.eat.call(void 0,se.TokenType.comma);)Qn(e)}Et.parseExpression=Hi;function Qn(e=!1,t=!1){return ie.isTypeScriptEnabled?no.tsParseMaybeAssign.call(void 0,e,t):ie.isFlowEnabled?Fr.flowParseMaybeAssign.call(void 0,e,t):Uw(e,t)}Et.parseMaybeAssign=Qn;function Uw(e,t){if(ye.match.call(void 0,se.TokenType._yield))return dI(),!1;(ye.match.call(void 0,se.TokenType.parenL)||ye.match.call(void 0,se.TokenType.name)||ye.match.call(void 0,se.TokenType._yield))&&(ie.state.potentialArrowAt=ie.state.start);let n=JM(e);return t&&yp(),ie.state.type&se.TokenType.IS_ASSIGN?(ye.next.call(void 0),Qn(e),!1):n}Et.baseParseMaybeAssign=Uw;function JM(e){return QM(e)?!0:(XM(e),!1)}function XM(e){ie.isTypeScriptEnabled||ie.isFlowEnabled?Dw.typedParseConditional.call(void 0,e):Gw(e)}function Gw(e){ye.eat.call(void 0,se.TokenType.question)&&(Qn(),it.expect.call(void 0,se.TokenType.colon),Qn(e))}Et.baseParseConditional=Gw;function QM(e){let t=ie.state.tokens.length;return Wi()?!0:(Fl(t,-1,e),!1)}function Fl(e,t,n){if(ie.isTypeScriptEnabled&&(se.TokenType._in&se.TokenType.PRECEDENCE_MASK)>t&&!it.hasPrecedingLineBreak.call(void 0)&&(it.eatContextual.call(void 0,Ir.ContextualKeyword._as)||it.eatContextual.call(void 0,Ir.ContextualKeyword._satisfies))){let o=ye.pushTypeContext.call(void 0,1);no.tsParseType.call(void 0),ye.popTypeContext.call(void 0,o),ye.rescan_gt.call(void 0),Fl(e,t,n);return}let r=ie.state.type&se.TokenType.PRECEDENCE_MASK;if(r>0&&(!n||!ye.match.call(void 0,se.TokenType._in))&&r>t){let o=ie.state.type;ye.next.call(void 0),o===se.TokenType.nullishCoalescing&&(ie.state.tokens[ie.state.tokens.length-1].nullishStartIndex=e);let s=ie.state.tokens.length;Wi(),Fl(s,o&se.TokenType.IS_RIGHT_ASSOCIATIVE?r-1:r,n),o===se.TokenType.nullishCoalescing&&(ie.state.tokens[e].numNullishCoalesceStarts++,ie.state.tokens[ie.state.tokens.length-1].numNullishCoalesceEnds++),Fl(e,t,n)}}function Wi(){if(ie.isTypeScriptEnabled&&!ie.isJSXEnabled&&ye.eat.call(void 0,se.TokenType.lessThan))return no.tsParseTypeAssertion.call(void 0),!1;if(it.isContextual.call(void 0,Ir.ContextualKeyword._module)&&ye.lookaheadCharCode.call(void 0)===qw.charCodes.leftCurlyBrace&&!it.hasFollowingLineBreak.call(void 0))return pI(),!1;if(ie.state.type&se.TokenType.IS_PREFIX)return ye.next.call(void 0),Wi(),!1;if(Hw())return!0;for(;ie.state.type&se.TokenType.IS_POSTFIX&&!it.canInsertSemicolon.call(void 0);)ie.state.type===se.TokenType.preIncDec&&(ie.state.type=se.TokenType.postIncDec),ye.next.call(void 0);return!1}Et.parseMaybeUnary=Wi;function Hw(){let e=ie.state.tokens.length;return Dl()?!0:(gp(e),ie.state.tokens.length>e&&ie.state.tokens[e].isOptionalChainStart&&(ie.state.tokens[ie.state.tokens.length-1].isOptionalChainEnd=!0),!1)}Et.parseExprSubscripts=Hw;function gp(e,t=!1){ie.isFlowEnabled?Fr.flowParseSubscripts.call(void 0,e,t):zw(e,t)}function zw(e,t=!1){let n=new Ll(!1);do YM(e,t,n);while(!n.stop&&!ie.state.error)}Et.baseParseSubscripts=zw;function YM(e,t,n){ie.isTypeScriptEnabled?no.tsParseSubscript.call(void 0,e,t,n):ie.isFlowEnabled?Fr.flowParseSubscript.call(void 0,e,t,n):Ww(e,t,n)}function Ww(e,t,n){if(!t&&ye.eat.call(void 0,se.TokenType.doubleColon))bp(),n.stop=!0,gp(e,t);else if(ye.match.call(void 0,se.TokenType.questionDot)){if(ie.state.tokens[e].isOptionalChainStart=!0,t&&ye.lookaheadType.call(void 0)===se.TokenType.parenL){n.stop=!0;return}ye.next.call(void 0),ie.state.tokens[ie.state.tokens.length-1].subscriptStartIndex=e,ye.eat.call(void 0,se.TokenType.bracketL)?(Hi(),it.expect.call(void 0,se.TokenType.bracketR)):ye.eat.call(void 0,se.TokenType.parenL)?Ol():Nl()}else if(ye.eat.call(void 0,se.TokenType.dot))ie.state.tokens[ie.state.tokens.length-1].subscriptStartIndex=e,Nl();else if(ye.eat.call(void 0,se.TokenType.bracketL))ie.state.tokens[ie.state.tokens.length-1].subscriptStartIndex=e,Hi(),it.expect.call(void 0,se.TokenType.bracketR);else if(!t&&ye.match.call(void 0,se.TokenType.parenL))if(Kw()){let r=ie.state.snapshot(),o=ie.state.tokens.length;ye.next.call(void 0),ie.state.tokens[ie.state.tokens.length-1].subscriptStartIndex=e;let s=ie.getNextContextId.call(void 0);ie.state.tokens[ie.state.tokens.length-1].contextId=s,Ol(),ie.state.tokens[ie.state.tokens.length-1].contextId=s,ZM()&&(ie.state.restoreFromSnapshot(r),n.stop=!0,ie.state.scopeDepth++,lr.parseFunctionParams.call(void 0),eI(o))}else{ye.next.call(void 0),ie.state.tokens[ie.state.tokens.length-1].subscriptStartIndex=e;let r=ie.getNextContextId.call(void 0);ie.state.tokens[ie.state.tokens.length-1].contextId=r,Ol(),ie.state.tokens[ie.state.tokens.length-1].contextId=r}else ye.match.call(void 0,se.TokenType.backQuote)?wp():n.stop=!0}Et.baseParseSubscript=Ww;function Kw(){return ie.state.tokens[ie.state.tokens.length-1].contextualKeyword===Ir.ContextualKeyword._async&&!it.canInsertSemicolon.call(void 0)}Et.atPossibleAsync=Kw;function Ol(){let e=!0;for(;!ye.eat.call(void 0,se.TokenType.parenR)&&!ie.state.error;){if(e)e=!1;else if(it.expect.call(void 0,se.TokenType.comma),ye.eat.call(void 0,se.TokenType.parenR))break;Zw(!1)}}Et.parseCallExpressionArguments=Ol;function ZM(){return ye.match.call(void 0,se.TokenType.colon)||ye.match.call(void 0,se.TokenType.arrow)}function eI(e){ie.isTypeScriptEnabled?no.tsStartParseAsyncArrowFromCallExpression.call(void 0):ie.isFlowEnabled&&Fr.flowStartParseAsyncArrowFromCallExpression.call(void 0),it.expect.call(void 0,se.TokenType.arrow),zi(e)}function bp(){let e=ie.state.tokens.length;Dl(),gp(e,!0)}function Dl(){if(ye.eat.call(void 0,se.TokenType.modulo))return Pr(),!1;if(ye.match.call(void 0,se.TokenType.jsxText)||ye.match.call(void 0,se.TokenType.jsxEmptyText))return Vw(),!1;if(ye.match.call(void 0,se.TokenType.lessThan)&&ie.isJSXEnabled)return ie.state.type=se.TokenType.jsxTagStart,KM.jsxParseElement.call(void 0),ye.next.call(void 0),!1;let e=ie.state.potentialArrowAt===ie.state.start;switch(ie.state.type){case se.TokenType.slash:case se.TokenType.assign:ye.retokenizeSlashAsRegex.call(void 0);case se.TokenType._super:case se.TokenType._this:case se.TokenType.regexp:case se.TokenType.num:case se.TokenType.bigint:case se.TokenType.decimal:case se.TokenType.string:case se.TokenType._null:case se.TokenType._true:case se.TokenType._false:return ye.next.call(void 0),!1;case se.TokenType._import:return ye.next.call(void 0),ye.match.call(void 0,se.TokenType.dot)&&(ie.state.tokens[ie.state.tokens.length-1].type=se.TokenType.name,ye.next.call(void 0),Pr()),!1;case se.TokenType.name:{let t=ie.state.tokens.length,n=ie.state.start,r=ie.state.contextualKeyword;return Pr(),r===Ir.ContextualKeyword._await?(uI(),!1):r===Ir.ContextualKeyword._async&&ye.match.call(void 0,se.TokenType._function)&&!it.canInsertSemicolon.call(void 0)?(ye.next.call(void 0),lr.parseFunction.call(void 0,n,!1),!1):e&&r===Ir.ContextualKeyword._async&&!it.canInsertSemicolon.call(void 0)&&ye.match.call(void 0,se.TokenType.name)?(ie.state.scopeDepth++,to.parseBindingIdentifier.call(void 0,!1),it.expect.call(void 0,se.TokenType.arrow),zi(t),!0):ye.match.call(void 0,se.TokenType._do)&&!it.canInsertSemicolon.call(void 0)?(ye.next.call(void 0),lr.parseBlock.call(void 0),!1):e&&!it.canInsertSemicolon.call(void 0)&&ye.match.call(void 0,se.TokenType.arrow)?(ie.state.scopeDepth++,to.markPriorBindingIdentifier.call(void 0,!1),it.expect.call(void 0,se.TokenType.arrow),zi(t),!0):(ie.state.tokens[ie.state.tokens.length-1].identifierRole=ye.IdentifierRole.Access,!1)}case se.TokenType._do:return ye.next.call(void 0),lr.parseBlock.call(void 0),!1;case se.TokenType.parenL:return Jw(e);case se.TokenType.bracketL:return ye.next.call(void 0),Yw(se.TokenType.bracketR,!0),!1;case se.TokenType.braceL:return Xw(!1,!1),!1;case se.TokenType._function:return tI(),!1;case se.TokenType.at:lr.parseDecorators.call(void 0);case se.TokenType._class:return lr.parseClass.call(void 0,!1),!1;case se.TokenType._new:return oI(),!1;case se.TokenType.backQuote:return wp(),!1;case se.TokenType.doubleColon:return ye.next.call(void 0),bp(),!1;case se.TokenType.hash:{let t=ye.lookaheadCharCode.call(void 0);return VM.IS_IDENTIFIER_START[t]||t===qw.charCodes.backslash?Nl():ye.next.call(void 0),!1}default:return it.unexpected.call(void 0),!1}}Et.parseExprAtom=Dl;function Nl(){ye.eat.call(void 0,se.TokenType.hash),Pr()}function tI(){let e=ie.state.start;Pr(),ye.eat.call(void 0,se.TokenType.dot)&&Pr(),lr.parseFunction.call(void 0,e,!1)}function Vw(){ye.next.call(void 0)}Et.parseLiteral=Vw;function nI(){it.expect.call(void 0,se.TokenType.parenL),Hi(),it.expect.call(void 0,se.TokenType.parenR)}Et.parseParenExpression=nI;function Jw(e){let t=ie.state.snapshot(),n=ie.state.tokens.length;it.expect.call(void 0,se.TokenType.parenL);let r=!0;for(;!ye.match.call(void 0,se.TokenType.parenR)&&!ie.state.error;){if(r)r=!1;else if(it.expect.call(void 0,se.TokenType.comma),ye.match.call(void 0,se.TokenType.parenR))break;if(ye.match.call(void 0,se.TokenType.ellipsis)){to.parseRest.call(void 0,!1),yp();break}else Qn(!1,!0)}return it.expect.call(void 0,se.TokenType.parenR),e&&rI()&&fp()?(ie.state.restoreFromSnapshot(t),ie.state.scopeDepth++,lr.parseFunctionParams.call(void 0),fp(),zi(n),ie.state.error?(ie.state.restoreFromSnapshot(t),Jw(!1),!1):!0):!1}function rI(){return ye.match.call(void 0,se.TokenType.colon)||!it.canInsertSemicolon.call(void 0)}function fp(){return ie.isTypeScriptEnabled?no.tsParseArrow.call(void 0):ie.isFlowEnabled?Fr.flowParseArrow.call(void 0):ye.eat.call(void 0,se.TokenType.arrow)}Et.parseArrow=fp;function yp(){(ie.isTypeScriptEnabled||ie.isFlowEnabled)&&Dw.typedParseParenItem.call(void 0)}function oI(){if(it.expect.call(void 0,se.TokenType._new),ye.eat.call(void 0,se.TokenType.dot)){Pr();return}sI(),ie.isFlowEnabled&&Fr.flowStartParseNewArguments.call(void 0),ye.eat.call(void 0,se.TokenType.parenL)&&Yw(se.TokenType.parenR)}function sI(){bp(),ye.eat.call(void 0,se.TokenType.questionDot)}function wp(){for(ye.nextTemplateToken.call(void 0),ye.nextTemplateToken.call(void 0);!ye.match.call(void 0,se.TokenType.backQuote)&&!ie.state.error;)it.expect.call(void 0,se.TokenType.dollarBraceL),Hi(),ye.nextTemplateToken.call(void 0),ye.nextTemplateToken.call(void 0);ye.next.call(void 0)}Et.parseTemplate=wp;function Xw(e,t){let n=ie.getNextContextId.call(void 0),r=!0;for(ye.next.call(void 0),ie.state.tokens[ie.state.tokens.length-1].contextId=n;!ye.eat.call(void 0,se.TokenType.braceR)&&!ie.state.error;){if(r)r=!1;else if(it.expect.call(void 0,se.TokenType.comma),ye.eat.call(void 0,se.TokenType.braceR))break;let o=!1;if(ye.match.call(void 0,se.TokenType.ellipsis)){let s=ie.state.tokens.length;if(to.parseSpread.call(void 0),e&&(ie.state.tokens.length===s+2&&to.markPriorBindingIdentifier.call(void 0,t),ye.eat.call(void 0,se.TokenType.braceR)))break;continue}e||(o=ye.eat.call(void 0,se.TokenType.star)),!e&&it.isContextual.call(void 0,Ir.ContextualKeyword._async)?(o&&it.unexpected.call(void 0),Pr(),ye.match.call(void 0,se.TokenType.colon)||ye.match.call(void 0,se.TokenType.parenL)||ye.match.call(void 0,se.TokenType.braceR)||ye.match.call(void 0,se.TokenType.eq)||ye.match.call(void 0,se.TokenType.comma)||(ye.match.call(void 0,se.TokenType.star)&&(ye.next.call(void 0),o=!0),jl(n))):jl(n),cI(e,t,n)}ie.state.tokens[ie.state.tokens.length-1].contextId=n}Et.parseObj=Xw;function iI(e){return!e&&(ye.match.call(void 0,se.TokenType.string)||ye.match.call(void 0,se.TokenType.num)||ye.match.call(void 0,se.TokenType.bracketL)||ye.match.call(void 0,se.TokenType.name)||!!(ie.state.type&se.TokenType.IS_KEYWORD))}function aI(e,t){let n=ie.state.start;return ye.match.call(void 0,se.TokenType.parenL)?(e&&it.unexpected.call(void 0),hp(n,!1),!0):iI(e)?(jl(t),hp(n,!1),!0):!1}function lI(e,t){if(ye.eat.call(void 0,se.TokenType.colon)){e?to.parseMaybeDefault.call(void 0,t):Qn(!1);return}let n;e?ie.state.scopeDepth===0?n=ye.IdentifierRole.ObjectShorthandTopLevelDeclaration:t?n=ye.IdentifierRole.ObjectShorthandBlockScopedDeclaration:n=ye.IdentifierRole.ObjectShorthandFunctionScopedDeclaration:n=ye.IdentifierRole.ObjectShorthand,ie.state.tokens[ie.state.tokens.length-1].identifierRole=n,to.parseMaybeDefault.call(void 0,t,!0)}function cI(e,t,n){ie.isTypeScriptEnabled?no.tsStartParseObjPropValue.call(void 0):ie.isFlowEnabled&&Fr.flowStartParseObjPropValue.call(void 0),aI(e,n)||lI(e,t)}function jl(e){ie.isFlowEnabled&&Fr.flowParseVariance.call(void 0),ye.eat.call(void 0,se.TokenType.bracketL)?(ie.state.tokens[ie.state.tokens.length-1].contextId=e,Qn(),it.expect.call(void 0,se.TokenType.bracketR),ie.state.tokens[ie.state.tokens.length-1].contextId=e):(ye.match.call(void 0,se.TokenType.num)||ye.match.call(void 0,se.TokenType.string)||ye.match.call(void 0,se.TokenType.bigint)||ye.match.call(void 0,se.TokenType.decimal)?Dl():Nl(),ie.state.tokens[ie.state.tokens.length-1].identifierRole=ye.IdentifierRole.ObjectKey,ie.state.tokens[ie.state.tokens.length-1].contextId=e)}Et.parsePropertyName=jl;function hp(e,t){let n=ie.getNextContextId.call(void 0);ie.state.scopeDepth++;let r=ie.state.tokens.length,o=t;lr.parseFunctionParams.call(void 0,o,n),Qw(e,n);let s=ie.state.tokens.length;ie.state.scopes.push(new Bw.Scope(r,s,!0)),ie.state.scopeDepth--}Et.parseMethod=hp;function zi(e){kp(!0);let t=ie.state.tokens.length;ie.state.scopes.push(new Bw.Scope(e,t,!0)),ie.state.scopeDepth--}Et.parseArrowExpression=zi;function Qw(e,t=0){ie.isTypeScriptEnabled?no.tsParseFunctionBodyAndFinish.call(void 0,e,t):ie.isFlowEnabled?Fr.flowParseFunctionBodyAndFinish.call(void 0,t):kp(!1,t)}Et.parseFunctionBodyAndFinish=Qw;function kp(e,t=0){e&&!ye.match.call(void 0,se.TokenType.braceL)?Qn():lr.parseBlock.call(void 0,!0,t)}Et.parseFunctionBody=kp;function Yw(e,t=!1){let n=!0;for(;!ye.eat.call(void 0,e)&&!ie.state.error;){if(n)n=!1;else if(it.expect.call(void 0,se.TokenType.comma),ye.eat.call(void 0,e))break;Zw(t)}}function Zw(e){e&&ye.match.call(void 0,se.TokenType.comma)||(ye.match.call(void 0,se.TokenType.ellipsis)?(to.parseSpread.call(void 0),yp()):ye.match.call(void 0,se.TokenType.question)?ye.next.call(void 0):Qn(!1,!0))}function Pr(){ye.next.call(void 0),ie.state.tokens[ie.state.tokens.length-1].type=se.TokenType.name}Et.parseIdentifier=Pr;function uI(){Wi()}function dI(){ye.next.call(void 0),!ye.match.call(void 0,se.TokenType.semi)&&!it.canInsertSemicolon.call(void 0)&&(ye.eat.call(void 0,se.TokenType.star),Qn())}function pI(){it.expectContextual.call(void 0,Ir.ContextualKeyword._module),it.expect.call(void 0,se.TokenType.braceL),lr.parseBlockBody.call(void 0,se.TokenType.braceR)}});var ji=Ie(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});var D=en(),Ge=rn(),F=et(),je=jn(),kt=Lo(),ro=Gi(),Te=Xr();function mI(e){return(e.type===F.TokenType.name||!!(e.type&F.TokenType.IS_KEYWORD))&&e.contextualKeyword!==Ge.ContextualKeyword._from}function xr(e){let t=D.pushTypeContext.call(void 0,0);Te.expect.call(void 0,e||F.TokenType.colon),Rn(),D.popTypeContext.call(void 0,t)}function ek(){Te.expect.call(void 0,F.TokenType.modulo),Te.expectContextual.call(void 0,Ge.ContextualKeyword._checks),D.eat.call(void 0,F.TokenType.parenL)&&(kt.parseExpression.call(void 0),Te.expect.call(void 0,F.TokenType.parenR))}function Tp(){let e=D.pushTypeContext.call(void 0,0);Te.expect.call(void 0,F.TokenType.colon),D.match.call(void 0,F.TokenType.modulo)?ek():(Rn(),D.match.call(void 0,F.TokenType.modulo)&&ek()),D.popTypeContext.call(void 0,e)}function fI(){D.next.call(void 0),xp(!0)}function hI(){D.next.call(void 0),kt.parseIdentifier.call(void 0),D.match.call(void 0,F.TokenType.lessThan)&&Sr(),Te.expect.call(void 0,F.TokenType.parenL),vp(),Te.expect.call(void 0,F.TokenType.parenR),Tp(),Te.semicolon.call(void 0)}function _p(){D.match.call(void 0,F.TokenType._class)?fI():D.match.call(void 0,F.TokenType._function)?hI():D.match.call(void 0,F.TokenType._var)?gI():Te.eatContextual.call(void 0,Ge.ContextualKeyword._module)?D.eat.call(void 0,F.TokenType.dot)?wI():bI():Te.isContextual.call(void 0,Ge.ContextualKeyword._type)?kI():Te.isContextual.call(void 0,Ge.ContextualKeyword._opaque)?_I():Te.isContextual.call(void 0,Ge.ContextualKeyword._interface)?vI():D.match.call(void 0,F.TokenType._export)?yI():Te.unexpected.call(void 0)}function gI(){D.next.call(void 0),ik(),Te.semicolon.call(void 0)}function bI(){for(D.match.call(void 0,F.TokenType.string)?kt.parseExprAtom.call(void 0):kt.parseIdentifier.call(void 0),Te.expect.call(void 0,F.TokenType.braceL);!D.match.call(void 0,F.TokenType.braceR)&&!je.state.error;)D.match.call(void 0,F.TokenType._import)?(D.next.call(void 0),ro.parseImport.call(void 0)):Te.unexpected.call(void 0);Te.expect.call(void 0,F.TokenType.braceR)}function yI(){Te.expect.call(void 0,F.TokenType._export),D.eat.call(void 0,F.TokenType._default)?D.match.call(void 0,F.TokenType._function)||D.match.call(void 0,F.TokenType._class)?_p():(Rn(),Te.semicolon.call(void 0)):D.match.call(void 0,F.TokenType._var)||D.match.call(void 0,F.TokenType._function)||D.match.call(void 0,F.TokenType._class)||Te.isContextual.call(void 0,Ge.ContextualKeyword._opaque)?_p():D.match.call(void 0,F.TokenType.star)||D.match.call(void 0,F.TokenType.braceL)||Te.isContextual.call(void 0,Ge.ContextualKeyword._interface)||Te.isContextual.call(void 0,Ge.ContextualKeyword._type)||Te.isContextual.call(void 0,Ge.ContextualKeyword._opaque)?ro.parseExport.call(void 0):Te.unexpected.call(void 0)}function wI(){Te.expectContextual.call(void 0,Ge.ContextualKeyword._exports),Os(),Te.semicolon.call(void 0)}function kI(){D.next.call(void 0),$p()}function _I(){D.next.call(void 0),Rp(!0)}function vI(){D.next.call(void 0),xp()}function xp(e=!1){if(Gl(),D.match.call(void 0,F.TokenType.lessThan)&&Sr(),D.eat.call(void 0,F.TokenType._extends))do Bl();while(!e&&D.eat.call(void 0,F.TokenType.comma));if(Te.isContextual.call(void 0,Ge.ContextualKeyword._mixins)){D.next.call(void 0);do Bl();while(D.eat.call(void 0,F.TokenType.comma))}if(Te.isContextual.call(void 0,Ge.ContextualKeyword._implements)){D.next.call(void 0);do Bl();while(D.eat.call(void 0,F.TokenType.comma))}ql(e,!1,e)}function Bl(){rk(!1),D.match.call(void 0,F.TokenType.lessThan)&&No()}function Sp(){xp()}function Gl(){kt.parseIdentifier.call(void 0)}function $p(){Gl(),D.match.call(void 0,F.TokenType.lessThan)&&Sr(),xr(F.TokenType.eq),Te.semicolon.call(void 0)}function Rp(e){Te.expectContextual.call(void 0,Ge.ContextualKeyword._type),Gl(),D.match.call(void 0,F.TokenType.lessThan)&&Sr(),D.match.call(void 0,F.TokenType.colon)&&xr(F.TokenType.colon),e||xr(F.TokenType.eq),Te.semicolon.call(void 0)}function TI(){Ep(),ik(),D.eat.call(void 0,F.TokenType.eq)&&Rn()}function Sr(){let e=D.pushTypeContext.call(void 0,0);D.match.call(void 0,F.TokenType.lessThan)||D.match.call(void 0,F.TokenType.typeParameterStart)?D.next.call(void 0):Te.unexpected.call(void 0);do TI(),D.match.call(void 0,F.TokenType.greaterThan)||Te.expect.call(void 0,F.TokenType.comma);while(!D.match.call(void 0,F.TokenType.greaterThan)&&!je.state.error);Te.expect.call(void 0,F.TokenType.greaterThan),D.popTypeContext.call(void 0,e)}Rt.flowParseTypeParameterDeclaration=Sr;function No(){let e=D.pushTypeContext.call(void 0,0);for(Te.expect.call(void 0,F.TokenType.lessThan);!D.match.call(void 0,F.TokenType.greaterThan)&&!je.state.error;)Rn(),D.match.call(void 0,F.TokenType.greaterThan)||Te.expect.call(void 0,F.TokenType.comma);Te.expect.call(void 0,F.TokenType.greaterThan),D.popTypeContext.call(void 0,e)}function xI(){if(Te.expectContextual.call(void 0,Ge.ContextualKeyword._interface),D.eat.call(void 0,F.TokenType._extends))do Bl();while(D.eat.call(void 0,F.TokenType.comma));ql(!1,!1,!1)}function Cp(){D.match.call(void 0,F.TokenType.num)||D.match.call(void 0,F.TokenType.string)?kt.parseExprAtom.call(void 0):kt.parseIdentifier.call(void 0)}function SI(){D.lookaheadType.call(void 0)===F.TokenType.colon?(Cp(),xr()):Rn(),Te.expect.call(void 0,F.TokenType.bracketR),xr()}function $I(){Cp(),Te.expect.call(void 0,F.TokenType.bracketR),Te.expect.call(void 0,F.TokenType.bracketR),D.match.call(void 0,F.TokenType.lessThan)||D.match.call(void 0,F.TokenType.parenL)?Ap():(D.eat.call(void 0,F.TokenType.question),xr())}function Ap(){for(D.match.call(void 0,F.TokenType.lessThan)&&Sr(),Te.expect.call(void 0,F.TokenType.parenL);!D.match.call(void 0,F.TokenType.parenR)&&!D.match.call(void 0,F.TokenType.ellipsis)&&!je.state.error;)Ul(),D.match.call(void 0,F.TokenType.parenR)||Te.expect.call(void 0,F.TokenType.comma);D.eat.call(void 0,F.TokenType.ellipsis)&&Ul(),Te.expect.call(void 0,F.TokenType.parenR),xr()}function RI(){Ap()}function ql(e,t,n){let r;for(t&&D.match.call(void 0,F.TokenType.braceBarL)?(Te.expect.call(void 0,F.TokenType.braceBarL),r=F.TokenType.braceBarR):(Te.expect.call(void 0,F.TokenType.braceL),r=F.TokenType.braceR);!D.match.call(void 0,r)&&!je.state.error;){if(n&&Te.isContextual.call(void 0,Ge.ContextualKeyword._proto)){let o=D.lookaheadType.call(void 0);o!==F.TokenType.colon&&o!==F.TokenType.question&&(D.next.call(void 0),e=!1)}if(e&&Te.isContextual.call(void 0,Ge.ContextualKeyword._static)){let o=D.lookaheadType.call(void 0);o!==F.TokenType.colon&&o!==F.TokenType.question&&D.next.call(void 0)}if(Ep(),D.eat.call(void 0,F.TokenType.bracketL))D.eat.call(void 0,F.TokenType.bracketL)?$I():SI();else if(D.match.call(void 0,F.TokenType.parenL)||D.match.call(void 0,F.TokenType.lessThan))RI();else{if(Te.isContextual.call(void 0,Ge.ContextualKeyword._get)||Te.isContextual.call(void 0,Ge.ContextualKeyword._set)){let o=D.lookaheadType.call(void 0);(o===F.TokenType.name||o===F.TokenType.string||o===F.TokenType.num)&&D.next.call(void 0)}CI()}AI()}Te.expect.call(void 0,r)}function CI(){if(D.match.call(void 0,F.TokenType.ellipsis)){if(Te.expect.call(void 0,F.TokenType.ellipsis),D.eat.call(void 0,F.TokenType.comma)||D.eat.call(void 0,F.TokenType.semi),D.match.call(void 0,F.TokenType.braceR))return;Rn()}else Cp(),D.match.call(void 0,F.TokenType.lessThan)||D.match.call(void 0,F.TokenType.parenL)?Ap():(D.eat.call(void 0,F.TokenType.question),xr())}function AI(){!D.eat.call(void 0,F.TokenType.semi)&&!D.eat.call(void 0,F.TokenType.comma)&&!D.match.call(void 0,F.TokenType.braceR)&&!D.match.call(void 0,F.TokenType.braceBarR)&&Te.unexpected.call(void 0)}function rk(e){for(e||kt.parseIdentifier.call(void 0);D.eat.call(void 0,F.TokenType.dot);)kt.parseIdentifier.call(void 0)}function EI(){rk(!0),D.match.call(void 0,F.TokenType.lessThan)&&No()}function MI(){Te.expect.call(void 0,F.TokenType._typeof),ok()}function II(){for(Te.expect.call(void 0,F.TokenType.bracketL);je.state.pos<je.input.length&&!D.match.call(void 0,F.TokenType.bracketR)&&(Rn(),!D.match.call(void 0,F.TokenType.bracketR));)Te.expect.call(void 0,F.TokenType.comma);Te.expect.call(void 0,F.TokenType.bracketR)}function Ul(){let e=D.lookaheadType.call(void 0);e===F.TokenType.colon||e===F.TokenType.question?(kt.parseIdentifier.call(void 0),D.eat.call(void 0,F.TokenType.question),xr()):Rn()}function vp(){for(;!D.match.call(void 0,F.TokenType.parenR)&&!D.match.call(void 0,F.TokenType.ellipsis)&&!je.state.error;)Ul(),D.match.call(void 0,F.TokenType.parenR)||Te.expect.call(void 0,F.TokenType.comma);D.eat.call(void 0,F.TokenType.ellipsis)&&Ul()}function ok(){let e=!1,t=je.state.noAnonFunctionType;switch(je.state.type){case F.TokenType.name:{if(Te.isContextual.call(void 0,Ge.ContextualKeyword._interface)){xI();return}kt.parseIdentifier.call(void 0),EI();return}case F.TokenType.braceL:ql(!1,!1,!1);return;case F.TokenType.braceBarL:ql(!1,!0,!1);return;case F.TokenType.bracketL:II();return;case F.TokenType.lessThan:Sr(),Te.expect.call(void 0,F.TokenType.parenL),vp(),Te.expect.call(void 0,F.TokenType.parenR),Te.expect.call(void 0,F.TokenType.arrow),Rn();return;case F.TokenType.parenL:if(D.next.call(void 0),!D.match.call(void 0,F.TokenType.parenR)&&!D.match.call(void 0,F.TokenType.ellipsis))if(D.match.call(void 0,F.TokenType.name)){let n=D.lookaheadType.call(void 0);e=n!==F.TokenType.question&&n!==F.TokenType.colon}else e=!0;if(e)if(je.state.noAnonFunctionType=!1,Rn(),je.state.noAnonFunctionType=t,je.state.noAnonFunctionType||!(D.match.call(void 0,F.TokenType.comma)||D.match.call(void 0,F.TokenType.parenR)&&D.lookaheadType.call(void 0)===F.TokenType.arrow)){Te.expect.call(void 0,F.TokenType.parenR);return}else D.eat.call(void 0,F.TokenType.comma);vp(),Te.expect.call(void 0,F.TokenType.parenR),Te.expect.call(void 0,F.TokenType.arrow),Rn();return;case F.TokenType.minus:D.next.call(void 0),kt.parseLiteral.call(void 0);return;case F.TokenType.string:case F.TokenType.num:case F.TokenType._true:case F.TokenType._false:case F.TokenType._null:case F.TokenType._this:case F.TokenType._void:case F.TokenType.star:D.next.call(void 0);return;default:if(je.state.type===F.TokenType._typeof){MI();return}else if(je.state.type&F.TokenType.IS_KEYWORD){D.next.call(void 0),je.state.tokens[je.state.tokens.length-1].type=F.TokenType.name;return}}Te.unexpected.call(void 0)}function PI(){for(ok();!Te.canInsertSemicolon.call(void 0)&&(D.match.call(void 0,F.TokenType.bracketL)||D.match.call(void 0,F.TokenType.questionDot));)D.eat.call(void 0,F.TokenType.questionDot),Te.expect.call(void 0,F.TokenType.bracketL),D.eat.call(void 0,F.TokenType.bracketR)||(Rn(),Te.expect.call(void 0,F.TokenType.bracketR))}function sk(){D.eat.call(void 0,F.TokenType.question)?sk():PI()}function tk(){sk(),!je.state.noAnonFunctionType&&D.eat.call(void 0,F.TokenType.arrow)&&Rn()}function nk(){for(D.eat.call(void 0,F.TokenType.bitwiseAND),tk();D.eat.call(void 0,F.TokenType.bitwiseAND);)tk()}function FI(){for(D.eat.call(void 0,F.TokenType.bitwiseOR),nk();D.eat.call(void 0,F.TokenType.bitwiseOR);)nk()}function Rn(){FI()}function Os(){xr()}Rt.flowParseTypeAnnotation=Os;function ik(){kt.parseIdentifier.call(void 0),D.match.call(void 0,F.TokenType.colon)&&Os()}function Ep(){(D.match.call(void 0,F.TokenType.plus)||D.match.call(void 0,F.TokenType.minus))&&(D.next.call(void 0),je.state.tokens[je.state.tokens.length-1].isType=!0)}Rt.flowParseVariance=Ep;function OI(e){D.match.call(void 0,F.TokenType.colon)&&Tp(),kt.parseFunctionBody.call(void 0,!1,e)}Rt.flowParseFunctionBodyAndFinish=OI;function LI(e,t,n){if(D.match.call(void 0,F.TokenType.questionDot)&&D.lookaheadType.call(void 0)===F.TokenType.lessThan){if(t){n.stop=!0;return}D.next.call(void 0),No(),Te.expect.call(void 0,F.TokenType.parenL),kt.parseCallExpressionArguments.call(void 0);return}else if(!t&&D.match.call(void 0,F.TokenType.lessThan)){let r=je.state.snapshot();if(No(),Te.expect.call(void 0,F.TokenType.parenL),kt.parseCallExpressionArguments.call(void 0),je.state.error)je.state.restoreFromSnapshot(r);else return}kt.baseParseSubscript.call(void 0,e,t,n)}Rt.flowParseSubscript=LI;function NI(){if(D.match.call(void 0,F.TokenType.lessThan)){let e=je.state.snapshot();No(),je.state.error&&je.state.restoreFromSnapshot(e)}}Rt.flowStartParseNewArguments=NI;function jI(){if(D.match.call(void 0,F.TokenType.name)&&je.state.contextualKeyword===Ge.ContextualKeyword._interface){let e=D.pushTypeContext.call(void 0,0);return D.next.call(void 0),Sp(),D.popTypeContext.call(void 0,e),!0}else if(Te.isContextual.call(void 0,Ge.ContextualKeyword._enum))return ak(),!0;return!1}Rt.flowTryParseStatement=jI;function DI(){return Te.isContextual.call(void 0,Ge.ContextualKeyword._enum)?(ak(),!0):!1}Rt.flowTryParseExportDefaultExpression=DI;function BI(e){if(e===Ge.ContextualKeyword._declare){if(D.match.call(void 0,F.TokenType._class)||D.match.call(void 0,F.TokenType.name)||D.match.call(void 0,F.TokenType._function)||D.match.call(void 0,F.TokenType._var)||D.match.call(void 0,F.TokenType._export)){let t=D.pushTypeContext.call(void 0,1);_p(),D.popTypeContext.call(void 0,t)}}else if(D.match.call(void 0,F.TokenType.name)){if(e===Ge.ContextualKeyword._interface){let t=D.pushTypeContext.call(void 0,1);Sp(),D.popTypeContext.call(void 0,t)}else if(e===Ge.ContextualKeyword._type){let t=D.pushTypeContext.call(void 0,1);$p(),D.popTypeContext.call(void 0,t)}else if(e===Ge.ContextualKeyword._opaque){let t=D.pushTypeContext.call(void 0,1);Rp(!1),D.popTypeContext.call(void 0,t)}}Te.semicolon.call(void 0)}Rt.flowParseIdentifierStatement=BI;function qI(){return Te.isContextual.call(void 0,Ge.ContextualKeyword._type)||Te.isContextual.call(void 0,Ge.ContextualKeyword._interface)||Te.isContextual.call(void 0,Ge.ContextualKeyword._opaque)||Te.isContextual.call(void 0,Ge.ContextualKeyword._enum)}Rt.flowShouldParseExportDeclaration=qI;function UI(){return D.match.call(void 0,F.TokenType.name)&&(je.state.contextualKeyword===Ge.ContextualKeyword._type||je.state.contextualKeyword===Ge.ContextualKeyword._interface||je.state.contextualKeyword===Ge.ContextualKeyword._opaque||je.state.contextualKeyword===Ge.ContextualKeyword._enum)}Rt.flowShouldDisallowExportDefaultSpecifier=UI;function GI(){if(Te.isContextual.call(void 0,Ge.ContextualKeyword._type)){let e=D.pushTypeContext.call(void 0,1);D.next.call(void 0),D.match.call(void 0,F.TokenType.braceL)?(ro.parseExportSpecifiers.call(void 0),ro.parseExportFrom.call(void 0)):$p(),D.popTypeContext.call(void 0,e)}else if(Te.isContextual.call(void 0,Ge.ContextualKeyword._opaque)){let e=D.pushTypeContext.call(void 0,1);D.next.call(void 0),Rp(!1),D.popTypeContext.call(void 0,e)}else if(Te.isContextual.call(void 0,Ge.ContextualKeyword._interface)){let e=D.pushTypeContext.call(void 0,1);D.next.call(void 0),Sp(),D.popTypeContext.call(void 0,e)}else ro.parseStatement.call(void 0,!0)}Rt.flowParseExportDeclaration=GI;function HI(){return D.match.call(void 0,F.TokenType.star)||Te.isContextual.call(void 0,Ge.ContextualKeyword._type)&&D.lookaheadType.call(void 0)===F.TokenType.star}Rt.flowShouldParseExportStar=HI;function zI(){if(Te.eatContextual.call(void 0,Ge.ContextualKeyword._type)){let e=D.pushTypeContext.call(void 0,2);ro.baseParseExportStar.call(void 0),D.popTypeContext.call(void 0,e)}else ro.baseParseExportStar.call(void 0)}Rt.flowParseExportStar=zI;function WI(e){if(e&&D.match.call(void 0,F.TokenType.lessThan)&&No(),Te.isContextual.call(void 0,Ge.ContextualKeyword._implements)){let t=D.pushTypeContext.call(void 0,0);D.next.call(void 0),je.state.tokens[je.state.tokens.length-1].type=F.TokenType._implements;do Gl(),D.match.call(void 0,F.TokenType.lessThan)&&No();while(D.eat.call(void 0,F.TokenType.comma));D.popTypeContext.call(void 0,t)}}Rt.flowAfterParseClassSuper=WI;function KI(){D.match.call(void 0,F.TokenType.lessThan)&&(Sr(),D.match.call(void 0,F.TokenType.parenL)||Te.unexpected.call(void 0))}Rt.flowStartParseObjPropValue=KI;function VI(){let e=D.pushTypeContext.call(void 0,0);D.eat.call(void 0,F.TokenType.question),D.match.call(void 0,F.TokenType.colon)&&Os(),D.popTypeContext.call(void 0,e)}Rt.flowParseAssignableListItemTypes=VI;function JI(){if(D.match.call(void 0,F.TokenType._typeof)||Te.isContextual.call(void 0,Ge.ContextualKeyword._type)){let e=D.lookaheadTypeAndKeyword.call(void 0);(mI(e)||e.type===F.TokenType.braceL||e.type===F.TokenType.star)&&D.next.call(void 0)}}Rt.flowStartParseImportSpecifiers=JI;function XI(){let e=je.state.contextualKeyword===Ge.ContextualKeyword._type||je.state.type===F.TokenType._typeof;e?D.next.call(void 0):kt.parseIdentifier.call(void 0),Te.isContextual.call(void 0,Ge.ContextualKeyword._as)&&!Te.isLookaheadContextual.call(void 0,Ge.ContextualKeyword._as)?(kt.parseIdentifier.call(void 0),e&&!D.match.call(void 0,F.TokenType.name)&&!(je.state.type&F.TokenType.IS_KEYWORD)||kt.parseIdentifier.call(void 0)):(e&&(D.match.call(void 0,F.TokenType.name)||je.state.type&F.TokenType.IS_KEYWORD)&&kt.parseIdentifier.call(void 0),Te.eatContextual.call(void 0,Ge.ContextualKeyword._as)&&kt.parseIdentifier.call(void 0))}Rt.flowParseImportSpecifier=XI;function QI(){if(D.match.call(void 0,F.TokenType.lessThan)){let e=D.pushTypeContext.call(void 0,0);Sr(),D.popTypeContext.call(void 0,e)}}Rt.flowStartParseFunctionParams=QI;function YI(){D.match.call(void 0,F.TokenType.colon)&&Os()}Rt.flowAfterParseVarHead=YI;function ZI(){if(D.match.call(void 0,F.TokenType.colon)){let e=je.state.noAnonFunctionType;je.state.noAnonFunctionType=!0,Os(),je.state.noAnonFunctionType=e}}Rt.flowStartParseAsyncArrowFromCallExpression=ZI;function eP(e,t){if(D.match.call(void 0,F.TokenType.lessThan)){let n=je.state.snapshot(),r=kt.baseParseMaybeAssign.call(void 0,e,t);if(je.state.error)je.state.restoreFromSnapshot(n),je.state.type=F.TokenType.typeParameterStart;else return r;let o=D.pushTypeContext.call(void 0,0);if(Sr(),D.popTypeContext.call(void 0,o),r=kt.baseParseMaybeAssign.call(void 0,e,t),r)return!0;Te.unexpected.call(void 0)}return kt.baseParseMaybeAssign.call(void 0,e,t)}Rt.flowParseMaybeAssign=eP;function tP(){if(D.match.call(void 0,F.TokenType.colon)){let e=D.pushTypeContext.call(void 0,0),t=je.state.snapshot(),n=je.state.noAnonFunctionType;je.state.noAnonFunctionType=!0,Tp(),je.state.noAnonFunctionType=n,Te.canInsertSemicolon.call(void 0)&&Te.unexpected.call(void 0),D.match.call(void 0,F.TokenType.arrow)||Te.unexpected.call(void 0),je.state.error&&je.state.restoreFromSnapshot(t),D.popTypeContext.call(void 0,e)}return D.eat.call(void 0,F.TokenType.arrow)}Rt.flowParseArrow=tP;function nP(e,t=!1){if(je.state.tokens[je.state.tokens.length-1].contextualKeyword===Ge.ContextualKeyword._async&&D.match.call(void 0,F.TokenType.lessThan)){let n=je.state.snapshot();if(rP()&&!je.state.error)return;je.state.restoreFromSnapshot(n)}kt.baseParseSubscripts.call(void 0,e,t)}Rt.flowParseSubscripts=nP;function rP(){je.state.scopeDepth++;let e=je.state.tokens.length;return ro.parseFunctionParams.call(void 0),kt.parseArrow.call(void 0)?(kt.parseArrowExpression.call(void 0,e),!0):!1}function ak(){Te.expectContextual.call(void 0,Ge.ContextualKeyword._enum),je.state.tokens[je.state.tokens.length-1].type=F.TokenType._enum,kt.parseIdentifier.call(void 0),oP()}function oP(){Te.eatContextual.call(void 0,Ge.ContextualKeyword._of)&&D.next.call(void 0),Te.expect.call(void 0,F.TokenType.braceL),sP(),Te.expect.call(void 0,F.TokenType.braceR)}function sP(){for(;!D.match.call(void 0,F.TokenType.braceR)&&!je.state.error&&!D.eat.call(void 0,F.TokenType.ellipsis);)iP(),D.match.call(void 0,F.TokenType.braceR)||Te.expect.call(void 0,F.TokenType.comma)}function iP(){kt.parseIdentifier.call(void 0),D.eat.call(void 0,F.TokenType.eq)&&D.next.call(void 0)}});var Gi=Ie(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});var aP=Lp(),fn=ji(),Vt=Cs(),ce=en(),ze=rn(),oo=ul(),Y=et(),lk=Nn(),K=jn(),dt=Lo(),so=$l(),Ce=Xr();function lP(){if(Fp(Y.TokenType.eof),K.state.scopes.push(new oo.Scope(0,K.state.tokens.length,!0)),K.state.scopeDepth!==0)throw new Error(`Invalid scope depth at end of file: ${K.state.scopeDepth}`);return new aP.File(K.state.tokens,K.state.scopes)}Jt.parseTopLevel=lP;function cr(e){K.isFlowEnabled&&fn.flowTryParseStatement.call(void 0)||(ce.match.call(void 0,Y.TokenType.at)&&Pp(),cP(e))}Jt.parseStatement=cr;function cP(e){if(K.isTypeScriptEnabled&&Vt.tsTryParseStatementContent.call(void 0))return;let t=K.state.type;switch(t){case Y.TokenType._break:case Y.TokenType._continue:dP();return;case Y.TokenType._debugger:pP();return;case Y.TokenType._do:mP();return;case Y.TokenType._for:fP();return;case Y.TokenType._function:if(ce.lookaheadType.call(void 0)===Y.TokenType.dot)break;e||Ce.unexpected.call(void 0),bP();return;case Y.TokenType._class:e||Ce.unexpected.call(void 0),zl(!0);return;case Y.TokenType._if:yP();return;case Y.TokenType._return:wP();return;case Y.TokenType._switch:kP();return;case Y.TokenType._throw:_P();return;case Y.TokenType._try:TP();return;case Y.TokenType._let:case Y.TokenType._const:e||Ce.unexpected.call(void 0);case Y.TokenType._var:Hl(t!==Y.TokenType._var);return;case Y.TokenType._while:xP();return;case Y.TokenType.braceL:Ns();return;case Y.TokenType.semi:SP();return;case Y.TokenType._export:case Y.TokenType._import:{let o=ce.lookaheadType.call(void 0);if(o===Y.TokenType.parenL||o===Y.TokenType.dot)break;ce.next.call(void 0),t===Y.TokenType._import?_k():yk();return}case Y.TokenType.name:if(K.state.contextualKeyword===ze.ContextualKeyword._async){let o=K.state.start,s=K.state.snapshot();if(ce.next.call(void 0),ce.match.call(void 0,Y.TokenType._function)&&!Ce.canInsertSemicolon.call(void 0)){Ce.expect.call(void 0,Y.TokenType._function),Ji(o,!0);return}else K.state.restoreFromSnapshot(s)}else if(K.state.contextualKeyword===ze.ContextualKeyword._using&&!Ce.hasFollowingLineBreak.call(void 0)&&ce.lookaheadType.call(void 0)===Y.TokenType.name){Hl(!0);return}else if(dk()){Ce.expectContextual.call(void 0,ze.ContextualKeyword._await),Hl(!0);return}default:break}let n=K.state.tokens.length;dt.parseExpression.call(void 0);let r=null;if(K.state.tokens.length===n+1){let o=K.state.tokens[K.state.tokens.length-1];o.type===Y.TokenType.name&&(r=o.contextualKeyword)}if(r==null){Ce.semicolon.call(void 0);return}ce.eat.call(void 0,Y.TokenType.colon)?$P():RP(r)}function dk(){if(!Ce.isContextual.call(void 0,ze.ContextualKeyword._await))return!1;let e=K.state.snapshot();return ce.next.call(void 0),!Ce.isContextual.call(void 0,ze.ContextualKeyword._using)||Ce.hasPrecedingLineBreak.call(void 0)||(ce.next.call(void 0),!ce.match.call(void 0,Y.TokenType.name)||Ce.hasPrecedingLineBreak.call(void 0))?(K.state.restoreFromSnapshot(e),!1):(K.state.restoreFromSnapshot(e),!0)}function Pp(){for(;ce.match.call(void 0,Y.TokenType.at);)pk()}Jt.parseDecorators=Pp;function pk(){if(ce.next.call(void 0),ce.eat.call(void 0,Y.TokenType.parenL))dt.parseExpression.call(void 0),Ce.expect.call(void 0,Y.TokenType.parenR);else{for(dt.parseIdentifier.call(void 0);ce.eat.call(void 0,Y.TokenType.dot);)dt.parseIdentifier.call(void 0);uP()}}function uP(){K.isTypeScriptEnabled?Vt.tsParseMaybeDecoratorArguments.call(void 0):mk()}function mk(){ce.eat.call(void 0,Y.TokenType.parenL)&&dt.parseCallExpressionArguments.call(void 0)}Jt.baseParseMaybeDecoratorArguments=mk;function dP(){ce.next.call(void 0),Ce.isLineTerminator.call(void 0)||(dt.parseIdentifier.call(void 0),Ce.semicolon.call(void 0))}function pP(){ce.next.call(void 0),Ce.semicolon.call(void 0)}function mP(){ce.next.call(void 0),cr(!1),Ce.expect.call(void 0,Y.TokenType._while),dt.parseParenExpression.call(void 0),ce.eat.call(void 0,Y.TokenType.semi)}function fP(){K.state.scopeDepth++;let e=K.state.tokens.length;gP();let t=K.state.tokens.length;K.state.scopes.push(new oo.Scope(e,t,!1)),K.state.scopeDepth--}function hP(){return!(!Ce.isContextual.call(void 0,ze.ContextualKeyword._using)||Ce.isLookaheadContextual.call(void 0,ze.ContextualKeyword._of))}function gP(){ce.next.call(void 0);let e=!1;if(Ce.isContextual.call(void 0,ze.ContextualKeyword._await)&&(e=!0,ce.next.call(void 0)),Ce.expect.call(void 0,Y.TokenType.parenL),ce.match.call(void 0,Y.TokenType.semi)){e&&Ce.unexpected.call(void 0),Mp();return}let t=dk();if(t||ce.match.call(void 0,Y.TokenType._var)||ce.match.call(void 0,Y.TokenType._let)||ce.match.call(void 0,Y.TokenType._const)||hP()){if(t&&Ce.expectContextual.call(void 0,ze.ContextualKeyword._await),ce.next.call(void 0),fk(!0,K.state.type!==Y.TokenType._var),ce.match.call(void 0,Y.TokenType._in)||Ce.isContextual.call(void 0,ze.ContextualKeyword._of)){ck(e);return}Mp();return}if(dt.parseExpression.call(void 0,!0),ce.match.call(void 0,Y.TokenType._in)||Ce.isContextual.call(void 0,ze.ContextualKeyword._of)){ck(e);return}e&&Ce.unexpected.call(void 0),Mp()}function bP(){let e=K.state.start;ce.next.call(void 0),Ji(e,!0)}function yP(){ce.next.call(void 0),dt.parseParenExpression.call(void 0),cr(!1),ce.eat.call(void 0,Y.TokenType._else)&&cr(!1)}function wP(){ce.next.call(void 0),Ce.isLineTerminator.call(void 0)||(dt.parseExpression.call(void 0),Ce.semicolon.call(void 0))}function kP(){ce.next.call(void 0),dt.parseParenExpression.call(void 0),K.state.scopeDepth++;let e=K.state.tokens.length;for(Ce.expect.call(void 0,Y.TokenType.braceL);!ce.match.call(void 0,Y.TokenType.braceR)&&!K.state.error;)if(ce.match.call(void 0,Y.TokenType._case)||ce.match.call(void 0,Y.TokenType._default)){let n=ce.match.call(void 0,Y.TokenType._case);ce.next.call(void 0),n&&dt.parseExpression.call(void 0),Ce.expect.call(void 0,Y.TokenType.colon)}else cr(!0);ce.next.call(void 0);let t=K.state.tokens.length;K.state.scopes.push(new oo.Scope(e,t,!1)),K.state.scopeDepth--}function _P(){ce.next.call(void 0),dt.parseExpression.call(void 0),Ce.semicolon.call(void 0)}function vP(){so.parseBindingAtom.call(void 0,!0),K.isTypeScriptEnabled&&Vt.tsTryParseTypeAnnotation.call(void 0)}function TP(){if(ce.next.call(void 0),Ns(),ce.match.call(void 0,Y.TokenType._catch)){ce.next.call(void 0);let e=null;if(ce.match.call(void 0,Y.TokenType.parenL)&&(K.state.scopeDepth++,e=K.state.tokens.length,Ce.expect.call(void 0,Y.TokenType.parenL),vP(),Ce.expect.call(void 0,Y.TokenType.parenR)),Ns(),e!=null){let t=K.state.tokens.length;K.state.scopes.push(new oo.Scope(e,t,!1)),K.state.scopeDepth--}}ce.eat.call(void 0,Y.TokenType._finally)&&Ns()}function Hl(e){ce.next.call(void 0),fk(!1,e),Ce.semicolon.call(void 0)}Jt.parseVarStatement=Hl;function xP(){ce.next.call(void 0),dt.parseParenExpression.call(void 0),cr(!1)}function SP(){ce.next.call(void 0)}function $P(){cr(!0)}function RP(e){K.isTypeScriptEnabled?Vt.tsParseIdentifierStatement.call(void 0,e):K.isFlowEnabled?fn.flowParseIdentifierStatement.call(void 0,e):Ce.semicolon.call(void 0)}function Ns(e=!1,t=0){let n=K.state.tokens.length;K.state.scopeDepth++,Ce.expect.call(void 0,Y.TokenType.braceL),t&&(K.state.tokens[K.state.tokens.length-1].contextId=t),Fp(Y.TokenType.braceR),t&&(K.state.tokens[K.state.tokens.length-1].contextId=t);let r=K.state.tokens.length;K.state.scopes.push(new oo.Scope(n,r,e)),K.state.scopeDepth--}Jt.parseBlock=Ns;function Fp(e){for(;!ce.eat.call(void 0,e)&&!K.state.error;)cr(!0)}Jt.parseBlockBody=Fp;function Mp(){Ce.expect.call(void 0,Y.TokenType.semi),ce.match.call(void 0,Y.TokenType.semi)||dt.parseExpression.call(void 0),Ce.expect.call(void 0,Y.TokenType.semi),ce.match.call(void 0,Y.TokenType.parenR)||dt.parseExpression.call(void 0),Ce.expect.call(void 0,Y.TokenType.parenR),cr(!1)}function ck(e){e?Ce.eatContextual.call(void 0,ze.ContextualKeyword._of):ce.next.call(void 0),dt.parseExpression.call(void 0),Ce.expect.call(void 0,Y.TokenType.parenR),cr(!1)}function fk(e,t){for(;;){if(CP(t),ce.eat.call(void 0,Y.TokenType.eq)){let n=K.state.tokens.length-1;dt.parseMaybeAssign.call(void 0,e),K.state.tokens[n].rhsEndIndex=K.state.tokens.length}if(!ce.eat.call(void 0,Y.TokenType.comma))break}}function CP(e){so.parseBindingAtom.call(void 0,e),K.isTypeScriptEnabled?Vt.tsAfterParseVarHead.call(void 0):K.isFlowEnabled&&fn.flowAfterParseVarHead.call(void 0)}function Ji(e,t,n=!1){ce.match.call(void 0,Y.TokenType.star)&&ce.next.call(void 0),t&&!n&&!ce.match.call(void 0,Y.TokenType.name)&&!ce.match.call(void 0,Y.TokenType._yield)&&Ce.unexpected.call(void 0);let r=null;ce.match.call(void 0,Y.TokenType.name)&&(t||(r=K.state.tokens.length,K.state.scopeDepth++),so.parseBindingIdentifier.call(void 0,!1));let o=K.state.tokens.length;K.state.scopeDepth++,hk(),dt.parseFunctionBodyAndFinish.call(void 0,e);let s=K.state.tokens.length;K.state.scopes.push(new oo.Scope(o,s,!0)),K.state.scopeDepth--,r!==null&&(K.state.scopes.push(new oo.Scope(r,s,!0)),K.state.scopeDepth--)}Jt.parseFunction=Ji;function hk(e=!1,t=0){K.isTypeScriptEnabled?Vt.tsStartParseFunctionParams.call(void 0):K.isFlowEnabled&&fn.flowStartParseFunctionParams.call(void 0),Ce.expect.call(void 0,Y.TokenType.parenL),t&&(K.state.tokens[K.state.tokens.length-1].contextId=t),so.parseBindingList.call(void 0,Y.TokenType.parenR,!1,!1,e,t),t&&(K.state.tokens[K.state.tokens.length-1].contextId=t)}Jt.parseFunctionParams=hk;function zl(e,t=!1){let n=K.getNextContextId.call(void 0);ce.next.call(void 0),K.state.tokens[K.state.tokens.length-1].contextId=n,K.state.tokens[K.state.tokens.length-1].isExpression=!e;let r=null;e||(r=K.state.tokens.length,K.state.scopeDepth++),IP(e,t),PP();let o=K.state.tokens.length;if(AP(n),!K.state.error&&(K.state.tokens[o].contextId=n,K.state.tokens[K.state.tokens.length-1].contextId=n,r!==null)){let s=K.state.tokens.length;K.state.scopes.push(new oo.Scope(r,s,!1)),K.state.scopeDepth--}}Jt.parseClass=zl;function gk(){return ce.match.call(void 0,Y.TokenType.eq)||ce.match.call(void 0,Y.TokenType.semi)||ce.match.call(void 0,Y.TokenType.braceR)||ce.match.call(void 0,Y.TokenType.bang)||ce.match.call(void 0,Y.TokenType.colon)}function bk(){return ce.match.call(void 0,Y.TokenType.parenL)||ce.match.call(void 0,Y.TokenType.lessThan)}function AP(e){for(Ce.expect.call(void 0,Y.TokenType.braceL);!ce.eat.call(void 0,Y.TokenType.braceR)&&!K.state.error;){if(ce.eat.call(void 0,Y.TokenType.semi))continue;if(ce.match.call(void 0,Y.TokenType.at)){pk();continue}let t=K.state.start;EP(t,e)}}function EP(e,t){K.isTypeScriptEnabled&&Vt.tsParseModifiers.call(void 0,[ze.ContextualKeyword._declare,ze.ContextualKeyword._public,ze.ContextualKeyword._protected,ze.ContextualKeyword._private,ze.ContextualKeyword._override]);let n=!1;if(ce.match.call(void 0,Y.TokenType.name)&&K.state.contextualKeyword===ze.ContextualKeyword._static){if(dt.parseIdentifier.call(void 0),bk()){Ki(e,!1);return}else if(gk()){Vi();return}if(K.state.tokens[K.state.tokens.length-1].type=Y.TokenType._static,n=!0,ce.match.call(void 0,Y.TokenType.braceL)){K.state.tokens[K.state.tokens.length-1].contextId=t,Ns();return}}MP(e,n,t)}function MP(e,t,n){if(K.isTypeScriptEnabled&&Vt.tsTryParseClassMemberWithIsStatic.call(void 0,t))return;if(ce.eat.call(void 0,Y.TokenType.star)){Ls(n),Ki(e,!1);return}Ls(n);let r=!1,o=K.state.tokens[K.state.tokens.length-1];o.contextualKeyword===ze.ContextualKeyword._constructor&&(r=!0),Ip(),bk()?Ki(e,r):gk()?Vi():o.contextualKeyword===ze.ContextualKeyword._async&&!Ce.isLineTerminator.call(void 0)?(K.state.tokens[K.state.tokens.length-1].type=Y.TokenType._async,ce.match.call(void 0,Y.TokenType.star)&&ce.next.call(void 0),Ls(n),Ip(),Ki(e,!1)):(o.contextualKeyword===ze.ContextualKeyword._get||o.contextualKeyword===ze.ContextualKeyword._set)&&!(Ce.isLineTerminator.call(void 0)&&ce.match.call(void 0,Y.TokenType.star))?(o.contextualKeyword===ze.ContextualKeyword._get?K.state.tokens[K.state.tokens.length-1].type=Y.TokenType._get:K.state.tokens[K.state.tokens.length-1].type=Y.TokenType._set,Ls(n),Ki(e,!1)):o.contextualKeyword===ze.ContextualKeyword._accessor&&!Ce.isLineTerminator.call(void 0)?(Ls(n),Vi()):Ce.isLineTerminator.call(void 0)?Vi():Ce.unexpected.call(void 0)}function Ki(e,t){K.isTypeScriptEnabled?Vt.tsTryParseTypeParameters.call(void 0):K.isFlowEnabled&&ce.match.call(void 0,Y.TokenType.lessThan)&&fn.flowParseTypeParameterDeclaration.call(void 0),dt.parseMethod.call(void 0,e,t)}function Ls(e){dt.parsePropertyName.call(void 0,e)}Jt.parseClassPropertyName=Ls;function Ip(){if(K.isTypeScriptEnabled){let e=ce.pushTypeContext.call(void 0,0);ce.eat.call(void 0,Y.TokenType.question),ce.popTypeContext.call(void 0,e)}}Jt.parsePostMemberNameModifiers=Ip;function Vi(){if(K.isTypeScriptEnabled?(ce.eatTypeToken.call(void 0,Y.TokenType.bang),Vt.tsTryParseTypeAnnotation.call(void 0)):K.isFlowEnabled&&ce.match.call(void 0,Y.TokenType.colon)&&fn.flowParseTypeAnnotation.call(void 0),ce.match.call(void 0,Y.TokenType.eq)){let e=K.state.tokens.length;ce.next.call(void 0),dt.parseMaybeAssign.call(void 0),K.state.tokens[e].rhsEndIndex=K.state.tokens.length}Ce.semicolon.call(void 0)}Jt.parseClassProperty=Vi;function IP(e,t=!1){K.isTypeScriptEnabled&&(!e||t)&&Ce.isContextual.call(void 0,ze.ContextualKeyword._implements)||(ce.match.call(void 0,Y.TokenType.name)&&so.parseBindingIdentifier.call(void 0,!0),K.isTypeScriptEnabled?Vt.tsTryParseTypeParameters.call(void 0):K.isFlowEnabled&&ce.match.call(void 0,Y.TokenType.lessThan)&&fn.flowParseTypeParameterDeclaration.call(void 0))}function PP(){let e=!1;ce.eat.call(void 0,Y.TokenType._extends)?(dt.parseExprSubscripts.call(void 0),e=!0):e=!1,K.isTypeScriptEnabled?Vt.tsAfterParseClassSuper.call(void 0,e):K.isFlowEnabled&&fn.flowAfterParseClassSuper.call(void 0,e)}function yk(){let e=K.state.tokens.length-1;K.isTypeScriptEnabled&&Vt.tsTryParseExport.call(void 0)||(NP()?jP():LP()?(dt.parseIdentifier.call(void 0),ce.match.call(void 0,Y.TokenType.comma)&&ce.lookaheadType.call(void 0)===Y.TokenType.star?(Ce.expect.call(void 0,Y.TokenType.comma),Ce.expect.call(void 0,Y.TokenType.star),Ce.expectContextual.call(void 0,ze.ContextualKeyword._as),dt.parseIdentifier.call(void 0)):wk(),Xi()):ce.eat.call(void 0,Y.TokenType._default)?FP():BP()?OP():(Op(),Xi()),K.state.tokens[e].rhsEndIndex=K.state.tokens.length)}Jt.parseExport=yk;function FP(){if(K.isTypeScriptEnabled&&Vt.tsTryParseExportDefaultExpression.call(void 0)||K.isFlowEnabled&&fn.flowTryParseExportDefaultExpression.call(void 0))return;let e=K.state.start;ce.eat.call(void 0,Y.TokenType._function)?Ji(e,!0,!0):Ce.isContextual.call(void 0,ze.ContextualKeyword._async)&&ce.lookaheadType.call(void 0)===Y.TokenType._function?(Ce.eatContextual.call(void 0,ze.ContextualKeyword._async),ce.eat.call(void 0,Y.TokenType._function),Ji(e,!0,!0)):ce.match.call(void 0,Y.TokenType._class)?zl(!0,!0):ce.match.call(void 0,Y.TokenType.at)?(Pp(),zl(!0,!0)):(dt.parseMaybeAssign.call(void 0),Ce.semicolon.call(void 0))}function OP(){K.isTypeScriptEnabled?Vt.tsParseExportDeclaration.call(void 0):K.isFlowEnabled?fn.flowParseExportDeclaration.call(void 0):cr(!0)}function LP(){if(K.isTypeScriptEnabled&&Vt.tsIsDeclarationStart.call(void 0))return!1;if(K.isFlowEnabled&&fn.flowShouldDisallowExportDefaultSpecifier.call(void 0))return!1;if(ce.match.call(void 0,Y.TokenType.name))return K.state.contextualKeyword!==ze.ContextualKeyword._async;if(!ce.match.call(void 0,Y.TokenType._default))return!1;let e=ce.nextTokenStart.call(void 0),t=ce.lookaheadTypeAndKeyword.call(void 0),n=t.type===Y.TokenType.name&&t.contextualKeyword===ze.ContextualKeyword._from;if(t.type===Y.TokenType.comma)return!0;if(n){let r=K.input.charCodeAt(ce.nextTokenStartSince.call(void 0,e+4));return r===lk.charCodes.quotationMark||r===lk.charCodes.apostrophe}return!1}function wk(){ce.eat.call(void 0,Y.TokenType.comma)&&Op()}function Xi(){Ce.eatContextual.call(void 0,ze.ContextualKeyword._from)&&(dt.parseExprAtom.call(void 0),vk()),Ce.semicolon.call(void 0)}Jt.parseExportFrom=Xi;function NP(){return K.isFlowEnabled?fn.flowShouldParseExportStar.call(void 0):ce.match.call(void 0,Y.TokenType.star)}function jP(){K.isFlowEnabled?fn.flowParseExportStar.call(void 0):kk()}function kk(){Ce.expect.call(void 0,Y.TokenType.star),Ce.isContextual.call(void 0,ze.ContextualKeyword._as)?DP():Xi()}Jt.baseParseExportStar=kk;function DP(){ce.next.call(void 0),K.state.tokens[K.state.tokens.length-1].type=Y.TokenType._as,dt.parseIdentifier.call(void 0),wk(),Xi()}function BP(){return K.isTypeScriptEnabled&&Vt.tsIsDeclarationStart.call(void 0)||K.isFlowEnabled&&fn.flowShouldParseExportDeclaration.call(void 0)||K.state.type===Y.TokenType._var||K.state.type===Y.TokenType._const||K.state.type===Y.TokenType._let||K.state.type===Y.TokenType._function||K.state.type===Y.TokenType._class||Ce.isContextual.call(void 0,ze.ContextualKeyword._async)||ce.match.call(void 0,Y.TokenType.at)}function Op(){let e=!0;for(Ce.expect.call(void 0,Y.TokenType.braceL);!ce.eat.call(void 0,Y.TokenType.braceR)&&!K.state.error;){if(e)e=!1;else if(Ce.expect.call(void 0,Y.TokenType.comma),ce.eat.call(void 0,Y.TokenType.braceR))break;qP()}}Jt.parseExportSpecifiers=Op;function qP(){if(K.isTypeScriptEnabled){Vt.tsParseExportSpecifier.call(void 0);return}dt.parseIdentifier.call(void 0),K.state.tokens[K.state.tokens.length-1].identifierRole=ce.IdentifierRole.ExportAccess,Ce.eatContextual.call(void 0,ze.ContextualKeyword._as)&&dt.parseIdentifier.call(void 0)}function UP(){let e=K.state.snapshot();return Ce.expectContextual.call(void 0,ze.ContextualKeyword._module),Ce.eatContextual.call(void 0,ze.ContextualKeyword._from)?Ce.isContextual.call(void 0,ze.ContextualKeyword._from)?(K.state.restoreFromSnapshot(e),!0):(K.state.restoreFromSnapshot(e),!1):ce.match.call(void 0,Y.TokenType.comma)?(K.state.restoreFromSnapshot(e),!1):(K.state.restoreFromSnapshot(e),!0)}function GP(){Ce.isContextual.call(void 0,ze.ContextualKeyword._module)&&UP()&&ce.next.call(void 0)}function _k(){if(K.isTypeScriptEnabled&&ce.match.call(void 0,Y.TokenType.name)&&ce.lookaheadType.call(void 0)===Y.TokenType.eq){Vt.tsParseImportEqualsDeclaration.call(void 0);return}if(K.isTypeScriptEnabled&&Ce.isContextual.call(void 0,ze.ContextualKeyword._type)){let e=ce.lookaheadTypeAndKeyword.call(void 0);if(e.type===Y.TokenType.name&&e.contextualKeyword!==ze.ContextualKeyword._from){if(Ce.expectContextual.call(void 0,ze.ContextualKeyword._type),ce.lookaheadType.call(void 0)===Y.TokenType.eq){Vt.tsParseImportEqualsDeclaration.call(void 0);return}}else(e.type===Y.TokenType.star||e.type===Y.TokenType.braceL)&&Ce.expectContextual.call(void 0,ze.ContextualKeyword._type)}ce.match.call(void 0,Y.TokenType.string)||(GP(),zP(),Ce.expectContextual.call(void 0,ze.ContextualKeyword._from)),dt.parseExprAtom.call(void 0),vk(),Ce.semicolon.call(void 0)}Jt.parseImport=_k;function HP(){return ce.match.call(void 0,Y.TokenType.name)}function uk(){so.parseImportedIdentifier.call(void 0)}function zP(){K.isFlowEnabled&&fn.flowStartParseImportSpecifiers.call(void 0);let e=!0;if(!(HP()&&(uk(),!ce.eat.call(void 0,Y.TokenType.comma)))){if(ce.match.call(void 0,Y.TokenType.star)){ce.next.call(void 0),Ce.expectContextual.call(void 0,ze.ContextualKeyword._as),uk();return}for(Ce.expect.call(void 0,Y.TokenType.braceL);!ce.eat.call(void 0,Y.TokenType.braceR)&&!K.state.error;){if(e)e=!1;else if(ce.eat.call(void 0,Y.TokenType.colon)&&Ce.unexpected.call(void 0,"ES2015 named imports do not destructure. Use another statement for destructuring after the import."),Ce.expect.call(void 0,Y.TokenType.comma),ce.eat.call(void 0,Y.TokenType.braceR))break;WP()}}}function WP(){if(K.isTypeScriptEnabled){Vt.tsParseImportSpecifier.call(void 0);return}if(K.isFlowEnabled){fn.flowParseImportSpecifier.call(void 0);return}so.parseImportedIdentifier.call(void 0),Ce.isContextual.call(void 0,ze.ContextualKeyword._as)&&(K.state.tokens[K.state.tokens.length-1].identifierRole=ce.IdentifierRole.ImportAccess,ce.next.call(void 0),so.parseImportedIdentifier.call(void 0))}function vk(){(ce.match.call(void 0,Y.TokenType._with)||Ce.isContextual.call(void 0,ze.ContextualKeyword._assert)&&!Ce.hasPrecedingLineBreak.call(void 0))&&(ce.next.call(void 0),dt.parseObj.call(void 0,!1,!1))}});var Sk=Ie(jp=>{"use strict";Object.defineProperty(jp,"__esModule",{value:!0});var Tk=en(),xk=Nn(),Np=jn(),KP=Gi();function VP(){return Np.state.pos===0&&Np.input.charCodeAt(0)===xk.charCodes.numberSign&&Np.input.charCodeAt(1)===xk.charCodes.exclamationMark&&Tk.skipLineComment.call(void 0,2),Tk.nextToken.call(void 0),KP.parseTopLevel.call(void 0)}jp.parseFile=VP});var Lp=Ie(Kl=>{"use strict";Object.defineProperty(Kl,"__esModule",{value:!0});var Wl=jn(),JP=Sk(),Dp=class{constructor(t,n){this.tokens=t,this.scopes=n}};Kl.File=Dp;function XP(e,t,n,r){if(r&&n)throw new Error("Cannot combine flow and typescript plugins.");Wl.initParser.call(void 0,e,t,n,r);let o=JP.parseFile.call(void 0);if(Wl.state.error)throw Wl.augmentError.call(void 0,Wl.state.error);return o}Kl.parse=XP});var $k=Ie(Bp=>{"use strict";Object.defineProperty(Bp,"__esModule",{value:!0});var QP=rn();function YP(e){let t=e.currentIndex(),n=0,r=e.currentToken();do{let o=e.tokens[t];if(o.isOptionalChainStart&&n++,o.isOptionalChainEnd&&n--,n+=o.numNullishCoalesceStarts,n-=o.numNullishCoalesceEnds,o.contextualKeyword===QP.ContextualKeyword._await&&o.identifierRole==null&&o.scopeDepth===r.scopeDepth)return!0;t+=1}while(n>0&&t<e.tokens.length);return!1}Bp.default=YP});var Rk=Ie(Up=>{"use strict";Object.defineProperty(Up,"__esModule",{value:!0});function ZP(e){return e&&e.__esModule?e:{default:e}}var Vl=et(),e2=$k(),t2=ZP(e2),qp=class e{__init(){this.resultCode=""}__init2(){this.resultMappings=new Array(this.tokens.length)}__init3(){this.tokenIndex=0}constructor(t,n,r,o,s){this.code=t,this.tokens=n,this.isFlowEnabled=r,this.disableESTransforms=o,this.helperManager=s,e.prototype.__init.call(this),e.prototype.__init2.call(this),e.prototype.__init3.call(this)}snapshot(){return{resultCode:this.resultCode,tokenIndex:this.tokenIndex}}restoreToSnapshot(t){this.resultCode=t.resultCode,this.tokenIndex=t.tokenIndex}dangerouslyGetAndRemoveCodeSinceSnapshot(t){let n=this.resultCode.slice(t.resultCode.length);return this.resultCode=t.resultCode,n}reset(){this.resultCode="",this.resultMappings=new Array(this.tokens.length),this.tokenIndex=0}matchesContextualAtIndex(t,n){return this.matches1AtIndex(t,Vl.TokenType.name)&&this.tokens[t].contextualKeyword===n}identifierNameAtIndex(t){return this.identifierNameForToken(this.tokens[t])}identifierNameAtRelativeIndex(t){return this.identifierNameForToken(this.tokenAtRelativeIndex(t))}identifierName(){return this.identifierNameForToken(this.currentToken())}identifierNameForToken(t){return this.code.slice(t.start,t.end)}rawCodeForToken(t){return this.code.slice(t.start,t.end)}stringValueAtIndex(t){return this.stringValueForToken(this.tokens[t])}stringValue(){return this.stringValueForToken(this.currentToken())}stringValueForToken(t){return this.code.slice(t.start+1,t.end-1)}matches1AtIndex(t,n){return this.tokens[t].type===n}matches2AtIndex(t,n,r){return this.tokens[t].type===n&&this.tokens[t+1].type===r}matches3AtIndex(t,n,r,o){return this.tokens[t].type===n&&this.tokens[t+1].type===r&&this.tokens[t+2].type===o}matches1(t){return this.tokens[this.tokenIndex].type===t}matches2(t,n){return this.tokens[this.tokenIndex].type===t&&this.tokens[this.tokenIndex+1].type===n}matches3(t,n,r){return this.tokens[this.tokenIndex].type===t&&this.tokens[this.tokenIndex+1].type===n&&this.tokens[this.tokenIndex+2].type===r}matches4(t,n,r,o){return this.tokens[this.tokenIndex].type===t&&this.tokens[this.tokenIndex+1].type===n&&this.tokens[this.tokenIndex+2].type===r&&this.tokens[this.tokenIndex+3].type===o}matches5(t,n,r,o,s){return this.tokens[this.tokenIndex].type===t&&this.tokens[this.tokenIndex+1].type===n&&this.tokens[this.tokenIndex+2].type===r&&this.tokens[this.tokenIndex+3].type===o&&this.tokens[this.tokenIndex+4].type===s}matchesContextual(t){return this.matchesContextualAtIndex(this.tokenIndex,t)}matchesContextIdAndLabel(t,n){return this.matches1(t)&&this.currentToken().contextId===n}previousWhitespaceAndComments(){let t=this.code.slice(this.tokenIndex>0?this.tokens[this.tokenIndex-1].end:0,this.tokenIndex<this.tokens.length?this.tokens[this.tokenIndex].start:this.code.length);return this.isFlowEnabled&&(t=t.replace(/@flow/g,"")),t}replaceToken(t){this.resultCode+=this.previousWhitespaceAndComments(),this.appendTokenPrefix(),this.resultMappings[this.tokenIndex]=this.resultCode.length,this.resultCode+=t,this.appendTokenSuffix(),this.tokenIndex++}replaceTokenTrimmingLeftWhitespace(t){this.resultCode+=this.previousWhitespaceAndComments().replace(/[^\r\n]/g,""),this.appendTokenPrefix(),this.resultMappings[this.tokenIndex]=this.resultCode.length,this.resultCode+=t,this.appendTokenSuffix(),this.tokenIndex++}removeInitialToken(){this.replaceToken("")}removeToken(){this.replaceTokenTrimmingLeftWhitespace("")}removeBalancedCode(){let t=0;for(;!this.isAtEnd();){if(this.matches1(Vl.TokenType.braceL))t++;else if(this.matches1(Vl.TokenType.braceR)){if(t===0)return;t--}this.removeToken()}}copyExpectedToken(t){if(this.tokens[this.tokenIndex].type!==t)throw new Error(`Expected token ${t}`);this.copyToken()}copyToken(){this.resultCode+=this.previousWhitespaceAndComments(),this.appendTokenPrefix(),this.resultMappings[this.tokenIndex]=this.resultCode.length,this.resultCode+=this.code.slice(this.tokens[this.tokenIndex].start,this.tokens[this.tokenIndex].end),this.appendTokenSuffix(),this.tokenIndex++}copyTokenWithPrefix(t){this.resultCode+=this.previousWhitespaceAndComments(),this.appendTokenPrefix(),this.resultCode+=t,this.resultMappings[this.tokenIndex]=this.resultCode.length,this.resultCode+=this.code.slice(this.tokens[this.tokenIndex].start,this.tokens[this.tokenIndex].end),this.appendTokenSuffix(),this.tokenIndex++}appendTokenPrefix(){let t=this.currentToken();if((t.numNullishCoalesceStarts||t.isOptionalChainStart)&&(t.isAsyncOperation=t2.default.call(void 0,this)),!this.disableESTransforms){if(t.numNullishCoalesceStarts)for(let n=0;n<t.numNullishCoalesceStarts;n++)t.isAsyncOperation?(this.resultCode+="await ",this.resultCode+=this.helperManager.getHelperName("asyncNullishCoalesce")):this.resultCode+=this.helperManager.getHelperName("nullishCoalesce"),this.resultCode+="(";t.isOptionalChainStart&&(t.isAsyncOperation&&(this.resultCode+="await "),this.tokenIndex>0&&this.tokenAtRelativeIndex(-1).type===Vl.TokenType._delete?t.isAsyncOperation?this.resultCode+=this.helperManager.getHelperName("asyncOptionalChainDelete"):this.resultCode+=this.helperManager.getHelperName("optionalChainDelete"):t.isAsyncOperation?this.resultCode+=this.helperManager.getHelperName("asyncOptionalChain"):this.resultCode+=this.helperManager.getHelperName("optionalChain"),this.resultCode+="([")}}appendTokenSuffix(){let t=this.currentToken();if(t.isOptionalChainEnd&&!this.disableESTransforms&&(this.resultCode+="])"),t.numNullishCoalesceEnds&&!this.disableESTransforms)for(let n=0;n<t.numNullishCoalesceEnds;n++)this.resultCode+="))"}appendCode(t){this.resultCode+=t}currentToken(){return this.tokens[this.tokenIndex]}currentTokenCode(){let t=this.currentToken();return this.code.slice(t.start,t.end)}tokenAtRelativeIndex(t){return this.tokens[this.tokenIndex+t]}currentIndex(){return this.tokenIndex}nextToken(){if(this.tokenIndex===this.tokens.length)throw new Error("Unexpectedly reached end of input.");this.tokenIndex++}previousToken(){this.tokenIndex--}finish(){if(this.tokenIndex!==this.tokens.length)throw new Error("Tried to finish processing tokens before reaching the end.");return this.resultCode+=this.previousWhitespaceAndComments(),{code:this.resultCode,mappings:this.resultMappings}}isAtEnd(){return this.tokenIndex===this.tokens.length}};Up.default=qp});var Ek=Ie(Hp=>{"use strict";Object.defineProperty(Hp,"__esModule",{value:!0});var Ck=rn(),at=et();function n2(e,t,n,r){let o=t.snapshot(),s=r2(t),i=[],a=[],l=[],c=null,u=[],d=[],p=t.currentToken().contextId;if(p==null)throw new Error("Expected non-null class context ID on class open-brace.");for(t.nextToken();!t.matchesContextIdAndLabel(at.TokenType.braceR,p);)if(t.matchesContextual(Ck.ContextualKeyword._constructor)&&!t.currentToken().isType)({constructorInitializerStatements:i,constructorInsertPos:c}=Ak(t));else if(t.matches1(at.TokenType.semi))r||d.push({start:t.currentIndex(),end:t.currentIndex()+1}),t.nextToken();else if(t.currentToken().isType)t.nextToken();else{let f=t.currentIndex(),h=!1,g=!1,b=!1;for(;Jl(t.currentToken());)t.matches1(at.TokenType._static)&&(h=!0),t.matches1(at.TokenType.hash)&&(g=!0),(t.matches1(at.TokenType._declare)||t.matches1(at.TokenType._abstract))&&(b=!0),t.nextToken();if(h&&t.matches1(at.TokenType.braceL)){Gp(t,p);continue}if(g){Gp(t,p);continue}if(t.matchesContextual(Ck.ContextualKeyword._constructor)&&!t.currentToken().isType){({constructorInitializerStatements:i,constructorInsertPos:c}=Ak(t));continue}let k=t.currentIndex();if(o2(t),t.matches1(at.TokenType.lessThan)||t.matches1(at.TokenType.parenL)){Gp(t,p);continue}for(;t.currentToken().isType;)t.nextToken();if(t.matches1(at.TokenType.eq)){let w=t.currentIndex(),y=t.currentToken().rhsEndIndex;if(y==null)throw new Error("Expected rhsEndIndex on class field assignment.");for(t.nextToken();t.currentIndex()<y;)e.processToken();let _;h?(_=n.claimFreeName("__initStatic"),l.push(_)):(_=n.claimFreeName("__init"),a.push(_)),u.push({initializerName:_,equalsIndex:w,start:k,end:t.currentIndex()})}else(!r||b)&&d.push({start:f,end:t.currentIndex()})}return t.restoreToSnapshot(o),r?{headerInfo:s,constructorInitializerStatements:i,instanceInitializerNames:[],staticInitializerNames:[],constructorInsertPos:c,fields:[],rangesToRemove:d}:{headerInfo:s,constructorInitializerStatements:i,instanceInitializerNames:a,staticInitializerNames:l,constructorInsertPos:c,fields:u,rangesToRemove:d}}Hp.default=n2;function Gp(e,t){for(e.nextToken();e.currentToken().contextId!==t;)e.nextToken();for(;Jl(e.tokenAtRelativeIndex(-1));)e.previousToken()}function r2(e){let t=e.currentToken(),n=t.contextId;if(n==null)throw new Error("Expected context ID on class token.");let r=t.isExpression;if(r==null)throw new Error("Expected isExpression on class token.");let o=null,s=!1;for(e.nextToken(),e.matches1(at.TokenType.name)&&(o=e.identifierName());!e.matchesContextIdAndLabel(at.TokenType.braceL,n);)e.matches1(at.TokenType._extends)&&!e.currentToken().isType&&(s=!0),e.nextToken();return{isExpression:r,className:o,hasSuperclass:s}}function Ak(e){let t=[];e.nextToken();let n=e.currentToken().contextId;if(n==null)throw new Error("Expected context ID on open-paren starting constructor params.");for(;!e.matchesContextIdAndLabel(at.TokenType.parenR,n);)if(e.currentToken().contextId===n){if(e.nextToken(),Jl(e.currentToken())){for(e.nextToken();Jl(e.currentToken());)e.nextToken();let s=e.currentToken();if(s.type!==at.TokenType.name)throw new Error("Expected identifier after access modifiers in constructor arg.");let i=e.identifierNameForToken(s);t.push(`this.${i} = ${i}`)}}else e.nextToken();for(e.nextToken();e.currentToken().isType;)e.nextToken();let r=e.currentIndex(),o=!1;for(;!e.matchesContextIdAndLabel(at.TokenType.braceR,n);){if(!o&&e.matches2(at.TokenType._super,at.TokenType.parenL)){e.nextToken();let s=e.currentToken().contextId;if(s==null)throw new Error("Expected a context ID on the super call");for(;!e.matchesContextIdAndLabel(at.TokenType.parenR,s);)e.nextToken();r=e.currentIndex(),o=!0}e.nextToken()}return e.nextToken(),{constructorInitializerStatements:t,constructorInsertPos:r}}function Jl(e){return[at.TokenType._async,at.TokenType._get,at.TokenType._set,at.TokenType.plus,at.TokenType.minus,at.TokenType._readonly,at.TokenType._static,at.TokenType._public,at.TokenType._private,at.TokenType._protected,at.TokenType._override,at.TokenType._abstract,at.TokenType.star,at.TokenType._declare,at.TokenType.hash].includes(e.type)}function o2(e){if(e.matches1(at.TokenType.bracketL)){let n=e.currentToken().contextId;if(n==null)throw new Error("Expected class context ID on computed name open bracket.");for(;!e.matchesContextIdAndLabel(at.TokenType.bracketR,n);)e.nextToken();e.nextToken()}else e.nextToken()}});var Wp=Ie(zp=>{"use strict";Object.defineProperty(zp,"__esModule",{value:!0});var Mk=et();function s2(e){if(e.removeInitialToken(),e.removeToken(),e.removeToken(),e.removeToken(),e.matches1(Mk.TokenType.parenL))e.removeToken(),e.removeToken(),e.removeToken();else for(;e.matches1(Mk.TokenType.dot);)e.removeToken(),e.removeToken()}zp.default=s2});var Kp=Ie(Xl=>{"use strict";Object.defineProperty(Xl,"__esModule",{value:!0});var i2=en(),a2=et(),l2={typeDeclarations:new Set,valueDeclarations:new Set};Xl.EMPTY_DECLARATION_INFO=l2;function c2(e){let t=new Set,n=new Set;for(let r=0;r<e.tokens.length;r++){let o=e.tokens[r];o.type===a2.TokenType.name&&i2.isTopLevelDeclaration.call(void 0,o)&&(o.isType?t.add(e.identifierNameForToken(o)):n.add(e.identifierNameForToken(o)))}return{typeDeclarations:t,valueDeclarations:n}}Xl.default=c2});var Jp=Ie(Vp=>{"use strict";Object.defineProperty(Vp,"__esModule",{value:!0});var u2=rn(),Ik=et();function d2(e){let t=e.currentIndex();for(;!e.matches1AtIndex(t,Ik.TokenType.braceR);)t++;return e.matchesContextualAtIndex(t+1,u2.ContextualKeyword._from)&&e.matches1AtIndex(t+2,Ik.TokenType.string)}Vp.default=d2});var Qp=Ie(Xp=>{"use strict";Object.defineProperty(Xp,"__esModule",{value:!0});var p2=rn(),Ql=et();function m2(e){(e.matches2(Ql.TokenType._with,Ql.TokenType.braceL)||e.matches2(Ql.TokenType.name,Ql.TokenType.braceL)&&e.matchesContextual(p2.ContextualKeyword._assert))&&(e.removeToken(),e.removeToken(),e.removeBalancedCode(),e.removeToken())}Xp.removeMaybeImportAttributes=m2});var Zp=Ie(Yp=>{"use strict";Object.defineProperty(Yp,"__esModule",{value:!0});var Pk=et();function f2(e,t,n,r){if(!e||t)return!1;let o=n.currentToken();if(o.rhsEndIndex==null)throw new Error("Expected non-null rhsEndIndex on export token.");let s=o.rhsEndIndex-n.currentIndex();if(s!==3&&!(s===4&&n.matches1AtIndex(o.rhsEndIndex-1,Pk.TokenType.semi)))return!1;let i=n.tokenAtRelativeIndex(2);if(i.type!==Pk.TokenType.name)return!1;let a=n.identifierNameForToken(i);return r.typeDeclarations.has(a)&&!r.valueDeclarations.has(a)}Yp.default=f2});var Ok=Ie(tm=>{"use strict";Object.defineProperty(tm,"__esModule",{value:!0});function js(e){return e&&e.__esModule?e:{default:e}}var Yl=en(),jo=rn(),J=et(),h2=Wp(),g2=js(h2),Fk=Kp(),b2=js(Fk),y2=Ei(),w2=js(y2),k2=Jp(),_2=js(k2),Zl=Qp(),v2=Zp(),T2=js(v2),x2=Vn(),S2=js(x2),em=class e extends S2.default{__init(){this.hadExport=!1}__init2(){this.hadNamedExport=!1}__init3(){this.hadDefaultExport=!1}constructor(t,n,r,o,s,i,a,l,c,u,d,p){super(),this.rootTransformer=t,this.tokens=n,this.importProcessor=r,this.nameManager=o,this.helperManager=s,this.reactHotLoaderTransformer=i,this.enableLegacyBabel5ModuleInterop=a,this.enableLegacyTypeScriptModuleInterop=l,this.isTypeScriptTransformEnabled=c,this.isFlowTransformEnabled=u,this.preserveDynamicImport=d,this.keepUnusedImports=p,e.prototype.__init.call(this),e.prototype.__init2.call(this),e.prototype.__init3.call(this),this.declarationInfo=c?b2.default.call(void 0,n):Fk.EMPTY_DECLARATION_INFO}getPrefixCode(){let t="";return this.hadExport&&(t+='Object.defineProperty(exports, "__esModule", {value: true});'),t}getSuffixCode(){return this.enableLegacyBabel5ModuleInterop&&this.hadDefaultExport&&!this.hadNamedExport?`
|
|
119
|
+
module.exports = exports.default;
|
|
120
|
+
`:""}process(){return this.tokens.matches3(J.TokenType._import,J.TokenType.name,J.TokenType.eq)?this.processImportEquals():this.tokens.matches1(J.TokenType._import)?(this.processImport(),!0):this.tokens.matches2(J.TokenType._export,J.TokenType.eq)?(this.tokens.replaceToken("module.exports"),!0):this.tokens.matches1(J.TokenType._export)&&!this.tokens.currentToken().isType?(this.hadExport=!0,this.processExport()):this.tokens.matches2(J.TokenType.name,J.TokenType.postIncDec)&&this.processPostIncDec()?!0:this.tokens.matches1(J.TokenType.name)||this.tokens.matches1(J.TokenType.jsxName)?this.processIdentifier():this.tokens.matches1(J.TokenType.eq)?this.processAssignment():this.tokens.matches1(J.TokenType.assign)?this.processComplexAssignment():this.tokens.matches1(J.TokenType.preIncDec)?this.processPreIncDec():!1}processImportEquals(){let t=this.tokens.identifierNameAtIndex(this.tokens.currentIndex()+1);return this.importProcessor.shouldAutomaticallyElideImportedName(t)?g2.default.call(void 0,this.tokens):this.tokens.replaceToken("const"),!0}processImport(){if(this.tokens.matches2(J.TokenType._import,J.TokenType.parenL)){if(this.preserveDynamicImport){this.tokens.copyToken();return}let n=this.enableLegacyTypeScriptModuleInterop?"":`${this.helperManager.getHelperName("interopRequireWildcard")}(`;this.tokens.replaceToken(`Promise.resolve().then(() => ${n}require`);let r=this.tokens.currentToken().contextId;if(r==null)throw new Error("Expected context ID on dynamic import invocation.");for(this.tokens.copyToken();!this.tokens.matchesContextIdAndLabel(J.TokenType.parenR,r);)this.rootTransformer.processToken();this.tokens.replaceToken(n?")))":"))");return}if(this.removeImportAndDetectIfShouldElide())this.tokens.removeToken();else{let n=this.tokens.stringValue();this.tokens.replaceTokenTrimmingLeftWhitespace(this.importProcessor.claimImportCode(n)),this.tokens.appendCode(this.importProcessor.claimImportCode(n))}Zl.removeMaybeImportAttributes.call(void 0,this.tokens),this.tokens.matches1(J.TokenType.semi)&&this.tokens.removeToken()}removeImportAndDetectIfShouldElide(){if(this.tokens.removeInitialToken(),this.tokens.matchesContextual(jo.ContextualKeyword._type)&&!this.tokens.matches1AtIndex(this.tokens.currentIndex()+1,J.TokenType.comma)&&!this.tokens.matchesContextualAtIndex(this.tokens.currentIndex()+1,jo.ContextualKeyword._from))return this.removeRemainingImport(),!0;if(this.tokens.matches1(J.TokenType.name)||this.tokens.matches1(J.TokenType.star))return this.removeRemainingImport(),!1;if(this.tokens.matches1(J.TokenType.string))return!1;let t=!1,n=!1;for(;!this.tokens.matches1(J.TokenType.string);)(!t&&this.tokens.matches1(J.TokenType.braceL)||this.tokens.matches1(J.TokenType.comma))&&(this.tokens.removeToken(),this.tokens.matches1(J.TokenType.braceR)||(n=!0),(this.tokens.matches2(J.TokenType.name,J.TokenType.comma)||this.tokens.matches2(J.TokenType.name,J.TokenType.braceR)||this.tokens.matches4(J.TokenType.name,J.TokenType.name,J.TokenType.name,J.TokenType.comma)||this.tokens.matches4(J.TokenType.name,J.TokenType.name,J.TokenType.name,J.TokenType.braceR))&&(t=!0)),this.tokens.removeToken();return this.keepUnusedImports?!1:this.isTypeScriptTransformEnabled?!t:this.isFlowTransformEnabled?n&&!t:!1}removeRemainingImport(){for(;!this.tokens.matches1(J.TokenType.string);)this.tokens.removeToken()}processIdentifier(){let t=this.tokens.currentToken();if(t.shadowsGlobal)return!1;if(t.identifierRole===Yl.IdentifierRole.ObjectShorthand)return this.processObjectShorthand();if(t.identifierRole!==Yl.IdentifierRole.Access)return!1;let n=this.importProcessor.getIdentifierReplacement(this.tokens.identifierNameForToken(t));if(!n)return!1;let r=this.tokens.currentIndex()+1;for(;r<this.tokens.tokens.length&&this.tokens.tokens[r].type===J.TokenType.parenR;)r++;return this.tokens.tokens[r].type===J.TokenType.parenL?this.tokens.tokenAtRelativeIndex(1).type===J.TokenType.parenL&&this.tokens.tokenAtRelativeIndex(-1).type!==J.TokenType._new?(this.tokens.replaceToken(`${n}.call(void 0, `),this.tokens.removeToken(),this.rootTransformer.processBalancedCode(),this.tokens.copyExpectedToken(J.TokenType.parenR)):this.tokens.replaceToken(`(0, ${n})`):this.tokens.replaceToken(n),!0}processObjectShorthand(){let t=this.tokens.identifierName(),n=this.importProcessor.getIdentifierReplacement(t);return n?(this.tokens.replaceToken(`${t}: ${n}`),!0):!1}processExport(){if(this.tokens.matches2(J.TokenType._export,J.TokenType._enum)||this.tokens.matches3(J.TokenType._export,J.TokenType._const,J.TokenType._enum))return this.hadNamedExport=!0,!1;if(this.tokens.matches2(J.TokenType._export,J.TokenType._default))return this.tokens.matches3(J.TokenType._export,J.TokenType._default,J.TokenType._enum)?(this.hadDefaultExport=!0,!1):(this.processExportDefault(),!0);if(this.tokens.matches2(J.TokenType._export,J.TokenType.braceL))return this.processExportBindings(),!0;if(this.tokens.matches2(J.TokenType._export,J.TokenType.name)&&this.tokens.matchesContextualAtIndex(this.tokens.currentIndex()+1,jo.ContextualKeyword._type)){if(this.tokens.removeInitialToken(),this.tokens.removeToken(),this.tokens.matches1(J.TokenType.braceL)){for(;!this.tokens.matches1(J.TokenType.braceR);)this.tokens.removeToken();this.tokens.removeToken()}else this.tokens.removeToken(),this.tokens.matches1(J.TokenType._as)&&(this.tokens.removeToken(),this.tokens.removeToken());return this.tokens.matchesContextual(jo.ContextualKeyword._from)&&this.tokens.matches1AtIndex(this.tokens.currentIndex()+1,J.TokenType.string)&&(this.tokens.removeToken(),this.tokens.removeToken(),Zl.removeMaybeImportAttributes.call(void 0,this.tokens)),!0}if(this.hadNamedExport=!0,this.tokens.matches2(J.TokenType._export,J.TokenType._var)||this.tokens.matches2(J.TokenType._export,J.TokenType._let)||this.tokens.matches2(J.TokenType._export,J.TokenType._const))return this.processExportVar(),!0;if(this.tokens.matches2(J.TokenType._export,J.TokenType._function)||this.tokens.matches3(J.TokenType._export,J.TokenType.name,J.TokenType._function))return this.processExportFunction(),!0;if(this.tokens.matches2(J.TokenType._export,J.TokenType._class)||this.tokens.matches3(J.TokenType._export,J.TokenType._abstract,J.TokenType._class)||this.tokens.matches2(J.TokenType._export,J.TokenType.at))return this.processExportClass(),!0;if(this.tokens.matches2(J.TokenType._export,J.TokenType.star))return this.processExportStar(),!0;throw new Error("Unrecognized export syntax.")}processAssignment(){let t=this.tokens.currentIndex(),n=this.tokens.tokens[t-1];if(n.isType||n.type!==J.TokenType.name||n.shadowsGlobal||t>=2&&this.tokens.matches1AtIndex(t-2,J.TokenType.dot)||t>=2&&[J.TokenType._var,J.TokenType._let,J.TokenType._const].includes(this.tokens.tokens[t-2].type))return!1;let r=this.importProcessor.resolveExportBinding(this.tokens.identifierNameForToken(n));return r?(this.tokens.copyToken(),this.tokens.appendCode(` ${r} =`),!0):!1}processComplexAssignment(){let t=this.tokens.currentIndex(),n=this.tokens.tokens[t-1];if(n.type!==J.TokenType.name||n.shadowsGlobal||t>=2&&this.tokens.matches1AtIndex(t-2,J.TokenType.dot))return!1;let r=this.importProcessor.resolveExportBinding(this.tokens.identifierNameForToken(n));return r?(this.tokens.appendCode(` = ${r}`),this.tokens.copyToken(),!0):!1}processPreIncDec(){let t=this.tokens.currentIndex(),n=this.tokens.tokens[t+1];if(n.type!==J.TokenType.name||n.shadowsGlobal||t+2<this.tokens.tokens.length&&(this.tokens.matches1AtIndex(t+2,J.TokenType.dot)||this.tokens.matches1AtIndex(t+2,J.TokenType.bracketL)||this.tokens.matches1AtIndex(t+2,J.TokenType.parenL)))return!1;let r=this.tokens.identifierNameForToken(n),o=this.importProcessor.resolveExportBinding(r);return o?(this.tokens.appendCode(`${o} = `),this.tokens.copyToken(),!0):!1}processPostIncDec(){let t=this.tokens.currentIndex(),n=this.tokens.tokens[t],r=this.tokens.tokens[t+1];if(n.type!==J.TokenType.name||n.shadowsGlobal||t>=1&&this.tokens.matches1AtIndex(t-1,J.TokenType.dot))return!1;let o=this.tokens.identifierNameForToken(n),s=this.importProcessor.resolveExportBinding(o);if(!s)return!1;let i=this.tokens.rawCodeForToken(r),a=this.importProcessor.getIdentifierReplacement(o)||o;if(i==="++")this.tokens.replaceToken(`(${a} = ${s} = ${a} + 1, ${a} - 1)`);else if(i==="--")this.tokens.replaceToken(`(${a} = ${s} = ${a} - 1, ${a} + 1)`);else throw new Error(`Unexpected operator: ${i}`);return this.tokens.removeToken(),!0}processExportDefault(){let t=!0;if(this.tokens.matches4(J.TokenType._export,J.TokenType._default,J.TokenType._function,J.TokenType.name)||this.tokens.matches5(J.TokenType._export,J.TokenType._default,J.TokenType.name,J.TokenType._function,J.TokenType.name)&&this.tokens.matchesContextualAtIndex(this.tokens.currentIndex()+2,jo.ContextualKeyword._async)){this.tokens.removeInitialToken(),this.tokens.removeToken();let n=this.processNamedFunction();this.tokens.appendCode(` exports.default = ${n};`)}else if(this.tokens.matches4(J.TokenType._export,J.TokenType._default,J.TokenType._class,J.TokenType.name)||this.tokens.matches5(J.TokenType._export,J.TokenType._default,J.TokenType._abstract,J.TokenType._class,J.TokenType.name)||this.tokens.matches3(J.TokenType._export,J.TokenType._default,J.TokenType.at)){this.tokens.removeInitialToken(),this.tokens.removeToken(),this.copyDecorators(),this.tokens.matches1(J.TokenType._abstract)&&this.tokens.removeToken();let n=this.rootTransformer.processNamedClass();this.tokens.appendCode(` exports.default = ${n};`)}else if(T2.default.call(void 0,this.isTypeScriptTransformEnabled,this.keepUnusedImports,this.tokens,this.declarationInfo))t=!1,this.tokens.removeInitialToken(),this.tokens.removeToken(),this.tokens.removeToken();else if(this.reactHotLoaderTransformer){let n=this.nameManager.claimFreeName("_default");this.tokens.replaceToken(`let ${n}; exports.`),this.tokens.copyToken(),this.tokens.appendCode(` = ${n} =`),this.reactHotLoaderTransformer.setExtractedDefaultExportName(n)}else this.tokens.replaceToken("exports."),this.tokens.copyToken(),this.tokens.appendCode(" =");t&&(this.hadDefaultExport=!0)}copyDecorators(){for(;this.tokens.matches1(J.TokenType.at);)if(this.tokens.copyToken(),this.tokens.matches1(J.TokenType.parenL))this.tokens.copyExpectedToken(J.TokenType.parenL),this.rootTransformer.processBalancedCode(),this.tokens.copyExpectedToken(J.TokenType.parenR);else{for(this.tokens.copyExpectedToken(J.TokenType.name);this.tokens.matches1(J.TokenType.dot);)this.tokens.copyExpectedToken(J.TokenType.dot),this.tokens.copyExpectedToken(J.TokenType.name);this.tokens.matches1(J.TokenType.parenL)&&(this.tokens.copyExpectedToken(J.TokenType.parenL),this.rootTransformer.processBalancedCode(),this.tokens.copyExpectedToken(J.TokenType.parenR))}}processExportVar(){this.isSimpleExportVar()?this.processSimpleExportVar():this.processComplexExportVar()}isSimpleExportVar(){let t=this.tokens.currentIndex();if(t++,t++,!this.tokens.matches1AtIndex(t,J.TokenType.name))return!1;for(t++;t<this.tokens.tokens.length&&this.tokens.tokens[t].isType;)t++;return!!this.tokens.matches1AtIndex(t,J.TokenType.eq)}processSimpleExportVar(){this.tokens.removeInitialToken(),this.tokens.copyToken();let t=this.tokens.identifierName();for(;!this.tokens.matches1(J.TokenType.eq);)this.rootTransformer.processToken();let n=this.tokens.currentToken().rhsEndIndex;if(n==null)throw new Error("Expected = token with an end index.");for(;this.tokens.currentIndex()<n;)this.rootTransformer.processToken();this.tokens.appendCode(`; exports.${t} = ${t}`)}processComplexExportVar(){this.tokens.removeInitialToken(),this.tokens.removeToken();let t=this.tokens.matches1(J.TokenType.braceL);t&&this.tokens.appendCode("(");let n=0;for(;;)if(this.tokens.matches1(J.TokenType.braceL)||this.tokens.matches1(J.TokenType.dollarBraceL)||this.tokens.matches1(J.TokenType.bracketL))n++,this.tokens.copyToken();else if(this.tokens.matches1(J.TokenType.braceR)||this.tokens.matches1(J.TokenType.bracketR))n--,this.tokens.copyToken();else{if(n===0&&!this.tokens.matches1(J.TokenType.name)&&!this.tokens.currentToken().isType)break;if(this.tokens.matches1(J.TokenType.eq)){let r=this.tokens.currentToken().rhsEndIndex;if(r==null)throw new Error("Expected = token with an end index.");for(;this.tokens.currentIndex()<r;)this.rootTransformer.processToken()}else{let r=this.tokens.currentToken();if(Yl.isDeclaration.call(void 0,r)){let o=this.tokens.identifierName(),s=this.importProcessor.getIdentifierReplacement(o);if(s===null)throw new Error(`Expected a replacement for ${o} in \`export var\` syntax.`);Yl.isObjectShorthandDeclaration.call(void 0,r)&&(s=`${o}: ${s}`),this.tokens.replaceToken(s)}else this.rootTransformer.processToken()}}if(t){let r=this.tokens.currentToken().rhsEndIndex;if(r==null)throw new Error("Expected = token with an end index.");for(;this.tokens.currentIndex()<r;)this.rootTransformer.processToken();this.tokens.appendCode(")")}}processExportFunction(){this.tokens.replaceToken("");let t=this.processNamedFunction();this.tokens.appendCode(` exports.${t} = ${t};`)}processNamedFunction(){if(this.tokens.matches1(J.TokenType._function))this.tokens.copyToken();else if(this.tokens.matches2(J.TokenType.name,J.TokenType._function)){if(!this.tokens.matchesContextual(jo.ContextualKeyword._async))throw new Error("Expected async keyword in function export.");this.tokens.copyToken(),this.tokens.copyToken()}if(this.tokens.matches1(J.TokenType.star)&&this.tokens.copyToken(),!this.tokens.matches1(J.TokenType.name))throw new Error("Expected identifier for exported function name.");let t=this.tokens.identifierName();if(this.tokens.copyToken(),this.tokens.currentToken().isType)for(this.tokens.removeInitialToken();this.tokens.currentToken().isType;)this.tokens.removeToken();return this.tokens.copyExpectedToken(J.TokenType.parenL),this.rootTransformer.processBalancedCode(),this.tokens.copyExpectedToken(J.TokenType.parenR),this.rootTransformer.processPossibleTypeRange(),this.tokens.copyExpectedToken(J.TokenType.braceL),this.rootTransformer.processBalancedCode(),this.tokens.copyExpectedToken(J.TokenType.braceR),t}processExportClass(){this.tokens.removeInitialToken(),this.copyDecorators(),this.tokens.matches1(J.TokenType._abstract)&&this.tokens.removeToken();let t=this.rootTransformer.processNamedClass();this.tokens.appendCode(` exports.${t} = ${t};`)}processExportBindings(){this.tokens.removeInitialToken(),this.tokens.removeToken();let t=_2.default.call(void 0,this.tokens),n=[];for(;;){if(this.tokens.matches1(J.TokenType.braceR)){this.tokens.removeToken();break}let r=w2.default.call(void 0,this.tokens);for(;this.tokens.currentIndex()<r.endIndex;)this.tokens.removeToken();if(!(r.isType||!t&&this.shouldElideExportedIdentifier(r.leftName))){let s=r.rightName;s==="default"?this.hadDefaultExport=!0:this.hadNamedExport=!0;let i=r.leftName,a=this.importProcessor.getIdentifierReplacement(i);n.push(`exports.${s} = ${a||i};`)}if(this.tokens.matches1(J.TokenType.braceR)){this.tokens.removeToken();break}if(this.tokens.matches2(J.TokenType.comma,J.TokenType.braceR)){this.tokens.removeToken(),this.tokens.removeToken();break}else if(this.tokens.matches1(J.TokenType.comma))this.tokens.removeToken();else throw new Error(`Unexpected token: ${JSON.stringify(this.tokens.currentToken())}`)}if(this.tokens.matchesContextual(jo.ContextualKeyword._from)){this.tokens.removeToken();let r=this.tokens.stringValue();this.tokens.replaceTokenTrimmingLeftWhitespace(this.importProcessor.claimImportCode(r)),Zl.removeMaybeImportAttributes.call(void 0,this.tokens)}else this.tokens.appendCode(n.join(" "));this.tokens.matches1(J.TokenType.semi)&&this.tokens.removeToken()}processExportStar(){for(this.tokens.removeInitialToken();!this.tokens.matches1(J.TokenType.string);)this.tokens.removeToken();let t=this.tokens.stringValue();this.tokens.replaceTokenTrimmingLeftWhitespace(this.importProcessor.claimImportCode(t)),Zl.removeMaybeImportAttributes.call(void 0,this.tokens),this.tokens.matches1(J.TokenType.semi)&&this.tokens.removeToken()}shouldElideExportedIdentifier(t){return this.isTypeScriptTransformEnabled&&!this.keepUnusedImports&&!this.declarationInfo.valueDeclarations.has(t)}};tm.default=em});var jk=Ie(om=>{"use strict";Object.defineProperty(om,"__esModule",{value:!0});function Ds(e){return e&&e.__esModule?e:{default:e}}var Or=rn(),Ee=et(),$2=Wp(),R2=Ds($2),Nk=Kp(),C2=Ds(Nk),A2=Ei(),Lk=Ds(A2),E2=Rd(),M2=Jp(),I2=Ds(M2),nm=Qp(),P2=Zp(),F2=Ds(P2),O2=Vn(),L2=Ds(O2),rm=class extends L2.default{constructor(t,n,r,o,s,i,a,l){super(),this.tokens=t,this.nameManager=n,this.helperManager=r,this.reactHotLoaderTransformer=o,this.isTypeScriptTransformEnabled=s,this.isFlowTransformEnabled=i,this.keepUnusedImports=a,this.nonTypeIdentifiers=s&&!a?E2.getNonTypeIdentifiers.call(void 0,t,l):new Set,this.declarationInfo=s&&!a?C2.default.call(void 0,t):Nk.EMPTY_DECLARATION_INFO,this.injectCreateRequireForImportRequire=!!l.injectCreateRequireForImportRequire}process(){if(this.tokens.matches3(Ee.TokenType._import,Ee.TokenType.name,Ee.TokenType.eq))return this.processImportEquals();if(this.tokens.matches4(Ee.TokenType._import,Ee.TokenType.name,Ee.TokenType.name,Ee.TokenType.eq)&&this.tokens.matchesContextualAtIndex(this.tokens.currentIndex()+1,Or.ContextualKeyword._type)){this.tokens.removeInitialToken();for(let t=0;t<7;t++)this.tokens.removeToken();return!0}if(this.tokens.matches2(Ee.TokenType._export,Ee.TokenType.eq))return this.tokens.replaceToken("module.exports"),!0;if(this.tokens.matches5(Ee.TokenType._export,Ee.TokenType._import,Ee.TokenType.name,Ee.TokenType.name,Ee.TokenType.eq)&&this.tokens.matchesContextualAtIndex(this.tokens.currentIndex()+2,Or.ContextualKeyword._type)){this.tokens.removeInitialToken();for(let t=0;t<8;t++)this.tokens.removeToken();return!0}if(this.tokens.matches1(Ee.TokenType._import))return this.processImport();if(this.tokens.matches2(Ee.TokenType._export,Ee.TokenType._default))return this.processExportDefault();if(this.tokens.matches2(Ee.TokenType._export,Ee.TokenType.braceL))return this.processNamedExports();if(this.tokens.matches2(Ee.TokenType._export,Ee.TokenType.name)&&this.tokens.matchesContextualAtIndex(this.tokens.currentIndex()+1,Or.ContextualKeyword._type)){if(this.tokens.removeInitialToken(),this.tokens.removeToken(),this.tokens.matches1(Ee.TokenType.braceL)){for(;!this.tokens.matches1(Ee.TokenType.braceR);)this.tokens.removeToken();this.tokens.removeToken()}else this.tokens.removeToken(),this.tokens.matches1(Ee.TokenType._as)&&(this.tokens.removeToken(),this.tokens.removeToken());return this.tokens.matchesContextual(Or.ContextualKeyword._from)&&this.tokens.matches1AtIndex(this.tokens.currentIndex()+1,Ee.TokenType.string)&&(this.tokens.removeToken(),this.tokens.removeToken(),nm.removeMaybeImportAttributes.call(void 0,this.tokens)),!0}return!1}processImportEquals(){let t=this.tokens.identifierNameAtIndex(this.tokens.currentIndex()+1);return this.shouldAutomaticallyElideImportedName(t)?R2.default.call(void 0,this.tokens):this.injectCreateRequireForImportRequire?(this.tokens.replaceToken("const"),this.tokens.copyToken(),this.tokens.copyToken(),this.tokens.replaceToken(this.helperManager.getHelperName("require"))):this.tokens.replaceToken("const"),!0}processImport(){if(this.tokens.matches2(Ee.TokenType._import,Ee.TokenType.parenL))return!1;let t=this.tokens.snapshot();if(this.removeImportTypeBindings()){for(this.tokens.restoreToSnapshot(t);!this.tokens.matches1(Ee.TokenType.string);)this.tokens.removeToken();this.tokens.removeToken(),nm.removeMaybeImportAttributes.call(void 0,this.tokens),this.tokens.matches1(Ee.TokenType.semi)&&this.tokens.removeToken()}return!0}removeImportTypeBindings(){if(this.tokens.copyExpectedToken(Ee.TokenType._import),this.tokens.matchesContextual(Or.ContextualKeyword._type)&&!this.tokens.matches1AtIndex(this.tokens.currentIndex()+1,Ee.TokenType.comma)&&!this.tokens.matchesContextualAtIndex(this.tokens.currentIndex()+1,Or.ContextualKeyword._from))return!0;if(this.tokens.matches1(Ee.TokenType.string))return this.tokens.copyToken(),!1;this.tokens.matchesContextual(Or.ContextualKeyword._module)&&this.tokens.matchesContextualAtIndex(this.tokens.currentIndex()+2,Or.ContextualKeyword._from)&&this.tokens.copyToken();let t=!1,n=!1,r=!1;if(this.tokens.matches1(Ee.TokenType.name)&&(this.shouldAutomaticallyElideImportedName(this.tokens.identifierName())?(this.tokens.removeToken(),this.tokens.matches1(Ee.TokenType.comma)&&this.tokens.removeToken()):(t=!0,this.tokens.copyToken(),this.tokens.matches1(Ee.TokenType.comma)&&(r=!0,this.tokens.removeToken()))),this.tokens.matches1(Ee.TokenType.star))this.shouldAutomaticallyElideImportedName(this.tokens.identifierNameAtRelativeIndex(2))?(this.tokens.removeToken(),this.tokens.removeToken(),this.tokens.removeToken()):(r&&this.tokens.appendCode(","),t=!0,this.tokens.copyExpectedToken(Ee.TokenType.star),this.tokens.copyExpectedToken(Ee.TokenType.name),this.tokens.copyExpectedToken(Ee.TokenType.name));else if(this.tokens.matches1(Ee.TokenType.braceL)){for(r&&this.tokens.appendCode(","),this.tokens.copyToken();!this.tokens.matches1(Ee.TokenType.braceR);){n=!0;let o=Lk.default.call(void 0,this.tokens);if(o.isType||this.shouldAutomaticallyElideImportedName(o.rightName)){for(;this.tokens.currentIndex()<o.endIndex;)this.tokens.removeToken();this.tokens.matches1(Ee.TokenType.comma)&&this.tokens.removeToken()}else{for(t=!0;this.tokens.currentIndex()<o.endIndex;)this.tokens.copyToken();this.tokens.matches1(Ee.TokenType.comma)&&this.tokens.copyToken()}}this.tokens.copyExpectedToken(Ee.TokenType.braceR)}return this.keepUnusedImports?!1:this.isTypeScriptTransformEnabled?!t:this.isFlowTransformEnabled?n&&!t:!1}shouldAutomaticallyElideImportedName(t){return this.isTypeScriptTransformEnabled&&!this.keepUnusedImports&&!this.nonTypeIdentifiers.has(t)}processExportDefault(){if(F2.default.call(void 0,this.isTypeScriptTransformEnabled,this.keepUnusedImports,this.tokens,this.declarationInfo))return this.tokens.removeInitialToken(),this.tokens.removeToken(),this.tokens.removeToken(),!0;if(!(this.tokens.matches4(Ee.TokenType._export,Ee.TokenType._default,Ee.TokenType._function,Ee.TokenType.name)||this.tokens.matches5(Ee.TokenType._export,Ee.TokenType._default,Ee.TokenType.name,Ee.TokenType._function,Ee.TokenType.name)&&this.tokens.matchesContextualAtIndex(this.tokens.currentIndex()+2,Or.ContextualKeyword._async)||this.tokens.matches4(Ee.TokenType._export,Ee.TokenType._default,Ee.TokenType._class,Ee.TokenType.name)||this.tokens.matches5(Ee.TokenType._export,Ee.TokenType._default,Ee.TokenType._abstract,Ee.TokenType._class,Ee.TokenType.name))&&this.reactHotLoaderTransformer){let n=this.nameManager.claimFreeName("_default");return this.tokens.replaceToken(`let ${n}; export`),this.tokens.copyToken(),this.tokens.appendCode(` ${n} =`),this.reactHotLoaderTransformer.setExtractedDefaultExportName(n),!0}return!1}processNamedExports(){if(!this.isTypeScriptTransformEnabled)return!1;this.tokens.copyExpectedToken(Ee.TokenType._export),this.tokens.copyExpectedToken(Ee.TokenType.braceL);let t=I2.default.call(void 0,this.tokens),n=!1;for(;!this.tokens.matches1(Ee.TokenType.braceR);){let r=Lk.default.call(void 0,this.tokens);if(r.isType||!t&&this.shouldElideExportedName(r.leftName)){for(;this.tokens.currentIndex()<r.endIndex;)this.tokens.removeToken();this.tokens.matches1(Ee.TokenType.comma)&&this.tokens.removeToken()}else{for(n=!0;this.tokens.currentIndex()<r.endIndex;)this.tokens.copyToken();this.tokens.matches1(Ee.TokenType.comma)&&this.tokens.copyToken()}}return this.tokens.copyExpectedToken(Ee.TokenType.braceR),!this.keepUnusedImports&&t&&!n&&(this.tokens.removeToken(),this.tokens.removeToken(),nm.removeMaybeImportAttributes.call(void 0,this.tokens)),!0}shouldElideExportedName(t){return this.isTypeScriptTransformEnabled&&!this.keepUnusedImports&&this.declarationInfo.typeDeclarations.has(t)&&!this.declarationInfo.valueDeclarations.has(t)}};om.default=rm});var Bk=Ie(im=>{"use strict";Object.defineProperty(im,"__esModule",{value:!0});function N2(e){return e&&e.__esModule?e:{default:e}}var Dk=rn(),Un=et(),j2=Vn(),D2=N2(j2),sm=class extends D2.default{constructor(t,n,r){super(),this.rootTransformer=t,this.tokens=n,this.isImportsTransformEnabled=r}process(){return this.rootTransformer.processPossibleArrowParamEnd()||this.rootTransformer.processPossibleAsyncArrowWithTypeParams()||this.rootTransformer.processPossibleTypeRange()?!0:this.tokens.matches1(Un.TokenType._enum)?(this.processEnum(),!0):this.tokens.matches2(Un.TokenType._export,Un.TokenType._enum)?(this.processNamedExportEnum(),!0):this.tokens.matches3(Un.TokenType._export,Un.TokenType._default,Un.TokenType._enum)?(this.processDefaultExportEnum(),!0):!1}processNamedExportEnum(){if(this.isImportsTransformEnabled){this.tokens.removeInitialToken();let t=this.tokens.identifierNameAtRelativeIndex(1);this.processEnum(),this.tokens.appendCode(` exports.${t} = ${t};`)}else this.tokens.copyToken(),this.processEnum()}processDefaultExportEnum(){this.tokens.removeInitialToken(),this.tokens.removeToken();let t=this.tokens.identifierNameAtRelativeIndex(1);this.processEnum(),this.isImportsTransformEnabled?this.tokens.appendCode(` exports.default = ${t};`):this.tokens.appendCode(` export default ${t};`)}processEnum(){this.tokens.replaceToken("const"),this.tokens.copyExpectedToken(Un.TokenType.name);let t=!1;this.tokens.matchesContextual(Dk.ContextualKeyword._of)&&(this.tokens.removeToken(),t=this.tokens.matchesContextual(Dk.ContextualKeyword._symbol),this.tokens.removeToken());let n=this.tokens.matches3(Un.TokenType.braceL,Un.TokenType.name,Un.TokenType.eq);this.tokens.appendCode(' = require("flow-enums-runtime")');let r=!t&&!n;for(this.tokens.replaceTokenTrimmingLeftWhitespace(r?".Mirrored([":"({");!this.tokens.matches1(Un.TokenType.braceR);){if(this.tokens.matches1(Un.TokenType.ellipsis)){this.tokens.removeToken();break}this.processEnumElement(t,n),this.tokens.matches1(Un.TokenType.comma)&&this.tokens.copyToken()}this.tokens.replaceToken(r?"]);":"});")}processEnumElement(t,n){if(t){let r=this.tokens.identifierName();this.tokens.copyToken(),this.tokens.appendCode(`: Symbol("${r}")`)}else n?(this.tokens.copyToken(),this.tokens.replaceTokenTrimmingLeftWhitespace(":"),this.tokens.copyToken()):this.tokens.replaceToken(`"${this.tokens.identifierName()}"`)}};im.default=sm});var qk=Ie(lm=>{"use strict";Object.defineProperty(lm,"__esModule",{value:!0});function B2(e){return e&&e.__esModule?e:{default:e}}function q2(e){let t,n=e[0],r=1;for(;r<e.length;){let o=e[r],s=e[r+1];if(r+=2,(o==="optionalAccess"||o==="optionalCall")&&n==null)return;o==="access"||o==="optionalAccess"?(t=n,n=s(n)):(o==="call"||o==="optionalCall")&&(n=s((...i)=>n.call(t,...i)),t=void 0)}return n}var Lr=et(),U2=Vn(),G2=B2(U2),ec="jest",H2=["mock","unmock","enableAutomock","disableAutomock"],am=class e extends G2.default{__init(){this.hoistedFunctionNames=[]}constructor(t,n,r,o){super(),this.rootTransformer=t,this.tokens=n,this.nameManager=r,this.importProcessor=o,e.prototype.__init.call(this)}process(){return this.tokens.currentToken().scopeDepth===0&&this.tokens.matches4(Lr.TokenType.name,Lr.TokenType.dot,Lr.TokenType.name,Lr.TokenType.parenL)&&this.tokens.identifierName()===ec?q2([this,"access",t=>t.importProcessor,"optionalAccess",t=>t.getGlobalNames,"call",t=>t(),"optionalAccess",t=>t.has,"call",t=>t(ec)])?!1:this.extractHoistedCalls():!1}getHoistedCode(){return this.hoistedFunctionNames.length>0?this.hoistedFunctionNames.map(t=>`${t}();`).join(""):""}extractHoistedCalls(){this.tokens.removeToken();let t=!1;for(;this.tokens.matches3(Lr.TokenType.dot,Lr.TokenType.name,Lr.TokenType.parenL);){let n=this.tokens.identifierNameAtIndex(this.tokens.currentIndex()+1);if(H2.includes(n)){let o=this.nameManager.claimFreeName("__jestHoist");this.hoistedFunctionNames.push(o),this.tokens.replaceToken(`function ${o}(){${ec}.`),this.tokens.copyToken(),this.tokens.copyToken(),this.rootTransformer.processBalancedCode(),this.tokens.copyExpectedToken(Lr.TokenType.parenR),this.tokens.appendCode(";}"),t=!1}else t?this.tokens.copyToken():this.tokens.replaceToken(`${ec}.`),this.tokens.copyToken(),this.tokens.copyToken(),this.rootTransformer.processBalancedCode(),this.tokens.copyExpectedToken(Lr.TokenType.parenR),t=!0}return!0}};lm.default=am});var Uk=Ie(um=>{"use strict";Object.defineProperty(um,"__esModule",{value:!0});function z2(e){return e&&e.__esModule?e:{default:e}}var W2=et(),K2=Vn(),V2=z2(K2),cm=class extends V2.default{constructor(t){super(),this.tokens=t}process(){if(this.tokens.matches1(W2.TokenType.num)){let t=this.tokens.currentTokenCode();if(t.includes("_"))return this.tokens.replaceToken(t.replace(/_/g,"")),!0}return!1}};um.default=cm});var Hk=Ie(pm=>{"use strict";Object.defineProperty(pm,"__esModule",{value:!0});function J2(e){return e&&e.__esModule?e:{default:e}}var Gk=et(),X2=Vn(),Q2=J2(X2),dm=class extends Q2.default{constructor(t,n){super(),this.tokens=t,this.nameManager=n}process(){return this.tokens.matches2(Gk.TokenType._catch,Gk.TokenType.braceL)?(this.tokens.copyToken(),this.tokens.appendCode(` (${this.nameManager.claimFreeName("e")})`),!0):!1}};pm.default=dm});var zk=Ie(fm=>{"use strict";Object.defineProperty(fm,"__esModule",{value:!0});function Y2(e){return e&&e.__esModule?e:{default:e}}var kn=et(),Z2=Vn(),eF=Y2(Z2),mm=class extends eF.default{constructor(t,n){super(),this.tokens=t,this.nameManager=n}process(){if(this.tokens.matches1(kn.TokenType.nullishCoalescing)){let r=this.tokens.currentToken();return this.tokens.tokens[r.nullishStartIndex].isAsyncOperation?this.tokens.replaceTokenTrimmingLeftWhitespace(", async () => ("):this.tokens.replaceTokenTrimmingLeftWhitespace(", () => ("),!0}if(this.tokens.matches1(kn.TokenType._delete)&&this.tokens.tokenAtRelativeIndex(1).isOptionalChainStart)return this.tokens.removeInitialToken(),!0;let n=this.tokens.currentToken().subscriptStartIndex;if(n!=null&&this.tokens.tokens[n].isOptionalChainStart&&this.tokens.tokenAtRelativeIndex(-1).type!==kn.TokenType._super){let r=this.nameManager.claimFreeName("_"),o;if(n>0&&this.tokens.matches1AtIndex(n-1,kn.TokenType._delete)&&this.isLastSubscriptInChain()?o=`${r} => delete ${r}`:o=`${r} => ${r}`,this.tokens.tokens[n].isAsyncOperation&&(o=`async ${o}`),this.tokens.matches2(kn.TokenType.questionDot,kn.TokenType.parenL)||this.tokens.matches2(kn.TokenType.questionDot,kn.TokenType.lessThan))this.justSkippedSuper()&&this.tokens.appendCode(".bind(this)"),this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'optionalCall', ${o}`);else if(this.tokens.matches2(kn.TokenType.questionDot,kn.TokenType.bracketL))this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'optionalAccess', ${o}`);else if(this.tokens.matches1(kn.TokenType.questionDot))this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'optionalAccess', ${o}.`);else if(this.tokens.matches1(kn.TokenType.dot))this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'access', ${o}.`);else if(this.tokens.matches1(kn.TokenType.bracketL))this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'access', ${o}[`);else if(this.tokens.matches1(kn.TokenType.parenL))this.justSkippedSuper()&&this.tokens.appendCode(".bind(this)"),this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'call', ${o}(`);else throw new Error("Unexpected subscript operator in optional chain.");return!0}return!1}isLastSubscriptInChain(){let t=0;for(let n=this.tokens.currentIndex()+1;;n++){if(n>=this.tokens.tokens.length)throw new Error("Reached the end of the code while finding the end of the access chain.");if(this.tokens.tokens[n].isOptionalChainStart?t++:this.tokens.tokens[n].isOptionalChainEnd&&t--,t<0)return!0;if(t===0&&this.tokens.tokens[n].subscriptStartIndex!=null)return!1}}justSkippedSuper(){let t=0,n=this.tokens.currentIndex()-1;for(;;){if(n<0)throw new Error("Reached the start of the code while finding the start of the access chain.");if(this.tokens.tokens[n].isOptionalChainStart?t--:this.tokens.tokens[n].isOptionalChainEnd&&t++,t<0)return!1;if(t===0&&this.tokens.tokens[n].subscriptStartIndex!=null)return this.tokens.tokens[n-1].type===kn.TokenType._super;n--}}};fm.default=mm});var Kk=Ie(gm=>{"use strict";Object.defineProperty(gm,"__esModule",{value:!0});function tF(e){return e&&e.__esModule?e:{default:e}}var Wk=en(),ln=et(),nF=Vn(),rF=tF(nF),hm=class extends rF.default{constructor(t,n,r,o){super(),this.rootTransformer=t,this.tokens=n,this.importProcessor=r,this.options=o}process(){let t=this.tokens.currentIndex();if(this.tokens.identifierName()==="createReactClass"){let n=this.importProcessor&&this.importProcessor.getIdentifierReplacement("createReactClass");return n?this.tokens.replaceToken(`(0, ${n})`):this.tokens.copyToken(),this.tryProcessCreateClassCall(t),!0}if(this.tokens.matches3(ln.TokenType.name,ln.TokenType.dot,ln.TokenType.name)&&this.tokens.identifierName()==="React"&&this.tokens.identifierNameAtIndex(this.tokens.currentIndex()+2)==="createClass"){let n=this.importProcessor&&this.importProcessor.getIdentifierReplacement("React")||"React";return n?(this.tokens.replaceToken(n),this.tokens.copyToken(),this.tokens.copyToken()):(this.tokens.copyToken(),this.tokens.copyToken(),this.tokens.copyToken()),this.tryProcessCreateClassCall(t),!0}return!1}tryProcessCreateClassCall(t){let n=this.findDisplayName(t);n&&this.classNeedsDisplayName()&&(this.tokens.copyExpectedToken(ln.TokenType.parenL),this.tokens.copyExpectedToken(ln.TokenType.braceL),this.tokens.appendCode(`displayName: '${n}',`),this.rootTransformer.processBalancedCode(),this.tokens.copyExpectedToken(ln.TokenType.braceR),this.tokens.copyExpectedToken(ln.TokenType.parenR))}findDisplayName(t){return t<2?null:this.tokens.matches2AtIndex(t-2,ln.TokenType.name,ln.TokenType.eq)?this.tokens.identifierNameAtIndex(t-2):t>=2&&this.tokens.tokens[t-2].identifierRole===Wk.IdentifierRole.ObjectKey?this.tokens.identifierNameAtIndex(t-2):this.tokens.matches2AtIndex(t-2,ln.TokenType._export,ln.TokenType._default)?this.getDisplayNameFromFilename():null}getDisplayNameFromFilename(){let n=(this.options.filePath||"unknown").split("/"),r=n[n.length-1],o=r.lastIndexOf("."),s=o===-1?r:r.slice(0,o);return s==="index"&&n[n.length-2]?n[n.length-2]:s}classNeedsDisplayName(){let t=this.tokens.currentIndex();if(!this.tokens.matches2(ln.TokenType.parenL,ln.TokenType.braceL))return!1;let n=t+1,r=this.tokens.tokens[n].contextId;if(r==null)throw new Error("Expected non-null context ID on object open-brace.");for(;t<this.tokens.tokens.length;t++){let o=this.tokens.tokens[t];if(o.type===ln.TokenType.braceR&&o.contextId===r){t++;break}if(this.tokens.identifierNameAtIndex(t)==="displayName"&&this.tokens.tokens[t].identifierRole===Wk.IdentifierRole.ObjectKey&&o.contextId===r)return!1}if(t===this.tokens.tokens.length)throw new Error("Unexpected end of input when processing React class.");return this.tokens.matches1AtIndex(t,ln.TokenType.parenR)||this.tokens.matches2AtIndex(t,ln.TokenType.comma,ln.TokenType.parenR)}};gm.default=hm});var Jk=Ie(ym=>{"use strict";Object.defineProperty(ym,"__esModule",{value:!0});function oF(e){return e&&e.__esModule?e:{default:e}}var Vk=en(),sF=Vn(),iF=oF(sF),bm=class e extends iF.default{__init(){this.extractedDefaultExportName=null}constructor(t,n){super(),this.tokens=t,this.filePath=n,e.prototype.__init.call(this)}setExtractedDefaultExportName(t){this.extractedDefaultExportName=t}getPrefixCode(){return`
|
|
121
|
+
(function () {
|
|
122
|
+
var enterModule = require('react-hot-loader').enterModule;
|
|
123
|
+
enterModule && enterModule(module);
|
|
124
|
+
})();`.replace(/\s+/g," ").trim()}getSuffixCode(){let t=new Set;for(let r of this.tokens.tokens)!r.isType&&Vk.isTopLevelDeclaration.call(void 0,r)&&r.identifierRole!==Vk.IdentifierRole.ImportDeclaration&&t.add(this.tokens.identifierNameForToken(r));let n=Array.from(t).map(r=>({variableName:r,uniqueLocalName:r}));return this.extractedDefaultExportName&&n.push({variableName:this.extractedDefaultExportName,uniqueLocalName:"default"}),`
|
|
125
|
+
;(function () {
|
|
126
|
+
var reactHotLoader = require('react-hot-loader').default;
|
|
127
|
+
var leaveModule = require('react-hot-loader').leaveModule;
|
|
128
|
+
if (!reactHotLoader) {
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
${n.map(({variableName:r,uniqueLocalName:o})=>` reactHotLoader.register(${r}, "${o}", ${JSON.stringify(this.filePath||"")});`).join(`
|
|
132
|
+
`)}
|
|
133
|
+
leaveModule(module);
|
|
134
|
+
})();`}process(){return!1}};ym.default=bm});var Qk=Ie(wm=>{"use strict";Object.defineProperty(wm,"__esModule",{value:!0});var Xk=xs(),aF=new Set(["break","case","catch","class","const","continue","debugger","default","delete","do","else","export","extends","finally","for","function","if","import","in","instanceof","new","return","super","switch","this","throw","try","typeof","var","void","while","with","yield","enum","implements","interface","let","package","private","protected","public","static","await","false","null","true"]);function lF(e){if(e.length===0||!Xk.IS_IDENTIFIER_START[e.charCodeAt(0)])return!1;for(let t=1;t<e.length;t++)if(!Xk.IS_IDENTIFIER_CHAR[e.charCodeAt(t)])return!1;return!aF.has(e)}wm.default=lF});var e_=Ie(_m=>{"use strict";Object.defineProperty(_m,"__esModule",{value:!0});function Zk(e){return e&&e.__esModule?e:{default:e}}var _t=et(),cF=Qk(),Yk=Zk(cF),uF=Vn(),dF=Zk(uF),km=class extends dF.default{constructor(t,n,r){super(),this.rootTransformer=t,this.tokens=n,this.isImportsTransformEnabled=r}process(){return this.rootTransformer.processPossibleArrowParamEnd()||this.rootTransformer.processPossibleAsyncArrowWithTypeParams()||this.rootTransformer.processPossibleTypeRange()?!0:this.tokens.matches1(_t.TokenType._public)||this.tokens.matches1(_t.TokenType._protected)||this.tokens.matches1(_t.TokenType._private)||this.tokens.matches1(_t.TokenType._abstract)||this.tokens.matches1(_t.TokenType._readonly)||this.tokens.matches1(_t.TokenType._override)||this.tokens.matches1(_t.TokenType.nonNullAssertion)?(this.tokens.removeInitialToken(),!0):this.tokens.matches1(_t.TokenType._enum)||this.tokens.matches2(_t.TokenType._const,_t.TokenType._enum)?(this.processEnum(),!0):this.tokens.matches2(_t.TokenType._export,_t.TokenType._enum)||this.tokens.matches3(_t.TokenType._export,_t.TokenType._const,_t.TokenType._enum)?(this.processEnum(!0),!0):!1}processEnum(t=!1){for(this.tokens.removeInitialToken();this.tokens.matches1(_t.TokenType._const)||this.tokens.matches1(_t.TokenType._enum);)this.tokens.removeToken();let n=this.tokens.identifierName();this.tokens.removeToken(),t&&!this.isImportsTransformEnabled&&this.tokens.appendCode("export "),this.tokens.appendCode(`var ${n}; (function (${n})`),this.tokens.copyExpectedToken(_t.TokenType.braceL),this.processEnumBody(n),this.tokens.copyExpectedToken(_t.TokenType.braceR),t&&this.isImportsTransformEnabled?this.tokens.appendCode(`)(${n} || (exports.${n} = ${n} = {}));`):this.tokens.appendCode(`)(${n} || (${n} = {}));`)}processEnumBody(t){let n=null;for(;!this.tokens.matches1(_t.TokenType.braceR);){let{nameStringCode:r,variableName:o}=this.extractEnumKeyInfo(this.tokens.currentToken());this.tokens.removeInitialToken(),this.tokens.matches3(_t.TokenType.eq,_t.TokenType.string,_t.TokenType.comma)||this.tokens.matches3(_t.TokenType.eq,_t.TokenType.string,_t.TokenType.braceR)?this.processStringLiteralEnumMember(t,r,o):this.tokens.matches1(_t.TokenType.eq)?this.processExplicitValueEnumMember(t,r,o):this.processImplicitValueEnumMember(t,r,o,n),this.tokens.matches1(_t.TokenType.comma)&&this.tokens.removeToken(),o!=null?n=o:n=`${t}[${r}]`}}extractEnumKeyInfo(t){if(t.type===_t.TokenType.name){let n=this.tokens.identifierNameForToken(t);return{nameStringCode:`"${n}"`,variableName:Yk.default.call(void 0,n)?n:null}}else if(t.type===_t.TokenType.string){let n=this.tokens.stringValueForToken(t);return{nameStringCode:this.tokens.code.slice(t.start,t.end),variableName:Yk.default.call(void 0,n)?n:null}}else throw new Error("Expected name or string at beginning of enum element.")}processStringLiteralEnumMember(t,n,r){r!=null?(this.tokens.appendCode(`const ${r}`),this.tokens.copyToken(),this.tokens.copyToken(),this.tokens.appendCode(`; ${t}[${n}] = ${r};`)):(this.tokens.appendCode(`${t}[${n}]`),this.tokens.copyToken(),this.tokens.copyToken(),this.tokens.appendCode(";"))}processExplicitValueEnumMember(t,n,r){let o=this.tokens.currentToken().rhsEndIndex;if(o==null)throw new Error("Expected rhsEndIndex on enum assign.");if(r!=null){for(this.tokens.appendCode(`const ${r}`),this.tokens.copyToken();this.tokens.currentIndex()<o;)this.rootTransformer.processToken();this.tokens.appendCode(`; ${t}[${t}[${n}] = ${r}] = ${n};`)}else{for(this.tokens.appendCode(`${t}[${t}[${n}]`),this.tokens.copyToken();this.tokens.currentIndex()<o;)this.rootTransformer.processToken();this.tokens.appendCode(`] = ${n};`)}}processImplicitValueEnumMember(t,n,r,o){let s=o!=null?`${o} + 1`:"0";r!=null&&(this.tokens.appendCode(`const ${r} = ${s}; `),s=r),this.tokens.appendCode(`${t}[${t}[${n}] = ${s}] = ${n};`)}};_m.default=km});var t_=Ie(Tm=>{"use strict";Object.defineProperty(Tm,"__esModule",{value:!0});function Yn(e){return e&&e.__esModule?e:{default:e}}var pF=rn(),Ht=et(),mF=Ek(),fF=Yn(mF),hF=Ok(),gF=Yn(hF),bF=jk(),yF=Yn(bF),wF=Bk(),kF=Yn(wF),_F=qk(),vF=Yn(_F),TF=Sd(),xF=Yn(TF),SF=Uk(),$F=Yn(SF),RF=Hk(),CF=Yn(RF),AF=zk(),EF=Yn(AF),MF=Kk(),IF=Yn(MF),PF=Jk(),FF=Yn(PF),OF=e_(),LF=Yn(OF),vm=class e{__init(){this.transformers=[]}__init2(){this.generatedVariables=[]}constructor(t,n,r,o){e.prototype.__init.call(this),e.prototype.__init2.call(this),this.nameManager=t.nameManager,this.helperManager=t.helperManager;let{tokenProcessor:s,importProcessor:i}=t;this.tokens=s,this.isImportsTransformEnabled=n.includes("imports"),this.isReactHotLoaderTransformEnabled=n.includes("react-hot-loader"),this.disableESTransforms=!!o.disableESTransforms,o.disableESTransforms||(this.transformers.push(new EF.default(s,this.nameManager)),this.transformers.push(new $F.default(s)),this.transformers.push(new CF.default(s,this.nameManager))),n.includes("jsx")&&(o.jsxRuntime!=="preserve"&&this.transformers.push(new xF.default(this,s,i,this.nameManager,o)),this.transformers.push(new IF.default(this,s,i,o)));let a=null;if(n.includes("react-hot-loader")){if(!o.filePath)throw new Error("filePath is required when using the react-hot-loader transform.");a=new FF.default(s,o.filePath),this.transformers.push(a)}if(n.includes("imports")){if(i===null)throw new Error("Expected non-null importProcessor with imports transform enabled.");this.transformers.push(new gF.default(this,s,i,this.nameManager,this.helperManager,a,r,!!o.enableLegacyTypeScriptModuleInterop,n.includes("typescript"),n.includes("flow"),!!o.preserveDynamicImport,!!o.keepUnusedImports))}else this.transformers.push(new yF.default(s,this.nameManager,this.helperManager,a,n.includes("typescript"),n.includes("flow"),!!o.keepUnusedImports,o));n.includes("flow")&&this.transformers.push(new kF.default(this,s,n.includes("imports"))),n.includes("typescript")&&this.transformers.push(new LF.default(this,s,n.includes("imports"))),n.includes("jest")&&this.transformers.push(new vF.default(this,s,this.nameManager,i))}transform(){this.tokens.reset(),this.processBalancedCode();let n=this.isImportsTransformEnabled?'"use strict";':"";for(let i of this.transformers)n+=i.getPrefixCode();n+=this.helperManager.emitHelpers(),n+=this.generatedVariables.map(i=>` var ${i};`).join("");for(let i of this.transformers)n+=i.getHoistedCode();let r="";for(let i of this.transformers)r+=i.getSuffixCode();let o=this.tokens.finish(),{code:s}=o;if(s.startsWith("#!")){let i=s.indexOf(`
|
|
135
|
+
`);return i===-1&&(i=s.length,s+=`
|
|
136
|
+
`),{code:s.slice(0,i+1)+n+s.slice(i+1)+r,mappings:this.shiftMappings(o.mappings,n.length)}}else return{code:n+s+r,mappings:this.shiftMappings(o.mappings,n.length)}}processBalancedCode(){let t=0,n=0;for(;!this.tokens.isAtEnd();){if(this.tokens.matches1(Ht.TokenType.braceL)||this.tokens.matches1(Ht.TokenType.dollarBraceL))t++;else if(this.tokens.matches1(Ht.TokenType.braceR)){if(t===0)return;t--}if(this.tokens.matches1(Ht.TokenType.parenL))n++;else if(this.tokens.matches1(Ht.TokenType.parenR)){if(n===0)return;n--}this.processToken()}}processToken(){if(this.tokens.matches1(Ht.TokenType._class)){this.processClass();return}for(let t of this.transformers)if(t.process())return;this.tokens.copyToken()}processNamedClass(){if(!this.tokens.matches2(Ht.TokenType._class,Ht.TokenType.name))throw new Error("Expected identifier for exported class name.");let t=this.tokens.identifierNameAtIndex(this.tokens.currentIndex()+1);return this.processClass(),t}processClass(){let t=fF.default.call(void 0,this,this.tokens,this.nameManager,this.disableESTransforms),n=(t.headerInfo.isExpression||!t.headerInfo.className)&&t.staticInitializerNames.length+t.instanceInitializerNames.length>0,r=t.headerInfo.className;n&&(r=this.nameManager.claimFreeName("_class"),this.generatedVariables.push(r),this.tokens.appendCode(` (${r} =`));let s=this.tokens.currentToken().contextId;if(s==null)throw new Error("Expected class to have a context ID.");for(this.tokens.copyExpectedToken(Ht.TokenType._class);!this.tokens.matchesContextIdAndLabel(Ht.TokenType.braceL,s);)this.processToken();this.processClassBody(t,r);let i=t.staticInitializerNames.map(a=>`${r}.${a}()`);n?this.tokens.appendCode(`, ${i.map(a=>`${a}, `).join("")}${r})`):t.staticInitializerNames.length>0&&this.tokens.appendCode(` ${i.map(a=>`${a};`).join(" ")}`)}processClassBody(t,n){let{headerInfo:r,constructorInsertPos:o,constructorInitializerStatements:s,fields:i,instanceInitializerNames:a,rangesToRemove:l}=t,c=0,u=0,d=this.tokens.currentToken().contextId;if(d==null)throw new Error("Expected non-null context ID on class.");this.tokens.copyExpectedToken(Ht.TokenType.braceL),this.isReactHotLoaderTransformEnabled&&this.tokens.appendCode("__reactstandin__regenerateByEval(key, code) {this[key] = eval(code);}");let p=s.length+a.length>0;if(o===null&&p){let f=this.makeConstructorInitCode(s,a,n);if(r.hasSuperclass){let h=this.nameManager.claimFreeName("args");this.tokens.appendCode(`constructor(...${h}) { super(...${h}); ${f}; }`)}else this.tokens.appendCode(`constructor() { ${f}; }`)}for(;!this.tokens.matchesContextIdAndLabel(Ht.TokenType.braceR,d);)if(c<i.length&&this.tokens.currentIndex()===i[c].start){let f=!1;for(this.tokens.matches1(Ht.TokenType.bracketL)?this.tokens.copyTokenWithPrefix(`${i[c].initializerName}() {this`):this.tokens.matches1(Ht.TokenType.string)||this.tokens.matches1(Ht.TokenType.num)?(this.tokens.copyTokenWithPrefix(`${i[c].initializerName}() {this[`),f=!0):this.tokens.copyTokenWithPrefix(`${i[c].initializerName}() {this.`);this.tokens.currentIndex()<i[c].end;)f&&this.tokens.currentIndex()===i[c].equalsIndex&&this.tokens.appendCode("]"),this.processToken();this.tokens.appendCode("}"),c++}else if(u<l.length&&this.tokens.currentIndex()>=l[u].start){for(this.tokens.currentIndex()<l[u].end&&this.tokens.removeInitialToken();this.tokens.currentIndex()<l[u].end;)this.tokens.removeToken();u++}else this.tokens.currentIndex()===o?(this.tokens.copyToken(),p&&this.tokens.appendCode(`;${this.makeConstructorInitCode(s,a,n)};`),this.processToken()):this.processToken();this.tokens.copyExpectedToken(Ht.TokenType.braceR)}makeConstructorInitCode(t,n,r){return[...t,...n.map(o=>`${r}.prototype.${o}.call(this)`)].join(";")}processPossibleArrowParamEnd(){if(this.tokens.matches2(Ht.TokenType.parenR,Ht.TokenType.colon)&&this.tokens.tokenAtRelativeIndex(1).isType){let t=this.tokens.currentIndex()+1;for(;this.tokens.tokens[t].isType;)t++;if(this.tokens.matches1AtIndex(t,Ht.TokenType.arrow)){for(this.tokens.removeInitialToken();this.tokens.currentIndex()<t;)this.tokens.removeToken();return this.tokens.replaceTokenTrimmingLeftWhitespace(") =>"),!0}}return!1}processPossibleAsyncArrowWithTypeParams(){if(!this.tokens.matchesContextual(pF.ContextualKeyword._async)&&!this.tokens.matches1(Ht.TokenType._async))return!1;let t=this.tokens.tokenAtRelativeIndex(1);if(t.type!==Ht.TokenType.lessThan||!t.isType)return!1;let n=this.tokens.currentIndex()+1;for(;this.tokens.tokens[n].isType;)n++;if(this.tokens.matches1AtIndex(n,Ht.TokenType.parenL)){for(this.tokens.replaceToken("async ("),this.tokens.removeInitialToken();this.tokens.currentIndex()<n;)this.tokens.removeToken();return this.tokens.removeToken(),this.processBalancedCode(),this.processToken(),!0}return!1}processPossibleTypeRange(){if(this.tokens.currentToken().isType){for(this.tokens.removeInitialToken();this.tokens.currentToken().isType;)this.tokens.removeToken();return!0}return!1}shiftMappings(t,n){for(let r=0;r<t.length;r++){let o=t[r];o!==void 0&&(t[r]=o+n)}return t}};Tm.default=vm});var o_=Ie(Qi=>{"use strict";Qi.__esModule=!0;Qi.LinesAndColumns=void 0;var tc=`
|
|
137
|
+
`,n_="\r",r_=(function(){function e(t){this.string=t;for(var n=[0],r=0;r<t.length;)switch(t[r]){case tc:r+=tc.length,n.push(r);break;case n_:r+=n_.length,t[r]===tc&&(r+=tc.length),n.push(r);break;default:r++;break}this.offsets=n}return e.prototype.locationForIndex=function(t){if(t<0||t>this.string.length)return null;for(var n=0,r=this.offsets;r[n+1]<=t;)n++;var o=t-r[n];return{line:n,column:o}},e.prototype.indexForLocation=function(t){var n=t.line,r=t.column;return n<0||n>=this.offsets.length||r<0||r>this.lengthOfLine(n)?null:this.offsets[n]+r},e.prototype.lengthOfLine=function(t){var n=this.offsets[t],r=t===this.offsets.length-1?this.string.length:this.offsets[t+1];return r-n},e})();Qi.LinesAndColumns=r_;Qi.default=r_});var s_=Ie(xm=>{"use strict";Object.defineProperty(xm,"__esModule",{value:!0});function NF(e){return e&&e.__esModule?e:{default:e}}var jF=o_(),DF=NF(jF),BF=et();function qF(e,t){if(t.length===0)return"";let n=Object.keys(t[0]).filter(p=>p!=="type"&&p!=="value"&&p!=="start"&&p!=="end"&&p!=="loc"),r=Object.keys(t[0].type).filter(p=>p!=="label"&&p!=="keyword"),o=["Location","Label","Raw",...n,...r],s=new DF.default(e),i=[o,...t.map(l)],a=o.map(()=>0);for(let p of i)for(let f=0;f<p.length;f++)a[f]=Math.max(a[f],p[f].length);return i.map(p=>p.map((f,h)=>f.padEnd(a[h])).join(" ")).join(`
|
|
138
|
+
`);function l(p){let f=e.slice(p.start,p.end);return[u(p.start,p.end),BF.formatTokenType.call(void 0,p.type),UF(String(f),14),...n.map(h=>c(p[h],h)),...r.map(h=>c(p.type[h],h))]}function c(p,f){return p===!0?f:p===!1||p===null?"":String(p)}function u(p,f){return`${d(p)}-${d(f)}`}function d(p){let f=s.locationForIndex(p);return f?`${f.line+1}:${f.column+1}`:"Unknown"}}xm.default=qF;function UF(e,t){return e.length>t?`${e.slice(0,t-3)}...`:e}});var i_=Ie(Sm=>{"use strict";Object.defineProperty(Sm,"__esModule",{value:!0});function GF(e){return e&&e.__esModule?e:{default:e}}var Cn=et(),HF=Ei(),zF=GF(HF);function WF(e){let t=new Set;for(let n=0;n<e.tokens.length;n++)e.matches1AtIndex(n,Cn.TokenType._import)&&!e.matches3AtIndex(n,Cn.TokenType._import,Cn.TokenType.name,Cn.TokenType.eq)&&KF(e,n,t);return t}Sm.default=WF;function KF(e,t,n){t++,!e.matches1AtIndex(t,Cn.TokenType.parenL)&&(e.matches1AtIndex(t,Cn.TokenType.name)&&(n.add(e.identifierNameAtIndex(t)),t++,e.matches1AtIndex(t,Cn.TokenType.comma)&&t++),e.matches1AtIndex(t,Cn.TokenType.star)&&(t+=2,n.add(e.identifierNameAtIndex(t)),t++),e.matches1AtIndex(t,Cn.TokenType.braceL)&&(t++,VF(e,t,n)))}function VF(e,t,n){for(;;){if(e.matches1AtIndex(t,Cn.TokenType.braceR))return;let r=zF.default.call(void 0,e,t);if(t=r.endIndex,r.isType||n.add(r.rightName),e.matches2AtIndex(t,Cn.TokenType.comma,Cn.TokenType.braceR))return;if(e.matches1AtIndex(t,Cn.TokenType.braceR))return;if(e.matches1AtIndex(t,Cn.TokenType.comma))t++;else throw new Error(`Unexpected token: ${JSON.stringify(e.tokens[t])}`)}}});var c_=Ie(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});function io(e){return e&&e.__esModule?e:{default:e}}var JF=L0(),XF=io(JF),QF=q0(),YF=io(QF),ZF=U0(),eO=z0(),a_=io(eO),tO=K0(),nO=io(tO),rO=dw(),oO=Lp(),sO=Rk(),iO=io(sO),aO=t_(),lO=io(aO),cO=s_(),uO=io(cO),dO=i_(),pO=io(dO);function mO(){return"3.35.1"}Yi.getVersion=mO;function fO(e,t){rO.validateOptions.call(void 0,t);try{let n=l_(e,t),o=new lO.default(n,t.transforms,!!t.enableLegacyBabel5ModuleInterop,t).transform(),s={code:o.code};if(t.sourceMapOptions){if(!t.filePath)throw new Error("filePath must be specified when generating a source map.");s={...s,sourceMap:YF.default.call(void 0,o,t.filePath,t.sourceMapOptions,e,n.tokenProcessor.tokens)}}return s}catch(n){throw t.filePath&&(n.message=`Error transforming ${t.filePath}: ${n.message}`),n}}Yi.transform=fO;function hO(e,t){let n=l_(e,t).tokenProcessor.tokens;return uO.default.call(void 0,e,n)}Yi.getFormattedTokens=hO;function l_(e,t){let n=t.transforms.includes("jsx"),r=t.transforms.includes("typescript"),o=t.transforms.includes("flow"),s=t.disableESTransforms===!0,i=oO.parse.call(void 0,e,n,r,o),a=i.tokens,l=i.scopes,c=new nO.default(e,a),u=new ZF.HelperManager(c),d=new iO.default(e,a,o,s,u),p=!!t.enableLegacyTypeScriptModuleInterop,f=null;return t.transforms.includes("imports")?(f=new XF.default(c,d,p,t,t.transforms.includes("typescript"),!!t.keepUnusedImports,u),f.preprocessTokens(),a_.default.call(void 0,d,l,f.getGlobalNames()),t.transforms.includes("typescript")&&!t.keepUnusedImports&&f.pruneTypeOnlyImports()):t.transforms.includes("typescript")&&!t.keepUnusedImports&&a_.default.call(void 0,d,l,pO.default.call(void 0,d)),{tokenProcessor:d,scopes:l,nameManager:c,importProcessor:f,helperManager:u}}});var ay=["solved","partly","failed"],ly=()=>({wrote:new Set,calls:0,failed:0}),zr=ly();function cy(){zr=ly()}function uy(){return{wrote:[...zr.wrote],calls:zr.calls,failed:zr.failed}}var z$=["out_path","output_path","out","destination","to","out_dir"],Wa=e=>typeof e=="string"&&(/^(~\/|\/)/.test(e)||/^[A-Za-z]:[\\/]/.test(e));function W$(e,t,n){if(n||t.isError)return[];let r=new Set;for(let i of z$)Wa(e[i])&&r.add(mt(e[i]));let o=t.structuredContent??{};if(Wa(o.csv_path)&&r.add(o.csv_path),Wa(o.folder)&&r.add(o.folder),Array.isArray(o.outputs))for(let i of o.outputs)i&&typeof i=="object"&&Wa(i.path)&&r.add(i.path);let s=t.content.map(i=>i.text).join(`
|
|
139
|
+
`);for(let i of s.matchAll(/^wrote (\/[^\s(]+?)\/?(?=[\s(]|$)/gm))r.add(i[1]);for(let i of s.matchAll(/→ (\/[^\s(]+)/g))r.add(i[1]);return[...r]}function dy(e,t,n){zr.calls++,t.isError&&zr.failed++;for(let r of W$(e,t,n))zr.wrote.add(r)}function K$(e){let t=[];for(let n of e.matchAll(/(?:^|[\s"'(`[])((?:~\/|\/)[^\s"'`)\]]+)/g)){let r=n[1].replace(/[.,;:!?]+$/,"");r.length>1&&!t.includes(r)&&t.push(r)}return t}async function py(e){let t=[],n=K$(e);for(let o of n)await Ye(mt(o))||t.push(`names a path this machine does not have: ${o}`);for(let o of zr.wrote){let s=o.replace(/\/$/,"");e.includes(fe(s))||n.some(a=>mt(a)===s||mt(a).startsWith(`${s}/`))||t.push(`the request wrote ${o} and the reply does not name it`)}let r=/\{[a-z][a-z0-9_]*\}/.exec(e);return r&&t.push(`a ${r[0]} placeholder is still in the reply (placeholders are for asked; the reply names the real thing)`),t}var V$=new Set(["begin","finish","find_verb","conform_learn","account_login","account_status","account_logout","account_telemetry","artist_profile"]),Ka=!1;function jD(e,t,n){return typeof t.asked=="string"&&t.asked.trim()?(Ka&&e==="begin"&&n?.(),Ka=!0,null):e==="finish"?(Ka=!1,null):Ka||V$.has(e)?null:ee(new P("begin_first","Start this user request with begin first: begin(asked = the user's message exactly as they wrote it (never reworded, shortened or with anything replaced: names and paths stay)), then call this tool again. End every request with finish(answer, outcome)."))}import my from"node:process";var J$=tt(),Mo=re(J$,"jobs"),ms=new Map;function X$(){let e=new Uint8Array(4);return crypto.getRandomValues(e),"job-"+Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}async function bi(e){try{await Ve(Mo),await Ke(re(Mo,`${e.id}.json`),JSON.stringify(e));let{result:t,...n}=e;await Ke(re(Mo,".current"),JSON.stringify(n))}catch{}}function yi(e,t,n){let r=new AbortController,o=new Date().toISOString(),s={id:X$(),verb:e,...n?{label:n}:{},pid:my.pid,status:"running",started_at:o,updated_at:o,phase:"starting",done:0,total:0},i=0,l=t((c,u,d)=>{s.done=c,s.total=u,s.phase=d,s.updated_at=new Date().toISOString();let p=Date.now();p-i>2e3&&(i=p,bi(s))},r.signal).then(c=>(s.status=c.isError?"failed":"done",s.result=c,s.error=c.isError?c.content[0]?.text:void 0,s.finished_at=new Date().toISOString(),bi(s),c),c=>{s.status=r.signal.aborted?"cancelled":"failed",s.error=c instanceof Error?c.message:String(c),s.finished_at=new Date().toISOString(),bi(s);let u={content:[{type:"text",text:`error: ${s.error}`}],isError:!0,structuredContent:{ok:!1,code:s.status==="cancelled"?"cancelled":"engine",message:s.error}};return s.result=u,u});return ms.set(s.id,{rec:s,ctrl:r,promise:l}),bi(s),s}function Du(e){return ms.get(e)?.promise??null}async function fy(e){let t=ms.get(e);if(t)return t.rec;try{return JSON.parse(await ct(re(Mo,`${e}.json`)))}catch{return null}}function Bu(e){let t=ms.get(e);return!t||t.rec.status!=="running"?!1:(t.ctrl.abort(),!0)}function Q$(e){try{return my.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function Y$(e){return e.status!=="running"||ms.has(e.id)?!1:e.pid?!Q$(e.pid):Date.now()-Date.parse(e.updated_at)>36e5}async function hy(){let e=new Map;try{await Ve(Mo);for await(let t of Ct(Mo))if(t.name.endsWith(".json"))try{let n=JSON.parse(await ct(re(Mo,t.name)));Y$(n)&&(Object.assign(n,{status:"failed",error:"interrupted: the process running it ended",finished_at:n.updated_at}),await bi(n)),e.set(n.id,n)}catch{}}catch{}for(let t of ms.values())e.set(t.rec.id,t.rec);return[...e.values()].sort((t,n)=>n.started_at.localeCompare(t.started_at)).slice(0,50)}function qu(e){let t=e.total?` ${Math.round(100*e.done/e.total)}%`:"";return`${e.id} ${e.verb} ${e.status} \u2014 ${e.phase}${t} (started ${e.started_at}${e.finished_at?`, finished ${e.finished_at}`:""})${e.error?`
|
|
140
|
+
${e.error}`:""}`}var Z$="klein4b-q8";function Ln(){return zt("CONFORM_AI_BALANCE")!=="0"}var wi="Autobalance is not in this release yet";async function gy(){return xa&&zt("CONFORM_AI_BALANCE")!=="0"?!0:iu((await ls()).tier)}var Gu=`Autobalance (part of Autocolor) is in the ${Mh.pro.name} plan`,eR="https://pub-ed884bfa772244d89e9b6178f3b8ec9a.r2.dev/klein4b-q8/v7/manifest.json",tR=["transformer.safetensors","vae.safetensors","balance.safetensors","exposure.safetensors","exposure_lora.sealed","yunet.safetensors","sface.safetensors","dinov2s.safetensors"],Ja={"darwin-arm64":["media-gen","mlx.metallib"],"linux-x64":["media-gen","libmlx.so","libmlxc.so"],"linux-arm64":["media-gen","libmlx.so","libmlxc.so"],"win32-x64":["media-gen.exe","mlx.dll","mlxc.dll"]},fs=()=>`${Xt()}-${ru()}`;function by(e,t){return e.files.filter(n=>!n.platform||n.platform===t)}function nR(e,t){let n=Ja[t]??[];return by(e,t).filter(r=>!tR.includes(r.name)&&!n.includes(r.name)&&!r.platform).map(r=>r.name)}var rR=["exposure.safetensors","exposure_lora.sealed"];async function yy(e){for(let t of rR)if(!await On(re(e.model,t)))return!1;return!0}var wy=["yunet.safetensors","sface.safetensors","dinov2s.safetensors"];async function ky(e){for(let t of wy)if(!await On(re(e.model,t)))return!1;return!0}var oR=16e9,Va=()=>re(tt(),"models",Z$);function ki(){return Ja[fs()]?nu()<oR?`the Autocolor model needs 16 GB of memory (this machine has ${Math.round(nu()/1e9)} GB)`:null:`the Autocolor model runs on Apple Silicon Macs, Linux and Windows (x64), not ${Xt()}/${ru()}`}async function Ar(){let e=zt("CONFORM_AI_MODEL")??Va(),t=zt("CONFORM_MEDIA_GEN")??re(Va(),Ja[fs()]?.[0]??"media-gen"),n={runner:t,model:e,preset:re(e,"balance.safetensors")};for(let r of[t,n.preset,re(e,"transformer.safetensors"),re(e,"vae.safetensors")])if(!await On(r))return null;return n}async function Xa(e={}){if(!Ln())throw new P("unsupported",`${wi}: nothing to download`);let t=ki();if(t)throw new Error(t);let n=e.manifestUrl??zt("CONFORM_AI_PACK_URL")??eR;if(!n)throw new Error("the Autocolor model has not been published yet (no pack manifest URL)");let r=await fetch(n);if(!r.ok)throw new Error(`could not read the Autocolor pack manifest (${r.status})`);let o=await r.json(),s=Va();await Ve(s);let i=Ja[fs()]??[],a=by(o,fs());if(!i.every(u=>a.some(d=>d.name===u)))throw new Error(`the published Autocolor pack has no runner for ${fs()} yet`);let l=nR(o,fs());if(l.length)throw new Error(`unexpected file in the Autocolor pack: ${l.join(", ")}`);for(let u of a){let d=re(s,u.name);if(await On(d)&&await su(d)===u.sha256)continue;let p=0;await Rh(new URL(u.url,n).href,d,(h,g)=>{let b=Math.floor(100*h/(g||u.bytes));b>=p+5&&(p=b,e.onProgress?.(`${u.name} ${b}% of ${(u.bytes/1e9).toFixed(2)} GB`))});let f=await su(d);if(f!==u.sha256)throw await Wt(d),new Error(`${u.name} failed its checksum (got ${f}); deleted, run again to re-download`);u.name==="media-gen"&&await br("chmod",["+x",d],()=>{})}let c=await Ar();if(!c)throw new Error("the Autocolor pack downloaded but is incomplete");return c}async function _y(e,t,n={}){let r=new Uint8Array(t.w*t.h*3);for(let l=0;l<r.length;l++)r[l]=Math.max(0,Math.min(255,Math.round(t.data[l]*255)));let o=await It("conform-ai-"),s=re(o,"in.rgb");await Gn(s,r);let i=[],a=Date.now();try{let l=await br(e.runner,["balance","--input-rgb",`${s}:${t.w}x${t.h}`,"--raw","u8","--model",e.model,"--preset",e.preset,"--edge",String(n.edge??512),"--seed",String(n.seed??376436993),"--steps",String(n.steps??3),"--sampler","sdcpp"],g=>i.push(g));if(l.code!==0&&/non-empty mlx_stream/.test(l.stderr))throw new Error(`the Autocolor model's GPU kernels (mlx.metallib) did not load on this macOS; delete ${Va()} and run color_match reference "ai" again to fetch the current pack`);if(l.code!==0)throw new Error(`the Autocolor model failed (exit ${l.code}): ${l.stderr.trim().slice(-400)}`);let c=l.stderr.match(/ (\d+)x(\d+) [\d.]+s/);if(!c)throw new Error(`the Autocolor model gave no output size: ${l.stderr.trim().slice(-200)}`);let[u,d]=[Number(c[1]),Number(c[2])],p=new Uint8Array(i.reduce((g,b)=>g+b.length,0)),f=0;for(let g of i)p.set(g,f),f+=g.length;if(p.length!==u*d*3)throw new Error(`the Autocolor model returned ${p.length} bytes for ${u}x${d}`);let h=new Float32Array(p.length);for(let g=0;g<p.length;g++)h[g]=p[g]/255;return{data:h,w:u,h:d,ms:Date.now()-a}}finally{await Wt(o).catch(()=>{})}}var Uu=[.2126,.7152,.0722];function vy(e,t,n=2){let r=(u,d)=>Uu[0]*Math.max(0,Math.min(1,u[d]))**2.4+Uu[1]*Math.max(0,Math.min(1,u[d+1]))**2.4+Uu[2]*Math.max(0,Math.min(1,u[d+2]))**2.4,o=[];for(let u=0;u<e.data.length;u+=3){let d=r(e.data,u);d>1e-5&&Math.max(e.data[u],e.data[u+1],e.data[u+2])<.99&&o.push(Math.log2(Math.max(r(t.data,u),1e-9)/Math.max(d,1e-9)))}if(o.length<64)return{image:t,askedStops:0,appliedStops:0};o.sort((u,d)=>u-d);let s=o.length,i=s%2?o[s-1>>1]:(o[s/2-1]+o[s/2])/2;if(Math.abs(i)<.01)return{image:t,askedStops:i,appliedStops:i};let a=i*Math.exp(-Math.abs(i)/n),l=2**(a-i),c=new Float32Array(t.data.length);for(let u=0;u<c.length;u++)c[u]=Math.min(1,(Math.max(0,Math.min(1,t.data[u]))**2.4*l)**(1/2.4));return{image:{data:c,w:t.w,h:t.h},askedStops:i,appliedStops:a}}async function Ty(e,t,n,r,o){let s=await It("conform-serve-"),i="",a="",l=[],c=$h(e.runner,["serve"],b=>{i+=new TextDecoder().decode(b);for(let k=i.indexOf(`
|
|
141
|
+
`);k>=0;k=i.indexOf(`
|
|
142
|
+
`)){let w=i.slice(0,k);i=i.slice(k+1),l.shift()?.(w)}},b=>{a=(a+b).slice(-4e3),n?.(b)});c.hold(!0);let u=!1;c.exited.then(()=>{u=!0;for(let b of l.splice(0))b(JSON.stringify({error:`media-gen serve exited: ${a.trim().slice(-400)}`}))});let d=async b=>{if(u)throw new Error(`media-gen serve is not running: ${a.trim().slice(-400)}`);let k=new Promise(y=>l.push(y));await c.write(new TextEncoder().encode(JSON.stringify(b)+`
|
|
143
|
+
`));let w=JSON.parse(await k);if(w.error)throw new Error(String(w.error));return w},p=zt("CONFORM_AUTOCOLOR_KEY"),f=r?p?(await ct(p)).trim():(await ls(),await Fh()):null;if(r&&!f){let b=await ls();throw b.signed_in&&iu(b.tier)&&!(await Ph()).length?new P("unsupported","this install has no machine ID (its native engine, conformtools-analyze, is missing), so Autobalance cannot be unlocked here: reinstall conform.tools, then run color prep again"):new P("not_entitled",`${Gu}: sign in with that plan (account_login), then run color prep again`)}let h=r?{preset:re(e.model,"exposure.safetensors"),...Array.isArray(r)?{view_cst:r}:{view_lut:r},model_key:f,loras:{exposure:re(e.model,"exposure_lora.sealed")}}:{preset:e.preset};await d({cmd:"open",model:e.model,consist:t,...h,...o??{}});let g=0;return{async balance(b,k={}){let w=new Uint8Array(b.w*b.h*3);for(let C=0;C<w.length;C++)w[C]=Math.max(0,Math.min(255,Math.round(b.data[C]*255)));let[y,_]=[re(s,`in${g}.rgb`),re(s,`out${g++}.rgb`)];await Gn(y,w);let v=await d({cmd:"balance",rgb:y,w:b.w,h:b.h,edge:k.edge??512,seed:k.seed??376436993,steps:k.steps??3,out:_}),T=await Ut(_);await Wt(y).catch(()=>{}),await Wt(_).catch(()=>{});let[$,x]=[Number(v.w),Number(v.h)];if(T.length!==$*x*3)throw new Error(`the Autocolor model returned ${T.length} bytes for ${$}x${x}`);let R=new Float32Array(T.length);for(let C=0;C<T.length;C++)R[C]=T[C]/255;return{data:R,w:$,h:x,ms:Number(v.ms)}},async step1(b){let k=await d({cmd:"step1",frame:b});return{values:k.values,ms:Number(k.ms)}},async p2(b){return(await d({cmd:"p2",shots:b})).values},async faces(b){let k=await d({cmd:"faces",shots:b,...Object.fromEntries(wy.map(w=>[w.split(".")[0].replace("dinov2s","dino"),re(e.model,w)]))});return{values:k.values,report:k.report}},async shot(b){return Number((await d({cmd:"shot",shot:b})).ms??0)},async finish(){return await d({cmd:"finish"})},close(){c.hold(!1),c.close(),dn(s).catch(()=>{})}}}var _i=new Set;function Wr(e){for(let t of _i)try{t(e)}catch{_i.delete(t)}}function sR(e){return _i.add(e),()=>_i.delete(e)}var xy=null,Ya=new Set,XD=e=>{xy={...e,at:new Date().toISOString()};for(let t of Ya)try{t(e)}catch{Ya.delete(t)}};function QD(e){return Ya.add(e),()=>Ya.delete(e)}var Sy=()=>xy,hs=()=>_i.size;function YD(){let e=new TextEncoder,t,n;return new ReadableStream({start(r){r.enqueue(e.encode(`: hello
|
|
144
|
+
|
|
145
|
+
`)),t=sR(o=>r.enqueue(e.encode(`data: ${JSON.stringify(o)}
|
|
146
|
+
|
|
147
|
+
`))),n=setInterval(()=>{try{r.enqueue(e.encode(`: .
|
|
148
|
+
|
|
149
|
+
`))}catch{t?.(),clearInterval(n)}},2e4)},cancel(){t?.(),clearInterval(n)}})}var Qa=new Map;function $y(e,t,n=8e3){let r=crypto.randomUUID();return new Promise(o=>{let s=setTimeout(()=>{Qa.delete(r),o({ok:!1,text:"the window did not answer (is it on a screen that is still loading?)"})},n);Qa.set(r,i=>{clearTimeout(s),Qa.delete(r),o(i)}),Wr({type:"ui",project:e,req_id:r,...t})})}function Ry(e,t){Qa.get(e)?.(t)}var Hu=["text","number","bool","choice","color","marker_color","file","files","folder","rename_steps","track","tracks","timeline","timelines","projects","render_preset","node","source","data"];var vi=e=>typeof e=="string"&&/^\$[A-Za-z_]/.test(e);var iR=m.object({id:m.string().regex(/^[a-z][a-z0-9_]*$/),label:m.string(),type:m.enum(Hu),choices:m.array(m.tuple([m.string(),m.string()])).optional().describe("choice: [value, label] pairs"),default:m.unknown().optional(),not:m.string().optional(),optional:m.boolean().optional(),placeholder:m.string().optional(),when:m.object({input:m.string(),is:m.array(m.string())}).optional(),hidden:m.boolean().optional()}),aR=m.object({id:m.string().regex(/^[a-z][a-z0-9_]*$/),use:m.string().describe("a block: verb.<verb>, resolve.pull, resolve.apply, rows.filter, review, plan.*"),args:m.record(m.unknown()).default({}),when:m.string().optional(),label:m.string().optional(),at:m.tuple([m.number(),m.number()]).optional()}),lR=["knobs","viewer","rows","result","compare","graphics","running"],Ay=m.lazy(()=>m.union([m.object({split:m.enum(["row","col"]),panes:m.array(Ay).min(1),size:m.number().positive().max(1).optional()}),m.object({pane:m.enum(lR),show:m.union([m.string(),m.array(m.string())]).optional(),title:m.string().optional(),size:m.number().positive().max(1).optional()})])),Ti=m.object({id:m.string().regex(/^[a-z][a-z0-9_-]{0,63}$/),name:m.string().min(1),group:m.string().default("Mine"),about:m.string().default(""),aka:m.array(m.string()).optional(),app:m.boolean().optional(),part:m.boolean().optional(),hidden:m.boolean().optional(),legacy:m.string().optional(),host:m.enum(Zt).optional(),pinned:m.boolean().optional(),output:m.enum(["timeline"]).optional(),playbook:m.string().optional(),preview:m.boolean().optional(),inputs:m.array(iR).default([]),nodes:m.array(aR).min(1),view:Ay.optional()}),Za=()=>re(tt(),"tools"),zu=e=>re(Za(),`${e}.json`);async function Io(){let e=new Map;try{for await(let o of Ct(Za()))if(o.name.endsWith(".json"))try{let s=Ti.parse(JSON.parse(await ct(re(Za(),o.name))));e.set(s.id,s)}catch{}}catch{}let t=[...ps,...$b(ys)],n=new Set(t.map(o=>o.id)),r=new Set((await gs()).hidden);return[...t.map(o=>e.has(o.id)?{...e.get(o.id),template:!1,shipped:!0}:{...Ti.parse(o),template:!0,shipped:!0}),...[...e.values()].filter(o=>!n.has(o.id)).map(o=>({...o,template:!1,shipped:!1}))].map(o=>({...o,hidden:r.has(o.id)||!!o.hidden||o.id==="autobalance"&&!Ln()}))}var cR=new Set(["rename_steps","files","tracks","timelines"]),Ey=e=>Object.fromEntries(e.inputs.map(t=>[t.id,t.default??(t.type==="bool"?!1:cR.has(t.type)?[]:"")]));async function wr(e){let t=(await Io()).find(n=>n.id===e);if(!t)throw new P("not_found",`no tool '${e}' (tool action=list)`);return t}function uR(e){let t=[],n=new Set(e.inputs.map(s=>s.id)),r=(s,i,a)=>{if(vi(s))for(let l of s.split("|").map(c=>c.trim())){if(/[[\]]/.test(l)){t.push(`${i}: '${l}' indexes a list; pass the whole list, or use a block that takes one (timeline.read_many)`);continue}let c=/^\$([a-z][a-z0-9_]*)(?:\.([A-Za-z0-9_.]+))?(?:=.*|!=.*)?$/.exec(l.replace(/(!=|=).*$/,""));if(!c){t.push(`${i}: '${l}' is not a reference ($in.x, $node, $node.field)`);continue}if(c[1]==="in"){let u=(c[2]??"").split(".")[0];n.has(u)||t.push(`${i}: no input '${u}'`)}else a.has(c[1])||t.push(`${i}: '$${c[1]}' is not an earlier node`)}else Array.isArray(s)?s.forEach(l=>r(l,i,a)):s&&typeof s=="object"&&Object.values(s).forEach(l=>r(l,i,a))},o=new Set;for(let s of e.nodes)r(s.args,s.id,o),s.when&&r(s.when,s.id,o),o.add(s.id);for(let s of e.inputs)s.when&&!n.has(s.when.input)&&t.push(`input ${s.id}: shown when '${s.when.input}', which is not an input`);return t}async function Wu(e,t){let n=Ti.safeParse(e);if(!n.success)throw new P("invalid_args",`not a tool: ${n.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join("; ")}`);let r=n.data,o=new Set;for(let i of r.nodes){if(o.has(i.id))throw new P("invalid_args",`two nodes are called '${i.id}'`);if(o.add(i.id),!t(i.use))throw new P("invalid_args",`node '${i.id}' uses '${i.use}', which is not a block (tool action=blocks)`)}let s=uR(r);if(s.length)throw new P("invalid_args",`the wiring is off: ${s.join("; ")}`);return await Ve(Za()),await Ke(zu(r.id),JSON.stringify(r,null,2)),r}async function My(e){if(!/^[a-z][a-z0-9_-]{0,63}$/.test(e))return!1;try{await ct(zu(e))}catch{return!1}return await Wt(zu(e)),!0}var el=m.object({hidden:m.array(m.string()).default([]),favourites:m.array(m.string()).nullable().default(null)}),Iy=()=>re(tt(),"tool-layout.json");async function gs(){try{return el.parse(JSON.parse(await ct(Iy())))}catch{return el.parse({})}}async function tl(e){let t=el.partial().safeParse(e);if(!t.success)throw new P("invalid_args",`not a layout: ${t.error.issues.map(r=>`${r.path.join(".")}: ${r.message}`).join("; ")}`);let n=el.parse({...await gs(),...Object.fromEntries(Object.entries(t.data).filter(([,r])=>r!==void 0))});return await Ve(tt()),await Ke(Iy(),JSON.stringify(n,null,2)),n}async function nl(e){let t=await gs();!t.favourites||t.favourites.includes(e)||await tl({favourites:[...t.favourites,e]})}var Cy=m.union([m.object({host:m.enum(Zt)}),m.object({session_id:m.string(),name:m.string().optional()}),m.object({path:m.string()})]),rl=m.object({open:m.array(m.string()).default([]).transform(e=>e.slice(-1)),source:Cy.nullable().default(null),sources:m.record(Cy).default({}),settings:m.record(m.record(m.unknown())).default({})}),Py=e=>re(tt(),"projects",e.replace(/[^\w-]/g,"_"),"workspace.json");async function ol(e){try{return rl.parse(JSON.parse(await ct(Py(e))))}catch{return null}}async function bs(e,t){let n=rl.safeParse(t);if(!n.success)throw new P("invalid_args",`not a workspace: ${n.error.issues.map(r=>`${r.path.join(".")}: ${r.message}`).join("; ")}`);return await Ve(re(tt(),"projects",e.replace(/[^\w-]/g,"_"))),await Ke(Py(e),JSON.stringify(n.data,null,2)),Wr({type:"workspace",project:e,workspace:n.data}),n.data}var Fy=1;async function Oy(e,t){if(!e.length)throw new P("invalid_args","export needs the tool ids");let n=await Io(),r=e.map(s=>{let i=n.find(d=>d.id===s);if(!i)throw new P("not_found",`no tool '${s}'`);let{template:a,shipped:l,hidden:c,...u}=i;return u}),o=/\.json$/i.test(t)?t:`${t}.json`;return await Ke(o,JSON.stringify({conformtools_tools:Fy,tools:r},null,2)),{path:o,tools:r.map(s=>s.id)}}async function Ly(e,t){let n;try{n=JSON.parse(await ct(e))}catch(i){throw new P("invalid_args",`not a recipe file: ${i.message}`)}let r=n,o=Array.isArray(r.tools)?r.tools:[n];if(typeof r.conformtools_tools=="number"&&r.conformtools_tools>Fy)throw new P("invalid_args","this recipe file is from a newer conform.tools: update the app");let s=[];for(let i of o)s.push(await Wu(i,t));return s}var sl=[["open","Open"],["fixed","Fixed"],["intent","Artistic intent"],["best_available","Best available"],["wont_fix","Won't fix"],["not_issue","Not an issue"]],vt=e=>String(e??"").replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]);function Ny(e,t){let n=t.filter(l=>!l.decision),r=t.filter(l=>l.decision),o=e.verdict??(n.some(l=>/fail/i.test(l.severity??""))?"FAIL":n.length?"CHECK":"PASS"),s=new Map;for(let l of n)s.set(l.kind||"finding",(s.get(l.kind||"finding")??0)+1);let i=(e.when??new Date).toISOString().replace("T"," ").slice(0,16),a=o==="PASS"?"#1f8a4c":o==="FAIL"?"#c0392b":"#b7791f";return`<!doctype html>
|
|
150
|
+
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
|
151
|
+
<title>QC \xB7 ${vt(e.subject)}</title>
|
|
152
|
+
<style>
|
|
153
|
+
body { font: 14px/1.45 -apple-system, "Segoe UI", Helvetica, Arial, sans-serif; color: #1b1b1b; margin: 32px; }
|
|
154
|
+
h1 { font-size: 20px; margin: 0 0 4px; } .meta { color: #666; margin-bottom: 18px; }
|
|
155
|
+
.verdict { display: inline-block; padding: 3px 10px; border-radius: 4px; color: #fff; background: ${a}; font-weight: 600; }
|
|
156
|
+
table { border-collapse: collapse; width: 100%; margin-top: 14px; } th, td { text-align: left; padding: 5px 8px; border-bottom: 1px solid #e3e3e3; vertical-align: top; }
|
|
157
|
+
th { font-weight: 600; background: #f6f6f6; } td.tc { font-family: ui-monospace, Menlo, monospace; white-space: nowrap; }
|
|
158
|
+
.sev-FAIL { color: #c0392b; font-weight: 600; } .sev-WARN, .sev-CHECK { color: #b7791f; }
|
|
159
|
+
.counts span { margin-right: 14px; } td.ev img { width: 192px; border-radius: 3px; display: block; } @media print { body { margin: 12mm; } }
|
|
160
|
+
</style></head><body>
|
|
161
|
+
<h1>${vt(e.subject)}</h1>
|
|
162
|
+
<div class="meta">Checked against <b>${vt(e.spec)}</b> \xB7 ${vt(i)}${e.by?` \xB7 ${vt(e.by)}`:""}</div>
|
|
163
|
+
<p><span class="verdict">${vt(o)}</span> ${n.length} finding${n.length===1?"":"s"}</p>
|
|
164
|
+
${s.size?`<p class="counts">${[...s].map(([l,c])=>`<span>${vt(l)}: <b>${c}</b></span>`).join("")}</p>`:""}
|
|
165
|
+
${e.summary?`<pre style="white-space:pre-wrap;color:#444">${vt(e.summary)}</pre>`:""}
|
|
166
|
+
${n.length?`<table><thead><tr><th>#</th><th>In</th><th>Out</th><th>Finding</th><th></th><th>Clip</th><th>Measured</th>${n.some(l=>l.evidence)?"<th>Frame</th>":""}</tr></thead><tbody>
|
|
167
|
+
${n.map((l,c)=>`<tr><td>${c+1}</td><td class="tc">${vt(l.tc)}</td><td class="tc">${vt(l.out)}</td><td>${vt(l.kind)}</td><td class="sev-${vt((l.severity??"").toUpperCase())}">${vt(l.severity)}</td><td>${vt(l.clip)}</td><td>${vt(l.detail)}</td>${n.some(u=>u.evidence)?`<td class="ev">${l.evidence?.startsWith("data:image/")?`<img alt="" src="${vt(l.evidence)}">`:""}</td>`:""}</tr>`).join(`
|
|
168
|
+
`)}
|
|
169
|
+
</tbody></table>`:"<p>Nothing found.</p>"}
|
|
170
|
+
${r.length?`<h2 style="font-size:16px;margin-top:28px">Reviewed (${r.length}, not counted)</h2>
|
|
171
|
+
<table><thead><tr><th>In</th><th>Out</th><th>Finding</th><th>Clip</th><th>Measured</th><th>Decision</th></tr></thead><tbody>
|
|
172
|
+
${r.map(l=>`<tr><td class="tc">${vt(l.tc)}</td><td class="tc">${vt(l.out)}</td><td>${vt(l.kind)}</td><td>${vt(l.clip)}</td><td>${vt(l.detail)}</td><td><b>${vt(l.decision)}</b></td></tr>`).join(`
|
|
173
|
+
`)}
|
|
174
|
+
</tbody></table>`:""}
|
|
175
|
+
<p class="meta" style="margin-top:24px">conform.tools</p>
|
|
176
|
+
</body></html>
|
|
177
|
+
`}function jy(e,t,n,r="",o=new Date){let s=o.toISOString().replace("T"," ").slice(0,16),i=t.filter(([a])=>n.some(l=>l[a]!==""&&l[a]!=null&&l[a]!==!1));return`<!doctype html>
|
|
178
|
+
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
|
179
|
+
<title>${vt(e)}</title>
|
|
180
|
+
<style>
|
|
181
|
+
body { font: 14px/1.45 -apple-system, "Segoe UI", Helvetica, Arial, sans-serif; color: #1b1b1b; margin: 32px; }
|
|
182
|
+
h1 { font-size: 20px; margin: 0 0 4px; } .meta { color: #666; margin-bottom: 18px; }
|
|
183
|
+
table { border-collapse: collapse; width: 100%; } th, td { text-align: left; padding: 5px 8px; border-bottom: 1px solid #e3e3e3; vertical-align: top; }
|
|
184
|
+
th { font-weight: 600; background: #f6f6f6; } @media print { body { margin: 12mm; } }
|
|
185
|
+
</style></head><body>
|
|
186
|
+
<h1>${vt(e)}</h1>
|
|
187
|
+
<div class="meta">${vt(s)} \xB7 ${n.length} row${n.length===1?"":"s"}${r?` \xB7 ${vt(r)}`:""}</div>
|
|
188
|
+
${n.length?`<table><thead><tr>${i.map(([,a])=>`<th>${vt(a)}</th>`).join("")}</tr></thead><tbody>
|
|
189
|
+
${n.map(a=>`<tr>${i.map(([l])=>`<td>${vt(a[l])}</td>`).join("")}</tr>`).join(`
|
|
190
|
+
`)}
|
|
191
|
+
</tbody></table>`:"<p>Nothing.</p>"}
|
|
192
|
+
<p class="meta" style="margin-top:24px">conform.tools</p>
|
|
193
|
+
</body></html>
|
|
194
|
+
`}import{gunzipSync as dR}from"node:zlib";function By(e,t){if(!t.tracks?.length)return;let n=e.timelines.find(r=>r.name===t.timeline)??e.timelines[0];if(n)for(let r of["video","audio"]){let o=n.tracks.filter(s=>(s.kind??"").toLowerCase()===r).sort((s,i)=>(s.track_index??0)-(i.track_index??0));for(let s of t.tracks.filter(i=>i.kind===r)){let i=o[s.index-1];i&&(typeof s.enabled=="boolean"&&(i.enabled=s.enabled),s.name&&!/^(Video|Audio) \d+$/.test(s.name)&&(i.name=s.name))}}}async function pR(){return(await sn("ps",["-axo","pid=,args="])).stdout.split(`
|
|
195
|
+
`).map(t=>t.trim()).filter(Boolean).map(t=>{let n=t.indexOf(" ");return{pid:Number(t.slice(0,n)),args:t.slice(n+1)}})}async function mR(){let e=`ObjC.import("CoreGraphics");
|
|
196
|
+
const a = $.CGWindowListCopyWindowInfo($.kCGWindowListOptionAll, 0);
|
|
197
|
+
const arr = ObjC.deepUnwrap(ObjC.castRefToObject(a)) || [];
|
|
198
|
+
JSON.stringify(arr.filter(w => w.kCGWindowName).map(w => ({ pid: w.kCGWindowOwnerPID, owner: w.kCGWindowOwnerName, title: w.kCGWindowName })));`;if(Xt()!=="darwin")return[];let t=await sn("osascript",["-l","JavaScript","-e",e]);try{return JSON.parse(t.stdout.trim())}catch{return[]}}async function Vu(e){return(await sn("lsof",["-p",String(e),"-Fn"])).stdout.split(`
|
|
199
|
+
`).filter(n=>n.startsWith("n/")).map(n=>n.slice(1))}var Ku=e=>new Date(e).toISOString();async function fR(e,t){let n=e.find(o=>/DaVinci Resolve\.app\/Contents\/MacOS\/Resolve(\s|$)|\\Resolve\.exe\b/.test(o.args)),r={host:"resolve",running:!!n,pid:n?.pid,notes:[]};return n?await hR(r,t):r}async function hR(e,t){let n=re(t,`resolve_current_${Date.now()}.drt`),r=await Ou("current",{},6e4),o;r.why!=="bridge"&&(o=r,r.ok&&r.timeline&&(o.exported=(await Ou("export",{out_path:n},6e4)).ok));let s=o?.db,i=s?.DbType?`the ${s.DbType==="Disk"?"local":s.DbType} project library${s.DbName?` "${s.DbName}"`:""}${s.IpAddress?` on ${s.IpAddress}`:""}`:"its project library";if(!o)return e.notes.push(`Resolve holds ${i}, and its scripting door could not be reached (${r.detail??"no answer"}). Export the timeline as a .drt from Resolve (File > Export > Timeline) and read that file.`),e;if(!o.ok){let l=o.why==="no_project"?"no project is open (only the Project Manager)":o.why==="no_connection"?"Resolve refused the local scripting connection (Preferences > System > General > External scripting using: Local)":`the Resolve scripting module is not installed (${o.detail??""})`;return e.notes.push(`Resolve holds ${i}; ${l}. Or export the timeline as a .drt from Resolve (File > Export > Timeline) and read that file.`),e}if(e.project=o.project,e.timelines=o.timelines,!o.timeline)return e.notes.push("no timeline is open in the viewer"),e;if(e.timeline=o.timeline,r.ok&&(e.tracks=r.tracks),!o.exported||!await Ye(n))return e.notes.push(`Resolve holds ${i}; it named the open timeline but its .drt export failed. Export it from Resolve (File > Export > Timeline) and read that file.`),e;let a=re(t,`${Dy(o.project??"resolve")}__${Dy(o.timeline)}.drt`);return await vo(n,a),e.read={path:a,format:"drt"},e.notes.push(`project in ${i}: the timeline was exported by Resolve itself (its own .drt of the current state, including unsaved edits)`),e}async function gR(e,t){let n=e.find(u=>/Adobe Premiere Pro( \d{4})?\.app\/Contents\/MacOS\/Adobe Premiere Pro|\\Adobe Premiere Pro\.exe\b/.test(u.args)),r={host:"premiere",running:!!n,pid:n?.pid,notes:[]};if(!n)return r;let s=t.find(u=>u.pid===n.pid&&/\.prproj/i.test(u.title))?.title?.replace(/\s*\*\s*$/,"").replace(/^.*?((?:\/|[A-Za-z]:[\\/]|\\\\).*\.prproj).*$/i,"$1");if(!s){if(t.some(u=>u.pid===n.pid&&u.title))return r.notes.push("Premiere is running with no project window (home screen)."),r;if(s=await bR(),!s)return r.notes.push("Premiere's window titles are hidden from this app (macOS: give it Screen Recording in System Settings \u203A Privacy & Security) and Premiere's recent-projects list names no project."),r;r.notes.push("window titles are hidden from this app (macOS Screen Recording permission), so the project is taken from Premiere's recent-projects list: the last one it opened, not confirmed open")}if(!await Ye(s))return r.notes.push(`window title names ${s} but it is not on disk`),r;r.project_path=s,r.project=fe(s).replace(/\.prproj$/i,""),r.read={path:s,format:"prproj"},await Ye(s.replace(/\.prproj$/i,".prlock"))&&r.notes.push("lock file present beside the project (project locking is on)");let i=await Ut(s),a=new TextDecoder().decode(i[0]===31&&i[1]===139?dR(i):i),l=[...a.matchAll(/<MZ\.PrefixKey\.OpenSequenceGuidList\.(\d+)>([0-9a-f-]{36})</g)].map(u=>({idx:Number(u[1]),uid:u[2]})).sort((u,d)=>u.idx-d.idx),c=u=>{let d=a.indexOf(`<Sequence ObjectUID="${u}"`);if(d<0)return null;let p=/<Name>([^<]*)<\/Name>/.exec(a.slice(d,d+2e4));return p?p[1]:null};return r.timelines=l.map(u=>c(u.uid)).filter(u=>!!u),r.timelines.length&&(r.timeline=r.timelines[0]),r.notes.push("last saved state of the project file (Premiere has no outside door to unsaved edits; the panel has)"),r.notes.push(r.timelines.length?"sequences open in the Timeline panel at the last save, in panel order; the first is taken as the active one":"the project file records no open sequences"),r}async function bR(){let e=re(ai(),"Documents","Adobe","Premiere Pro"),t;try{for await(let r of Ct(e))if(!(!r.isDirectory||!/^\d+\.\d+$/.test(r.name)))for await(let o of Ct(re(e,r.name))){if(!o.isDirectory||!o.name.startsWith("Profile-"))continue;let s=re(e,r.name,o.name,"Adobe Premiere Pro Prefs"),i=(await Bt(s).catch(()=>null))?.mtimeMs??0;i&&(!t||i>t.at)&&(t={at:i,path:s})}}catch{return}return t?/<BE\.Prefs\.MRU\.Document\.0>([^<]+\.prproj)</i.exec(await ct(t.path).catch(()=>""))?.[1]:void 0}async function yR(e,t,n){let r=e.find(p=>/AvidMediaComposer\.app\/Contents\/MacOS\/AvidMediaComposer(\s|$)|\\AvidMediaComposer\.exe\b/.test(p.args)),o={host:"avid",running:!!r,pid:r?.pid,notes:[]};if(!r)return o;let s=t.find(p=>p.pid===r.pid&&/Media Composer/.test(p.title))?.title??"",i=/Media Composer[^-]*-\s*([^-]+?)\s*(?:-|$)/.exec(s)?.[1]?.trim(),a=(await Vu(r.pid)).find(p=>/\.avp$/i.test(p))??(Xt()==="win32"&&i?await wR(i):void 0);if(!a)return o.notes.push(i?`project "${i}" per the window title, but ${Xt()==="win32"?"its .avp is not in Media Composer's project folders":"no .avp is held open"}`:"no project open"),o.project=i,o;o.project_path=a,o.project=fe(a).replace(/\.avp$/i,"");let l=xn(a),c=[];for await(let p of Ct(l))if(p.isFile&&/\.avb$/i.test(p.name)&&!p.name.startsWith("_")){let f=await Bt(re(l,p.name));c.push({path:re(l,p.name),modified_at:Ku(f.mtimeMs)})}c.sort((p,f)=>f.modified_at.localeCompare(p.modified_at)),o.bins=c;let u=c[0];if(n){for(let p of c.slice(0,12))if(await n(p.path,"avb")){u=p;break}}u&&(o.read={path:u.path,format:"avb"}),o.notes.push("Media Composer keeps the sequence loaded in the Timeline only in memory; bins are the saved state. The newest-modified bin holding a sequence is offered; pass another bin path to timeline_read to choose.");let d=re("/Users/Shared/AvidMediaComposer/Avid Attic",o.project,"Bins");if(await Ye(d)){let p=null;for await(let f of Ct(d)){if(!f.isDirectory)continue;let h=await Bt(re(d,f.name));(!p||h.mtimeMs>p.m)&&(p={name:f.name,m:h.mtimeMs})}p&&o.notes.push(`Attic: last bin autosaved while open was "${p.name.replace(/\.[^.]*$/,"")}" at ${Ku(p.m)}`)}return o}async function wR(e){let t=re(zt("PUBLIC")??"C:\\Users\\Public","Documents","Avid Media Composer");for(let n of["Shared Avid Projects","Avid Projects"]){let r=re(t,n,e,`${e}.avp`);if(await Ye(r))return r}}async function kR(e){let t=e.find(l=>/\/flame\.app\/Contents\/MacOS\/flame(\s|$)/.test(l.args)||/\/flame_\d{4}\/bin\/flame(\s|$)/.test(l.args)),n={host:"flame",running:!!t,pid:t?.pid,notes:[]};if(!t)return n;let r=/\s-J\s+(\S+)/.exec(t.args)?.[1],o=/\s-W\s+(\S+)/.exec(t.args)?.[1]??"Workspace";if(!r)return n.notes.push("Flame is running but its command line names no project (-J)"),n;n.project=r;let s=["/opt/Autodesk/project","/private/var/opt/Autodesk/flame/projects","/var/opt/Autodesk/flame/projects"],i=null;for(let l of s){let c=re(l,r,"catalog",`${o}.wksp`);if(await Ye(c)){i=c;break}}if(!i)return n.notes.push(`no catalog folder for project ${r} / workspace ${o} under ${s.join(", ")}`),n;n.project_path=i;let a=null;for await(let l of Ct(i))if(l.isFile&&/^\.#workspace\.\d+\.wks$/.test(l.name)){let c=await Bt(re(i,l.name));(!a||c.mtimeMs>a.m)&&(a={path:re(i,l.name),m:c.mtimeMs})}return a?(n.read={path:a.path,format:"flame"},n.notes.push(`live workspace file, written by Flame at ${Ku(a.m)}; holds the desktop's reels and sequences. Which sequence sits in the Timeline is not yet decoded \u2014 every sequence on the desktop is returned.`),n):(n.notes.push("no workspace file in the catalog"),n)}async function _R(e){let t=e.find(c=>/Final Cut Pro\.app\/Contents\/MacOS\/Final Cut Pro(\s|$)/.test(c.args)),n={host:"fcp",running:!!t,pid:t?.pid,notes:[]};if(!t)return n;let r=[...new Set((await Vu(t.pid)).map(c=>/^(.*?\.fcpbundle)(\/|$)/.exec(c)?.[1]).filter(c=>!!c))];if(!r.length)return n.notes.push("Final Cut is running with no library open"),n;n.timelines=[];let o=new Map;for(let c of r)for await(let u of Ct(c))if(!(!u.isDirectory||/\.(localized)$/.test(u.name)||u.name.startsWith("_")))for await(let d of Ct(re(c,u.name)))d.isDirectory&&!/^(Original Media|Render Files|Analysis Files|Transcoded Media|Shared Items)$/.test(d.name)&&await Ye(re(c,u.name,d.name,"CurrentVersion.fcpevent"))&&o.set(d.name,{library:c,event:u.name});let s=await sn("osascript",["-e",'tell application "System Events" to tell process "Final Cut Pro" to get value of every static text of group 1 of group 4 of splitter group 1 of group 1 of splitter group 1 of group 1 of splitter group 1 of window 2']),i=s.success?s.stdout.trim().split(", ").find(c=>o.has(c)):void 0;if(!i){let c=await sn("osascript",["-e",'tell application "System Events" to tell process "Final Cut Pro" to get entire contents of window 2']);for(let u of c.stdout.matchAll(/static text ([^,]+?) of group/g))if(o.has(u[1])){i=u[1];break}}let a=i?o.get(i):void 0;n.project=a?fe(a.library).replace(/\.fcpbundle$/,""):r.length===1?fe(r[0]).replace(/\.fcpbundle$/,""):void 0,n.project_path=a?.library??(r.length===1?r[0]:void 0),n.timeline=i,n.timelines=[...o.keys()],n.notes.push(`${r.length} librar${r.length===1?"y":"ies"} open: ${r.map(c=>fe(c)).join(" | ")}`),i&&a?n.notes.push(`project "${i}" is in event "${a.event}" of ${fe(a.library)}`):n.notes.push("could not read the Timeline title (no project loaded, or the accessibility layout differs)");let l=i&&a?re(a.library,a.event,i,"CurrentVersion.fcpevent"):void 0;return l&&await Ye(l)?(n.read={path:l,format:"fcpevent"},n.notes.push("read from the project's own store in the library (Final Cut saves it as you edit; read from a copy, the library is never written)")):i&&n.notes.push(`no project store found for "${i}"${l?` at ${l}`:""}`),n}function vR(e){let t=e.find(r=>/\/Baselight[^/]*\.app\/Contents\/MacOS\/|\/usr\/fl\/baselight[^ ]*\/bin\/baselight\b/i.test(r.args)),n={host:"baselight",running:!!t,pid:t?.pid,notes:[]};return t&&n.notes.push("the open scene is not read here (it lives in Baselight's scene database): host_export host=baselight reads it through FLAPI"),n}async function TR(e,t){let n=e.find(s=>/Pro Tools\.app\/Contents\/MacOS\/Pro Tools(\s|$)/.test(s.args)),r={host:"protools",running:!!n,pid:n?.pid,notes:[]};if(!n)return r;let o=(await Vu(n.pid)).find(s=>/\.ptx$/i.test(s));if(r.project=t.find(s=>s.pid===n.pid&&/^Edit: /.test(s.title))?.title.slice(6).trim()||void 0,!o){let s=await new zb().current();s&&(r.project=s.project,o=s.project_path||void 0)}return!o||!await Ye(o)?(r.notes.push(r.project?`session "${r.project}" has no saved .ptx found`:"no session open (or Pro Tools' scripting door did not answer)"),r):(r.project_path=o,r.project??=fe(o).replace(/\.ptx$/i,""),r.timeline=r.project,r.timelines=[r.project],r.read={path:o,format:"ptx"},r.notes.push("the session file as last saved; edits since the last save are not in it"),r)}var Dy=e=>e.replace(/[^\w.-]+/g,"_").slice(0,80);function xR(e=Xt()){return e==="darwin"||e==="linux"||e==="win32"?null:`host_current is not available on ${e} yet: it reads the process table and open files (ps, lsof), which this OS does not have. Export the timeline from the host and use timeline_read.`}async function qy(e,t,n){let r=xR();if(r)throw new P("unsupported",r);let o=e?.length?e:[...Zt],s=t??await It("conform-host-"),i=Xt()==="win32"?await Sh():null,a=i??await pR(),l=i?i.filter(u=>u.title):o.some(u=>u==="premiere"||u==="avid"||u==="protools")?await mR():[],c=[];for(let u of o)try{u==="resolve"?c.push(await fR(a,s)):u==="premiere"?c.push(await gR(a,l)):u==="avid"?c.push(await yR(a,l,n)):u==="flame"?c.push(await kR(a)):u==="baselight"?c.push(vR(a)):u==="protools"?c.push(await TR(a,l)):c.push(await _R(a))}catch(d){c.push({host:u,running:!0,notes:[`failed: ${d instanceof Error?d.message:String(d)}`]})}return c}function Ju(e){return e.map(t=>`${t.kind[0].toUpperCase()}${t.index}${t.name&&!/^(Video|Audio|Subtitle) \d+$/.test(t.name)?` ${t.name}`:""}${t.enabled===!1?" (off)":""}${t.locked?" (locked)":""}`).join(" | ")}function Uy(e){let t=[`${e.host}: ${e.running?`running (pid ${e.pid})`:"not running"}`];e.project&&t.push(` project: ${e.project}${e.project_path?` [${e.project_path}]`:""}`),e.timeline&&t.push(` open timeline: ${e.timeline}`),e.timelines?.length&&t.push(` timelines: ${e.timelines.join(" | ")}`),e.tracks?.length&&t.push(` tracks: ${Ju(e.tracks)}`),e.bins?.length&&t.push(` bins (newest first): ${e.bins.slice(0,8).map(n=>fe(n.path)).join(" | ")}${e.bins.length>8?` \u2026 +${e.bins.length-8}`:""}`),e.read&&t.push(` read as: ${e.read.format} ${e.read.path}`);for(let n of e.notes)t.push(` note: ${n}`);return t.join(`
|
|
200
|
+
`)}var zy={"YYYY-MM-DD":e=>`${e.Y}-${e.M}-${e.D}`,YYYYMMDD:e=>`${e.Y}${e.M}${e.D}`,YYMMDD:e=>`${e.y}${e.M}${e.D}`,"YYYY-MM-DD_HHMM":e=>`${e.Y}-${e.M}-${e.D}_${e.h}${e.m}`,YYYYMMDD_HHMMSS:e=>`${e.Y}${e.M}${e.D}_${e.h}${e.m}${e.s}`,HHMMSS:e=>`${e.h}${e.m}${e.s}`};function SR(e,t){let n=r=>String(r).padStart(2,"0");return zy[e]({Y:String(t.getFullYear()),y:n(t.getFullYear()%100),M:n(t.getMonth()+1),D:n(t.getDate()),h:n(t.getHours()),m:n(t.getMinutes()),s:n(t.getSeconds())})}var al="[\\p{L}\\p{N}]",$R=`(?<!${al})`,RR=`(?!${al})`,Gy=new RegExp(`${al}+(?:'${al}+)*`,"gu"),Xu=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),CR=e=>Array.from(e,t=>t==="*"?".*":t==="?"?".":Xu(t)).join(""),Hy=e=>(...t)=>{let n=t.slice(0,t.findIndex(r=>typeof r=="number"));return e.replace(/[$\\](\d+)|\\\\/g,(r,o)=>o===void 0?"\\":String(n[Number(o)]??""))};function il(e,t,n=!1){try{return new RegExp(e,(t?"g":"gi")+(n?"u":""))}catch(r){throw new Error(`Invalid regex: ${r.message}`)}}var Kr=e=>Array.from(e);function Wy(e,t){switch(t){case"upper":return e.toUpperCase();case"lower":return e.toLowerCase();case"title":return e.replace(Gy,n=>Kr(n)[0].toUpperCase()+Kr(n).slice(1).join("").toLowerCase());case"capitalize":return e.replace(Gy,n=>Kr(n)[0].toUpperCase()+Kr(n).slice(1).join(""));case"sentence":{let n=e.length-e.trimStart().length,r=Kr(e.slice(n));return r.length?e.slice(0,n)+r[0].toUpperCase()+r.slice(1).join("").toLowerCase():e}}throw new Error(`Unknown case mode: ${t}`)}function AR(e,t,n,r=new Date){switch(t.type){case"find_replace":{if(!t.find)return e;let o=t.regex?t.find:t.wildcard?CR(t.find):Xu(t.find),s=t.whole_word?il($R+o+RR,!!t.case_sensitive,!0):il(o,!!t.case_sensitive),i=t.replace??"";return e.replace(s,t.regex?Hy(i):()=>i)}case"regex_replace":return t.pattern?e.replace(il(t.pattern,t.case_sensitive??!0),Hy(t.replacement??"")):e;case"add_prefix":return(t.text??"")+e;case"add_suffix":return e+(t.text??"");case"insert":{if(!t.text)return e;let o=Kr(e),s=Math.max(0,Math.min(t.position??0,o.length)),i=t.from_end?o.length-s:s;return o.slice(0,i).join("")+t.text+o.slice(i).join("")}case"remove_text":return t.text?e.replace(il(Xu(t.text),!!t.case_sensitive),""):e;case"remove_chars":{let o=t.count??0;if(o<=0)return e;let s=Kr(e),i=s.length,a=t.mode??"from_end",l;if(a==="from_start")l=s.slice(o);else if(a==="from_end")l=s.slice(0,Math.max(0,i-o));else if(a==="from_position"){let c=t.position??0,u=Math.min(c>=0?c:Math.max(0,i+c),i);l=[...s.slice(0,u),...s.slice(u+o)]}else throw new Error(`Unknown remove mode: ${a}`);if(i&&!l.length)throw new Error(`Removing ${o} character(s) would leave an empty name`);return l.join("")}case"trim_whitespace":return e.replace(/\s+/gu," ").trim();case"change_case":return Wy(e,t.mode);case"substring":{let o=Kr(e),s=t.start??0,i=t.length??0,a=s>=0?s:Math.max(0,o.length+s);return(i<=0?o.slice(a):o.slice(a,a+i)).join("")}case"sequential_numbering":{let o=String((t.start??1)+n*(t.increment||1)).padStart(Math.max(1,t.pad??3),"0"),s=t.separator??"_";return t.position==="prefix"?o+s+e:e+s+o}case"add_date":{let o=t.format??"YYYY-MM-DD";if(!(o in zy))throw new Error(`Unknown date format: ${o}`);let s=t.separator??"_",i=SR(o,r);return t.position==="prefix"?i+s+e:e+s+i}}throw new Error(`Unknown rule type: ${t.type}`)}var ER=/^(.*?)([._-]?)(\d+)(\.[^.]+)$/u;function Qu(e,t,n={}){let r=t.filter(i=>i.enabled!==!1),o=e.map((i,a)=>{let l=n.sequence?ER.exec(i):null;if(n.sequence&&!l)return{old:i,new:i,dupe:!1};let c=l?l[1]:i,u=l?l[4]:"";try{for(let d of r){if(d.type==="set_extension"){l&&d.extension.trim()&&(u=`.${d.extension.trim().replace(/^\./,"")}`);continue}d.type==="change_case"&&l&&d.scope&&d.scope!=="name_only"&&(u=`.${Wy(u.slice(1),d.mode)}`,d.scope==="extension_only")||(c=AR(c,d,a,n.now))}}catch(d){return{old:i,new:i,dupe:!1,error:d.message}}return i&&!c?{old:i,new:i,dupe:!1,error:"The steps leave an empty name"}:{old:i,new:l?c+l[2]+l[3]+u:c,dupe:!1}}),s=new Map;for(let i of o)s.set(i.new,(s.get(i.new)??new Set).add(i.old));for(let i of o)i.new!==i.old&&s.get(i.new).size>1&&(i.dupe=!0);return o}function Ky(e,t){let n=o=>/^(.*?)([._])(\d+)(\.[A-Za-z0-9]+)$/.exec(o),r=new Map;for(let o of e){let s=n(o);if(s){let i=`${s[1]}${s[2]}|${s[4]}`;r.set(i,Math.min(r.get(i)??1/0,Number(s[3])))}}return e.map(o=>{let s=n(o);if(!s)return o;let i=`${s[1]}${s[2]}|${s[4]}`,a=Number(s[3]),l=t.start!=null?t.start+(a-r.get(i))*(t.increment??1):a+(t.offset??0);return l<0?o:`${s[1]}${s[2]}${String(l).padStart(t.digits&&t.digits>0?t.digits:s[3].length,"0")}${s[4]}`})}async function xi(e,t=new Map){return await Promise.all(e.map(async n=>{let r=String(n.cells.target_url??"");if(Number(n.cells["available_range.dur"])>0||!r)return n;t.has(r)||t.set(r,Po("media_probe",{path:r}).then(s=>{let i=s?.structuredContent?.available_range;return i?{start:i.start.value,dur:i.duration.value,rate:i.start.rate}:null},()=>null));let o=await t.get(r);return o?{...n,cells:{...n.cells,"available_range.start":o.start,"available_range.dur":o.dur,"available_range.rate":o.rate}}:n}))}async function MR(e,t=new Map){let n=await ft(e),r=n.session.media_references??[],o=r.map((a,l)=>({id:String(l),cells:{target_url:a.target_url??"","available_range.dur":a.available_range?.duration?.value??0}})),s=await xi(o,t),i=0;s.forEach((a,l)=>{let c=r[l],u=Number(a.cells["available_range.dur"]);if(u>0&&!(Number(c.available_range?.duration?.value)>0)){let d=Number(a.cells["available_range.rate"])||c.source_fps||24;c.available_range={start:{value:Number(a.cells["available_range.start"]),rate:d},duration:{value:u,rate:d}},i++}}),i&&await Yt(n,`media lengths probed for ${i} file(s)`)}async function Vy(e){return{...e,media:await xi(e.media)}}async function qe(e,t,n={}){t=IR(e,t);let r=nn(e),o=r?m.object(r.inputSchema).safeParse(t):null;o?.success&&(t=o.data);let s=await Po(e,t,{signal:n.signal,progress:n.progress}),i=s.content.map(l=>l.text).join(`
|
|
201
|
+
`);if(s.isError)throw new P(s.structuredContent?.code??"engine",i.replace(/^error \[\w+\]: /,""));let a=s.structuredContent?.session_id??i.match(/session_id[:=]\s*([0-9a-f]{8})\b/)?.[1]??t.session_id;return{...s.structuredContent??{},...a?{session_id:a}:{},ok:!0,text:i}}function IR(e,t){let n=nn(e)?.inputSchema??{},r=o=>o instanceof m.ZodOptional||o instanceof m.ZodDefault||o instanceof m.ZodNullable?r(o._def.innerType):o;return Object.fromEntries(Object.entries(t).flatMap(([o,s])=>{if(s===""||s===null||Array.isArray(s)&&!s.length)return[];let i=n[o]?r(n[o]):void 0;return typeof s=="string"&&i instanceof m.ZodNumber&&s.trim()!==""&&Number.isFinite(Number(s))?[[o,Number(s)]]:typeof s=="string"&&i instanceof m.ZodUnion&&i._def.options.some(a=>a instanceof m.ZodNumber)&&/^\d+(\.\d+)?$/.test(s)?[[o,Number(s)]]:[[o,s]]}))}var Yu=(e,t)=>qe(e,t).catch(n=>({ok:!1,text:n.message})),PR={items:"items",apply:"apply",pool:"project"};function Er(e){return Zt.filter(t=>{let n=an(t);if(n.wired===!1||t==="protools"&&(e==="open"||e==="render"))return!1;let r=PR[e];return!r||typeof n[r]=="function"})}var sr={host:{type:"string",about:`the host: ${Zt.join(" | ")} (default resolve)`}},Ft=e=>String(e.host||"resolve"),ws=new Map,FR=4e3;async function OR(e,t){let n=await an(e).current?.().catch(()=>null);if(!n)return!0;let r=await t.catch(()=>null);return!!n.ok&&!!r&&n.timeline===r.timeline&&(n.project==null||n.project===r.project)}async function LR(e,t,n=!1){let r=`${e}\0${t??""}`,o=ws.get(r);if(!n&&o&&Date.now()-o.at<FR&&(t||await OR(e,o.live)))return o.live;let s=cg(Yu,t,e);return ws.set(r,{at:Date.now(),live:s}),s.catch(()=>ws.delete(r)),s}var Jy={clip_color:"Clip color",flags:"Flags",enabled:"Enable / disable",name:"Clip name",properties:"Properties (sizing, crop, opacity, retime)",metadata:"Media pool metadata",copy_grade:"Copy grade",copy_properties:"Copy properties",version:"Color version",color_group:"Color group",cache:"Render cache",fades:"Fades",normalize_audio:"Normalize audio",output_blanking:"Output blanking",drx:"Apply a .drx still",lut:"LUT on a node",marker_add:"Add marker",marker_update:"Change marker",marker_delete:"Delete marker",playhead:"Move the playhead",timeline_duplicate:"Duplicate the timeline",goto:"Go to",pool_rename:"Rename pool clip",pool_move:"Move pool clips",pool_delete:"Delete pool clips",pool_import:"Import into the pool",track_delete:"Delete a track",timeline_rename:"Rename timeline"};function NR(e,t){let{rows:n,...r}=t;return Array.isArray(n)?e.startsWith("pool_")?n.length?[{op:e,clips:n.map(o=>o.id),...r}]:[]:n.flatMap(o=>{let s="cells"in o?lg(o):typeof o.track=="number"?{kind:o.kind??"video",track:o.track,start:Number(o.start)}:null;if(s)return[{op:e,item:s,...r}];let i="cells"in o?Number(o.cells.frame):NaN;return Number.isFinite(i)?[{op:e,frame:i,...r}]:[]}):[{op:e,...r}]}async function jR(e,t,n,r,o){return await qe("host_render",{host:e,...t?{timeline:t}:{},...n},{signal:r.signal,progress:(i,a,l)=>r.progress?.(i,a,`${o} \xB7 ${l}`)}).catch(i=>({ok:!1,text:i.message}))}var Si={"source.file":{label:"Timeline file",group:"Sources",effect:!1,about:"Read a timeline file from any host (.drt .aaf .avb .prproj .fcpxml .xml .otio .edl, a Flame archive) into a session; `engine` local (this machine) or hosted.",params:{path:{type:"string",required:!0,about:"the timeline file"},engine:{type:"string"}},run:(e,t)=>qe("timeline_read",e,t)},"source.session":{label:"Project timeline",group:"Sources",effect:!1,about:"A timeline already in the project (a session read earlier, from Exchange, the chat, a pull).",params:{session_id:{type:"string",required:!0}},run:async e=>{let t=await ft(String(e.session_id));return{ok:!0,text:`${t.source_path.split(/[\\/]/).pop()} (${e.session_id})`,session_id:e.session_id,source_path:t.source_path}}},"transfer.inbox":{label:"Inbox",group:"Transfers",effect:!1,about:"What clients sent into the project through its links (bucket sends) and who is sharing live peer to peer: rows {from, label, sender, when, size, status}, for transfer.receive.",params:{project_id:{type:"string",required:!0}},run:async e=>{let t=await qe("project",{action:"show",project_id:e.project_id}),n=r=>r>=1e9?`${(r/1e9).toFixed(1)} GB`:`${(r/1e6).toFixed(1)} MB`;return[...(t.links??[]).filter(r=>r.peer).map(r=>({id:`live:${r.id}`,from:r.peer.ticket,cells:{label:`${r.label??"A client"} (live)`,sender:"",when:"now",size:"",status:"sharing",from:"peer to peer"}})),...(t.sessions??[]).map(r=>({id:r.id,from:`bucket:${r.id}`,cells:{label:r.label||"Send",sender:r.sender_email??"",when:r.created_at.slice(0,16).replace("T"," "),size:n(r.total_bytes),status:r.status,from:`bucket:${r.id}`}}))]}},"transfer.receive":{label:"Receive",group:"Transfers",effect:!0,about:"Open deliveries \u2014 `from` (a peer-to-peer ticket, bucket:<id>, a .iso path) or inbox rows \u2014 as = list | mount (live, sparse) | trims (cut the media into out_path) | iso (fetch the .iso into out_path).",params:{from:{type:"string"},rows:{type:"array"},as:{type:"string"},out_path:{type:"string"}},run:async(e,t)=>{let n=e.rows?e.rows.map(s=>s.from).filter(Boolean):e.from?[String(e.from)]:[];if(!n.length)throw new P("invalid_args","nothing to receive: wire an inbox, or give from");let r=[],o={};for(let[s,i]of n.entries()){let a=String(e.as??"list"),l=a==="iso"&&e.out_path&&!/\.iso$/i.test(String(e.out_path))?`${String(e.out_path).replace(/[\\/]$/,"")}/${i.replace(/^bucket:/,"").replace(/[^\w.-]+/g,"_").slice(0,40)}.iso`:e.out_path;t.progress?.(s,n.length,`${s+1}/${n.length}`),o=await qe("delivery_fetch",{from:i,as:a,...l?{out_path:l}:{}},t),r.push(String(o.text).split(`
|
|
202
|
+
`)[0])}return{...o,ok:!0,text:r.join(`
|
|
203
|
+
`)}}},"transfer.deliver":{label:"Deliver",group:"Transfers",effect:!0,about:"A timeline with its media, trimmed with handles, as a package: destination folder | iso | bucket (your bucket, recipients emailed) | p2p (served from this machine: a ticket to hand over).",params:{session_id:{type:"string",required:!0},destination:{type:"string",required:!0},handles:{type:"number"},out_path:{type:"string"},recipients:{type:"array"}},run:(e,t)=>qe("media_deliver",e,t)},"transfer.share":{label:"Share peer to peer",group:"Transfers",effect:!0,about:"Serve a file or folder on this machine peer to peer (encrypted, nothing uploaded) until stopped: answers the ticket the recipient opens.",params:{path:{type:"string",required:!0}},run:(e,t)=>qe("p2p_send",e,t)},"transfer.link":{label:"Client link",group:"Transfers",effect:!0,about:"A link a client sends into this project with (a small app named for you: their cut's media, trimmed, lands in the inbox).",params:{project_id:{type:"string",required:!0},label:{type:"string"},recipient_email:{type:"string"}},run:e=>qe("project_link",{action:"create",...e})},"ui.graphics":{label:"Graphics",group:"Make",effect:!1,about:"Lower thirds, locators, legal lines and end crawls designed over the timeline wired in (the designer opens in the knobs, the graphic draws on the viewer); its Render makes ProRes 4444 with alpha for every aspect and position.",params:{session_id:{type:"string"}},run:async e=>({ok:!0,text:"graphics",...e.session_id?{session_id:e.session_id}:{}})},"gfx.place":{label:"Graphics onto the timeline",group:"Make",effect:!0,hosts:["resolve"],about:"Lay a graphics package (gfx_make's answer) on a new track of the timeline read: one graphic after another from frame `at`, each in the position given (default the package's first) and the format that fits the timeline.",params:{package:{type:"object",required:!0,about:"gfx_make's answer"},from:{type:"object",about:"the timeline read (host.read)"},at:{type:"number",about:"the frame the first graphic starts on (default 0)"},position:{type:"string",about:"an anchor (bottom-left\u2026) or a list (its first); default the package's first"}},run:async(e,t)=>{let n=e.from??{},r=n.session_id?(await ft(String(n.session_id)).catch(()=>null))?.session.timelines.find(i=>i.kind!=="compound"):void 0,o=Array.isArray(e.position)?e.position[0]:e.position,s=zR(e.package,r?.resolution_w??void 0,r?.resolution_h??void 0,o,Number(e.at??0));if(!s.paths.length)throw new P("not_found","the package has no file for that position and format");return qe("host_apply",{host:"resolve",...n.timeline?{timeline:n.timeline}:{},ops:[{op:"pool_import",paths:s.paths,folder:s.folder,at:s.at}]},t)}},"host.read":{label:"Host: the open timeline",group:"Hosts",effect:!1,hosts:Er("read"),about:"Read the timeline open in the host (or `timeline`): clips, markers and media as rows, a session for the timeline blocks, and on Resolve the live items (clip color, flags, versions, groups) and tracks. `from` = a timeline wired in instead (another read, a file, any node with a session): the same rows from it.",params:{...sr,timeline:{type:"string",about:"a timeline by name; default the open one"},from:{type:"object",about:"a timeline wired in (a read, a file source, any node with a session_id)"},blanking:{type:"boolean",about:"Resolve: also the timeline's output blanking (Resolve shows its Color page for a moment to answer)"},fresh:{type:"boolean",about:"read the host now, not the read kept for a few seconds (a Refresh: what was changed in the host just now)"}},run:async e=>{let t=e.from,n=e.timeline&&t?.timeline&&t.timeline!==e.timeline?void 0:t,r=n&&Array.isArray(n.clips)&&Array.isArray(n.items)?n:n?.session_id?await ug(Yu,String(n.session_id),{timeline:String(n.source_path??"").split(/[\\/]/).pop()}):await LR(Ft(e),e.timeline,e.fresh===!0);if((r===n||e.blanking)&&r.host==="resolve"){let o=await Yu("host_items",{timeline:r.timeline,...e.blanking?{blanking:!0}:{}}).catch(()=>null);o?.playhead_tc&&(r.playhead=(At(String(o.playhead_tc),r.fps||24)??0)-Number(o.start_frame??r.start_frame??0)),e.blanking&&Object.assign(r,dg(o?.output_blanking,o?.raster))}for(let o of r.markers){o.cells.on=o.cells.item_id?"clip":"timeline";let s=Number(o.cells.frame),i=Math.max(1,Number(o.cells.frames??1));r.playhead!=null&&r.playhead>=s&&r.playhead<s+i&&(o.cells.at="playhead")}return pg(r)}},"host.apply":{label:"Host: apply edits",group:"Hosts",effect:!0,hosts:Er("apply"),about:"Carry out a batch of edits in the host, each read back; one undo for the batch.",params:{...sr,ops:{type:"array",required:!0},timeline:{type:"string"},source:{type:"object",about:"the read the edits are for: one from a file cannot be applied (write it instead)"}},run:async e=>{let t=e.source;if(t&&t.clips&&!t.host)throw new P("refused","this timeline came from a file, not a running host: its edits cannot be applied live (write it for a host instead)");let n=(e.ops??[]).flat().filter(Boolean);if(!n.length)return{ok:!0,text:"nothing to change",applied:0};let r=await qe("host_apply",{host:t?.host??Ft(e),timeline:e.timeline,ops:n});return ws.clear(),r}},"host.export_many":{label:"Host: read several timelines",group:"Hosts",effect:!1,hosts:Er("read"),about:"Export timelines of the open project by name (none = the open one), or every timeline in a media pool `bin` (Resolve; `subfolders` too): the first as session_id, the rest as sources for timeline.all_clips / timeline.join.",params:{...sr,timelines:{type:"array"},bin:{type:"string",about:"Resolve: every timeline in this media pool folder (0.9.5 All Clips' source)"},subfolders:{type:"boolean"},selected_bin:{type:"boolean",about:"Resolve: every timeline in the bin selected in the Media Pool; none there = the bin the open timeline is in (0.9.5 All Clips)"}},run:async e=>{let t=(e.timelines??[]).map(String).filter(s=>s.trim()),n=String(e.bin??"").replace(/^\/+|\/+$/g,"");if(n||e.selected_bin){if(Ft(e)!=="resolve")throw new P("unsupported",`${Ft(e)}: a bin of timelines is Resolve only (name the timelines)`);let s=await qe("host_project",{host:"resolve",clips:!0}),i=La(s.pool).filter(l=>l.type?.toLowerCase()==="timeline"),a=(l,c)=>i.filter(u=>u.folder===l||c&&(l===""||u.folder.startsWith(`${l}/`))).map(u=>u.name);if(!n&&e.selected_bin){let l=typeof s.selected_bin=="string"?s.selected_bin:null;if(n=l!=null&&a(l,e.subfolders===!0).length?l:i.find(c=>c.name===s.timeline)?.folder??l??"",!a(n,e.subfolders===!0).length)throw new P("not_found",`no timelines in the selected bin (${n||"Master"}) or the open timeline's`);t=[...t,...a(n,e.subfolders===!0)]}else t=[...t,...a(n,e.subfolders!==!1)];if(!t.length)throw new P("not_found",`no timelines in the bin ${n||"Master"}`)}let r=[],o=[];for(let s of t.length?t:[void 0]){let i=await qe("host_export",{host:Ft(e),...s?{timeline:s}:{}});r.push(String(i.session_id)),o.push(String(i.timeline??s??""))}return{ok:!0,text:`read ${r.length} timeline(s)${n||e.selected_bin?` in ${n||"Master"}`:""}`,session_id:r[0],sources:r.slice(1),sessions:r,timelines:o,...n||e.selected_bin?{bin:n||"Master"}:{},first:{host:Ft(e),timeline:o[0]}}}},"host.open":{label:"Host: open as a new timeline",group:"Hosts",effect:!0,hosts:Er("open"),about:"Bring a session's timeline(s) into the host as NEW timelines linked to the clips already in the project (nothing open is edited). timeline_ids = several (all_clips per resolution).",params:{...sr,session_id:{type:"string",required:!0},timeline_id:{type:"string"},timeline_ids:{type:"array"},name:{type:"string"},like:{type:"object",about:"the read the new timeline derives from: when it is this host's live timeline, the new one takes its settings, verified (Resolve)"},built:{type:"object",about:"the build node's answer (timeline.add_handles \u2026): its skipped clips are said again here, with how many landed"},read:{type:"object",about:"the read node's answer (host.export_many): which timelines, from which bin, said again here"}},run:async e=>{let t=e.timeline_ids?.length?e.timeline_ids:[e.timeline_id],n=e.like,r=n?.host===Ft(e)&&Ft(e)==="resolve"&&n.timeline?n.timeline:void 0,o=[],s={},i=[];for(let p of t)if(s=await qe("host_open",{host:Ft(e),session_id:e.session_id,...p?{timeline_id:p}:{},...e.name?{name:e.name}:{},link_existing:!0,...r?{settings_from:r}:{}}),o.push(String(s.text).split(`
|
|
204
|
+
`)[0]),Ft(e)==="resolve"&&s.timeline){let f=await ft(String(e.session_id)),g=((f.session.timelines.find(w=>w.id===p)??f.session.timelines.find(w=>w.kind!=="compound"))?.tracks??[]).filter(w=>w.kind==="Video").flatMap((w,y)=>w.items.filter(_=>_.kind==="clip"&&_.enabled!==!1).map(_=>`V${y+1}:${Math.round(_.timeline_range.start.value)}:${Math.round(_.timeline_range.duration.value)}`)),b=new Set(((await qe("host_items",{timeline:s.timeline,kind:"video"})).items??[]).map(w=>`V${w.track}:${w.start}:${w.end-w.start}`)),k=g.filter(w=>!b.has(w));k.length?(i.push(...k.map(w=>`${s.timeline} ${w}`)),o.push(`${k.length} of ${g.length} clip(s) did not land as built (track:start:length): ${k.slice(0,8).join(", ")}${k.length>8?" \u2026":""}`)):o.push(`all ${g.length} clip(s) landed as built`)}ws.clear();let a=e.built?.meta??{},l=a.skipped,c=Array.isArray(l)?l.map(p=>`${p.name??"?"} (${p.reason})`):Object.entries(l??{}).filter(([,p])=>p>0).map(([p,f])=>`${f} ${p.replace(/_/g," ")}`),u=Array.isArray(l)?l.length:Object.values(l??{}).reduce((p,f)=>p+f,0);u&&o.push(`${u} clip(s) skipped: ${c.slice(0,8).join(", ")}${c.length>8?" \u2026":""}`);let d=Number(o.join(`
|
|
205
|
+
`).match(/all (\d+) clip/)?.[1]??NaN);return{...s,ok:!0,text:o.join(`
|
|
206
|
+
`),...Number.isFinite(d)?{clips:d}:{},skipped:u,made:a,...e.read?{from:{timelines:e.read.timelines??[],bin:e.read.bin}}:{},...i.length?{not_landed:i}:{}}}},"host.render":{label:"Host: render jobs",group:"Hosts",effect:!0,hosts:Er("render"),about:"Render each job {name, in, out, target_dir, preset?} from `timeline` with the host's own renderer, one after another (only these jobs are queued; the artist's queue and Deliver settings stay). jobs may be review rows carrying `job`.",params:{...sr,timeline:{type:"string"},jobs:{type:"array",required:!0},queue:{type:"boolean",about:"Resolve: leave the jobs in the render queue for the artist (nothing rendered)"}},run:async(e,t)=>{let n=(e.jobs??[]).map(i=>({...i.job??i,...e.queue===!0?{queue:!0}:{}})),r=[],o=[];for(let[i,{name:a,in:l,out:c,...u}]of n.entries()){if(t.signal?.aborted){r.push("stopped");break}t.progress?.(i,n.length,`${i+1}/${n.length} ${a}`);let d=await jR(Ft(e),e.timeline,{name:a,range:{in:l,out:c},...u},t,`${i+1}/${n.length} ${a}`);r.push(`${a}: ${d.ok?e.queue===!0?"queued":"rendered":String(d.text).split(`
|
|
207
|
+
`)[0]}`),d.ok&&d.host_render_job&&o.push(String(d.host_render_job))}let s=i=>i.endsWith("rendered")||i.endsWith("queued");return{ok:r.every(s),text:r.join(`
|
|
208
|
+
`)||"nothing to render",rendered:r.filter(s).length,job_ids:o}}},"host.pool":{label:"Host: media pool clips",group:"Hosts",effect:!1,hosts:Er("pool"),about:"Every clip in the project's media pool with its file, bin, start TC and how many timelines use it; unused=true keeps the ones no timeline uses (outside `skip_folder`). Rows {name, folder, start_tc, file, drive}.",params:{...sr,unused:{type:"boolean"},skip_folder:{type:"string"}},run:async(e,t)=>{let n=await qe("host_project",{host:Ft(e),clips:!0,used:!!e.unused}),r=n.pool;if(!e.unused)return La(r).map(s=>({id:s.id,cells:{...s,drive:hg(s.file)}}));let o=n.used;if(!o){let s=new Set,i=n.timelines??[];for(let[a,l]of i.entries()){t.progress?.(a,i.length,`reading ${l}`);for(let c of(await qe("host_items",{host:Ft(e),timeline:l})).items??[])c.media_id&&s.add(c.media_id)}o=[...s]}return gg(r,String(e.skip_folder??""),new Set(o))}},"host.timelines":{label:"Host: the project's timelines",group:"Hosts",effect:!1,hosts:Er("pool"),about:"Every timeline in the open project, by name (rows), for a review or a filter.",params:{...sr},run:async e=>((await qe("host_project",{host:Ft(e)})).timelines??[]).map(t=>({id:t,cells:{name:t}}))},"qc.report":{label:"QC report (HTML)",group:"Checks",effect:!0,about:"The findings as one self-contained HTML page (the spec, the verdict, counts, every finding with its timecodes) saved into `folder` as <subject>_QC.html.",params:{rows:{type:"array"},text:{type:"string"},subject:{type:"string"},pack:{type:"string"},folder:{type:"string",required:!0},verdict:{type:"string",about:"the check's own verdict (default: from the rows)"}},run:async e=>{let t=String(e.subject||"master").split(/[\\/]/).pop(),n=e.rows??[],r=new Set(n.map(i=>i.cells.timeline)).size>1,o=await Promise.all(n.map(async i=>({...i.cells,...r?{clip:`${i.cells.timeline} \xB7 ${i.cells.clip??""}`}:{},...i.evidence?{evidence:`data:image/jpeg;base64,${To(await Ut(i.evidence).catch(()=>new Uint8Array))}`}:{}}))),s=re(mt(String(e.folder)),`${t.replace(/\.[^.]+$/,"").replace(/[^\w.-]+/g,"_")}_QC.html`);return await Ve(mt(String(e.folder))),await Ke(s,Ny({subject:t,spec:$u(e.pack?String(e.pack):"conform_default")?.label??"no spec",summary:e.text?String(e.text):void 0,...e.verdict?{verdict:String(e.verdict)}:{}},o)),{ok:!0,text:`report: ${s}`,path:s}}},"rows.html":{label:"Save the rows as a page (HTML)",group:"Checks",effect:!0,about:"Any tool's rows (a review or a table) as one self-contained HTML page \u2014 the title, a summary, the columns as shown \u2014 saved into `folder` as <title>.html (0.9.5's per-tool reports).",params:{rows:{type:"array"},columns:{type:"array",required:!0},title:{type:"string",required:!0},text:{type:"string"},folder:{type:"string",required:!0}},run:async e=>{let t=e.title==null||String(e.title).trim()===""||String(e.title)==="undefined"?"Change list":String(e.title),n=mt(String(e.folder)),r=re(n,`${t.replace(/[^\w.-]+/g,"_")}.html`);return await Ve(n),await Ke(r,jy(t,e.columns,(e.rows??[]).map(o=>o.cells),e.text?String(e.text).split(`
|
|
209
|
+
`)[0]:"")),{ok:!0,text:`report: ${r}`,path:r}}},"qc.master_file":{label:"QC a rendered master",group:"Checks",effect:!1,about:"A rendered master from any host, every frame measured by the analysis engine (black, freeze, flash, duplicates, blanking on each edge, dead / stuck / hot pixels; each audio track's loudness, true peak, clipping, dropouts, silence, phase) and held to a spec pack's loudness and true peak: rows for a table, at the file's own timecode.",params:{path:{type:"string",required:!0},pack:{type:"string"}},run:async(e,t)=>{let n=String(e.path),r=$u(e.pack?String(e.pack):"conform_default"),o=await qe("qc_media",{path:n},t),s=o.fps||24,i=d=>He(o.startFrame+d,s,o.dropFrame),a=[],l=(d,p,f,h,g)=>a.push({id:String(a.length),cells:{tc:d==null?"":i(d),out:p==null?"":i(p),kind:f,severity:h.toUpperCase(),detail:g}});for(let d of o.temporal.findings.filter(p=>p.severity!=="info"))l(d.start,d.end,d.check,d.severity,d.detail);for(let d of["top","bottom","left","right"])for(let p of o.edges[d]??[])l(p.start,p.end,`blanking ${d}`,"fail",`${p.thickness} px`);for(let d of o.pixels.defects)l(null,null,`${d.kind} pixel`,"fail",`at ${d.x},${d.y}, value ${d.value}`);for(let d of o.audio??[])for(let p of d.findings)l(p.start!=null?Math.floor(p.start*s):null,null,p.check,p.severity,`track ${d.track}${p.channel?` ch ${p.channel}`:""}: ${p.detail}`);let c=await qe("qc_deliverable",{path:n,name:!1,...r?.audio?{loudness_lufs:r.audio.lufs,loudness_tolerance:r.audio.tolerance,true_peak:r.audio.true_peak}:{}},t);for(let d of c.rows.filter(p=>p.outcome!=="PASS"&&p.outcome!=="INFO"))l(null,null,d.check,d.outcome,[d.expected&&`expected ${d.expected}`,d.measured&&`measured ${d.measured}`,d.note].filter(Boolean).join("; "));let u=o.verdict==="FAIL"||c.verdict==="FAIL"?"FAIL":o.verdict==="CHECK"?"CHECK":"PASS";return{ok:!0,verdict:u,rows:a,text:`${n.split(/[\\/]/).pop()}: ${u} against ${r?.label??"no spec"} \u2014 ${a.length} finding(s)
|
|
210
|
+
${String(o.text??"")}
|
|
211
|
+
${String(c.text??"")}`}}},"files.move":{label:"Move the files on disk",group:"Media",effect:!0,about:"The kept rows' files (`field`, default file) into `destination` (media_move: writability checked, clashes numbered, missing files named); its undo_id puts them back.",params:{rows:{type:"array",required:!0},destination:{type:"string",required:!0},field:{type:"string"}},run:async(e,t)=>{let n=(e.rows??[]).map(r=>String(r.cells[String(e.field??"file")]??"")).filter(Boolean);return n.length?qe("media_move",{paths:n,destination:e.destination},t):{ok:!0,text:"no files to move"}}},"files.rename_plan":{label:"Plan file renames",group:"Planners",effect:!1,about:"Every file in `folder` (image sequences frame by frame) through the rename steps on the name part, then the frame numbers offset or shifted to start at a number (0.9.5 Image Sequence Renamer); rows {where, old, new, dupe, error, hold} for every file (`hold`: not renamed \u2014 a DUPE, or unchanged), each with its from / to path.",params:{folder:{type:"string",required:!0},steps:{type:"array"},only:{type:"string"},offset:{type:"number"},start_at:{type:"number"},increment:{type:"number",about:"start_at: frames this far apart (default 1)"},digits:{type:"number",about:"frame-number padding (default as it is)"}},run:async e=>{let t=mt(String(e.folder)),n=[];for await(let h of Ct(t))h.isFile&&!h.name.startsWith(".")&&n.push(h.name);n.sort();let r=e.only?new RegExp(String(e.only)):null,o=n.filter(h=>!r||r.test(h)),s=Qu(o,e.steps??[],{sequence:!0}),i=e.offset!=null&&e.offset!==""?Number(e.offset):void 0,a=e.start_at!=null&&e.start_at!==""?Number(e.start_at):void 0,l=Number(e.digits)>0?Number(e.digits):void 0,c=Number(e.increment)>0?Number(e.increment):void 0,u=i!=null||a!=null||l?Ky(s.map(h=>h.new),{offset:i??0,start:a,increment:c,digits:l}):s.map(h=>h.new),d=new Set(o.filter((h,g)=>u[g]!==h)),p=new Set(n.filter(h=>!d.has(h))),f=new Set;return o.map((h,g)=>{let b=u[g],k=s[g].dupe||f.has(b)||b!==h&&p.has(b);return f.add(b),{id:h,from:re(t,h),to:re(t,b),cells:{where:t.split(/[\\/]/).pop(),old:h,new:b,dupe:k?"DUPE":"",error:s[g].error??"",hold:k||b===h?"1":""}}})}},"files.patch_plan":{label:"Plan a sequence patch",group:"Planners",effect:!1,about:"Every frame of the patch folders beside an image sequence's folder (0.9.5 Image Sequence Patcher), one row each: the frame, its folder, and whether the sequence has that frame to replace.",params:{sequence:{type:"string",required:!0}},run:async(e,t)=>((await qe("media_patch_sequence",{sequence:e.sequence,mode:"plan"},t)).rows??[]).map(r=>({id:`${r.folder}/${r.file}`,cells:{frame:r.file,folder:r.folder,status:r.replaces?"replaces":"not in the sequence",cant:!r.replaces}}))},"files.patch":{label:"Patch the frames in",group:"Media",effect:!0,about:"The kept patch frames into the sequence (media_patch_sequence apply): originals to <sequence>_originalframes, the patch folders filed under zAPPLIED_PATCHES; its undo_id puts it all back.",params:{sequence:{type:"string",required:!0},rows:{type:"array",required:!0}},run:async(e,t)=>{let n=(e.rows??[]).filter(r=>!r.cells.cant).map(r=>r.id);return n.length?qe("media_patch_sequence",{sequence:e.sequence,mode:"apply",only:n},t):{ok:!0,text:"no frames to patch"}}},"files.sort_plan":{label:"Plan the filing",group:"Planners",effect:!1,about:"Where every file of `folder` goes by the recipe (media_sort plan): one row each \u2014 file, rule, project, where it goes, and its status (ready, renamed, conflict, in place, unmatched, invalid); only ready / renamed rows can be applied.",params:{folder:{type:"string",required:!0},recipe:{type:"string"},recursive:{type:"boolean"},destination_root:{type:"string"},operation:{type:"move|copy"}},run:async(e,t)=>((await qe("media_sort",{folder:e.folder,recipe:e.recipe||"mixes-splits",mode:"plan",recursive:!!e.recursive,...e.destination_root?{destination_root:e.destination_root}:{},...e.operation?{operation:e.operation}:{}},t)).files??[]).map(r=>({id:r.source_path,cells:{file:r.name,rule:r.rule_name??"",project:r.project,to:[r.dest_rel,r.dest_name!==r.name?r.dest_name:""].filter(Boolean).join("/"),status:r.status.replace("_"," "),why:r.reason??"",cant:!(r.status==="ready"||r.status==="renamed")}}))},"files.sort":{label:"File them",group:"Media",effect:!0,about:"The kept rows filed by the recipe (media_sort apply, re-planned from disk: nothing overwritten); its undo_id puts every file back.",params:{folder:{type:"string",required:!0},recipe:{type:"string"},recursive:{type:"boolean"},destination_root:{type:"string"},operation:{type:"move|copy"},rows:{type:"array",required:!0}},run:async(e,t)=>{let n=(e.rows??[]).filter(r=>!r.cells.cant).map(r=>r.id);return n.length?qe("media_sort",{folder:e.folder,recipe:e.recipe||"mixes-splits",mode:"apply",recursive:!!e.recursive,only:n,...e.destination_root?{destination_root:e.destination_root}:{},...e.operation?{operation:e.operation}:{}},t):{ok:!0,text:"nothing to file"}}},"files.odd_plan":{label:"Find odd-sized stills",group:"Planners",effect:!1,about:"Every still of `folder` whose width or height is odd (or larger than `max`), one row each with the size it would become (media_odd_images plan).",params:{folder:{type:"string"},files:{type:"array",about:"\u2026or these stills (0.9.5: the selected Media Pool bin's)"},max:{type:"number"}},run:async(e,t)=>((await qe("media_odd_images",{...e.folder?{folder:e.folder}:{files:e.files??[]},mode:"plan",...Number(e.max)>0?{max:Number(e.max)}:{}},t)).files??[]).filter(r=>r.status!=="skipped").map(r=>({id:r.path,cells:{file:r.path.split(/[\\/]/).pop(),now:r.original??"",becomes:r.new??"",why:r.why??"",cant:r.status!=="fixed"}}))},"files.odd_fix":{label:"Make them even",group:"Media",effect:!0,about:"The kept stills rewritten at even sizes (media_odd_images apply: originals to 'zORIGINAL IMAGES'); its undo_id puts every original back.",params:{rows:{type:"array",required:!0},max:{type:"number"}},run:async(e,t)=>{let n=(e.rows??[]).filter(o=>!o.cells.cant).map(o=>o.id);if(!n.length)return{ok:!0,text:"nothing to fix",paths:[]};let r=await qe("media_odd_images",{files:n,mode:"apply",...Number(e.max)>0?{max:Number(e.max)}:{}},t);return{...r,paths:(r.files??[]).filter(o=>o.status==="fixed").map(o=>o.path)}}},"files.rename":{label:"Rename the files on disk",group:"Media",effect:!0,about:"The kept rows' files renamed (media_move renames: collision-safe, refused whole when a target is a file outside the batch); its undo_id puts every name back.",params:{rows:{type:"array",required:!0}},run:async(e,t)=>{let n=(e.rows??[]).filter(r=>r.from&&r.to&&!r.cells.dupe).map(r=>({from:r.from,to:r.to}));return n.length?qe("media_move",{renames:n},t):{ok:!0,text:"nothing to rename"}}},"rows.times":{label:"Times on the timeline",group:"Logic",effect:!1,fresh:!0,about:"Rows at regular times on a read timeline: one every `seconds` (or `frames`), from `from` to `to` seconds (default the whole timeline). Each row has frame (from the head) and tc; an edit block given these rows acts on the timeline at that frame (edit.marker_add: a marker every N seconds).",params:{live:{type:"object",required:!0},seconds:{type:"number"},frames:{type:"number"},from:{type:"number"},to:{type:"number"}},run:async e=>{let t=e.live,n=Number(t.fps??24),r=Math.round(Number(e.frames??0)||Number(e.seconds??1)*n);if(!(r>0))throw new P("invalid_args","times need seconds or frames above 0");let o=e.to!=null&&e.to!==""?Math.round(Number(e.to)*n):Number(t.frames??0),s=[];for(let i=Math.round(Number(e.from??0)*n);i<o&&s.length<1e4;i+=r)s.push({id:`t${i}`,cells:{frame:i,tc:He(i+Number(t.start_frame??0),n,!1)}});return s}},"rows.filter":{label:"Filter rows",group:"Logic",effect:!1,about:'Keep the rows where every condition holds: [field, op, value] (field "a|b": either field), op = | != | contains | starts | !starts (a comma list: any of them) | in | empty | set | < | <= | > | >= (numbers: frames, speed %, duration). A track cell ("V2") matches a track number (2), so a track input filters directly. A condition whose value is unset is skipped (an optional filter left blank).',params:{rows:{type:"array",required:!0},where:{type:"array"}},run:async e=>{let t=(e.where??[]).filter(([,r,o])=>r==="empty"||r==="set"||o!=null&&o!==""),n=(r,o)=>r.cells[o];return(e.rows??[]).filter(r=>t.every(([o,s,i])=>String(o).split("|").some(a=>{let l=n(r,a),c=String(l??"").toLowerCase(),u=String(i??"").toLowerCase(),d=()=>c===u||/^[va]\d+$/.test(c)&&/^\d+$/.test(u)&&c.slice(1)===u,p=h=>typeof h=="number"?h:parseFloat(String(h??"").replace(/[^0-9.+-]/g,"")),f=()=>{let h=p(l),g=p(i);return Number.isFinite(h)&&Number.isFinite(g)?h-g:NaN};switch(s){case"=":return typeof i=="boolean"?!!l===i:d();case"!=":return!d();case"<":return f()<0;case"<=":return f()<=0;case">":return f()>0;case">=":return f()>=0;case"contains":return c.includes(u);case"starts":return u.split(",").map(h=>h.trim()).filter(Boolean).some(h=>c.startsWith(h));case"!starts":return!u.split(",").map(h=>h.trim()).filter(Boolean).some(h=>c.startsWith(h));case"in":return Array.isArray(i)&&i.map(h=>String(h).toLowerCase()).includes(c);case"empty":return!c;case"set":return!!c;default:return!0}})))}},review:{label:"Review",group:"Logic",effect:!1,about:"Show the rows (with `columns`) and wait: the artist unticks what to leave out and applies. Its output is the rows kept.",params:{rows:{type:"array",required:!0},columns:{type:"array",about:"[cell key, label] pairs"},skip:{type:"string",about:"a cell that marks rows that cannot be applied (e.g. dupe)"},empty:{type:"string",about:'what no rows means here ("no markers match"): the run ends with it'}},run:async()=>{throw new P("internal","review is the runner's")}},"ops.collect":{label:"Collect edits",group:"Logic",effect:!1,about:"The edits a planner put on each row (`field`, default op) as one batch for host.apply.",params:{rows:{type:"array",required:!0},field:{type:"string"}},run:async e=>(e.rows??[]).map(t=>t[String(e.field??"op")]).filter(Boolean)},"plan.marker_ops":{label:"Plan marker edits",group:"Planners",effect:!1,about:"Existing marker rows \u2192 edits: action = recolor | swap (color \u2194 text, over `all`) | rename | note | keyword | prefix | suffix | replace (text \u2192 with, any case) | duration (frames) | delete | to_clip / copy_to_clip (onto the clip under it: `track`, else the topmost) | to_timeline / copy_to_timeline | swap_places (timeline \u2194 clip); `field` = name | note | keyword for rename / prefix / suffix / replace, `separator` for prefix / suffix. It changes markers that are there; to ADD markers use edit.marker_add (one per row: clip rows mark each clip, rows.times rows mark those times).",params:{live:{type:"object",required:!0},rows:{type:"array",required:!0},action:{type:"recolor|swap|rename|note|keyword|prefix|suffix|replace|duration|delete|to_clip|to_timeline|copy_to_clip|copy_to_timeline|swap_places",required:!0},color:{type:"string"},text:{type:"string"},with:{type:"string"},field:{type:"name|note|keyword"},separator:{type:"string"},track:{type:"number"},frames:{type:"number"},overwrite:{type:"boolean",about:"move / copy onto a frame another marker holds: replace it (default) or leave both"},all:{type:"array",about:"swap: the markers it swaps across (default every marker of the timeline); the color filter does not narrow a swap"}},run:async e=>{let t=e.live,n=e.action,r=Number(e.track)||void 0;return mg(t,n==="swap"?e.all??t.markers:e.rows,n,String(e.color??"Green"),String(e.text??(n==="swap"?"Red":"")),{field:e.field||"name",separator:e.separator==null?"":String(e.separator),with:String(e.with??""),track:r,frames:Number(e.frames)||void 0,overwrite:e.overwrite!==!1})}},"rename.subjects":{label:"What to rename",group:"Planners",effect:!1,about:"The names to rename and how each is renamed in the host: target = clips (timeline video clips) | timelines | pool (media pool clips, `folder` to narrow; Resolve).",params:{...sr,live:{type:"object",required:!0},target:{type:"string",required:!0},folder:{type:"string",about:'pool: a bin path; "@selected" = the bin selected in Resolve; "Master" = the root'},subfolders:{type:"boolean",about:"pool: the folder's subfolders too (default true)"},only:{type:"string",about:"a regex (any case): only the names it finds; numbering counts these"}},run:async e=>{let t=null;try{t=e.only?new RegExp(String(e.only),"i"):null}catch(r){throw new P("invalid_args",`the filter is not a valid pattern: ${r.message}`)}let n=await HR(e);return t?n.filter(r=>t.test(r.name)):n}},"plan.rename":{label:"Plan renames",group:"Planners",effect:!1,about:"Run the rename steps over every subject's name; rows {id, where, old, new, dupe, error, hold, op} for every subject (as 0.9.5's preview: the whole list, the new name beside each) \u2014 `hold` marks a row that is not applied (a DUPE, or a name the steps leave as it is).",params:{subjects:{type:"array",required:!0},steps:{type:"array",required:!0}},run:async e=>{let t=e.subjects??[],n=Qu(t.map(r=>r.name),e.steps??[]);return t.map((r,o)=>({id:r.id,cells:{where:r.where,old:n[o].old,new:n[o].new,dupe:n[o].dupe?"DUPE":"",error:n[o].error??"",hold:n[o].dupe||n[o].new===n[o].old?"1":""},op:{...r.op,name:n[o].new}}))}},table:{label:"Show a table",group:"Logic",effect:!1,about:"End a tool with a table of rows (with `columns`) and a summary `text`: findings to read, not to apply. A row's `tc` cell moves the host's playhead when clicked.",params:{rows:{type:"array",required:!0},columns:{type:"array"},text:{type:"string"}},run:async e=>({ok:!0,text:String(e.text??`${(e.rows??[]).length} row(s)`),table:{rows:e.rows??[],columns:e.columns??[]}})},"plan.clips":{label:"Clips as rows",group:"Planners",effect:!1,about:"The read timeline's clips as rows with what the host holds live on each (color, flags, on, version, group, nodes, keywords); `query` narrows them with the Edit Index grammar (is:offline \xB7 speed!=100 \xB7 track:V2 \xB7 name:/^A0\\d+/).",params:{live:{type:"object",required:!0},query:{type:"string"}},run:async e=>{let t=e.live,n=String(e.query??"").trim();if(!n)return Tu(t);let r=await qe("timeline_query",{session_id:t.session_id,table:"clips",query:n,limit:5e3,columns:["#"]});return Tu(t,new Set((r.rows??[]).map(o=>o.id)))}},"plan.index_ops":{label:"Plan clip edits",group:"Planners",effect:!1,about:`Clip rows \u2192 one edit each: action = ${vu.map(([e])=>e).join(" | ")}; color (clip color), marker_color (flags, markers), text.`,params:{live:{type:"object",required:!0},rows:{type:"array",required:!0},action:{type:vu.map(([e])=>e).join("|"),required:!0},color:{type:"string"},marker_color:{type:"string"},text:{type:"string"}},run:async e=>{let t=String(e.action),n=String(t==="color"?e.color??"":e.marker_color??"Blue");return fg(e.live,e.rows??[],t,n,String(e.text??""))}},"plan.pool_ops":{label:"Plan pool moves",group:"Planners",effect:!1,about:"Pool clip rows \u2192 one batch: action = move (into `folder`, made if missing) | remove (out of the pool; files on disk stay; cannot be undone).",params:{rows:{type:"array",required:!0},action:{type:"move|remove"},folder:{type:"string"}},run:async e=>bg(e.rows??[],String(e.action??"move"),String(e.folder??""))},"plan.copy_pairs":{label:"Pair clips by overlap",group:"Planners",effect:!1,about:"Every clip on track `to` paired with the clip on track `from` it overlaps most (rows; a clip with nothing over it is a row too).",params:{live:{type:"object",required:!0},from:{type:"number",required:!0},to:{type:"number",required:!0}},run:async e=>yg(e.live,Number(e.from),Number(e.to))},"plan.copy_ops":{label:"Plan copies",group:"Planners",effect:!1,about:"Paired rows \u2192 copy_grade / copy_properties / clip color / flags / clip markers / color group / keywords edits for what is switched on (grade, sizing, crop, composite, clip_color, flags, markers, group, keywords); unpaired rows get a `miss_color` marker.",params:{rows:{type:"array",required:!0},grade:{type:"boolean"},sizing:{type:"boolean"},crop:{type:"boolean"},composite:{type:"boolean"},clip_color:{type:"boolean"},flags:{type:"boolean"},markers:{type:"boolean"},versions:{type:"boolean"},group:{type:"boolean"},keywords:{type:"boolean"},miss_color:{type:"string"},overwrite_markers:{type:"boolean"},live:{type:"object",about:"the read (clip markers need it)"},nodes:{type:"string",about:'only these nodes of the grade, e.g. "2, Skin" (numbers as Resolve shows them, or labels; matched by label on both clips): copy_nodes instead of the whole grade'}},run:async e=>kg(e.rows??[],new Set(xu.map(([t])=>t).filter(t=>e[t])),String(e.miss_color??""),e.live,!!e.overwrite_markers,wg(e.nodes))},"plan.grade_trace":{label:"Trace earlier grades",group:"Planners",effect:!1,about:"Score every clip of the read timeline against the clips of earlier `timelines` and of other `projects` (source TC overlap, reel, file name, path, duration): rows with the best match and up to top_n alternatives.",params:{...sr,live:{type:"object",required:!0},timelines:{type:"array"},projects:{type:"array",about:"other projects of the library to search (Resolve opens each, then yours again)"},top_n:{type:"number"},min_score:{type:"number"},floor:{type:"number"},tracks:{type:"string",about:'only these video tracks of the read, e.g. "1, 3" (default all)'},clip_color:{type:"boolean",about:"read the earlier clips' clip color (to copy it with the grade)"},flags:{type:"boolean",about:"and their flags"},weights:{type:"object",about:"what a match counts, by clue: {tc, reel, filename, camera_roll, duration, filepath}; 0 leaves a clue out (default 35/25/20/10/5/5)"}},run:async(e,t)=>{let n=e.live,r=[],o=new Map,s=String(e.tracks??"").split(",").map(c=>Number(c.trim().replace(/^v/i,""))).filter(c=>c>0),i=(e.timelines??[]).filter(c=>c&&c!==n.timeline),a=(e.projects??[]).filter(Boolean);if(!i.length&&!a.length)throw new P("invalid_args","choose the earlier timelines (or other projects) to trace from");for(let[c,u]of a.entries()){t.progress?.(c,a.length,`reading the project ${u}`);let d=await qe("host_project",{host:"resolve",project:u,export_dir:await It("conform-trace-")});for(let p of d.exported??[]){let f=await qe("timeline_read",{path:p.path}),[h,g]=await Promise.all([qe("timeline_query",{session_id:f.session_id,table:"clips",limit:5e3,columns:["track","track_no","name","timeline_range.start","reel_name","media_reference_id"]}),qe("timeline_query",{session_id:f.session_id,table:"media",limit:5e3,columns:["name","target_url","available_range.start","available_range.dur","source_fps","source_resolution_w","source_resolution_h"]})]);r.push(...Na(p.timeline,h.rows,await xi(g.rows,o)).map(b=>({...b,project:u})))}}for(let[c,u]of i.entries()){t.progress?.(c,i.length,`reading ${u}`);let d=await qe("host_export",{host:Ft(e),timeline:u}),[p,f]=await Promise.all([qe("timeline_query",{session_id:d.session_id,table:"clips",limit:5e3,columns:["track","track_no","name","timeline_range.start","reel_name","media_reference_id"]}),qe("timeline_query",{session_id:d.session_id,table:"media",limit:5e3,columns:["name","target_url","available_range.start","available_range.dur","source_fps","source_resolution_w","source_resolution_h"]})]),h=Ft(e)==="resolve"&&(e.clip_color||e.flags)?(await qe("host_items",{timeline:u,kind:"video"})).items??[]:[];r.push(...Na(u,p.rows,await xi(f.rows,o),h))}let l=Na(n.timeline,n.clips,await xi(n.media,o),n.items,{enabledOnly:!0}).filter(c=>!s.length||s.includes(c.track));if(Ft(e)==="resolve"){let c=La((await qe("host_project",{host:"resolve",clips:!0}).catch(()=>({pool:{folders:[]}}))).pool),u=new Map(c.filter(d=>d.camera).map(d=>[d.file,d.camera]));for(let d of[...l,...r])d.file_path&&u.has(d.file_path)&&(d.camera_roll=u.get(d.file_path))}return _g(l,r,{topN:Number(e.top_n??3),minScore:Number(e.min_score??60),floor:Number(e.floor??60),weights:e.weights})}},"plan.grade_trace_ops":{label:"Plan traced grades",group:"Planners",effect:!1,about:"Traced rows \u2192 copy_grade from the best match (only_trusted: trusted matches only), or with variants the top matches as named local versions; unmatched rows get a `mark_color` marker.",params:{rows:{type:"array",required:!0},variants:{type:"boolean"},only_trusted:{type:"boolean"},mark_color:{type:"string"},prefix:{type:"string",about:"variants' name prefix (default trace)"},unsure_only:{type:"boolean",about:"variants only where the match is not trusted"},sizing:{type:"boolean"},crop:{type:"boolean"},composite:{type:"boolean"},clip_color:{type:"boolean"},flags:{type:"boolean"},live:{type:"object",about:"the read: its earlier tracer markers are cleared when `clear`"},clear:{type:"boolean"},keyframes:{type:"copy|none|source_tc|start",about:"how the grade's keyframes land: copy = as Resolve copies a grade (default); none / source_tc / start = through the grade's .drx, keyframes dropped or aligned to source timecode or to the clip's start"}},run:async(e,t)=>{let n=vg(e.rows??[],{variants:!!e.variants,onlyTrusted:e.only_trusted!==!1,markColor:String(e.mark_color??""),prefix:e.prefix?String(e.prefix):void 0,unsureOnly:e.unsure_only===!0,keys:xu.filter(([i])=>["sizing","crop","composite"].includes(i)&&e[i]===!0).flatMap(([,,i])=>i),clear:e.clear===!0?e.live?.markers:void 0,color:e.clip_color===!0,flags:e.flags===!0}),r=String(e.keyframes??"copy"),o=e.live?.project;if(r!=="copy"&&o)for(let i of n)i.op==="copy_grade"&&!i.from_project&&(i.from_project=o);let s=n.filter(i=>i.from_project);for(let[i,a]of[...new Set(s.map(l=>String(l.from_project)))].entries()){t.progress?.(i,0,`grabbing grades in ${a}`);let l=s.filter(d=>d.from_project===a),c=l.map((d,p)=>({key:p,timeline:d.from_timeline,...d.item})),u=(await qe("host_project",{host:"resolve",project:a,grades:c,grades_dir:await It("conform-trace-")})).grades??{};l.forEach((d,p)=>{let f=u[p],{from_project:h,from_timeline:g,...b}=d;Object.keys(d).forEach(k=>delete d[k]),Object.assign(d,typeof f=="string"?{...b,item:b.to[0],drx:f,mode:{none:0,source_tc:1,start:2}[r]??2}:{op:"skip",why:`${a}: ${f?.error??"no grade"}`})})}return n.filter(i=>i.op!=="skip")}},"align.against":{label:"Align a build to B, track by track",group:"Planners",effect:!1,about:"Reconform's Match Sizing: every one of B's video tracks that is on laid onto the build's read as its own reference track (stack_track), then each of the build's tracks aligned against B's track of the same number \u2014 both decoded from the files (media-core), B's own reframe composed in. One answer {rows, ops} for plan.align_rows / plan.align_ops.",params:{session_id:{type:"string",required:!0},timeline:{type:"string",required:!0},b_session_id:{type:"string",required:!0},b_timeline:{type:"string",required:!0}},run:async(e,t)=>{let n=(await ft(String(e.b_session_id))).session,r=n.timelines.find(l=>l.name===e.b_timeline)??n.timelines.find(l=>l.kind==="primary");if(!r)throw new P("not_found",`no timeline ${e.b_timeline} in B's read`);let o=r.tracks.filter(l=>l.kind==="Video").sort((l,c)=>l.track_index-c.track_index),s=new Map;for(let[l,c]of o.entries()){if(c.enabled===!1)continue;let u=await qe("timeline_edit",{session_id:e.session_id,kind:"stack_track",args:{timeline_id:e.timeline,from:r.name,from_track:l+1,sources:[e.b_session_id]}},t);u.meta?.track&&s.set(l+1,u.meta.track)}let i=[],a=[];for(let[l,c]of s){let u=await qe("timeline_align",{session_id:e.session_id,reference_track:c,tracks:[l],markers:!1},t);i.push(...u.rows??[]),a.push(...u.ops??[])}return{ok:!0,rows:i,ops:a,sizing_target:"edit",text:`${i.length} clip(s) measured against B, track by track`}}},"plan.align_rows":{label:"Align results as rows",group:"Planners",effect:!1,about:"timeline_align's answer as rows: record TC, track, clip, verdict, confidence, the host sizing (rows not aligned cannot be applied: cell `cant`).",params:{result:{type:"object",required:!0}},run:async e=>Tg(e.result?.rows??[],e.result?.sizing_target)},"plan.align_ops":{label:"Plan sizing",group:"Planners",effect:!1,about:"The sizing edits of the kept aligned rows, and timeline_align's markers when `markers`.",params:{result:{type:"object",required:!0},rows:{type:"array",required:!0},markers:{type:"boolean"}},run:async e=>xg(e.result?.ops??[],e.rows??[],e.markers!==!1)},"plan.blanking_rows":{label:"Blanking findings as rows",group:"Planners",effect:!1,about:"qc_blanking's findings as rows: record TC, frames, track, clip, black per edge, the zoom that fills.",params:{result:{type:"object",required:!0},live:{type:"object",about:"the read: its playhead marks the finding under it (at=playhead) and the next one (at=next)"}},run:async e=>Sg(e.result?.findings??[],e.live?.playhead)},"plan.blanking_ops":{label:"Plan blanking fixes",group:"Planners",effect:!1,about:"The kept findings' markers, and the zoom fix of each clip they sit on when `fixes`.",params:{result:{type:"object",required:!0},rows:{type:"array",required:!0},live:{type:"object",required:!0},fixes:{type:"boolean"},clear:{type:"boolean",about:"take an earlier run's blanking markers off first"},which:{type:"string",about:"a one-finding run (playhead / next) never clears the others' markers"}},run:async e=>$g(e.result?.ops??[],e.rows??[],e.live,e.fixes!==!1,e.clear===!0&&!e.which)},"plan.vfx_dropin":{label:"Match comps to plates",group:"Planners",effect:!1,about:"Every finished comp in `folder` (movies, and image sequences by their first frame) probed and matched to a plate of the read (0.9.5 Drop in VFX): by the shot id in its name \u2014 the VFX shot markers, the plates' names \u2014 then by source timecode and reel; each row ready (with where its frames go), ambiguous, retimed or unmatched, and why.",params:{live:{type:"object",required:!0},folder:{type:"string",required:!0}},run:async e=>{let t=mt(String(e.folder)),n=new Set,r=[];for await(let s of Ct(t)){if(!s.isFile||s.name.startsWith("."))continue;let i=/^(.*?)[._](\d{3,8})\.(exr|dpx|tiff?|png|jpe?g)$/i.exec(s.name),a=i?`${i[1]}|${i[3]}`:s.name;!/\.(mov|mxf|mp4|m4v|exr|dpx|tiff?|png|jpe?g)$/i.test(s.name)||n.has(a)||(n.add(a),r.push(re(t,s.name)))}r.sort();let o=(await Promise.all(r.map(async s=>{let i=await Po("media_probe",{path:s}),a=i.structuredContent;return i.isError||!a?null:{path:s,name:s.split(/[\\/]/).pop(),frames:Number(a.available_range?.duration.value??0),fps:Number(a.source_fps??24),start_tc:a.source_timecode??void 0,reel:a.reel_name??void 0,...a.source_resolution_w?{raster:[a.source_resolution_w,a.source_resolution_h]}:{}}}))).filter(s=>s!==null);return Ug(await Vy(e.live),o)}},"plan.vfx_dropin_ops":{label:"Drop the comps in",group:"Planners",effect:!1,about:"The kept ready rows as one drop_in: the comps into the pool's VFX bin, onto a new top track over their plates (the plate's sizing when the rasters agree), the plates switched off when asked.",params:{rows:{type:"array",required:!0},name:{type:"string"},disable_plates:{type:"boolean"}},run:async e=>Gg(e.rows??[],{name:e.name?String(e.name):void 0,disable_plates:e.disable_plates===!0})},"plan.history":{label:"A's program as a history track",group:"Planners",effect:!1,about:"The op that cuts A's program (the topmost enabled clip at every span, its source window) onto a new, switched-off video track of the target (0.9.5 Reconformer's V1 HISTORY).",params:{a:{type:"object",required:!0},name:{type:"string"}},run:async e=>{let t=qg(e.a);return t.length?[{op:"history_track",name:String(e.name||"V1 HISTORY"),pieces:t}]:[]}},"plan.edit_changes":{label:"The change list by the edit",group:"Planners",effect:!1,about:"A (the old cut) and B (the new one), both reads: each B clip paired with the A clip holding the most of the same source frames, and what happened \u2014 moved, trimmed / extended at either end, slipped, split, joined, retimed, reframed; inserted / deleted for the unpaired. Rows carry their marker (on B, a deletion on A).",params:{a:{type:"object",required:!0},b:{type:"object",required:!0}},run:async e=>Dg(e.a,e.b)},"plan.parity_map":{label:"The change map",group:"Planners",effect:!1,about:"A (the old cut) and B (the new one), both reads: A's clips over B's with every pair linked by its change (0.9.5 Reconformer's map); the screen draws it.",params:{a:{type:"object",required:!0},b:{type:"object",required:!0}},run:async e=>({parity:jg(e.a,e.b)})},"verify.pictures":{label:"Check the picture (decode both sides)",group:"Checks",effect:!1,about:"For every change row pairing an A clip with a B clip, both sides' source frame at the middle of what they share decoded straight from the files (media-core, no render, no app) and compared by the analysis engine's picture distance (it survives a regrade, a burn-in, a rescale; another shot does not): `picture` says same / DIFFERS, with the A/B frame beside it. `which`: loose (just the pairs made by name, default) or all.",params:{rows:{type:"array",required:!0},which:{type:"loose|all"}},run:async e=>{let t=e.rows??[],n=[];for(let r of t){if(!r.pair||e.which!=="all"&&!r.cells.paired){n.push(r);continue}try{let o=await Eo({path:r.pair.a.path,frame:r.pair.a.frame,b:r.pair.b.path,width:320}),s=o.diff?.[0];n.push({...r,evidence:o.out_path,cells:{...r.cells,picture:s?s.same?"same":`DIFFERS (${s.distance})`:"not decoded"}})}catch(o){n.push({...r,cells:{...r.cells,picture:`not decoded: ${o.message.slice(0,80)}`}})}}return n}},"plan.edit_change_ops":{label:"Markers for the changes",group:"Planners",effect:!1,about:"The kept change rows' markers for one side: B (the changes) or A (the deletions).",params:{rows:{type:"array",required:!0},side:{type:"A|B",required:!0},live:{type:"object",about:"that side's read: its own markers' frames are left alone"}},run:async e=>Bg(e.rows??[],e.side==="A"?"A":"B",e.live)},"plan.reconform":{label:"Cut changes as rows",group:"Planners",effect:!1,about:"timeline_diff's ranges as rows (record in/out, change, both sides), each carrying the marker for A at its first frame (start_frame = A's timeline start).",params:{diff:{type:"object",required:!0},start_frame:{type:"number"}},run:async e=>Rg(e.diff?.ranges??[],Number(e.start_frame??0))},"plan.carry_rows":{label:"Pair the new cut with the color cut",group:"Planners",effect:!1,about:"Every video clip of B (a read) paired with the clip of A (a read) holding the most of the same source frames of the same media: the clip whose grade it takes. New material is a row with no source.",params:{a:{type:"object",required:!0},b:{type:"object",required:!0}},run:async e=>{let t=e.a,n=e.b;if(!n?.items?.length)throw new P("invalid_args","B has to be a timeline in this project to build the reconform on (import the new cut into Resolve first)");return Cg(t,n)}},"plan.carry_ops":{label:"Plan the carry",group:"Planners",effect:!1,about:"Kept carry rows \u2192 edits on B's copy, each source read in A: grade (a remote one selected, a local one copied onto a local version), sizing, crop, composite, clip color, clip markers (what is switched on; flags are the media's, so B has A's); new material gets a `miss_color` marker.",params:{rows:{type:"array",required:!0},a:{type:"object",required:!0},grade:{type:"boolean"},sizing:{type:"boolean"},crop:{type:"boolean"},composite:{type:"boolean"},clip_color:{type:"boolean"},markers:{type:"boolean"},speed:{type:"boolean"},fades:{type:"boolean"},miss_color:{type:"string"},a_sizing:{type:"array",about:"of the clips whose sizing differs, the ones that take A's (kept rows of the sizing review); the others keep B's"}},run:async e=>{let t=e.rows??[],n=e.a_sizing,r=n?new Set(t.filter(o=>o.cells.sizing_differs&&!n.some(s=>s.id===o.id)).map(o=>o.id)):void 0;return Eg(t,new Set(Ag.map(([o])=>o).filter(o=>e[o])),e.a,String(e.miss_color??""),r)}},"host.duplicate":{label:"Host: duplicate a timeline",group:"Hosts",effect:!0,hosts:["resolve"],about:"A copy of `timeline` under `name` (made unique: never over another timeline), opened. Answers `timeline`: its name, for the next host.apply.",params:{...sr,timeline:{type:"string",required:!0},name:{type:"string"}},run:async e=>{let t=await qe("host_apply",{host:Ft(e),timeline:e.timeline,ops:[{op:"timeline_duplicate",name:e.name||`${e.timeline}_RECONFORMED`}]}),n=t.results?.[0]?.name;if(!n)throw new P("engine",`Resolve did not duplicate ${e.timeline}: ${String(t.text).split(`
|
|
212
|
+
`)[0]}`);return ws.clear(),{ok:!0,text:`made ${n}`,timeline:n,made:n}}},"plan.vfx_pulls":{label:"Plan VFX pulls",group:"Planners",effect:!1,about:"Markers of `color` \u2192 numbered shots (prefix, increment, digits) with their plates (the clips under each marker; hero = lowest | highest track) and the reference_track clip; rows per pull, and the string-out with handles and a gap between shots.",params:{live:{type:"object",required:!0},color:{type:"string"},prefix:{type:"string"},increment:{type:"number"},digits:{type:"number"},handles:{type:"number"},gap:{type:"number"},start_frame:{type:"number"},hero:{type:"string"},reference_track:{type:"number"},skip_disabled:{type:"boolean"},naming:{type:"plates|scene_take|clip"},folder:{type:"string",about:"the shot folder: {prefix} {shot} {number} {scene} {take}"},names:{type:"string",about:`the artist's own pull names: "VFX_0010_PLATE01=SMOKE_0010, \u2026"`}},run:async e=>Mg(await Vy(e.live),{...e.names?{names:String(e.names)}:{},naming:["scene_take","clip"].includes(String(e.naming))?e.naming:"plates",folder:e.folder?String(e.folder):void 0,color:String(e.color??"Blue"),prefix:String(e.prefix??"VFX"),increment:Number(e.increment??10),digits:Number(e.digits??4),handles:Number(e.handles??8),gap:Number(e.gap??24),startFrame:Number(e.start_frame??1001),hero:e.hero==="highest"?"highest":"lowest",referenceTrack:Number(e.reference_track)||void 0,skipDisabled:e.skip_disabled!==!1})},"plan.output_blanking":{label:"Output blanking for the aspect",group:"Planners",effect:!1,about:"The timeline's output blanking (Resolve 21.1+) that shows `aspect` in the checked raster: even bars, top and bottom or left and right; nothing when it is already set so.",params:{aspect:{type:"string",required:!0},check:{type:"object",required:!0,about:"qc_blanking's result (its raster)"},live:{type:"object"}},run:async e=>{let t=_b(e.aspect),[n,r]=e.check.raster;if(t==null)return[];let o=vb(t,n,r),s=e.live?.output_blanking;return s&&["top","bottom","left","right"].every(i=>s[i]===o[i])?[]:[{op:"timeline_output_blanking",...o}]}},"plan.vfx_next_marker":{label:"The next VFX marker",group:"Planners",effect:!1,about:"A marker at the read's playhead named for the next shot number on the grid (after every shot the plan holds): prefix_NNNN, in `color`.",params:{live:{type:"object",required:!0},plan:{type:"object",required:!0},color:{type:"string"},prefix:{type:"string"},digits:{type:"number"},increment:{type:"number"}},run:async e=>{let t=e.live,n=Number(e.increment??10)||10;if(t.playhead==null)throw new P("unsupported","the host did not say where its playhead is (Resolve does)");let r=t.markers.find(i=>!i.cells.item_id&&Number(i.cells.frame)===t.playhead);if(r)throw new P("usage",`a marker is already at the playhead ("${r.cells.name??""}"); move the playhead`);let o=Math.max(0,...(e.plan.shots??[]).map(i=>i.number)),s=Math.floor(o/n)*n+n;return[{op:"marker_add",frame:t.playhead,color:String(e.color??"Blue"),name:`${e.prefix??"VFX"}_${String(s).padStart(Number(e.digits??4),"0")}`,note:"conform.tools VFX Pulls"}]}},"plan.vfx_names":{label:"Plan shot names",group:"Planners",effect:!1,about:"The shot names onto their markers, for the shots with a kept pull.",params:{plan:{type:"object",required:!0},rows:{type:"array",required:!0}},run:async e=>Ig(e.plan,e.rows??[])},"vfx.stringout":{label:"Build the VFX string-out",group:"Planners",effect:!0,hosts:Er("open"),about:"The kept pulls end to end (handles, a gap between shots) as a new timeline <name>_VFX_STRINGOUT in the host, linked to the clips already there; its name and start frame for host.render.",params:{...sr,live:{type:"object",required:!0},plan:{type:"object",required:!0},rows:{type:"array",required:!0}},run:async e=>{let t=e.live,n=Pg(e.plan,e.rows??[]);if(!n.length)throw new P("invalid_args","no kept pull has linked media");let o=(await ft(t.session_id)).session.timelines?.find(u=>u.kind!=="compound"),s=await qe("timeline_author",{name:`${t.timeline}_VFX_STRINGOUT`,fps_num:o?.fps_num??24,fps_den:o?.fps_den??1,width:o?.resolution_w??1920,height:o?.resolution_h??1080,shots:n.map(u=>({path:u.media,source_in:u.src_in,duration:u.src_out-u.src_in,at:u.rec_in,track:1}))});await qe("timeline_edit",{session_id:s.session_id,kind:"add_markers",args:{markers:n.map(u=>({time:u.rec_in,duration:Math.max(1,u.src_out-u.src_in),name:"conform.tools VFX Pulls",color:u.role==="REFERENCE"?"Purple":"Blue",note:`${u.name} \xB7 Folder: ${u.shot}${u.role==="REFERENCE"?" \xB7 Reference":""}`}))}});let i=Ft(e)==="resolve"&&t.host==="resolve"&&t.timeline?t.timeline:void 0,a=await qe("host_open",{host:Ft(e),session_id:s.session_id,link_existing:!0,...i?{settings_from:i}:{}}),l=String(a.timeline),c=Ft(e)==="resolve"?Number((await qe("host_items",{timeline:l,kind:"video",track:1})).start_frame??0):0;return{ok:!0,text:String(a.text).split(`
|
|
213
|
+
`)[0],timeline:l,start_frame:c}}},"plan.vfx_renders":{label:"Plan pull renders",group:"Planners",effect:!1,about:"One render job per kept pull from the built string-out (its timeline start), into root/<shot>/, plates and reference each with their preset.",params:{plan:{type:"object",required:!0},rows:{type:"array",required:!0},start_frame:{type:"number"},root:{type:"string",required:!0},plate_preset:{type:"string"},reference_preset:{type:"string"}},run:async e=>{if(e.start_frame===void 0)throw new P("invalid_args","build the string-out first (switch on Build)");return Og(e.plan,e.rows??[],Number(e.start_frame),String(e.root),String(e.plate_preset??""),String(e.reference_preset??""))}},"plan.vfx_cut_renders":{label:"Plan pull renders off the cut",group:"Planners",effect:!1,about:"One render job per kept pull straight off the cut (no string-out): a plate with only its track on, a reference with every track; record span \xB1 handles; into root/<shot>/.",params:{plan:{type:"object",required:!0},rows:{type:"array",required:!0},live:{type:"object",required:!0},handles:{type:"number"},root:{type:"string",required:!0},plate_preset:{type:"string"},reference_preset:{type:"string"}},run:async e=>Fg(e.plan,e.rows??[],e.live,Number(e.handles??8),String(e.root),String(e.plate_preset??""),String(e.reference_preset??""))},"plan.marker_renders":{label:"Plan marker renders",group:"Planners",effect:!1,about:`One render job per marker of \`color\` (scope all | duration | frame), named by a delivery convention (naming: ${Lg.map(([e])=>e).join(" | ")}; fields {show, season, episode, film, reel, version, artist \u2026}), with handles, into the convention's folder under root. Rows carry the job; a name two jobs share is marked dupe.`,params:{live:{type:"object",required:!0},color:{type:"string"},scope:{type:"string"},naming:{type:"string"},handles:{type:"number"},fields:{type:"object"},root:{type:"string",required:!0},preset:{type:"string"},folder:{type:"string",about:"a folder template instead of the convention's"},template:{type:"string",about:"a name pattern instead of the convention's: {MARKER} {TL_TC} {SRC_TC} {N} {show} {episode} \u2026"},case:{type:"none|uppercase|lowercase"}},run:async e=>{let t=Ng(e.live,{...e.folder?{folder:String(e.folder)}:{},...e.template?{template:String(e.template)}:{},...e.case?{case:String(e.case)}:{},color:String(e.color??"Blue"),scope:["all","duration","frame"].includes(String(e.scope))?e.scope:"all",naming:String(e.naming??"conformtools"),handles:Number(e.handles??0),fields:Object.fromEntries(Object.entries(e.fields??{}).filter(([,i])=>i!==void 0&&i!=="").map(([i,a])=>[i,String(a)])),root:String(e.root??""),preset:e.preset?String(e.preset):void 0});if(t.length)return t;let n=String(e.color??"Blue"),r=e.live.markers.filter(i=>!i.cells.item_id&&String(i.cells.color).toLowerCase()===n.toLowerCase()),o=r.filter(i=>Number(i.cells.frames??1)>1).length,s=r.length?e.scope==="duration"?`the ${r.length} ${n} marker${r.length===1?" is a single frame":"s are single frames"}; Render: Every marker or Single frames takes ${r.length===1?"it":"them"}`:e.scope==="frame"?`the ${o} ${n} marker${o===1?" is a range":"s are ranges"}; Render: Every marker or Ranges only takes ${o===1?"it":"them"}`:`no ${n} markers on the timeline`:`no ${n} markers on the timeline`;return Object.assign(t,{text:s})}}};for(let[e,t]of Object.entries(Jy))Si[`edit.${e}`]={label:`Edit: ${t}`,group:"Host edits",effect:!1,hosts:Er("apply").filter(n=>Kg(n,e)),about:`One '${e}' edit per row (clip rows or live items), with the other args as its fields (host_apply's '${e}'); feed the result to host.apply.`,params:{rows:{type:"array",about:"the items to edit; leave out for a one-off edit"}},run:async n=>NR(e,n)};var DR={"resolve.pull":"host.read","resolve.apply":"host.apply",...Object.fromEntries(Object.keys(Jy).map(e=>[`resolve.${e}`,`edit.${e}`]))},BR={join:"Join timelines end to end",remove_audio:"Remove audio",stringout:"String-out with handles",add_handles:"Add handles (new timeline)",all_clips:"All clips (new timeline)",reformat:"Change the raster",timeline_rate:"Change the frame rate",add_markers:"Add markers",add_track:"Add a track",delete_track:"Delete a track",add_clip:"Cut a media file in",transform:"Transform a clip",trim:"Trim a clip",slip:"Slip a clip",delete:"Delete a clip",move_clip:"Move a clip",new_timeline:"New empty timeline",carry:"Carry a finished cut's sizing / crop / opacity / effects onto a new cut"},qR=new Set(["add_handles","all_clips","stringout"]);for(let[e,t]of Object.entries(BR))Si[`timeline.${e}`]={label:`Timeline: ${t}`,group:"Timeline",effect:!1,about:`timeline_edit '${e}' on the session (frame-accurate, on the IR, no host needed): its args as this block's; \`sources\` = other sessions whose timelines take part (join several reads).`,params:{session_id:{type:"string",required:!0},sources:{type:"array"}},run:async(n,r)=>{let{session_id:o,...s}=n;if(qR.has(e)){let c=new Map;for(let u of[o,...n.sources??[]])u&&await MR(String(u),c)}let i=await qe("timeline_edit",{session_id:o,kind:e,args:s},r),a=i.meta??{},l=typeof a.timeline_id=="string"?[a.timeline_id]:(a.timelines??[]).map(c=>c.id);return{...i,session_id:o,...l.length?{timeline_id:l[0],timeline_ids:l}:{}}}};Si["timeline.read_many"]={label:"Read timelines",group:"Timeline",effect:!1,about:"Read several timeline files (any host): the first as session_id, the rest as sources for timeline.join and the other timeline blocks.",params:{paths:{type:"array",required:!0},engine:{type:"string"}},run:async(e,t)=>{let n=(e.paths??[]).map(o=>String(o).trim()).filter(Boolean);if(!n.length)throw new P("invalid_args","no timeline files");let r=[];for(let o of n)r.push(String((await qe("timeline_read",{path:o,...e.engine?{engine:e.engine}:{}},t)).session_id));return{ok:!0,text:`read ${r.length} timeline file(s)`,session_id:r[0],sources:r.slice(1),sessions:r}}};var UR=new Set(["timeline_align","timeline_diff"]);function Xy(e){let t=e.startsWith("verb.")?nn(e.slice(5)):void 0;if(!t)return null;let n=Eh(m.object(t.inputSchema));return{label:t.title??t.name,group:"conform.tools",about:String(t.description??"").split(". ")[0],effect:!ks.has(t.name)&&!UR.has(t.name),params:Object.fromEntries(Object.entries(n.properties??{}).map(([r,o])=>[r,{type:o.enum?o.enum.join("|"):o.type,about:o.description,required:n.required?.includes(r)}])),run:(r,o)=>qe(t.name,r,o)}}var Zu=e=>Si[DR[e]??e]??Xy(e),ed=e=>!!Zu(e);function Qy(){let e=ys.filter(t=>!["tool","account_login","account_logout","feedback","job"].includes(t.name)).map(t=>({use:`verb.${t.name}`,...Xy(`verb.${t.name}`)}));return[...Object.entries(Si).map(([t,n])=>({use:t,...n})),...e].map(({run:t,...n})=>n)}var GR=e=>Sb[e]?.slug??e;async function HR(e){let t=e.live;if(e.target==="clips")return t.items.filter(a=>a.kind==="video").sort((a,l)=>a.start-l.start||a.track-l.track).map(a=>({id:a.id,name:a.name,where:`V${a.track}`,op:{op:"name",item:{track:a.track,start:a.start}}}));if(e.target==="pool"&&Ft(e)!=="resolve")throw new P("unsupported",`${Ft(e)}: renaming media pool clips is Resolve only (rename the timeline clips or the timelines)`);let n=await qe("host_project",{host:Ft(e),clips:e.target==="pool"});if(e.target==="timelines"){let a=new Map;return(n.timelines??[]).map(l=>{let c=a.get(l)??0;return a.set(l,c+1),{id:c?`${l}#${c+1}`:l,name:l,where:"timeline",op:{op:"timeline_rename",timeline:l,...c?{nth:c}:{}}}})}let r=a=>[...a.clip_list??[],...(a.folders??[]).flatMap(r)],o=String(e.folder??""),s=o?o==="@selected"?String(n.selected_bin??""):o==="Master"?"":o:null,i=e.subfolders!==!1;return r(n.pool).filter(a=>a.type?.toLowerCase()!=="timeline"&&(s===null||a.folder===s||i&&(s===""||a.folder.startsWith(`${s}/`)))).map(a=>({id:a.id,name:a.name,where:a.folder||"Master",op:{op:"pool_rename",clip:a.id}}))}function zR(e,t,n,r,o=0){let s=e.graphics.flatMap(f=>f.files),i=r?GR(r):s[0]?.position,a=[...new Map(s.map(f=>[f.format,f.width/f.height])).entries()],l=t&&n?t/n:16/9,c=a.sort((f,h)=>Math.abs(Math.log(f[1]/l))-Math.abs(Math.log(h[1]/l)))[0]?.[0],u=e.graphics.map(f=>f.files.find(h=>h.position===i&&h.format===c)??f.files.find(h=>h.format===c)).filter(f=>!!f),d=o,p=u.map(f=>{let h=d;return d+=f.frames,h});return{paths:u.map(f=>f.path),at:p,folder:`Graphics/${e.out_dir.split(/[\\/]/).pop()}`}}var _s=()=>re(tt(),"move-undo");async function WR(e,t){let n=Hn(t),r=t.slice(0,t.length-n.length);for(let o=0;;o++){let s=re(e,o?`${r} (${o})${n}`:t);if(!await Ye(s))return s}}async function Yy(e,t){try{await vo(e,t);return}catch(n){if(!/EXDEV|cross-device/i.test(String(n.message??n)))throw n}if(await wa(e,t),(await Bt(t)).size!==(await Bt(e)).size)throw await Wt(t),new Error("the copy's size differs; the original was kept");await Wt(e)}async function Zy(e,t,n){if(!await Ye(t)||!(await Bt(t)).isDirectory)throw new P("invalid_args",`not a folder: ${t}`);let r=re(t,".conform-tools-write-check.tmp");try{await Ke(r,"ok"),await Wt(r)}catch(s){throw new P("refused",`cannot write to ${t}: ${s.message}`)}let o={moved:[],skipped:[],failed:[]};for(let[s,i]of[...new Set(e)].entries()){if(n?.(s,e.length,fe(i)),!await Ye(i)){o.skipped.push(i);continue}try{let a=await WR(t,fe(i));await Yy(i,a),o.moved.push({source:i,destination:a})}catch(a){o.failed.push({path:i,error:a.message})}}return o.moved.length&&(o.undo_id=`files-${Date.now().toString(36)}`,await Ve(_s()),await Ke(re(_s(),`${o.undo_id}.json`),JSON.stringify(o.moved))),o}async function td(e){let t={moved:[],skipped:[],failed:[]},n=e.filter(l=>l.from!==l.to),r=new Set(n.map(l=>l.from)),o=new Set;for(let l of n){if(o.has(l.to))throw new P("refused",`two files would be named ${fe(l.to)}`);if(o.add(l.to),!r.has(l.to)&&await Ye(l.to))throw new P("refused",`${fe(l.to)} already exists and is not being renamed: nothing moved`)}let s=[];for(let l of n)await Ye(l.from)?s.push(l):t.skipped.push(l.from);let i=`.ct-rename-${Date.now().toString(36)}`,a=[];for(let l of s){let c=`${l.from}${i}`;try{await vo(l.from,c),a.push({...l,tmp:c})}catch(u){t.failed.push({path:l.from,error:u.message})}}for(let l of a)try{await vo(l.tmp,l.to),t.moved.push({source:l.from,destination:l.to})}catch(c){await vo(l.tmp,l.from).catch(()=>{}),t.failed.push({path:l.from,error:c.message})}return t.moved.length&&(t.undo_id=`files-${Date.now().toString(36)}`,await Ve(_s()),await Ke(re(_s(),`${t.undo_id}.json`),JSON.stringify({rename:!0,moves:t.moved}))),t}async function e0(e){let t=re(_s(),`${e.replace(/[^\w-]/g,"")}.json`);if(!await Ye(t))throw new P("not_found",`no file moves recorded as ${e}`);let n=JSON.parse(await ct(t));if(!Array.isArray(n)&&"odd"in n){let{analysisOp:i}=await import("./analysis-engine-VNGF3DE4.js"),a=await i({op:"odd_undo",fixed:n.fixed});return a.errors?.length||await Wt(t),{restored:a.restored??0,failed:(a.errors??[]).map(l=>({path:"",error:l}))}}if(!Array.isArray(n)&&"sort"in n){let{analysisOp:i}=await import("./analysis-engine-VNGF3DE4.js"),a=await i({op:"sort_undo",request:n});return a.errors?.length||await Wt(t),{restored:a.restored??0,failed:(a.errors??[]).map(l=>({path:"",error:l}))}}if(!Array.isArray(n)&&"patch"in n){let{undoPatch:i}=await import("./sequence-patch-5MFTY52Q.js"),a=await i(n);return a.failed.length||await Wt(t),a}if(!Array.isArray(n)){let i=await td(n.moves.map(a=>({from:a.destination,to:a.source})));return i.undo_id&&await Wt(re(_s(),`${i.undo_id}.json`)),i.failed.length||await Wt(t),{restored:i.moved.length,failed:i.failed}}let r=n,o=0,s=[];for(let i of r)try{if(await Ye(i.source))throw new Error("a file is at the original path again; left where it is");await Ve(i.source.replace(/[\\/][^\\/]*$/,"")),await Yy(i.destination,i.source),o++}catch(a){s.push({path:i.destination,error:a.message})}return s.length||await Wt(t),{restored:o,failed:s}}var KR=e=>e.length>4?e.replace(/(ings?|ers?|ed|es|s)$/,"").replace(/e$/,""):e,nd=e=>e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().split(" ").filter(Boolean).map(KR);var VR=new Set(nd("a an the and or but to of in on at by for from with into onto as is are be been do does make made can could please me my i we our you your it its this that these those them they there here what which how when where all every each any some one just only also then than so not no up out over use using want need get got let tell show give know see look help like have has did done go going would should will file files folder clip clips timeline timelines thing things way").concat(["{","}"]));function vs(e){return[...new Set(nd(e.replace(/\{[^{}]*\}/g," ")).filter(t=>t.length>1&&!VR.has(t)))]}var $i=(e,t)=>e===t||e.length>=4&&t.length>=4&&(e.startsWith(t)||t.startsWith(e)),JR=.4;function rd(e,t,n=5){let r=t.filter(c=>c.id.includes("_")&&new RegExp(`(^|[^a-z_])${c.id}([^a-z_]|$)`,"i").test(e)).map(c=>({id:c.id,title:c.title,score:1}));if(r.length)return r.slice(0,n);let o=vs(e);if(!o.length)return[];let s=t.map(c=>({d:c,head:vs(`${c.id.replace(/[_-]/g," ")} ${c.title} ${(c.aka??[]).join(" ")}`),body:vs(c.text)})),i=c=>Math.log(1+s.length/(1+s.filter(u=>u.head.some(d=>$i(c,d))||u.body.some(d=>$i(c,d))).length)),a=o.map(i),l=a.reduce((c,u)=>c+u,0);return s.map(({d:c,head:u,body:d})=>{let p=o.reduce((f,h,g)=>f+a[g]*(u.some(b=>$i(h,b))?1:d.some(b=>$i(h,b))?.6:0),0);return{id:c.id,title:c.title,score:Math.round(p/l*100)/100}}).filter(c=>c.score>=JR).sort((c,u)=>u.score-c.score||c.id.localeCompare(u.id)).slice(0,n)}var XR=3;function od(e,t,n=5){let r=vs(e),o=t.map(a=>({d:a,head:vs(`${a.id.replace(/[_-]/g," ")} ${a.title} ${(a.aka??[]).join(" ")}`),body:vs(a.text)})),s=(a,l)=>a.some(c=>$i(l,c)),i=a=>Math.log(1+o.length/(1+o.filter(l=>s(l.head,a)||s(l.body,a)).length));return o.map(({d:a,head:l,body:c})=>({id:a.id,title:a.title,score:Math.round(r.reduce((u,d)=>u+i(d)*(s(l,d)?XR:s(c,d)?.6:0),0)*100)/100})).filter(a=>a.score>0).sort((a,l)=>l.score-a.score||a.id.localeCompare(l.id)).slice(0,n)}var QR=2e4,YR=100,t0=3e3,ZR=6e4,Ts=()=>re(tt(),"telemetry","capture.jsonl"),eC=0,n0=0,Ri=null;function tC(e,t,n,r,o){let s=(n.content??[]).map(a=>a.text??"").join(`
|
|
214
|
+
`),i={};try{i=JSON.parse(JSON.stringify(t,(a,l)=>a.startsWith("__")||typeof l=="function"?void 0:l))}catch{}return{event_id:crypto.randomUUID(),run_id:t1,req:o.req,seq:++eC,client:o.client??null,version:ka,verb:e,ok:!n.isError,args:i,result:s.slice(0,QR),result_chars:s.length,duration_ms:Math.round(r),run_at:new Date().toISOString()}}async function r0(e,t,n,r,o){try{if(!await Ua()){await Wt(Ts()).catch(()=>{});return}await Ve(re(tt(),"telemetry")),await Ke(Ts(),JSON.stringify(tC(e,t,n,r,{req:Ob()||void 0,client:o??Fb()}))+`
|
|
215
|
+
`,{append:!0}),nC()}catch{}}function nC(e={}){return Ri||(Ri=(async()=>{try{if(!e.force&&Date.now()-n0<ZR)return;let t=(await ct(Ts()).catch(()=>"")).split(`
|
|
216
|
+
`).filter(Boolean);if(!t.length)return;let n=await Oh().catch(()=>null);if(!n){t.length>t0&&await Ke(Ts(),t.slice(-t0).join(`
|
|
217
|
+
`)+`
|
|
218
|
+
`);return}n0=Date.now();let r=t.slice(0,YR),o=await fetch(`${li().supabaseUrl}/functions/v1/v1-me/v1/engine/capture`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${n}`,apikey:li().anonKey},body:`{"calls":[${r.join(",")}]}`,signal:AbortSignal.timeout(15e3)}).catch(()=>null);if(o?.ok||o?.status===400||o?.status===413){let s=(await ct(Ts()).catch(()=>"")).split(`
|
|
219
|
+
`).filter(Boolean);await Ke(Ts(),s.slice(r.length).map(i=>i+`
|
|
220
|
+
`).join(""))}await o?.body?.cancel().catch(()=>{})}catch{}finally{Ri=null}})(),Ri)}async function o0(e){let t=sd(await e),[n,r,{QuickJSWASMModule:o}]=await Promise.all([t.importModuleLoader().then(sd),t.importFFI(),import("./module-ES6BEMUI-L6VQ7K3J.js").then(sd)]),s=await n();s.type="sync";let i=new r(s);return new o(s,i)}function sd(e){return e&&"default"in e&&e.default?e.default&&"default"in e.default&&e.default.default?e.default.default:e.default:e}var rC={type:"sync",importFFI:()=>import("./ffi-7KTOX2T4.js").then(e=>e.QuickJSFFI),importModuleLoader:()=>import("./emscripten-module-Q67P5WYC-HW3D2R5O.js").then(e=>e.default)},s0=rC;var d_=H$(c_(),1);var gO=256*2**20,bO=3e4,$m=200,yO,u_="async function __main() {",wO='const ct = new Proxy({}, { get: (_, name) => typeof name !== "string" || name === "then" ? undefined : (args = {}) => __call(name, JSON.stringify(args ?? {})).then(JSON.parse, (e) => { const o = JSON.parse(e); const x = new Error(o.message); x.code = o.code; x.verb = name; throw x; }) });';function kO(e){try{return(0,d_.transform)(`${u_}${e}
|
|
221
|
+
}`,{transforms:["typescript"],disableESTransforms:!0}).code}catch(t){throw new P("invalid_args",`the script does not parse: ${t.message.replace(/\((\d+):(\d+)\)/,(n,r,o)=>`(line ${r}, column ${r==="1"?Number(o)-u_.length:o})`)}`)}}async function p_(e,t,{signal:n,onCall:r,cpuMs:o=bO}={}){let s=kO(e),a=(await(yO??=o0(s0))).newRuntime();a.setMemoryLimit(gO),a.setMaxStackSize(2**20);let l=performance.now();a.setInterruptHandler(()=>n?.aborted||performance.now()-l>o);let c=a.newContext(),u=[],d=[],p=!0,f=()=>{p&&(l=performance.now(),a.executePendingJobs())},h=new Set;try{let g=c.newObject();for(let v of["log","info","warn","error"])c.newFunction(v,(...T)=>{u.length<$m?u.push(T.map($=>{let x=c.dump($);return typeof x=="string"?x:JSON.stringify(x)}).join(" ")):u.length===$m&&u.push(`\u2026 (console lines after ${$m} dropped)`)}).consume(T=>c.setProp(g,v,T));c.setProp(c.global,"console",g),g.dispose(),c.newFunction("__call",(v,T)=>{let $=c.newPromise();h.add($);let x=c.getString(v),R=c.getString(T);return d.push(x),r?.(d.length,x),Promise.resolve().then(()=>t(x,JSON.parse(R))).then(C=>{p&&$.alive&&c.newString(JSON.stringify(C??null)).consume(B=>$.resolve(B))},C=>{let B=C instanceof P?C:new P("engine",C instanceof Error?C.message:String(C));p&&$.alive&&c.newString(JSON.stringify({code:B.code,message:B.message})).consume(L=>$.reject(L))}).finally(()=>{h.delete($),$.alive&&$.dispose(),f()}),$.handle}).consume(v=>c.setProp(c.global,"__call",v));let b=c.evalCode(`${wO} ${s}
|
|
222
|
+
__main();`,"script"),k=c.unwrapResult(b),w=c.resolvePromise(k);k.dispose(),f();let y=new Promise((v,T)=>{n?.aborted&&T(new P("cancelled","script cancelled")),n?.addEventListener("abort",()=>T(new P("cancelled","script cancelled")),{once:!0})}),_=await Promise.race([w,y]);if(_.error){let v=_.error.consume(x=>c.dump(x));if(typeof v=="object"&&v?.message==="interrupted"&&n?.aborted)throw new P("cancelled","script cancelled");if(typeof v=="object"&&v?.message==="interrupted")throw new P("refused",`the script computed for over ${o/1e3} s without calling a verb (a loop that never ends?) and was stopped`);let T=typeof v=="object"?v.verb?`ct.${v.verb}: ${v.message}`:`${v.name??"Error"}: ${v.message}${v.stack?`
|
|
223
|
+
${v.stack.replace(/^/gm," ").trimEnd()}`:""}`:String(v),$=typeof v=="object"&&v.name==="ReferenceError"?`
|
|
224
|
+
(the script has no globals but ct: take every value from an await ct.<tool>(\u2026) answer or write it as a literal; a {placeholder} is for begin's asked line, never code)`:"";throw new P(typeof v=="object"&&v.code?v.code:"engine",`the script stopped after ${d.length} call${d.length===1?"":"s"}: ${T}${$}${u.length?`
|
|
225
|
+
console:
|
|
226
|
+
${u.join(`
|
|
227
|
+
`)}`:""}`,{calls:d})}return{value:_.value.consume(v=>c.dump(v)),logs:u,calls:d}}finally{p=!1;for(let g of h)g.alive&&g.dispose();c.dispose(),a.dispose()}}function m_(e){let t=e._def;if(t.typeName)return t.typeName;let n=typeof t.type=="string"?t.type:"";return n==="pipe"?"ZodPipeline":`Zod${n.charAt(0).toUpperCase()}${n.slice(1)}`}function Zn(e){let t=e._def;switch(m_(e)){case"ZodString":return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodLiteral":return(t.values??[t.value]).map(n=>JSON.stringify(n)).join(" | ");case"ZodEnum":return Object.values(t.entries??t.values).map(n=>JSON.stringify(n)).join(" | ");case"ZodNativeEnum":return Object.values(t.values).map(n=>JSON.stringify(n)).join(" | ");case"ZodArray":{let n=Zn(t.element??t.type);return/[ |]/.test(n)?`(${n})[]`:`${n}[]`}case"ZodTuple":return`[${t.items.map(Zn).join(", ")}]`;case"ZodObject":return g_(e.shape);case"ZodRecord":return`Record<string, ${Zn(t.valueType)}>`;case"ZodUnion":case"ZodDiscriminatedUnion":return t.options.map(Zn).join(" | ");case"ZodIntersection":return`${Zn(t.left)} & ${Zn(t.right)}`;case"ZodOptional":case"ZodDefault":case"ZodCatch":case"ZodReadonly":return Zn(t.innerType);case"ZodNullable":return`${Zn(t.innerType)} | null`;case"ZodEffects":return Zn(t.schema);case"ZodPipeline":return Zn(t.in);case"ZodLazy":return Zn(t.getter());default:return"unknown"}}var f_=e=>e.isOptional()||m_(e)==="ZodDefault",h_=(e,t)=>e?`${t}/** ${e.replace(/\*\//g,"*\\/").replace(/\s*\n\s*/g," ")} */
|
|
228
|
+
`:"";function g_(e,t=" "){let n=Object.keys(e);return n.length?`{
|
|
229
|
+
${n.map(r=>`${h_(e[r].description,t)}${t}${/^[A-Za-z_$][\w$]*$/.test(r)?r:JSON.stringify(r)}${f_(e[r])?"?":""}: ${Zn(e[r])};`).join(`
|
|
230
|
+
`)}
|
|
231
|
+
${t.slice(2)}}`:"{}"}function b_(e,t={}){return["/** Every verb's answer: its structured fields plus `text`, the same answer as the tool gives. A failed verb throws an Error with `code` and `verb`. */","type Answer = { ok: boolean; text: string; [field: string]: any };",`declare const ct: {
|
|
232
|
+
${e.map(r=>`${h_(r.description," ")} ${r.name}(args${Object.values(r.inputSchema).every(f_)?"?":""}: ${g_(r.inputSchema," ")}): Promise<${t[r.name]?`Answer & ${t[r.name]}`:"Answer"}>;`).join(`
|
|
233
|
+
`)}
|
|
234
|
+
};`].join(`
|
|
235
|
+
`)}function nc(e,t=0){if(e==null)return"null";if(Array.isArray(e))return{arr:e.slice(0,50).map(r=>nc(r,t)).reduce(Zi,"null")};if(typeof e!="object")return typeof e;if(t>=3)return"object";let n=Object.keys(e).filter(r=>r!=="text");return n.length>40||n.some(r=>!/^[a-z][a-z0-9_]*$/i.test(r))?"Record<string, any>":{obj:Object.fromEntries(n.map(r=>[r,nc(e[r],t+1)]))}}function Zi(e,t){if(e==="null")return t;if(t==="null"||e===t)return e;if(typeof e=="object"&&typeof t=="object"){if("arr"in e&&"arr"in t)return{arr:Zi(e.arr,t.arr)};if("obj"in e&&"obj"in t){let n={...e.obj};for(let[r,o]of Object.entries(t.obj))n[r]=r in n?Zi(n[r],o):o;return{obj:n}}}return"any"}function ea(e){if(typeof e=="string")return e;if("arr"in e){let n=ea(e.arr);return/^[\w<>, ]+$|^\{.*\}$/.test(n)?`${n}[]`:`(${n})[]`}let t=Object.keys(e.obj);return t.length?`{ ${t.map(n=>`${n}: ${ea(e.obj[n])}`).join("; ")} }`:"{}"}var Rm=e=>Object.values(e.out).map(t=>t?.parity).find(Boolean),Do=e=>Object.fromEntries(Object.entries(e.out).flatMap(([t,n])=>{let r=n,o=typeof r?.timeline_id=="string"?r.timeline_id:Array.isArray(r?.timeline_ids)&&typeof r.timeline_ids[0]=="string"?r.timeline_ids[0]:void 0;return o?[[t,o]]:[]})),Bo=e=>Object.fromEntries(Object.entries(e.out).flatMap(([t,n])=>{let r=n?.session_id;return typeof r=="string"?[[t,r]]:[]})),Bs=new Map,_O=50,y_=(e,t)=>t.reduce((n,r)=>n?.[r],e);function Nr(e,t){if(vi(e)){for(let n of e.split("|")){let[r,...o]=n.trim().slice(1).split("."),s=y_(r==="in"?t.in:t.out[r],o);if(s!=null&&s!=="")return s}return}return Array.isArray(e)?e.map(n=>Nr(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,Nr(r,t)])):e}function k_(e,t){if(!e)return!0;if(e.includes(" & "))return e.split(" & ").every(o=>k_(o,t));let n=/^(.*?)(!=|=)(.*)$/.exec(e);if(!n){let o=Nr(e,t);return o!==void 0&&o!==!1}let r=String(Nr(n[1].trim(),t)??"");return n[2]==="="?r===n[3].trim():r!==n[3].trim()}function vO(e,t){let n=new Map(e.nodes.map(i=>[i.id,i])),r=new Set,o=(i,a)=>{if(vi(i))for(let l of i.split("|")){let c=l.trim().slice(1).split(/[.=!]/)[0];c&&c!=="in"&&a.push(c)}else Array.isArray(i)?i.forEach(l=>o(l,a)):i&&typeof i=="object"&&Object.values(i).forEach(l=>o(l,a));return a},s=i=>{if(r.has(i)||!n.has(i))return;r.add(i);let a=n.get(i);for(let l of o(a.when,o(a.args,[])))s(l)};return s(t),r}async function qo(e,t,n={}){let r,o=0,s,i;if(n.resume){let g=Bs.get(n.resume.run_id);if(!g)throw new P("not_found","that run is no longer waiting (run the tool again)");Bs.delete(n.resume.run_id),{spec:e,ctx:r,at:o}=g,n.resume.inputs&&(r={...r,in:{...r.in,...n.resume.inputs}}),s=g.only?new Set(g.only):void 0;let b=e.nodes[o];if(g.inner){let k=await qo({},{},{...n,resume:n.resume&&{run_id:g.inner.run_id,keep:n.resume.keep,...n.resume.inputs?{inputs:Nr(b.args,r)}:{}},until:void 0});if(k.state==="review")return w_(k,{spec:e,ctx:r,at:o,only:g.only,inner:{run_id:k.run_id,node:b.id}});if(k.state==="ready")return{state:"ready",node:b.id,label:k.label};if(!k.ok)return k;i=r.out[b.id]=k.output}else{let k=Nr(b.args.rows,r)??[],w=new Set(n.resume.keep),y=b.args.skip;i=r.out[b.id]=k.filter(_=>w.has(_.id)&&!(y&&_.cells[y]))}o++}else{let g=Object.fromEntries(e.inputs.map(b=>[b.id,t[b.id]??b.default]));for(let b of e.inputs)b.when&&!b.when.is.includes(String(g[b.when.input]??""))&&delete g[b.id];if(r={in:{...Object.fromEntries(Object.entries(t).filter(([b])=>b in g||!e.inputs.some(k=>k.id===b))),...g},out:{}},n.until){if(!e.nodes.some(b=>b.id===n.until))throw new P("not_found",`no node '${n.until}'`);s=vO(e,n.until)}}let a=[];for(;o<e.nodes.length;o++){let g=e.nodes[o];if(s&&!s.has(g.id)||!k_(g.when,r))continue;if(g.use.startsWith("tool.")){if(!n.tool)throw new P("invalid_args",`node '${g.id}': tools inside tools need the tool table`);let w=await n.tool(g.use.slice(5)),y=await qo(w,Nr(g.args,r),{...n,until:void 0,resume:void 0});if(y.state==="review")return w_(y,{spec:e,ctx:r,at:o,only:s&&[...s],inner:{run_id:y.run_id,node:g.id}});if(y.state==="ready")return{state:"ready",node:g.id,label:`${w.name}: ${y.label}`,sessions:{...Bo(r),...y.sessions},timelines:{...Do(r),...y.timelines}};if(!y.ok)return{...y,text:`${g.label??w.name}: ${y.text}`};i=r.out[g.id]=y.output??{ok:!0,text:y.text},a.push(y.text);continue}let b=Zu(g.use);if(!b)throw new P("invalid_args",`node '${g.id}': no block '${g.use}'`);let k=g.label??b.label;if(g.use==="review"){let w=Nr(g.args.rows,r)??[];if(!w.length){let v=/^\$(\w+)/.exec(String(g.args.rows??""))?.[1];return{state:"done",ok:!0,text:`Nothing to do: ${(v&&r.out[v]?.text)??g.args.empty??"it found nothing"}.`,node:g.id,sessions:Bo(r),timelines:Do(r)}}let y=crypto.randomUUID();__(y,{spec:e,ctx:r,at:o,only:s&&[...s]});let _=Rm(r);return{state:"review",run_id:y,node:g.id,label:k,rows:w,columns:g.args.columns??[],skip:g.args.skip,sessions:Bo(r),timelines:Do(r),..._?{parity:_}:{}}}if(n.preview&&b.effect)return{state:"ready",node:g.id,label:k,sessions:Bo(r),timelines:Do(r)};try{i=r.out[g.id]=await b.run(Nr(g.args,r),{signal:n.signal,progress:n.progress});let w=i?.text;b.effect&&typeof w=="string"&&a.push(w)}catch(w){return{state:"done",ok:!1,text:`${k}: ${w.message}`,node:g.id,sessions:Bo(r),timelines:Do(r)}}}let l=i&&typeof i=="object"&&!Array.isArray(i)?i:{},c=typeof l.text=="string"?l.text:Array.isArray(i)?`${i.length} result(s)`:i===void 0?"done":JSON.stringify(i).slice(0,2e3),u=a.length?a.join(`
|
|
236
|
+
`):c,d=Object.values(r.out).map(g=>g?.undo_id).filter(g=>typeof g=="string"),p=d.length?d.join("+"):void 0,f=Object.values(r.out).map(g=>g?.made).filter(g=>typeof g=="string").at(-1),h=Object.values(r.out).find(g=>typeof g?.clips=="object");return{state:"done",ok:l.ok!==!1,text:u,...p?{undo_id:p}:{},...typeof h?.timeline=="string"?{timeline:h.timeline}:{},...f?{made:f}:{},...l.table?{table:l.table}:{},output:i,sessions:Bo(r),timelines:Do(r),...Rm(r)?{parity:Rm(r)}:{}}}function __(e,t){for(Bs.set(e,{...t,at:t.at});Bs.size>_O;)Bs.delete(Bs.keys().next().value)}function w_(e,t){let n=crypto.randomUUID();return __(n,t),{...e,run_id:n,sessions:{...Bo(t.ctx),...e.sessions},timelines:{...Do(t.ctx),...e.timelines}}}var Uo=new Map,TO=100,na=()=>new Date().toISOString();function ra(e){for(e.updated=na(),Uo.set(e.id,e);Uo.size>TO;)Uo.delete(Uo.keys().next().value);return Wr({type:"run",run:e}),e}function ta(e,t){return e.state=t,e.status=t.state==="review"?"review":t.state==="ready"||t.ok?"done":"failed",ra(e)}function Go(e,t){return[...Uo.values()].filter(n=>n.project===e&&(!t||n.tool===t)).reverse()}function oa(e){return Uo.get(e)??[...Uo.values()].find(t=>t.state?.state==="review"&&t.state.run_id===e)}async function v_(e,t,n,r={}){if(r?.until||r?.preview&&n.by==="app")return{state:await qo(e,t,r)};let o=ra({id:crypto.randomUUID(),tool:e.id,name:e.name,project:n.project,by:n.by,inputs:t,status:"running",started:na(),updated:na()});try{let s=await qo(e,t,r);return{run:ta(o,s),state:s}}catch(s){throw ta(o,{state:"done",ok:!1,text:s.message}),s}}function xO(e,t,n,r){if(n)return n;let o=new Set(r?.map(s=>(typeof s=="number"||/^\d+$/.test(String(s)))&&!e.some(i=>i.id===String(s))?e[Number(s)-1]?.id:String(s)));return e.filter(s=>!(t&&s.cells[t])&&!o.has(s.id)).map(s=>s.id)}async function T_(e,t,n={}){let r=t.id?oa(t.id):Go(e,t.tool).find(i=>i.status==="review");if(!r){if(t.id){let i=await qo({},{},{...n,resume:{run_id:t.id,keep:t.keep??[],inputs:t.inputs}}),a={id:crypto.randomUUID(),tool:t.tool??"",name:t.name??t.tool??"",project:e,by:t.by??"app",inputs:t.inputs??{},status:"running",started:na(),updated:na()};return{run:ta(a,i),state:i}}throw new P("not_found",t.tool?`nothing from ${t.tool} is waiting for an OK`:"nothing is waiting for an OK in this job")}if(r.state?.state!=="review")throw new P("invalid_args",`${r.name} is not waiting for an OK (it is ${r.status})`);let o=r.state,s=xO(o.rows,o.skip,t.keep,t.drop);r.status="running",ra(r);try{let i=await qo({},{},{...n,resume:{run_id:o.run_id,keep:s,inputs:t.inputs}});return{run:ta(r,i),state:i}}catch(i){throw ta(r,{state:"done",ok:!1,text:i.message}),i}}function x_(e,t){let n=t.id?oa(t.id):Go(e,t.tool).find(r=>r.status==="review");if(!n||n.status!=="review")throw new P("not_found","nothing is waiting for an OK");return n.status="dropped",ra(n)}async function S_(e,t,n){let r=a=>a.status==="done"&&a.state?.state==="done"&&!!a.state.undo_id,o=t.id?oa(t.id):Go(e,t.tool).find(r);if(!o||!r(o))throw new P("not_found",o?`${o.name}'s run left nothing to undo`:"nothing in this job to undo");let s=o.state,i=await n(s.undo_id,s.timeline);if(!i.ok)throw new P("engine",i.text);return o.status="undone",o.undone=i.text,ra(o)}function Cm(e,t=25){let n=e.state,r=`${e.name} (${e.tool}) \xB7 run ${e.id} \xB7 ${e.status} \xB7 by ${e.by}`;if(e.status==="review"&&n?.state==="review"){let o=n.columns.length?n.columns.map(([i])=>i):[...new Set(n.rows.slice(0,20).flatMap(i=>Object.keys(i.cells)))].slice(0,6),s=n.rows.slice(0,t).map((i,a)=>` ${a+1}. [${i.id}] ${o.map(l=>`${l}: ${String(i.cells[l]??"")}`).join(" \xB7 ")}${n.skip&&i.cells[n.skip]?" (skipped)":""}`);return[`${r} \u2014 ${n.label}: ${n.rows.length} row(s) waiting for an OK`,...s,...n.rows.length>t?[` \u2026 ${n.rows.length-t} more`]:[]].join(`
|
|
237
|
+
`)}return n?.state==="done"?`${r} \u2014 ${e.undone?`undone: ${e.undone}`:n.text.split(`
|
|
238
|
+
`)[0]}${n.undo_id&&e.status==="done"?" (can undo)":""}`:r}function $_(e,t){let n=e.state,r=n?.state==="review"?n:n?.state==="done"?n.table:void 0,o=a=>String(a==null?"":typeof a=="object"?JSON.stringify(a):a).replace(/[&<>"]/g,l=>`&#${l.charCodeAt(0)};`),s=(r?.columns.length?r.columns:[...new Set((r?.rows??[]).flatMap(a=>Object.keys(a.cells)))].map(a=>[a,a])).filter(([a])=>a!=="__keep"),i=t.size>0;return`<!doctype html><meta charset="utf-8"><title>${o(e.name)}</title>
|
|
239
|
+
<style>body{font:12px system-ui,sans-serif;margin:16px}table{border-collapse:collapse}th,td{border-bottom:1px solid #ddd;padding:4px 8px;text-align:left;vertical-align:middle}th{position:sticky;top:0;background:#fff}img{width:160px;display:block}</style>
|
|
240
|
+
<h1>${o(e.name)}</h1><table><thead><tr>${i?"<th></th>":""}${s.map(([a,l])=>`<th>${o(l||a)}</th>`).join("")}</tr></thead><tbody>
|
|
241
|
+
${(r?.rows??[]).map(a=>`<tr>${i?`<td>${t.has(a.id)?`<img src="${t.get(a.id)}" alt="">`:""}</td>`:""}${s.map(([l])=>`<td>${o(a.cells[l])}</td>`).join("")}</tr>`).join(`
|
|
242
|
+
`)}
|
|
243
|
+
</tbody></table>`}function R_(e){let t=e.state,n=t?.state==="review"?t:t?.state==="done"?t.table:void 0;if(!n)return null;let r=n.columns.length?n.columns:[...new Set(n.rows.flatMap(o=>Object.keys(o.cells)))].map(o=>[o,o]);return Oa(r.filter(([o])=>o!=="__keep").map(([o,s])=>({header:s||o,value:i=>{let a=i.cells[o];return a==null?"":typeof a=="object"?JSON.stringify(a):String(a)}})),n.rows)}function SO(e){let t=e?.duration?.value,n=e?.duration?.rate;if(!t||!n)return"n/a";let r=o=>String(o).padStart(2,"0");if(n>=1e3){let o=t/n,s=Math.round((o-Math.floor(o))*1e3);return`${r(Math.floor(o/3600))}:${r(Math.floor(o/60)%60)}:${r(Math.floor(o)%60)}.${String(s).padStart(3,"0")}`}return He(Math.max(0,t),n)}function C_(e){for(let t of e?.streams??[])if(t.kind==="video"&&t.bit_depth!=null)return t.bit_depth;return null}var Am=[{label:"Start TC",criterion:"timecode",standing:!0,get:e=>e?.source_timecode||"00:00:00:00",has:e=>!!e?.source_timecode},{label:"Reel",criterion:"reelName",get:e=>e?.reel_name||"n/a",has:e=>!!e?.reel_name},{label:"Duration",criterion:"totalDuration",get:e=>SO(e?.available_range?.duration?.value?e.available_range:e?.declared_duration?{duration:e.declared_duration}:null),has:e=>(e?.available_range?.duration?.value??0)>0||(e?.declared_duration?.value??0)>0},{label:"Resolution",criterion:"resolution",get:e=>e?.source_resolution_w&&e?.source_resolution_h?`${e.source_resolution_w}\xD7${e.source_resolution_h}`:"n/a",has:e=>!!(e?.source_resolution_w&&e?.source_resolution_h)},{label:"Bit depth",criterion:"bitDepth",get:e=>{let t=C_(e);return t!=null?`${t}-bit`:"n/a"},has:e=>C_(e)!=null},{label:"Frame rate",criterion:"frameRate",standing:!0,get:e=>e?.source_fps!=null?ku(e.source_fps):"n/a",has:e=>e?.source_fps!=null},{label:"Format",criterion:"fileFormat",get:e=>e?.container||"n/a",has:e=>!!e?.container},{label:"Codec",criterion:"codec",get:e=>e?.codec||"n/a",has:e=>!!e?.codec}],A_=Am.map(e=>e.label);var E_=["#","name","track","timeline","kind","item_index","enabled","timeline_range.start","timeline_range.dur","source_range.start","source_range.dur","media_reference_id","source_element_id","reel_name","source_timecode","nested_timeline_id","is_nested","is_multicam","is_reinterpreted","speed","speed_ramped","speed_reverse","scale","scale_x","scale_y","position_x","position_y","rotation","anchor_x","anchor_y","crop_left","crop_right","crop_top","crop_bottom","opacity","blend_mode","keyframes","effects","effect_names","binding_state",...A_];function $O(e){if(!e||typeof e!="object")return!1;let t=e,n=t.start,r=t.duration;return!!n&&!!r&&typeof n.value=="number"&&typeof r.value=="number"}function I_(e,t,n){for(let[r,o]of Object.entries(t)){let s=e?`${e}.${r}`:r;if(o==null)n[s]=null;else if(typeof o=="string"||typeof o=="number"||typeof o=="boolean")n[s]=o;else if($O(o))n[`${s}.start`]=Math.round(o.start.value),n[`${s}.dur`]=Math.round(o.duration.value);else if(Array.isArray(o))n[s]=o.length?`[${o.length}]`:null;else if(typeof o=="object"){let i=JSON.stringify(o);n[s]=i==="{}"?null:i}}}function P_(e){let t=[],n=new Set,r=[],o=a=>{n.has(a)||(n.add(a),r.push(a))},s=0;for(let a of us(e))for(let l of a.tracks??[])for(let c of l.items??[]){if(c.kind==="gap")continue;let u={};u["#"]=++s,u.timeline=a.name,u.timeline_fps=Pt(a),u.track=Sn(l,a.tracks??[]),I_("",c,u);let d=(c.effects??[]).map(f=>f.name||f.plugin_name||f.kind||"").filter(Boolean);u.effect_names=d.length?d.join(", "):null,u.source_fps_n=_u(e,c)?.source_fps??null;let p=_u(e,c);for(let f of Am){let h=p?f.get(p):null;u[f.label]=h==="n/a"?null:h}u.binding_state=p?p.binding_state??"unbound":null;for(let f of Object.keys(u))o(f);t.push({id:c.id,item:c,cells:u})}return{columns:[...E_,...r.filter(a=>!E_.includes(a))],rows:t}}var M_=["name","binding_state","usage","origin","content_kind","kind","target_url","local_path","reel_name","reel_sources","source_timecode","available_range.start","available_range.dur","source_resolution_w","source_resolution_h","source_pixel_aspect","source_fps","container","codec","size_bytes","bitrate_bps","streams","display_name","file_modified_at","keykode","vendor_metadata","bundle","recipe","raw_extraction","metadata"];function F_(e){let t=[],n=new Set,r=[],o=i=>{n.has(i)||(n.add(i),r.push(i))};for(let i of e){let a={};a.name=i.name,a.origin=i.origin,i.ref&&I_("",i.ref,a),i.extra&&Object.assign(a,i.extra);for(let l of Object.keys(a))o(l);t.push({id:i.id,name:i.name,ref:i.ref,origin:i.origin,cells:a})}return{columns:[...M_,...r.filter(i=>!M_.includes(i))],rows:t}}var RO={name:"Name",origin:"Origin",usage:"Usage",id:"ID",binding_state:"State",content_kind:"Kind",target_url:"Path",reel_name:"Reel",source_timecode:"Start TC",source_resolution_w:"Source W",source_resolution_h:"Source H",source_pixel_aspect:"PAR",source_fps:"FPS",size_bytes:"Size",codec:"Codec",container:"Format",declared_duration:"Declared",available_range:"Range",source_facts_origin:"Facts",coverage_reason:"Coverage",display_name:"Display name"};function rc(e){let t=RO[e];return t||e.split(".").map(n=>n.replace(/_/g," ").replace(/^./,r=>r.toUpperCase())).join(" \xB7 ")}var CO=/^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/,Ho="[-+]?(?:\\d+\\.?\\d*|\\.\\d+)(?:[eE][-+]?\\d+)?";function zo(e){let t=e.trim();if(!CO.test(t))return null;let n=Number(t);return Number.isFinite(n)?n:null}function AO(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string")return null;let t=zo(e);if(t!==null)return t;let n=e.trim().match(new RegExp(`^(${Ho})\\s*[a-zA-Z%\xB0\xD7]*$`));if(!n)return null;let r=Number(n[1]);return Number.isFinite(r)?r:null}function O_(e){let t=e.trim(),n=t.indexOf(".");if(n===-1||/[eE]/.test(t))return 1e-4;let r=t.length-n-1;return Math.max(1e-4,.5*Math.pow(10,-(r+1)))}function qs(e){let t=e.trim();if(!t||t.includes("...."))return null;let r=t.match(new RegExp(`^between\\s+(${Ho})\\s+and\\s+(${Ho})$`,"i"))??t.match(new RegExp(`^(${Ho})\\s*(?:\\.\\.\\.?|,,|\\s+to\\s+|-)\\s*(${Ho})$`,"i"));if(r){let a=zo(r[1]),l=zo(r[2]);return a===null||l===null?null:{op:"range",value:Math.min(a,l),high:Math.max(a,l)}}let o=t.match(new RegExp(`^(?:in\\s+)?(${Ho}(?:\\s*[,|]\\s*${Ho})+)$`,"i"));if(o){let a=o[1].split(/\s*[,|]\s*/).map(zo);if(a.some(c=>c===null))return null;let l=a;return{op:"in",value:l[0],values:l,tolerance:1e-4}}let s=t.match(/^(>=|<=|!=|==|=|>|<)\s*(.+)$/);if(s){let a=zo(s[2]);return a===null?null:{op:s[1]==="=="?"=":s[1],value:a,tolerance:O_(s[2])}}let i=zo(t);return i!==null?{op:"=",value:i,tolerance:O_(t)}:null}function EO(e){let t=e.trim();if(!t)return null;let n=qs(t);if(n)return[n];let r=t.split(/(?:\s*(?:,|&|\band\b)\s*|\s+)(?=(?:>=|<=|!=|==|=|>|<))/i).map(s=>s.trim().replace(/(?:\s*(?:,|&|\band))+$/i,"").trim()).filter(Boolean);if(r.length<2)return null;let o=r.map(qs);return o.some(s=>s===null)?null:o}function MO(e,t,n){if(!Number.isFinite(e))return!1;let r=n??t.tolerance??1e-6;switch(t.op){case"=":return Math.abs(e-t.value)<=r;case"!=":return Math.abs(e-t.value)>r;case">":return e>t.value;case"<":return e<t.value;case">=":return e>=t.value-r;case"<=":return e<=t.value+r;case"range":return e>=t.value-r&&e<=(t.high??t.value)+r;case"in":return(t.values??[t.value]).some(o=>Math.abs(e-o)<=r);default:return!1}}function Em(e,t=0){if(t>4||e===null||e===void 0)return[];let n=AO(e);return n!==null?[n]:Array.isArray(e)?e.flatMap(r=>Em(r,t+1)):typeof e=="object"?Object.values(e).flatMap(r=>Em(r,t+1)):[]}function Us(e,t,n="="){let r=EO(t);if(!r)return!1;let o=Em(e);if(o.length===0)return!1;let s=zo(t)!==null,i=r.map(a=>s&&n!=="="?{...a,op:n}:a);return o.some(a=>i.every(l=>MO(a,l)))}var L_="Key > value \xB7 Key = value \xB7 Key ~ text \xB7 Key (exists)",N_=">1.2 \xB7 <0.5 \xB7 =62.5 \xB7 !=0 \xB7 1..2 \xB7 61-64 \xB7 >61 <64 \xB7 in 5,6,8";var IO=/^is:(.*)$/,PO=/^([A-Za-z_][\w. -]*?)\s*(>=|<=|!=|=|>|<|:)\s*(.*)$/s,FO=/^"([^"]+)"\s*(>=|<=|!=|=|>|<|:)\s*(.*)$/s,j_=/^\/(.*)\/([a-z]*)$/s,Mm=e=>e.toLowerCase().replace(/[^a-z0-9]/g,"");function sc(e){return e.match(/[^\s"]*(?::|=)in\s+[^\s"]+|(?:[^\s"]+|"[^"]*")+/gi)??[]}function q_(e){return/^".*"$/s.test(e)?e.slice(1,-1):null}function D_(e,t){let n=Mm(t);if(!n)return[];let r=Object.keys(e.cells),o=r.filter(i=>Mm(i)===n);return(o.length?o:r.filter(i=>Mm(i).includes(n))).map(i=>e.cells[i])}var OO=e=>e==null?null:String(e);function oc(e,t,n){let r=OO(e),o=q_(n.trim());if(o!=null)return r==null?!1:t==="="?r.toLowerCase()===o.toLowerCase():t==="!="?r.toLowerCase()!==o.toLowerCase():r.toLowerCase().includes(o.toLowerCase());let s=n.trim(),i=/^in\s+(.+)$/is.exec(s);if(i&&(t===":"||t==="="))return i[1].split(/\s*[,|]\s*/).some(l=>l!==""&&oc(e,"=",l));if(!s)return r!=null&&r!==""&&r!=="n/a";if(s.includes("|")&&!j_.test(s))return s.split("|").some(l=>l.trim()&&oc(e,t,l));let a=j_.exec(s);if(a){if(r==null)return!1;try{return new RegExp(a[1],a[2]||"i").test(r)}catch{return!1}}if(t===":"){let l=qs(s);return l&&!/^[-+]?[\d.]+$/.test(s)?Us(e,s):l!=null&&Us(e,s)||r!=null&&r.toLowerCase().includes(s.toLowerCase())}if(qs(s)&&t!=="="&&t!=="!=")return Us(e,t+s);if(t==="="||t==="!="){let l=qs(s)?Us(e,s):r!=null&&r.toLowerCase()===s.toLowerCase();return t==="="?l:!l}return Us(e,t+s)}function Im(e,t,n){let r=FO.exec(t);if(r){let a=D_(e,r[1]);return a.length>0&&a.some(l=>oc(l,r[2],r[3]))}let o=q_(t);if(o!=null)return B_(e,o);let s=IO.exec(t);if(s){let a=n[s[1].toLowerCase()];return a?a(e):!1}let i=PO.exec(t.replace(/^"([^"]+)"(?=\s*(?:[<>!=:]))/,(a,l)=>l));if(i){let a=D_(e,i[1]);return a.length?a.some(l=>oc(l,i[2],i[3])):!1}return t.includes("|")?t.split("|").some(a=>a.trim()&&Im(e,a.trim(),n)):B_(e,t)}function B_(e,t){let n=t.toLowerCase();return Object.values(e.cells).some(r=>r!=null&&String(r).toLowerCase().includes(n))}function Pm(e,t,n={}){let r=t.trim();if(!r)return!0;let o=r.split(/\s+OR\s+/);if(o.length>1)return o.some(i=>Pm(e,i,n));let s=Object.fromEntries(Object.entries(n).map(([i,a])=>[i.toLowerCase(),a]));return sc(r).every(i=>{let a=i.startsWith("-")||i.startsWith("!"),l=a?i.slice(1):i;if(!l)return Im(e,i,s);let c=Im(e,l,s);return a?!c:c})}function U_(e){return Object.keys(e).sort()}var G_={offline:e=>e.cells.binding_state!=null&&e.cells.binding_state!=="linked",rate_mismatch:e=>{let t=Number(e.cells.source_fps_n),n=Number(e.cells.timeline_fps);return e.cells.source_fps_n!=null&&t>0&&n>0&&Math.abs(t-n)>.001},stabilized:e=>/stabiliz/i.test(String(e.cells.effect_names??"")),effects:e=>!!e.cells.effect_names,retimed:e=>e.cells.speed_ramped===!0||e.cells.speed_reverse===!0||e.cells.speed!=null&&Math.abs(Number(e.cells.speed)-100)>1e-6,nested:e=>e.cells.kind==="nested"||e.cells.is_nested===!0,multicam:e=>e.cells.is_multicam===!0},H_={unused:e=>Number(e.cells.usage??0)===0,offline:e=>e.cells.binding_state!=="linked",linked:e=>e.cells.binding_state==="linked"};function z_(e){let t=new Map;for(let n of e?.timelines??[])for(let r of n?.tracks??[])for(let o of r?.items??[]){let s=o?.media_reference_id;!s||o.kind==="gap"||t.set(s,(t.get(s)??0)+1)}return t}function LO(e){return(typeof e.display_name=="string"?e.display_name:"")||e.target_url&&e.target_url.split(/[\\/]/).pop()||e.id}function W_(e,t={}){let n=z_(e),r=t.idPrefix??"mr:";return(e?.media_references??[]).flatMap(o=>{let s=LO(o);return t.skip?.(s)?[]:[{id:`${r}${o.id}`,name:s,ref:o,origin:"from timeline",extra:{usage:n.get(o.id)??0}}]})}function K_(e,t){let n=e.map(r=>({header:rc(r),value:o=>{let s=o.cells[r];return s==null?"":typeof s=="boolean"?s?"true":"false":s}}));return Oa(n,[...t])}function V_(e,t,n=new Date){let r=n.toISOString().slice(0,16).replace(/[-:T]/g,""),o=s=>s.replace(/[^a-zA-Z0-9_-]/g,"_");return`${r}_${o(e)}_${o(t)}.csv`}var J_=["clips","media","markers"],NO={clips:["#","timeline","track","name","timeline_range.start","timeline_range.dur","rec_in_tc","rec_out_tc","source_range.start","reel_name","speed","binding_state"],media:["name","binding_state","usage","codec","source_resolution_w","source_resolution_h","source_fps","source_timecode","target_url"],markers:["timeline","tc","color","name","note","duration","clip"]},Fm=`Terms are separated by spaces and ALL must match; a leading - negates a term; OR (capitals, its own word) = either side (reel:A001 OR speed!=100). text = in any column; field:text = in that column (field:/regex/, field:"two words", field:a|b; a field name with a space is quoted: "Frame rate":!=24); numbers: ${N_} (e.g. speed!=100, crop:1..2, track:in V5,V6 \u2014 whole-cell membership); field: alone = has a value; clips: overlaps:A..B = clips whose RECORD range touches A..B inclusive (record TC like 01:00:10:00, or timeline frames; overlaps:A alone = clips under that frame) \u2014 unlike timeline_range.start:A..B, which only asks where a clip starts. is:<lens> = a named question (clips: is:offline, is:visible = the topmost enabled picture somewhere, what actually plays, is:rate_mismatch, is:stabilized, is:effects, is:retimed, is:nested, is:multicam; media: is:unused, is:offline, is:linked; markers: is:<color>, is:duration). An unknown field or lens matches nothing.`,jO=/^([-!]?)overlaps?:(.+)$/i;function DO(e){let t=[];return{rest:sc(e).filter(r=>{let o=jO.exec(r);if(!o)return!0;let[s,i=s]=o[2].split(/\.\.\.?|-(?=\d)/);return t.push(a=>{if(!a.item||!a.tl)return!1;let l=Pt(a.tl),c=He(a.tl.start_frame??0,l,!!a.tl.is_drop_frame),u,d;try{u=yr(s,l,c),d=yr(i,l,c)}catch{return!1}u>d&&([u,d]=[d,u]);let p=a.item.timeline_range.start.value,f=p+a.item.timeline_range.duration.value,h=p<=d&&f>u;return o[1]?!h:h}),!1}).join(" "),tests:t}}function BO(e){let t=s=>[s.timeline_range.start.value,s.timeline_range.start.value+s.timeline_range.duration.value],n=(e.tracks??[]).filter(s=>s.kind==="Video"&&s.enabled!==!1).sort((s,i)=>i.track_index-s.track_index).map(s=>s.items.filter(i=>i.enabled!==!1&&(i.kind==="clip"||i.kind==="nested")&&!i.title)),r=[...new Set(n.flat().flatMap(s=>t(s)))].sort((s,i)=>s-i),o=new Set;for(let s=0;s+1<r.length;s++){let i=r[s];for(let a of n){let l=a.find(c=>t(c)[0]<=i&&i<t(c)[1]);if(l){o.add(l.id);break}}}return o}var qO=/^([-!]?)is:visible$/i;function UO(e){let t=new Map,n=[];return{rest:sc(e).filter(o=>{let s=qO.exec(o);return s?(n.push(i=>{if(!i.tl)return!1;t.has(i.tl)||t.set(i.tl,BO(i.tl));let a=t.get(i.tl).has(i.id);return s[1]?!a:a}),!1):!0}).join(" "),tests:n}}function GO(e,t,n){let r=e,o=us(r).filter(i=>!n||i.id===n);if(n&&!o.length){let i=us(r).map(a=>`${a.id} "${a.name}"`).join(", ");throw new P("not_found",`no timeline ${n} in this session (timelines: ${i||"none"})`)}if(t==="clips"){let i=new Set(o.map(d=>d.id)),a=new Map;for(let d of e.timelines){if(!i.has(d.id))continue;let p=Pt(d),f=h=>He(h+(d.start_frame??0),p,!!d.is_drop_frame);for(let h of d.tracks??[])for(let g of h.items??[]){let b=g.timeline_range.start.value,k=b+g.timeline_range.duration.value,w=Sn({...h,name:null},d.tracks??[]);a.set(g.id,{tl:d,cells:{track_no:w,track_name:h.name??null,track_enabled:h.enabled!==!1,rec_in_tc:f(b),rec_out_tc:f(k)}})}}let l=P_(r),c=l.rows.filter(d=>a.has(d.id)).map(d=>({...d,tl:a.get(d.id).tl,cells:{...d.cells,...a.get(d.id).cells}})),u=[...l.columns];return u.splice(u.indexOf("track")+1,0,"track_no","track_name","track_enabled"),u.splice(u.indexOf("timeline_range.dur")+1,0,"rec_in_tc","rec_out_tc"),{rows:c,columns:u,lenses:G_}}if(t==="media"){let i=F_(W_(r));return{rows:i.rows,columns:i.columns,lenses:H_}}return{rows:o.flatMap(i=>sg(i,r).map(a=>({...a,id:`${i.id}:${a.id}`,cells:{timeline:i.name,...a.cells}}))),columns:["timeline","tc","frame","color","name","note","duration","frames","clip","item_id"],lenses:ig}}function HO(e,t,n){let r=()=>NO[t].filter(l=>n.includes(l));if(!e?.length)return{out:r(),unknown:[]};let o=l=>l.toLowerCase().replace(/[^a-z0-9]/g,""),s=l=>l.toLowerCase().split(/[^a-z0-9]+/).filter(c=>c.length>2),i=[],a=[];for(let l of e){let c=n.find(d=>d===l)??n.find(d=>o(d)===o(l)||o(rc(d))===o(l));if(c){i.push(c);continue}let u=s(l);a.push({asked:l,near:n.filter(d=>s(d).some(p=>u.includes(p))).slice(0,8)})}return{out:i.length?i:r(),unknown:a}}function X_(e,t){let{rows:n,columns:r,lenses:o}=GO(e,t.table,t.timeline_id),{out:s,unknown:i}=HO(t.columns,t.table,r),a=UO(t.query?.trim()??""),{rest:l,tests:c}=DO(a.rest),u=[...a.tests,...c],d=n.filter(f=>u.every(h=>h(f))&&(!l||Pm(f,l,o))),p={table:t.table,columns:s,available:r,lenses:U_(o),total:n.length,matched:d.length,fps:(()=>{let f=us(e).find(h=>!t.timeline_id||h.id===t.timeline_id);return f?Pt(f):void 0})(),rows:d.map(f=>({id:f.id,cells:Object.fromEntries(s.map(h=>[h,f.cells[h]??null]))})),...i.length?{unknown_columns:i}:{}};return t.csv&&(p.csv=t.table==="markers"&&!t.columns?.length?ag(d):K_(s,d)),p}async function Q_(e,t,n){let r=e.table==="clips"?"Edit_Index":e.table==="media"?"Media":"Markers",o=await vh(t)?re(t,V_(n,r)):t;return await Ke(o,e.csv??""),o}function Y_(e){return!e||e<1?5e3:Math.min(Math.floor(e),5e3)}function Z_(e,t,n){let r=`${e.table}: ${e.matched} of ${e.total} row${e.total===1?"":"s"}${t?` match "${t}"`:""}`+(e.unknown_columns?.length?`
|
|
244
|
+
no column ${e.unknown_columns.map(d=>`${d.asked}${d.near.length?` (near: ${d.near.join(", ")})`:""}`).join("; ")}: answered with the rest`:"");if(!e.matched)return`${r}
|
|
245
|
+
lenses: ${e.lenses.map(d=>`is:${d}`).join(" ")||"(none)"}
|
|
246
|
+
columns: ${e.available.slice(0,40).join(", ")}${e.available.length>40?", \u2026":""}
|
|
247
|
+
grammar: ${Fm}
|
|
248
|
+
field queries: ${L_}`;let o=e.rows.slice(0,n),s=d=>(d==null?"":String(d)).replace(/\s+/g," ").slice(0,60),i=e.columns.map(d=>Math.min(60,Math.max(d.length,...o.map(p=>s(p.cells[d]).length)))),a=d=>d.map((p,f)=>p.padEnd(i[f])).join(" ").trimEnd(),l=[a(e.columns),...o.map(d=>a(e.columns.map(p=>s(d.cells[p]))))],c=e.matched>o.length?`TRUNCATED: showing ${o.length} of ${e.matched} matching rows \u2014 NOT the full list. Pass limit=${Math.min(e.matched,5e3)}, narrow the query, or out_path for the full CSV.
|
|
249
|
+
`:"",u=c?`
|
|
250
|
+
\u2026 ${e.matched-o.length} more not shown (see TRUNCATED above)`:"";return`${c}${r}
|
|
251
|
+
${l.join(`
|
|
252
|
+
`)}${u}`}var zO=/^0[1-4]_[A-Z_]+\//;function Lm(e,t){let n=Om(e.target_url);if(!n)return"";let r=e.role==="reference"?"03_REFERENCES":"02_MEDIA";if(t&&e.target_url){let o=KO(e.target_url),s=o?o.replace(zO,""):n;return`${r}/${s}`}return`${r}/${n}`}function Nm(e,t,n){return{entries:WO(e,t,n).entries.map(s=>{if(s.inlineBytes)return{path:s.path,bytes:s.inlineBytes};if(s.sourceBasename)return{path:s.path,sourceBasename:s.sourceBasename};throw new Error(`folder-layout entry missing both inlineBytes and sourceBasename: ${s.path}`)})}}function WO(e,t,n){let r=[],o=new Map,s=new Set;for(let l of n.sourceFiles??[]){let c=Gs(`01_PROJECT_FILES/source/${l.name}`,s);r.push({path:c,section:"project-source",inlineBytes:l.data})}let i=new Set,a=(e.media_references??[]).filter(l=>{if(!l.target_url)return!1;let c=Om(l.target_url);if(!(c.length>0&&t.has(c)))return!1;let u=`${c.toLowerCase()}\0${l.role??""}`;return i.has(u)?!1:(i.add(u),!0)});for(let l of a){let c=Om(l.target_url);if(l.bundle&&l.bundle.files.length>0){for(let d of l.bundle.files){if(!t.has(d.basename))continue;let p=Gs(`02_MEDIA/${d.rel_path}`,s);r.push({path:p,section:"media",sourceBasename:d.basename}),o.set(d.basename,p)}continue}let u=Gs(Lm(l,n.preserveStructure===!0),s);r.push({path:u,section:l.role==="reference"?"reference":"media",sourceBasename:c}),l.role!=="reference"&&o.set(c,u)}for(let l of n.exchangeFiles??[]){let c=l.text?ev(l.bytes,o,n.volumeName):l.bytes,u=Gs(`01_PROJECT_FILES/converted/${l.filename}`,s);r.push({path:u,section:"project-converted",inlineBytes:c})}if(n.timelineFile){let l=n.timelineFile,c=ev(l.bytes,o,n.volumeName);if(l.isConversion){let u=Gs(`01_PROJECT_FILES/converted/${l.filename}`,s);r.push({path:u,section:"project-converted",inlineBytes:c})}else{let u=l.filename.includes(".")?l.filename.slice(l.filename.lastIndexOf(".")):"",p=`${l.filename.includes(".")?l.filename.slice(0,l.filename.lastIndexOf(".")):l.filename}_relinked${u}`,f=Gs(`01_PROJECT_FILES/source/${p}`,s);r.push({path:f,section:"project-source",inlineBytes:c})}}return{entries:r,basenameToIsoPath:o}}function ev(e,t,n){let r;try{r=new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{return e}for(let[o,s]of t){let i=`/Volumes/${n}/${s}`,a=VO(o);r=r.replace(new RegExp(`(<pathurl>)[^<]*${a}(</pathurl>)`,"g"),`$1file://localhost${i}$2`).replace(new RegExp(`("target_url"\\s*:\\s*")[^"]*${a}"`,"g"),`$1${i}"`).replace(new RegExp(`(src="file://)[^"]*${a}"`,"g"),`$1localhost${i}"`)}return new TextEncoder().encode(r)}function Om(e){return e?e.split(/[/\\]/).pop()??"":""}function KO(e){if(e)try{return decodeURIComponent(e.replace(/^file:\/\//,"").replace(/^\//,"").replace(/^Volumes\//,""))||void 0}catch{return}}function Gs(e,t){if(!t.has(e))return t.add(e),e;let n=e.lastIndexOf("."),r=n>0?e.slice(0,n):e,o=n>0?e.slice(n):"",s=2,i=`${r}_${s}${o}`;for(;t.has(i);)s++,i=`${r}_${s}${o}`;return t.add(i),i}function VO(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function tv(e){return O1(e)}function nv(e,t){let n=Math.max(0,Math.floor(e.handles??0)),r=e.frame_in-n,o=e.frame_out+n,s=Math.max(0,r),i=t!==void 0?Math.min(t,o):o;return{frame_in:s,frame_out:i,handles_applied_in:e.frame_in-s,handles_applied_out:i-e.frame_out,handles_requested:n}}function Wo(e,t){if(t.format==="iso")return XO(e,t);if(t.format==="folder")return JO(e,t);throw new Error(`deriveLayout: unsupported format "${t.format}"`)}function JO(e,t){let n=rv(e),r=[],o=new Set,s=new Set,i=0;for(let a of n){let l=jm(a);if(!l)continue;s.add(l);let c=QO(a,l,t);o.add(c);let u=ov(a.id??l,t),d=sv(e,a,u,t.handles??0);r.push({dest_file:c,dest_offset:0,length:d,source:{kind:"file",basename:l,offset:0}}),i+=d}return{regions:r,total_bytes:i,dest_files:Array.from(o),source_basenames:Array.from(s)}}function XO(e,t){if(!t.volume_name)throw new Error("deriveLayout(iso): intent.volume_name is required");let n=rv(e),r=`${t.volume_name}.iso`,o=[],s=new Set,i=0;for(let a of n){let l=jm(a);if(!l)continue;s.add(l);let c=ov(a.id??l,t),u=sv(e,a,c,t.handles??0);o.push({dest_file:r,dest_offset:i,length:u,source:{kind:"file",basename:l,offset:0}}),i+=u}return{regions:o,total_bytes:i,dest_files:[r],source_basenames:Array.from(s)}}function rv(e){let t=e.media_references;return Array.isArray(t)?t.filter(n=>n.carry_whole===!0||!(n.binding_state&&n.binding_state!=="linked")):[]}function jm(e){if(!e.target_url)return null;let t=e.target_url.split(/[\\/]/).pop();return t&&t.length>0?t:null}function QO(e,t,n){let r=n.per_file_overrides?.[e.id]?.rel_path;if(r)return r;switch(n.folder_layout??"flat"){case"flat":return t;case"by-camera":{let o=e.reel_name;return o?`${o}/${t}`:t}case"media-organized":{let o=YO(e);return o?`${o}/${t}`:t}case"canonical-i2o":return Lm(e,!1)}}function YO(e){if(P1(e))return"Stills";switch(e.content_kind){case"still":return"Stills";case"audio":return"Audio";case"video":case"video_audio":return"Footage";case"compound":return"Compounds";default:return null}}function ov(e,t){return t.per_file_overrides?.[e]?.mode??t.per_file_mode}function sv(e,t,n,r){let o=t.size_bytes??0;if(o===0)return 0;let s=jm(t);if(!s||!tv(s)||n.mode==="sparse"&&n.populate.full===!0)return o;let i=t.available_range?.duration?.value??0;if(i<=0)return o;let a=ZO(e,t.id);if(a.length===0)return o;let l=a.map(p=>{let f=nv({frame_in:p.start,frame_out:p.end,handles:r},i);return{start:f.frame_in,end:f.frame_out}});l.sort((p,f)=>p.start-f.start);let c=[{...l[0]}];for(let p=1;p<l.length;p++){let f=l[p],h=c[c.length-1];f.start<=h.end?h.end=Math.max(h.end,f.end):c.push({...f})}let u=0;for(let p of c){let f=Math.max(0,p.start),h=Math.min(i,p.end);h>f&&(u+=h-f)}let d=Math.min(1,u/i);return Math.round(d*o)}function ZO(e,t){let n=[],r=e?.timelines??[];for(let o of r)for(let s of o.tracks??[])for(let i of s.items??[]){if(i.media_reference_id!==t||!i.source_range)continue;let a=i.source_range.start.value,l=i.source_range.duration.value;l>0&&n.push({start:a,end:a+l})}return n}function iv(e,t){let n=e3(e),r=n>=0?e.slice(0,n+1):"",o=n>=0?e.slice(n+1):e,s=o.lastIndexOf(".");return s<=0?r+o+t:r+o.slice(0,s)+t+o.slice(s)}function e3(e){let t=e.lastIndexOf("/"),n=e.lastIndexOf("\\");return t>n?t:n}async function av(e){try{return await e()}catch(t){let n=j1(t);throw n?new D1(n):t}}async function ic(e){let t=F1(e);if(!t||!t.trimSupported)return null;let n=t.flavor,r=o=>Ca(n,[L1(e,o)]);return{byteSourceFromFile:t3,async prepareWrite(o,s,i){let l=(await av(()=>$o(r(o),{verb:"sparsify",selection:{items:s,handles:i}})))[0];return{fileSize:l.fileSize,structuralRanges:l.structuralRanges,essenceRanges:l.essenceRanges,trimInputs:l.trimInputs??[],wholeFileFallback:l.wholeFileFallback}},async planTrim(o,s,i){let a=await av(()=>$o(r(o),{verb:"trim",selection:{items:s,handles:i}}));if(n==="r3d")throw new Error(`planTrim(${e}): R3D must route through the R3D compact pass (r3d-trim-pass.ts), not the per-file path`);return a}}}async function t3(e){return{fileSize:e.size,async read(t,n){let r=Math.min(t+n,e.size),o=e.slice(t,r);return new Uint8Array(await o.arrayBuffer())}}}function n3(e){let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}async function sa(e,t="i2o",n,r,o=ci){await lu();let s;try{s=Bh(JSON.stringify(e),t,r?JSON.stringify(r):"",o)}catch(a){let l="";try{l=qh()}catch{}throw l?new Error(`udf_build_layout failed: ${l} (raw: ${a instanceof Error?a.message:String(a)})`):a instanceof Error?a:new Error(`udf_build_layout failed: ${String(a)}`)}let i=JSON.parse(s);return{totalBytes:i.totalBytes,totalSectors:i.totalSectors,structuralRegions:i.structuralRegions.map(a=>({sectorStart:a.sectorStart,sectorCount:a.sectorCount,data:n3(a.dataB64)})),fileDataRegions:i.fileDataRegions}}async function cv(e){await lu();let t=32*2048,n=16*2048,r;if(e instanceof Uint8Array){if(e.length<t+n)return null;r=e.subarray(t,t+n)}else{if(e.size<t+n)return null;r=new Uint8Array(await e.slice(t,t+n).arrayBuffer())}let o=Uh(r);if(!o)return null;try{return JSON.parse(o)}catch{return null}}function r3(e){return e.speed!=null&&e.speed!==100||e.speed_reverse||e.speed_ramped?!0:(e.keyframes??[]).some(t=>t.parameter_path==="speed")}function o3(e,t){let n=e.timelines??[];if(t)return n.filter(s=>s.name===t);let r=new Set;for(let s of n)for(let i of s.tracks??[])for(let a of i.items??[])a.nested_timeline_id&&r.add(a.nested_timeline_id);let o=n.filter(s=>!r.has(s.id));return o.length?o:n}function s3(e,t,n){let r=new Map((e.timelines??[]).map(s=>[s.id,s])),o=(s,i,a,l)=>{if(!(!s||a>8))for(let c of s.tracks??[])for(let u of c.items??[]){let d=a===0?u:l??u,p=Math.round(u.timeline_range?.start?.value??0),f=p+Math.round(u.timeline_range?.duration?.value??0),h=i?i.map(([b,k])=>[Math.max(p,b),Math.min(f,k)]).filter(([b,k])=>k>b):[[p,f]];if(h.length===0)continue;let g=r3(u);if(u.nested_timeline_id){let b=r.get(u.nested_timeline_id),k=Math.round(u.source_range?.start?.value??0),w=(s.fps_num??0)/Math.max(s.fps_den??1,1),y=b?(b.fps_num??0)/Math.max(b.fps_den??1,1):w,_=w>0&&y>0?y/w:1,v=h.map(([T,$])=>[Math.floor((k+(T-p))*_),Math.floor((k+($-p))*_)]);o(b,v,a+1,d)}else if(u.media_reference_id){let b=Math.round(u.source_range?.start?.value??0),k=Math.round(u.source_range?.duration?.value??0);if(g){n({item:u,root:d,tl_id:s.id,depth:a,has_speed:!0,tl_in:p,src_in:b,a:p,b:p+k,reached_in:b,reached_out:b+k});continue}for(let[w,y]of h)n({item:u,root:d,tl_id:s.id,depth:a,has_speed:!1,tl_in:p,src_in:b,a:w,b:y,reached_in:b+(w-p),reached_out:b+(y-p)})}}};for(let s of o3(e,t.rootTimelineName))o(s,null,0,null)}function uv(e,t={}){let n=new Map;return s3(e,t,r=>{let o=r.item.media_reference_id,s={clip_src_in:r.src_in,reached_in:r.reached_in,reached_out:r.reached_out,has_speed:r.has_speed},i=n.get(o);i?i.push(s):n.set(o,[s])}),n}var er=2048;function ac(e,t,n){console.error(`[planIsoRegions] DROPPING "${t}" \u2014 ${n}. NOT shipping it whole: that would deliver the entire file to carry a few seconds of it.`),e.push({basename:t,reason:n})}async function lc(e){if(e.perFile.mode==="trim")throw new Error("planIsoRegions: ISO + trim is not supported. Use folder collection for compact trim output, or ISO sparse-segments for the canonical cloud / P2P shape (recipient can derive folder-of-trims at download time per project_upload_once_choose_at_download).");let t=e.perFile.populate,n=new Set;for(let T of e.session.media_references??[])(T.role==="reference"||T.carry_whole===!0)&&n.add((T.target_url??"").split(/[\\/]/).pop()??"");let{ranges:r,dropped:o}=await i3(e),s=[],i=[];for(let T of e.entries){if("bytes"in T){s.push({path:T.path,totalSize:T.bytes.length,keptRanges:[{offset:0,length:T.bytes.length}],inlineBytes:T.bytes});continue}let $=e.files.get(T.sourceBasename);if(!$)continue;if(T.keptRanges){s.push({path:T.path,sourceBasename:T.sourceBasename,totalSize:$.size,keptRanges:T.keptRanges,prep:{fileSize:$.size,structuralRanges:T.keptRanges,essenceRanges:[],trimInputs:[]},file:$,given:!0});continue}let x=()=>({path:T.path,sourceBasename:T.sourceBasename,totalSize:$.size,keptRanges:[{offset:0,length:$.size}],file:$}),R=await ic(T.sourceBasename);if(!R||t.full||T.section==="reference"||n.has(T.sourceBasename)){s.push(x());continue}if(rr(T.sourceBasename)){if(o.has(T.sourceBasename)){ac(i,T.sourceBasename,"delivery coverage miss (cut outside the clip's real frames)");continue}let X=r.get(T.sourceBasename);if(X&&(X.structuralRanges.length>0||X.essenceRanges.length>0)){let O=[...X.structuralRanges];t.segments&&O.push(...X.essenceRanges),s.push({path:T.path,sourceBasename:T.sourceBasename,totalSize:$.size,keptRanges:O,prep:{fileSize:$.size,structuralRanges:X.structuralRanges,essenceRanges:X.essenceRanges,trimInputs:[]},file:$})}else ac(i,T.sourceBasename,"R3D part has no planned sparse ranges");continue}let C=dv(e.session,T.sourceBasename),B=await R.byteSourceFromFile($),L;try{L=await R.prepareWrite(B,C,e.handles)}catch(X){let O=So(X);if(O){console.warn(`[planIsoRegions] coverage miss detail for "${T.sourceBasename}":`,O),ac(i,T.sourceBasename,"delivery coverage miss (cut outside the clip's real frames)");continue}ac(i,T.sourceBasename,X instanceof Error?X.message:String(X));continue}let Z=[...L.structuralRanges];t.segments&&Z.push(...L.essenceRanges),s.push({path:T.path,sourceBasename:T.sourceBasename,totalSize:$.size,keptRanges:Z,prep:L,source:B,file:$})}let a=s.map(T=>{let $=T.prep?a3(T.keptRanges,T.totalSize):void 0;T.given&&$&&!$.length&&T.totalSize>0&&($=[{offset:0,length:0}]);let x=e.pinSectorByPath?.get(T.path);return{name:T.path,totalSize:T.totalSize,...$?{dataExtents:$}:{},...x!==void 0?{fixedPartSector:x}:{}}}),l=await sa(a,e.volumeName,{},e.iuvd,e.buildTimestamp),c=new Map;for(let T of l.fileDataRegions)c.has(T.name)||c.set(T.name,{byteOffset:T.sectorStart*er,partSector:T.sectorStart-257});let u=`${e.volumeName}.iso`,d=[],p=new Set;for(let T of l.structuralRegions)T.data.length!==0&&d.push({dest_file:u,dest_offset:T.sectorStart*er,length:T.data.length,source:{kind:"inline",bytes:T.data}});let f=new Map;for(let T of s)f.set(T.path,T);let h=new Map,g=new Map,b=new Map,k=(T,$,x)=>{let R=b.get(T);R?R.push({at:$,len:x}):b.set(T,[{at:$,len:x}])},w=new Map;for(let T of l.fileDataRegions){let $=f.get(T.name);if(!$)continue;let x=!!$.file&&!$.inlineBytes&&(!$.prep||$.prep.wholeFileFallback===!0);if(g.has($.path)||g.set($.path,x),$.inlineBytes){let O=$.inlineBytes.subarray(T.sourceOffset,T.sourceOffset+T.sourceLength);d.push({dest_file:u,dest_offset:T.sectorStart*er,length:O.length,source:{kind:"inline",bytes:O}}),k($.path,T.sectorStart*er,O.length),h.set($.path,(h.get($.path)??0)+O.length);continue}if(!$.file){g.set($.path,!0);continue}if(!$.prep){p.add($.sourceBasename??$.file.name),d.push({dest_file:u,dest_offset:T.sectorStart*er,length:T.sourceLength,source:{kind:"file",basename:$.sourceBasename??$.file.name,offset:T.sourceOffset}}),k($.path,T.sectorStart*er,T.sourceLength),h.set($.path,(h.get($.path)??0)+T.sourceLength);continue}let R=$.sourceBasename??$.file.name;p.add(R);let C=T.sourceOffset,B=T.sourceOffset+T.sourceLength,L=w.get($.path);if(!L){let O=[...$.keptRanges].sort((ne,z)=>ne.offset-z.offset),ae=[],W=-1/0;for(let ne of O)W=Math.max(W,ne.offset+ne.length),ae.push(W);L={ranges:O,maxEnd:ae},w.set($.path,L)}let Z=0,X=L.ranges.length;for(;Z<X;){let O=Z+X>>1;L.maxEnd[O]>C?X=O:Z=O+1}for(let O=Z;O<L.ranges.length&&L.ranges[O].offset<B;O++){let ae=L.ranges[O],W=Math.max(ae.offset,C),ne=Math.min(ae.offset+ae.length,B);if(ne<=W)continue;let z=ne-W,q=T.sectorStart*er+(W-C);d.push({dest_file:u,dest_offset:q,length:z,source:{kind:"file",basename:R,offset:W}}),k($.path,q,z),h.set($.path,(h.get($.path)??0)+z)}}d.sort((T,$)=>T.dest_offset-$.dest_offset);let y=new Map;for(let T of l.fileDataRegions){let $=y.get(T.name);$?$.push(T):y.set(T.name,[T])}let _=s.map(T=>({path:T.path,bytesWritten:h.get(T.path)??0,fellBack:g.get(T.path)??!1})),v=0;for(let T of d)v+=T.length;return{layout:{regions:d,total_bytes:v,dest_files:[u],source_basenames:Array.from(p),image_total_bytes:l.totalBytes,file_extents:s.map(T=>{let $=(y.get(T.path)??[]).map(R=>({at:R.sectorStart*er,from:R.sourceOffset,len:R.sourceLength})),x=(b.get(T.path)??[]).sort((R,C)=>R.at-C.at);return{path:T.path,size:T.totalSize,extents:$,data:x}})},isoPositions:c,totalBytes:l.totalBytes,perFileSummary:_,untrimmable:i}}async function cc(e,t,n,r={}){let{layout:o,totalBytes:s}=e;if(o.dest_files.length!==1)throw new Error(`executeIsoPlan: expected single dest_file, got ${o.dest_files.length}`);let i=0;for(let l of o.regions)l.source.kind!=="zero"&&(i+=l.length);await n.reserveSize(s);let a=0;try{for(let l of o.regions){if(r.signal?.aborted)throw new DOMException("Aborted","AbortError");if(l.length!==0){switch(l.source.kind){case"inline":{await n.writeAt(l.dest_offset,l.source.bytes),a+=l.source.bytes.length;break}case"file":{let c=t.get(l.source.basename);if(!c)throw new Error(`executeIsoPlan: file not in files map: "${l.source.basename}"`);let u=16*1024*1024,d=0;for(;d<l.length;){let p=Math.min(u,l.length-d),f=c.slice(l.source.offset+d,l.source.offset+d+p),h=new Uint8Array(await f.arrayBuffer());await n.writeAt(l.dest_offset+d,h),d+=p,a+=p,r.onProgress?.({bytesWritten:a,totalBytes:i,currentFile:l.source.basename})}continue}case"zero":break;case"pack":throw new Error("executeIsoPlan: `pack` regions require the CAS executor, not a local-file build")}r.onProgress?.({bytesWritten:a,totalBytes:i})}}await n.close()}catch(l){throw await n.abort?.(l),l}return{bytesWritten:a}}async function i3(e){let t=new Map,n=new Set,r=e.session.media_references??[],o=[],s=new Set;for(let l of r){if(l.bundle?.kind!=="rdc")continue;let c=l.bundle,u=c.files.filter(p=>p.role==="anchor"||p.role==="part").slice().sort((p,f)=>(p.part_number??0)-(f.part_number??0)).map(p=>({filename:p.basename,file:e.files.get(p.basename)})).filter(p=>!!p.file);if(u.length===0)continue;let d=(l.target_url??"").split(/[/\\]/).pop()||u[0].filename;o.push({label:c.folder,anchorBasename:d,parts:u});for(let p of u)s.add(p.filename)}for(let l of r){if(l.bundle?.kind==="rdc")continue;let c=(l.target_url??"").split(/[/\\]/).pop()??"";if(!rr(c)||s.has(c))continue;let u=B1(c,e.files.keys()).map(d=>({filename:d,file:e.files.get(d)})).filter(d=>!!d.file);if(u.length!==0){o.push({label:c,anchorBasename:c,parts:u});for(let d of u)s.add(d.filename)}}if(o.length===0)return{ranges:t,dropped:n};let{mediaOp:i}=await import("./ops-UGZODMYE.js"),{sourceFromFiles:a}=await import("./source-L2JNTYS6.js");for(let l of o){let{label:c,anchorBasename:u,parts:d}=l,p=dv(e.session,u);try{let f=a(d.map(g=>g.file)),h=await i(f,{verb:"sparsify",selection:{items:p,handles:e.handles}});for(let g of h)t.set(g.filename,{structuralRanges:g.structuralRanges,essenceRanges:g.essenceRanges})}catch(f){let h=So(f);if(h){for(let g of d)n.add(g.filename);console.warn(`[planIsoRegions] DROPPING R3D clip "${c}" fail-closed \u2014 delivery coverage miss; NOT whole-filing:`,h);continue}console.warn(`[planIsoRegions] R3D spanned prep failed for "${c}":`,f)}}return{ranges:t,dropped:n}}function dv(e,t){let n=new Set,r=t.toLowerCase();for(let u of e.media_references??[]){if(!u.target_url)continue;(u.target_url.split(/[/\\]/).pop()??"").toLowerCase()===r&&n.add(u.id)}let o=[],s=!1;for(let u of e.timelines??[])for(let d of u.tracks??[])for(let p of d.items??[])p.media_reference_id&&n.has(p.media_reference_id)&&o.push(p),p.nested_timeline_id&&(s=!0);if(!s||o.length===0)return o;let i=uv(e),a=[...n].flatMap(u=>i.get(u)??[]);if(a.length===0)return o;let l=o[0],c=l.source_range?.start?.rate??l.source_range?.duration?.rate??1;return a.map(u=>({...l,kind:"clip",source_range:{start:{value:u.reached_in,rate:c},duration:{value:u.reached_out-u.reached_in,rate:c}}}))}function a3(e,t){if(e.length===0)return e;let n=e.map(o=>{let s=Math.floor(o.offset/er)*er,i=Math.min(Math.ceil((o.offset+o.length)/er)*er,t);return{offset:s,length:Math.max(0,i-s)}}).filter(o=>o.length>0);n.sort((o,s)=>o.offset-s.offset);let r=[];for(let o of n){let s=r[r.length-1];s&&o.offset<=s.offset+s.length?s.length=Math.max(s.length,o.offset+o.length-s.offset):r.push({...o})}return r}async function Hs(e,t,n,r,o){if(r.format==="iso"){if(!o)throw new Error("refineLayoutForTrim(iso): isoOptions is required (entries, pinSectorByPath, iuvd come from buildI2oFolderLayout in the wizard).");if(!r.volume_name)throw new Error("refineLayoutForTrim(iso): intent.volume_name is required");let c=u3(r,n),u=await lc({session:n,files:t,handles:r.handles??0,perFile:c,volumeName:r.volume_name,entries:o.entries,pinSectorByPath:o.pinSectorByPath,iuvd:o.iuvd,buildTimestamp:o.buildTimestamp});return u.untrimmable.length>0?{...u.layout,untrimmable:u.untrimmable}:u.layout}if(r.per_file_mode.mode!=="trim")return e;let s=Bm(n),i=qm(n),a=new Map;for(let c of e.regions){let u=a.get(c.dest_file);u?u.push(c):a.set(c.dest_file,[c])}let l=[];for(let[c,u]of a){let d=u.length===1?u[0]:null;if(!d||d.source.kind!=="file"){l.push(...u);continue}let p=d.source.basename,f=t.get(p);if(!f){l.push(d);continue}let h=i.get(p),g=h?s.get(h.id)??[]:[],b=await l3({destFile:c,basename:p,file:f,ref:h,items:g,handles:r.handles??0});b!=="coverage-miss"&&(b?l.push(...b):l.push({dest_file:c,dest_offset:0,length:f.size,source:{kind:"file",basename:p,offset:0}}))}return c3(l)}async function l3(e){if(e.items.length===0)return null;let t=await ic(e.basename);if(!t||!t.planTrim)return null;let n;try{let o=await t.byteSourceFromFile(e.file);n=await t.planTrim(o,e.items,e.handles)}catch(o){let s=So(o);return s?(console.warn(`[refineLayoutForTrim] DROPPING "${e.basename}" fail-closed \u2014 delivery coverage miss; NOT whole-filing:`,s),"coverage-miss"):null}if(n.length===0)return null;if(n.length===1)return ia(n[0],e.destFile,e.basename);let r=Math.max(3,String(n.length).length);return n.flatMap((o,s)=>ia(o,iv(e.destFile,`_S${String(s+1).padStart(r,"0")}`),e.basename))}function ia(e,t,n){let r=[],o=e.dest_header_bytes_base64?Dm(e.dest_header_bytes_base64):null;o&&o.length>0&&r.push({dest_file:t,dest_offset:0,length:o.length,source:{kind:"inline",bytes:o}});for(let s of e.src_byte_ranges)s.length<=0||r.push({dest_file:t,dest_offset:s.write_to_dest_offset,length:s.length,source:{kind:"file",basename:s.src_file_name??n,offset:s.offset}});if(e.dest_footer_bytes_base64&&e.dest_footer_offset!=null){let s=Dm(e.dest_footer_bytes_base64);s.length>0&&r.push({dest_file:t,dest_offset:e.dest_footer_offset,length:s.length,source:{kind:"inline",bytes:s}})}if(e.dest_patches)for(let s of e.dest_patches){let i=Dm(s.bytes_base64);i.length!==0&&r.push({dest_file:t,dest_offset:s.offset,length:i.length,source:{kind:"inline",bytes:i}})}return r.sort((s,i)=>s.dest_offset-i.dest_offset),r}function Bm(e){let t=new Map,n=e?.timelines??[];for(let r of n)for(let o of r.tracks??[])for(let s of o.items??[]){if(!s?.media_reference_id)continue;let i=t.get(s.media_reference_id);i?i.push(s):t.set(s.media_reference_id,[s])}return t}function pv(e,t,n){let r=t?.source_timecode?At(t.source_timecode,n):null;return r==null?e:e.map(o=>{let s=o?.raw_extraction;if(s?.sourceConformedToMedia)return o;let i=s?.alternateFrame;if(i==null||!o.source_range)return o;let a=i-r;return a===0?o:{...o,source_range:{...o.source_range,start:{...o.source_range.start,value:o.source_range.start.value+a}}}})}function qm(e){let t=new Map,n=e?.media_references??[];for(let r of n){if(!r.target_url)continue;let o=r.target_url.split(/[\\/]/).pop();o&&o.length>0&&t.set(o,r)}return t}function c3(e){let t=new Set,n=new Set,r=0;for(let o of e)t.add(o.dest_file),o.source.kind==="file"&&n.add(o.source.basename),r+=o.length;return{regions:e,total_bytes:r,dest_files:Array.from(t),source_basenames:Array.from(n)}}function Dm(e){let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function u3(e,t){return e.per_file_mode.mode==="trim"?{mode:"trim"}:{mode:"sparse",populate:{structural:!0,segments:e.per_file_mode.populate.segments,full:e.per_file_mode.populate.full}}}var zs=class{constructor(t){this.opts=t}async execute(){let{layout:t,sink:n}=this.opts,r=t.total_bytes,o=d3(t.regions),s=Math.max(1,this.opts.concurrency??1),i=0,a=0,l=[],c,u=async(d,p)=>{this.opts.signal?.throwIfAborted(),p.sort((b,k)=>b.dest_offset-k.dest_offset);let f=p3(p),h=await n.openFile(d,f),g=0;try{for(let b of p){this.opts.signal?.throwIfAborted(),c=d,this.opts.onProgress?.({bytesWritten:i,totalBytes:r,currentFile:c});let k=0,w=await this.writeRegion(b,h,y=>{a+=y-k,k=y,this.opts.onProgress?.({bytesWritten:a,totalBytes:r,currentFile:c})});g+=w,i+=w}await h.close()}catch(b){throw await h.abort?.(b),b}return{path:d,bytesWritten:g}};if(s===1)for(let[d,p]of o)l.push(await u(d,p));else{let d=Array.from(o.entries()),p=0,f=[];for(let h=0;h<Math.min(s,d.length);h++)f.push((async()=>{for(;p<d.length;){let g=p++;if(g>=d.length)break;let[b,k]=d[g],w=await u(b,k);l.push(w)}})());await Promise.all(f)}return await n.closeCollection(),this.opts.onProgress?.({bytesWritten:i,totalBytes:r}),{bytesWritten:i,perFile:l}}async writeRegion(t,n,r){if(t.length===0)return 0;switch(t.source.kind){case"inline":return await n.writeAt(t.dest_offset,t.source.bytes),r?.(t.source.bytes.length),t.source.bytes.length;case"file":{let o=this.opts.files.get(t.source.basename);if(!o)throw new Error(`LocalDirectoryExecutor: file not found in files map: "${t.source.basename}"`);let s=16*1024*1024,i=t.source.offset,a=0;for(;a<t.length;){let l=Math.min(s,t.length-a),c=o.slice(i+a,i+a+l),u=new Uint8Array(await c.arrayBuffer());await n.writeAt(t.dest_offset+a,u),a+=l,r?.(a)}return t.length}case"zero":return 0;case"pack":throw new Error("LocalDirectoryExecutor: `pack` regions require the CAS executor, not a local-file executor")}}};function d3(e){let t=new Map;for(let n of e){let r=t.get(n.dest_file);r?r.push(n):t.set(n.dest_file,[n])}return t}function p3(e){let t=0;for(let n of e){let r=n.dest_offset+n.length;r>t&&(t=r)}return t}var uc=class{constructor(t){this.opts=t}async execute(){return cc({layout:this.opts.layout,totalBytes:this.opts.totalBytes},this.opts.files,this.opts.sink,{onProgress:this.opts.onProgress,signal:this.opts.signal})}};import{mkdir as m3,open as mv}from"node:fs/promises";import{dirname as f3,join as h3}from"node:path";function fv(e){let t=!1;return{async reserveSize(n){await e.truncate(n)},async writeAt(n,r){if(t)throw new Error("nodeFileStream: closed");let o=Buffer.from(r.buffer,r.byteOffset,r.byteLength);await e.write(o,0,r.byteLength,n)},async close(){t||(t=!0,await e.close())},async abort(n){if(!t){t=!0;try{await e.close()}catch{}}}}}async function dc(e){let t=await mv(e,"w");return fv(t)}function pc(e){return{async openFile(t,n){let r=h3(e,t);await m3(f3(r),{recursive:!0});let o=await mv(r,"w"),s=fv(o);return await s.reserveSize(n),s},async closeCollection(){}}}async function Gm(e){let t=Um(e),n=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}function Um(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Um).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(o=>`${JSON.stringify(o)}:${Um(t[o])}`).join(",")}}`}var b3="i2o-2026-05-08",y3=1;function hv(e){let t=e?.created_at?Date.parse(e.created_at):NaN;return Number.isFinite(t)?t:ci}async function gv(e){let[t,n]=await Promise.all([Gm(e.session),Gm(e.layoutIntent)]);return{payload:{v:1,conform_tools_version:b3,session_sha256:t,delivery_intent_sha256:n,layout_fn_version:y3,written_at:e.writtenAt??new Date(ci).toISOString(),...e.sessionIdHint?{session_id_hint:e.sessionIdHint}:{}},session_sha256:t,delivery_intent_sha256:n}}function mc(e){return e.map((t,n)=>({partNumber:t.output_part_number??n+1,clipNumber:t.output_clip_number,clipCount:t.output_clip_count,plan:t}))}function w3(e,t,n,r=""){let o=Hr(t),s=o?o.clipBase:t.replace(/\.R3D$/i,""),i=`${s}_${String(n).padStart(3,"0")}.R3D`,a=e.split("/");return a.pop(),a.length&&/\.rdc$/i.test(a[a.length-1])&&a.pop(),[...a,`${s}${r}.RDC`,i].join("/")}function k3(e){let t=e.clipCount??1;if(t<=1)return"";let n=Math.max(3,String(t).length);return`_S${String(e.clipNumber??1).padStart(n,"0")}`}function _3(e){let t=new Map;for(let n of e){let r=Hr(n.basename),o=r?r.clipBase:n.basename,s=t.get(o);s?s.push(n):t.set(o,[n])}for(let n of t.values())n.sort((r,o)=>(Hr(r.basename)?.partNumber??0)-(Hr(o.basename)?.partNumber??0));return[...t.values()]}async function fc(e){let t=[],n=new Map,r=[],o=0;for(let s of _3(e.parts)){let i=s[0];if(new Set(s.map(l=>l.basename)).size!==s.length){let l=Hr(i.basename),c=l?l.clipBase:i.basename.replace(/\.R3D$/i,""),u={reason:"duplicate .R3D part filenames in one send (same clip name in two .RDC folders \u2014 e.g. re-sending two _S### islands of one source); byte-identical routing would be ambiguous"};console.warn(`[r3d-trim-pass] DROPPING R3D clip "${c}" fail-closed:`,u.reason),r.push({clipBase:c,parts:s.map(d=>d.basename),reason:u});continue}let a;try{a=await e.planClip(s)}catch(l){let c=So(l);if(!c)throw l;let u=Hr(i.basename),d=u?u.clipBase:i.basename.replace(/\.R3D$/i,"");console.warn(`[r3d-trim-pass] DROPPING R3D clip "${d}" fail-closed \u2014 delivery coverage miss (cut not within the file's real frames); NOT whole-filing:`,c),r.push({clipBase:d,parts:s.map(p=>p.basename),reason:c});continue}for(let l of s)n.set(l.basename,l.file);for(let l of a){let c=w3(i.destPathHint,i.basename,l.partNumber,k3(l));t.push(...ia(l.plan,c,i.basename)),o+=l.plan.src_byte_ranges.reduce((u,d)=>u+d.length,0)}}return{regions:t,filesByBasename:n,bytes:o,dropped:r}}function bv(e){switch(e){case"trim":return{mode:"trim"};case"skeleton":return{mode:"sparse",populate:{structural:!0}};case"sparse":return{mode:"sparse",populate:{structural:!0,segments:!0}};case"full":return{mode:"sparse",populate:{structural:!0,full:!0}}}}var v3=2048,ao=".conform",yv=`${ao}/delivery.json`;function wv(e,t){let n=new Set;for(let s of e.timelines)for(let i of s.tracks)for(let a of i.items)a.media_reference_id&&n.add(a.media_reference_id);let r=(e.media_references??[]).filter(s=>n.has(s.id)).map(s=>{let{local_path:i,target_url:a,...l}=s;return{...l,target_url:a&&a.split(/[\\/]/).pop()}}),o={v:1,timelines:e.timelines,media_references:r,handles:t};return new TextEncoder().encode(JSON.stringify(o))}var hc=class{constructor(t,n,r,o){this.img=t;this.info=n;this.f=r;this.name=o;this.size=r.totalSize}slice(t=0,n=this.size){let r=Math.max(0,Math.min(t,this.size)),o=Math.max(r,Math.min(n,this.size)),{img:s,info:i,f:a}=this;return{size:o-r,async arrayBuffer(){let l=new Uint8Array(o-r);for(let c of Wn(a)){let u=Math.max(r,c.offset),d=Math.min(o,c.offset+c.length);d>u&&l.set(await s.read((i.partitionStartSector+c.imageSector)*v3+(u-c.offset),d-u),u-r)}return l.buffer}}}async arrayBuffer(){return this.slice().arrayBuffer()}dataRanges(){return Wn(this.f).map(({offset:t,length:n})=>({offset:t,length:n}))}},Ko=e=>e.split("/").pop()||e,Hm=e=>e.startsWith("02_MEDIA/")||e.startsWith("03_PROXIES/");async function zm(e){let t=await zn(e);return{image:e.size(),recipes:t.files.filter(n=>n.name.startsWith(`${ao}/`)).length,files:t.files.filter(n=>!n.name.startsWith(`${ao}/`)&&n.name!==".i2o-manifest.json").map(n=>({name:n.name,size:n.totalSize,recorded:Wn(n).reduce((r,o)=>r+o.length,0)}))}}async function kv(e,t){let n=t.files.filter(i=>i.name.startsWith(`${ao}/delivery`)&&i.name.endsWith(".json"));if(!n.length)return null;let r=[],o=new Map,s=0;for(let i of n){let a=JSON.parse(new TextDecoder().decode(await new hc(e,t,i,i.name).arrayBuffer()));r.push(...a.timelines);for(let l of a.media_references)l.id&&o.set(l.id,l);s=Math.max(s,a.handles??0)}return{session:{timelines:r,media_references:[...o.values()]},handles:s}}async function _v(e,t){let n=await kv(e,t);return n?{timelines:n.session.timelines,media:n.session.media_references??[],handles:n.handles}:{timelines:[],media:[],handles:0}}async function Wm(e,t,n={}){let r=await zn(e),o=w=>!n.only?.length||n.only.some(y=>w.includes(y)),s=await kv(e,r),i=new Map,a=new Map,l=[];for(let w of r.files){if(w.name.startsWith(`${ao}/`)||w.name===".i2o-manifest.json"||!o(w.name))continue;let y=new hc(e,r,w,Ko(w.name));Hm(w.name)&&rr(Ko(w.name))?l.push({udfPath:w.name,basename:Ko(w.name),file:y}):Hm(w.name)&&s?i.set(Ko(w.name),y):a.set(w.name,y)}n.onProgress?.(0,0,"planning trims");let c=[],u={regions:[],total_bytes:0,dest_files:[],source_basenames:[]};if(s&&i.size){let w={format:"folder",folder_layout:"canonical-i2o",per_file_mode:{mode:"trim"},handles:s.handles},y={...s.session,media_references:(s.session.media_references??[]).filter(_=>i.has(Ko(_.target_url??""))).map(_=>({..._,binding_state:"linked"}))};u=await Hs(Wo(y,w),i,y,w);for(let _ of u.untrimmable??[])c.push(`${_.basename}: ${_.reason}`)}else if(!s)for(let w of a.keys())Hm(w)&&c.push(`${Ko(w)}: no recipe in this .iso \u2014 written as stored`);let d=await fc({parts:l.map(w=>({basename:w.basename,destPathHint:w.udfPath,file:w.file,dataRanges:w.file.dataRanges()})),planClip:async w=>{let y=Ca("r3d",w.map(_=>({filename:_.basename,fileSize:_.file.size,dataRanges:_.dataRanges??[],read:(v,T)=>_.file.slice(v,v+T).arrayBuffer().then($=>new Uint8Array($))})));return mc(await $o(y,{verb:"trim",selection:{items:[],handles:0}}))}}),p=new Set([...u.dest_files,...d.regions.map(w=>w.dest_file)]),f=[];for(let[w,y]of a)p.has(w)||f.push({dest_file:w,dest_offset:0,length:y.size,source:{kind:"file",basename:w,offset:0}});for(let[w,y]of i){let _=r.files.find(v=>Ko(v.name)===w).name;!u.dest_files.includes(_)&&!u.regions.some(v=>v.source.kind==="file"&&v.source.basename===w)&&(f.push({dest_file:_,dest_offset:0,length:y.size,source:{kind:"file",basename:_,offset:0}}),a.set(_,y),c.push(`${w}: not in the recipe's cut \u2014 written as stored`))}let h=[...u.regions,...d.regions,...f],g={regions:h,total_bytes:h.reduce((w,y)=>w+y.length,0),dest_files:[...new Set(h.map(w=>w.dest_file))],source_basenames:[]},b=new Map([...i,...a,...d.filesByBasename]);await Ve(t);let k=await new zs({layout:g,files:b,sink:pc(t),signal:n.signal,concurrency:4,onProgress:w=>n.onProgress?.(w.bytesWritten,w.totalBytes,"writing trims")}).execute();return{files:g.dest_files.length,bytes:k.bytesWritten,untrimmed:c}}import{open as Km}from"node:fs/promises";import{createServer as T3}from"node:http";function vv(e,t=8*1024*1024,n=32){let r=new Map,o=(s,i)=>{let a=`${s}@${i}`,l=r.get(a);if(l)return r.delete(a),r.set(a,l),l;if(l=e(s,i*t,t).catch(c=>{throw r.delete(a),c}),r.set(a,l),r.size>n){let c=r.keys().next().value;c!==void 0&&r.delete(c)}return l};return async(s,i,a)=>{let l=Math.floor(i/t),c=Math.floor((i+a-1)/t);if(l===c){let f=await o(s,l),h=i-l*t;return f.subarray(h,Math.min(h+a,f.length))}let u=await Promise.all(Array.from({length:c-l+1},(f,h)=>o(s,l+h))),d=new Uint8Array(a),p=0;for(let f=0;f<u.length;f++){let h=u[f],g=(l+f)*t,b=Math.max(0,i-g),k=Math.min(h.length,i+a-g);k>b&&(d.set(h.subarray(b,k),p),p+=k-b)}return p===a?d:d.subarray(0,p)}}async function Vo(e,t=!1){let n=await Km(e,t?"r+":"r"),r=(await n.stat()).size;return{read:async(o,s)=>{let i=new Uint8Array(s),{bytesRead:a}=await n.read(i,0,s,o);return a===s?i:i.subarray(0,a)},write:async(o,s)=>{await n.write(s,0,s.length,o),r=Math.max(r,o+s.length)},getSize:async()=>r,setSize:async o=>{await n.truncate(o),r=o},size:()=>r,close:()=>n.close()}}var x3=4<<20;async function Vm(e,t=fetch){let n=await e(),r=async(a,l)=>{for(let c=0;;c++){let u=await t(n,{headers:{range:`bytes=${a}-${a+l-1}`}});if(u.status===403&&c===0){await u.body?.cancel(),n=await e();continue}if(u.status===416)return await u.body?.cancel(),new Uint8Array(0);if(!u.ok)throw new Error(`reading the .iso: ${u.status} ${(await u.text()).slice(0,200)}`);if(u.status===200&&a>0)throw new Error("the bucket ignored the byte range (no ranged GET)");return new Uint8Array(await u.arrayBuffer())}},o=await t(n,{headers:{range:"bytes=0-0"}});await o.body?.cancel();let s=Number(/\/(\d+)$/.exec(o.headers.get("content-range")??"")?.[1]??o.headers.get("content-length"));if(!o.ok||!Number.isFinite(s))throw new Error(`reading the .iso: ${o.status}`);let i=vv((a,l,c)=>r(l,Math.min(c,s-l)),1<<20,64);return{read:(a,l)=>{let c=Math.max(0,Math.min(l,s-a));return c?c<x3?i("iso",a,c):r(a,c):Promise.resolve(new Uint8Array(0))},write:()=>Promise.reject(new Error("a bucket .iso is read-only here (add_to patches an overlay)")),getSize:async()=>s,size:()=>s,close:async()=>{}}}function S3(e){let t=[];for(let n of[...e].sort((r,o)=>r.offset-o.offset)){let r=t[t.length-1];r&&n.offset<=r.offset+r.length?r.length=Math.max(r.length,n.offset+n.length-r.offset):t.push({...n})}return t}async function Tv(e,t){let n=await Km(t,"w+"),r=[],o=e.size();return{read:async(i,a)=>{a=Math.max(0,Math.min(a,o-i));let l=new Uint8Array(a),c=Math.max(0,Math.min(a,e.size()-i));c>0&&l.set(await e.read(i,c),0);for(let u of r){let d=Math.max(u.offset,i),p=Math.min(u.offset+u.length,i+a);p>d&&await n.read(l,d-i,p-d,d)}return l},write:async(i,a)=>{await n.write(a,0,a.length,i),r=S3([...r,{offset:i,length:a.length}]),o=Math.max(o,i+a.length)},getSize:async()=>o,setSize:async i=>{o=i},size:()=>o,writes:()=>r,scratch:t,close:()=>n.close()}}async function xv(e){let t=T3((n,r)=>void(async()=>{let o=e.size(),s=/bytes=(\d+)-(\d*)/.exec(n.headers.range??""),i=s?Number(s[1]):0,a=s&&s[2]?Math.min(Number(s[2])+1,o):o;if(r.writeHead(s?206:200,{"Accept-Ranges":"bytes","Content-Length":a-i,...s?{"Content-Range":`bytes ${i}-${a-1}/${o}`}:{}}),n.method==="HEAD")return r.end();for(let l=i;l<a;l+=8388608)r.write(await e.read(l,Math.min(8388608,a-l)));r.end()})().catch(()=>{r.headersSent||r.writeHead(503),r.end()}));return await new Promise(n=>t.listen(0,"127.0.0.1",n)),{url:`http://127.0.0.1:${t.address().port}/disk.iso`,close:()=>new Promise(n=>t.close(()=>n()))}}async function Sv(e){if(Xt()!=="darwin")throw new Error("a live mount needs macOS (hdiutil attaches the image over HTTP); fetch the .iso or its trims elsewhere");let{execFile:t}=await import("node:child_process"),n=await new Promise((o,s)=>t("/usr/bin/hdiutil",["attach",e,"-readonly","-noverify","-noautoopen"],(i,a,l)=>i?s(new Error(l||i.message)):o(a))),r=n.trim().split(`
|
|
253
|
+
`).map(o=>o.split(" ").pop().trim()).filter(o=>o.startsWith("/")).pop();if(!r)throw new Error(`hdiutil attached nothing: ${n}`);return{mountpoint:r,detach:()=>new Promise(o=>t("/usr/bin/hdiutil",["detach",r,"-force"],()=>o()))}}async function $v(e,t,n,r,o=32<<20){let s=await Km(t,"w"),i=e.size(),a=0,l=0;try{await s.truncate(i),await Promise.all(Array.from({length:4},async()=>{for(;a<i;){r?.throwIfAborted();let c=a;a+=o;let u=await e.read(c,Math.min(o,i-c));await s.write(u,0,u.length,c),l+=u.length,n?.(l,i)}}))}finally{await s.close()}return i}var Jo=class e extends File{#e;constructor(t,n,r){super([],n),this.path=t,this.#e=r}get size(){return this.#e}static async open(t,n=fe(t)){return new e(t,n,(await Bt(t)).size)}slice(t=0,n=this.size){let r=Math.max(0,t),o=Math.min(this.size,n),s=this.path;return{size:o-r,async arrayBuffer(){let i=await ou(s);try{let a=await i.readAt(r,o-r);return a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength)}finally{await i.close()}}}}arrayBuffer(){return this.slice().arrayBuffer()}stream(){let t=this;return new ReadableStream({async start(n){n.enqueue(new Uint8Array(await t.arrayBuffer())),n.close()}})}text(){return this.arrayBuffer().then(t=>new TextDecoder().decode(t))}static async openClip(t){let n=rr(fe(t))?await pi(t):[t];return n.length<2?e.open(t):new Jm(t,await Promise.all(n.map(async r=>({path:r,name:fe(r),size:(await Bt(r)).size}))))}},Jm=class extends Jo{constructor(t,n){super(t,fe(t),n.reduce((o,s)=>o+s.size,0)),this.parts=n;let r=0;this.bases=n.map(o=>(r+=o.size)-o.size)}slice(t=0,n=this.size){let r=Math.max(0,t),o=Math.min(this.size,n),s=this;return{size:Math.max(0,o-r),async arrayBuffer(){let i=new Uint8Array(Math.max(0,o-r));for(let a=0;a<s.parts.length;a++){let l=Math.max(r,s.bases[a]),c=Math.min(o,s.bases[a]+s.parts[a].size);if(l>=c)continue;let u=await ou(s.parts[a].path);try{i.set(await u.readAt(l-s.bases[a],c-l),l-r)}finally{await u.close()}}return i.buffer}}}};async function Rv(e,t){let n=new Map,r=[],o=new Set;for(let s of e.timelines)for(let i of s.tracks)for(let a of i.items)a.media_reference_id&&o.add(a.media_reference_id);for(let s of e.media_references??[]){if(!o.has(s.id))continue;let i=s.local_path??s.target_url;if(!i){r.push(`${s.id}: no path`);continue}if(t.only_linked&&s.binding_state!=="linked"){r.push(`${s.id} ${fe(i)}: not linked (run timeline_relink, or only_linked=false)`);continue}if(!await Ye(i)){r.push(`${s.id} ${i}: not on this machine`);continue}if(!Ea.has(Hn(i).toLowerCase())){r.push(`${s.id} ${fe(i)}: unsupported container`);continue}for(let a of await pi(i))n.set(fe(a),await Jo.open(a))}return{files:n,skipped:r}}var $3=new Set(["resolve-xmeml","flame-fcpxml","resolve-otio","premiere-otio"]);async function Cv(e,t,n){let r=await Ye(t)?[{name:fe(t),data:await Ut(t)}]:[],o=[],s=[];for(let a of n){let l=qa(a),c=await c1(l,e),u=typeof c.body=="string"?new TextEncoder().encode(c.body):c.body;if(l==="finalcut-fcpxmld"){for(let[d,p]of Object.entries(cs(u)))d.endsWith("/")||o.push({filename:d,bytes:p,text:!0});for(let d of c.issues??[])s.push(`${l}: ${d.message}`);continue}o.push({filename:c.filenameSuggestion,bytes:u,text:$3.has(l)});for(let d of c.issues??[])s.push(`${l}: ${d.message}`)}return{timelineFile:o.length?{bytes:o[0].bytes,filename:o[0].filename,isConversion:!0}:void 0,sourceFiles:r,exchangeFiles:o.slice(1),issues:s}}function R3(e,t){let n=t.filter(r=>r.bytes).map(r=>({dest_file:r.path,dest_offset:0,length:r.bytes.length,source:{kind:"inline",bytes:r.bytes}}));return n.length?{...e,regions:[...e.regions,...n],dest_files:[...new Set([...e.dest_files,...n.map(r=>r.dest_file)])],total_bytes:e.total_bytes+n.reduce((r,o)=>r+o.length,0)}:e}var Av=(e,t,n,r)=>["deliver",...t.length?["untrimmable"]:[],...n.length?["skipped"]:[],...e.length?["capability"]:[],...r?[]:["iso_unverified"]];async function Ev(e,t,n){let{files:r,skipped:o}=await Rv(e,{only_linked:n.only_linked});if(!r.size)throw new Error(`nothing to deliver \u2014 no linked media on this machine${o.length?`:
|
|
254
|
+
- ${o.join(`
|
|
255
|
+
- `)}`:""}`);let s=n.volume_name??fe(n.out_path),i=await Cv(e,t,n.timeline_formats),{entries:a}=Nm(e,r,{volumeName:s,preserveStructure:n.preserve_structure,timelineFile:i.timelineFile,sourceFiles:i.sourceFiles,exchangeFiles:i.exchangeFiles,handles:n.handles}),l={format:"folder",volume_name:s,folder_layout:"canonical-i2o",per_file_mode:{mode:"trim"},handles:n.handles},c=Wo(e,l),u=[...r.keys()].filter(rr),d=u.length?{...e,media_references:(e.media_references??[]).filter(w=>!rr(fe(w.target_url??"")))}:e,p=await Hs(c,r,d,l),f=[];if(u.length){let w=new Map;for(let x of c.regions){let R=fe(x.dest_file);rr(R)&&w.set(R,x.dest_file)}let y=Bm(e),_=qm(e),v=await fc({parts:u.map(x=>({basename:x,destPathHint:w.get(x)??`02_MEDIA/${x}`,file:r.get(x)})),planClip:async x=>{let R=_.get(x[0].basename),C=pv(R?y.get(R.id)??[]:[],R,R?.source_fps??24),B=await $o(N1(x.map(L=>L.file)),{verb:"trim",selection:{items:C,handles:n.handles}});return mc(B)}});f=v.dropped??[];let $=[...p.regions.filter(x=>!rr(fe(x.dest_file))),...v.regions];p={...p,regions:$,total_bytes:$.reduce((x,R)=>x+R.length,0),dest_files:[...new Set($.map(x=>x.dest_file))],source_basenames:[...new Set($.map(x=>x.source.kind==="file"?x.source.basename:"").filter(Boolean))]}}p=R3(p,a);let h=p.regions.filter(w=>w.source.kind!=="file"||r.has(w.source.basename));p={...p,regions:h,dest_files:[...new Set(h.map(w=>w.dest_file))],total_bytes:h.reduce((w,y)=>w+y.length,0)},await Ve(n.out_path);let g=await new zs({layout:p,files:r,sink:pc(n.out_path)}).execute(),b=[...p.untrimmable??[],...f],k=[...r.values()].reduce((w,y)=>w+y.size,0);return{text:[`delivered ${p.dest_files.length} file(s), ${(g.bytesWritten/1e6).toFixed(1)} MB (sources ${(k/1e6).toFixed(1)} MB) \u2192 ${n.out_path}`,...p.dest_files.map(w=>`- ${w}`),...i.issues.length?["timeline capability issues:",...i.issues.map(w=>` - ${w}`)]:[],...b.length?["not shipped (could not be trimmed \u2014 never shipped whole):",...b.map(w=>` - ${w.basename}: ${w.reason}`)]:[],...o.length?["skipped:",...o.map(w=>` - ${w}`)]:[]].join(`
|
|
256
|
+
`),files:p.dest_files.length,bytes:g.bytesWritten,keys:Av(i.issues,b,o,!0)}}async function Mv(e,t,n){let{files:r,skipped:o}=await Rv(e,{only_linked:n.only_linked});if(!r.size)throw new Error(`nothing to deliver \u2014 no linked media on this machine${o.length?`:
|
|
257
|
+
- ${o.join(`
|
|
258
|
+
- `)}`:""}`);let s=n.out_path.toLowerCase().endsWith(".iso")?n.out_path:re(n.out_path,`${n.volume_name??fe(t,Hn(t))}.iso`),i=n.volume_name??fe(s,".iso"),a=await Cv(e,t,n.timeline_formats),l=Nm(e,r,{volumeName:i,preserveStructure:n.preserve_structure,timelineFile:a.timelineFile,sourceFiles:a.sourceFiles,exchangeFiles:a.exchangeFiles,handles:n.handles}),{pinSectorByPath:c}=l,u=[...l.entries,{path:yv,bytes:wv(e,n.handles)}],d={format:"iso",volume_name:i,per_file_mode:bv("sparse"),handles:n.handles},p=hv(e),{payload:f}=await gv({session:e,layoutIntent:d,writtenAt:new Date(p).toISOString()}),h=await Hs(Wo(e,d),r,e,d,{entries:u,pinSectorByPath:c,iuvd:f,buildTimestamp:p}),g=h.image_total_bytes??h.total_bytes;await Ve(xn(s));let b=await new uc({layout:h,files:r,totalBytes:g,sink:await dc(s)}).execute(),k=await cv(await Jo.open(s)).catch(()=>null),w=h.untrimmable??[],y=[...r.values()].reduce((_,v)=>_+v.size,0);return{text:[`wrote ${s}: ${(g/1e6).toFixed(1)} MB image, ${(b.bytesWritten/1e6).toFixed(1)} MB real data (sources ${(y/1e6).toFixed(1)} MB), volume "${i}"${k?", IUVD verified":", IUVD readback FAILED"}`,...[...new Set(h.dest_files)].map(_=>`- ${_}`),...a.issues.length?["timeline capability issues:",...a.issues.map(_=>` - ${_}`)]:[],...w.length?["not shipped (could not be planned \u2014 never shipped whole):",...w.map(_=>` - ${_.basename}: ${_.reason}`)]:[],...o.length?["skipped:",...o.map(_=>` - ${_}`)]:[]].join(`
|
|
259
|
+
`),path:s,bytes:g,keys:Av(a.issues,w,o,!!k)}}function C3(e,t){let n=[];for(let r of e){let o=[r];for(let s of t)o=o.flatMap(i=>{let a=Math.max(i.offset,s.offset),l=Math.min(i.offset+i.length,s.offset+s.length);return l<=a?[i]:[{offset:i.offset,length:a-i.offset},{offset:l,length:i.offset+i.length-l}].filter(c=>c.length>0)});n.push(...o)}return n}async function Xm(e,t){let n=typeof t=="string"?await Vo(t):t,r=typeof e=="string"?await Vo(e,!0):e;try{let o=await zn(n),s=await zn(r),i=2048,a=o.partitionStartSector,l=(f,h)=>{let g=new Uint8Array(h.length);return Promise.all(Wn(f).map(async b=>{let k=Math.max(b.offset,h.offset),w=Math.min(b.offset+b.length,h.offset+h.length);w<=k||g.set(await n.read((a+b.imageSector)*i+(k-b.offset),w-k),k-h.offset)})).then(()=>g)},c=0,u=0,d=[],p=[];for(let f of o.files){let h=Wn(f).map(({offset:R,length:C})=>({offset:R,length:C})),g=f.name.lastIndexOf("."),b=g>f.name.lastIndexOf("/")?f.name.slice(0,g):f.name,k=b===f.name?"":f.name.slice(g),w=s.files.filter(R=>R.name===f.name||R.name.startsWith(`${b}_v`)&&R.name.endsWith(k)&&/^\d+$/.test(R.name.slice(b.length+2,R.name.length-k.length))),y=async R=>{if(R.totalSize!==f.totalSize)return!1;for(let C of Wn(R))for(let B of h){let L=Math.max(C.offset,B.offset),Z=Math.min(C.offset+C.length,B.offset+B.length);if(Z<=L)continue;let X=await l(f,{offset:L,length:Z-L}),O=await r.read((s.partitionStartSector+C.imageSector)*i+(L-C.offset),Z-L);if(X.some((ae,W)=>ae!==O[W]))return!1}return!0},_;for(let R of w)if(await y(R)){_=R;break}let v=_?.name??f.name;if(!_&&w.length){let R=2;for(;s.files.some(C=>C.name===`${b}_v${R}${k}`);)R++;v=`${b}_v${R}${k}`,p.push(v)}if(!_){try{s=await zh(r,s,v,f.totalSize)}catch(R){if(v.startsWith(".conform/"))continue;throw R}p.includes(v)||d.push(v)}let T=s.files.find(R=>R.name===v),$=C3(h,Wn(T).map(({offset:R,length:C})=>({offset:R,length:C}))),x=Gh(T).flatMap(R=>$.map(C=>{let B=Math.max(R.offset,C.offset),L=Math.min(R.offset+R.length,C.offset+C.length);return{offset:B,length:L-B}})).filter(R=>R.length>0);for(let R of x)s=await Hh(r,s,v,R.offset,await l(f,R)),c++,u+=R.length}return{filled:c,added:d,versioned:p,bytes:u}}finally{typeof t=="string"&&await n.close(),typeof e=="string"&&await r.close()}}function A3(e){return e=e-(e>>>1&1431655765),e=(e&858993459)+(e>>>2&858993459),e=e+(e>>>4)&252645135,Math.imul(e,16843009)>>>24}var xt=64,Iv=(()=>{let e=new Float64Array(16*xt);for(let t=0;t<16;t++)for(let n=0;n<xt;n++)e[t*xt+n]=Math.cos(Math.PI*(t+1)*(2*n+1)/(2*xt));return e})();function gc(e,t){let n=0;for(let r=0;r<8;r++)n+=A3((e.bits[r]^t.bits[r])>>>0);return n}var Qm=72;function Pv(e,t,n){let r=new Float64Array(xt*xt),o=t/xt,s=n/xt;for(let f=0;f<xt;f++)for(let h=0;h<xt;h++){let g=0,b=0,k=h*o|0,w=(h+1)*o|0,y=f*s|0,_=(f+1)*s|0;for(let v=y;v<_;v++){let T=v*t;for(let $=k;$<w;$++)g+=e[T+$],b++}r[f*xt+h]=b?g/b:0}let i=new Float64Array(16*xt);for(let f=0;f<16;f++)for(let h=0;h<xt;h++){let g=0;for(let b=0;b<xt;b++)g+=Iv[f*xt+b]*r[b*xt+h];i[f*xt+h]=g}let a=new Float64Array(256);for(let f=0;f<16;f++)for(let h=0;h<16;h++){let g=0;for(let b=0;b<xt;b++)g+=i[f*xt+b]*Iv[h*xt+b];a[f*16+h]=g}let l=Array.from(a).sort((f,h)=>f-h),c=(l[127]+l[128])/2,u=new Uint32Array(8);for(let f=0;f<256;f++)a[f]>c&&(u[f>>5]|=1<<(f&31));let d=0;for(let f=0;f<xt;f++)for(let h=0;h<xt-1;h++)d+=Math.abs(r[f*xt+h+1]-r[f*xt+h]);let p=0;for(let f=0;f<xt*xt;f++)p+=r[f];return{bits:u,quality:d,meanY:p/(xt*xt)}}function Fv(e){let t={aSource:0,hole:0};for(let n of e)n.kind==="hole"?t.hole+=n.count:t.aSource+=n.count;return t}function Ym(e,t="AX"){return e.replace(/\.[^.]+$/,"").replace(/[^A-Za-z0-9]/g,"").toUpperCase().slice(0,8)||t}function Ov(e,t,n){let r=n?.title??"QC RECONFORM",o=Ym(n?.aReel??"AX"),s=(n?.aReel??"").replace(/[\r\n]+/g," ").trim(),i=t.fps??24,a=q1(i,t.dropFrame)?"DROP FRAME":"NON-DROP FRAME",l=He(0,i,t.dropFrame),c=[`TITLE: ${r}`,`FCM: ${a}`],u=0;for(let d of e){u++;let p=String(u).padStart(3,"0");if(d.kind==="hole"){let f=He(d.count,i,t.dropFrame);c.push(`${p} ${"BL".padEnd(8)} V C ${l} ${f} ${d.recordInTc} ${d.recordOutTc}`),c.push(`* NEW MATERIAL (${d.count} frames)`)}else{if(c.push(`${p} ${o.padEnd(8)} V C ${d.aInTc} ${d.aOutTc} ${d.recordInTc} ${d.recordOutTc}`),s&&c.push(`* FROM CLIP NAME: ${s}`),d.motion&&!d.motion.ramp){let f=i*d.motion.percent/100,h=`${f<0?"-":""}${Math.abs(f).toFixed(1).padStart(5,"0")}`;c.push(`M2 ${o.padEnd(8)} ${h.padStart(6)} ${d.motion.entryTc}`),d.motion.percent<0&&c.push(`* REVERSE \u2014 PLAYS DOWN FROM ${d.motion.entryTc}`),d.motion.percent===0&&c.push(`* FREEZE FRAME AT ${d.motion.entryTc}`)}d.motion?.ramp&&c.push("* SPEED RAMP \u2014 NOT EXPRESSIBLE IN CMX3600; THE SESSION CARRIES THE CURVE"),d.unreproducible&&(c.push(`* CHECK BY EYE \u2014 ${d.unreproducible.note.toUpperCase()}`),d.motion||c.push("* THIS EVENT MAY NOT REBUILD THE CUT (HOLD / REVERSE / RETIME NOT EXPRESSIBLE)"))}}return c.join(`\r
|
|
260
|
+
`)+`\r
|
|
261
|
+
`}function E3(e){return/[",\r\n]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function Lv(e){let t=e.some(r=>r.motion),n=[["#","kind","rec_in","rec_out","A_in","A_out","frames",...t?["speed"]:[]]];for(let r of e)n.push([String(r.index),r.kind==="hole"?"HOLE":"A-SOURCE",r.recordInTc,r.recordOutTc,r.aInTc??"",r.aOutTc??"",String(r.count),...t?[r.motion?r.motion.ramp?"ramp":`${r.motion.percent.toFixed(1)}%`:""]:[]]);return n.map(r=>r.map(E3).join(",")).join(`\r
|
|
262
|
+
`)+`\r
|
|
263
|
+
`}var Zm=["only_in_a","only_in_b","different_file","same_name_different_clip","source_tc"],M3=e=>e.replace(/^file:\/\//,"").split(/[\\/]/).pop()??e;function Ws(e,t){let n=e.timelines??[],r=t?n.find(o=>o.id===t):n.find(o=>o.kind==="primary"&&o.tracks?.some(s=>s.items?.length))??n[0];if(!r)throw new P("not_found",t?`no timeline ${t} (timelines: ${n.map(o=>`${o.id} "${o.name}"`).join(", ")})`:"the session has no timeline");return r}function lo(e,t){let n=e.start_frame??0,r=[];for(let i of t)if(i.enabled!==!1)for(let a of i.items){if(a.kind!=="clip"||a.enabled===!1||!a.timeline_range.duration.value)continue;let l=n+a.timeline_range.start.value;r.push({s:l,e:l+a.timeline_range.duration.value,it:a,track:Sn(i,e.tracks),z:i.track_index??0})}let o=[...new Set(r.flatMap(i=>[i.s,i.e]))].sort((i,a)=>i-a),s=[];for(let i=0;i+1<o.length;i++){let[a,l]=[o[i],o[i+1]],c;for(let u of r)u.s<=a&&u.e>=l&&(!c||u.z>=c.z)&&(c=u);c&&s.push({s:a,e:l,it:c.it,track:c.track})}return s}function Nv(e,t,n,r){let o=e.it,s=o.media_reference_id?r.get(o.media_reference_id):void 0,i=s?.local_path??s?.target_url??null,a=o.source_range?.start.rate||Pt(n),l=s?.source_fps||a,c=s?.source_timecode?At(s.source_timecode,l)??0:0,u=(n.start_frame??0)+o.timeline_range.start.value,d=(o.speed??100)/100*(o.speed_reverse?-1:1),p=(o.source_range?.start.value??0)+(t-u)*d*a/Pt(n),f=Math.round(c+p*l/a);return{item_id:o.id,track:e.track,file:i?M3(i):o.name??"(unnamed)",path:i,reel:s?.reel_name??o.reel_name??null,file_tc:s?.source_timecode??null,file_frames:s?.available_range?.duration?.value??s?.declared_duration?.value??null,src_tc:He(f,l,!!s?.source_timecode?.includes(";")),src_frame:f,rate:l}}function I3(e,t){if(!e&&!t)return null;if(!t)return{kind:"only_in_a",note:"A has picture here, B has none"};if(!e)return{kind:"only_in_b",note:"B has picture here, A has none (missing from A)"};let n=e.file.toLowerCase(),r=t.file.toLowerCase();if(n!==r)return{kind:"different_file",note:`${e.reel&&t.reel&&e.reel===t.reel?"same reel, ":""}different file; source TC ${e.src_tc} vs ${t.src_tc}${Math.abs(e.src_frame-t.src_frame)>1440?" (different TC base: temp vs master?)":""}`};if(e.file_tc&&t.file_tc&&e.file_tc!==t.file_tc||e.file_frames!=null&&t.file_frames!=null&&e.file_frames!==t.file_frames)return{kind:"same_name_different_clip",note:`same name, different clip: file TC ${e.file_tc??"?"} vs ${t.file_tc??"?"}, ${e.file_frames??"?"} vs ${t.file_frames??"?"} fr${e.path!==t.path?" (different folders)":""}`};let o=t.src_frame-e.src_frame;return o?{kind:"source_tc",note:`same file, source ${o>0?"+":""}${o} fr (A ${e.src_tc}, B ${t.src_tc})`}:null}function Dv(e,t,n={}){let r=Ws(e,n.a_timeline_id),o=Ws(t,n.b_timeline_id),s=Pt(r),i=Pt(o);if(Math.abs(s-i)>.001)throw new P("invalid_args",`the timelines run at different rates (${s} vs ${i} fps); record TC cannot be aligned frame for frame`);let a=new Map((e.media_references??[]).map(f=>[f.id,f])),l=new Map((t.media_references??[]).map(f=>[f.id,f])),c=f=>f.tracks.filter(h=>h.kind==="Video"),u=[];if(n.by_track){let f=new Set([...c(r).map(h=>Sn(h,r.tracks)),...c(o).map(h=>Sn(h,o.tracks))]);for(let h of f)u.push({name:h,a:c(r).filter(g=>Sn(g,r.tracks)===h),b:c(o).filter(g=>Sn(g,o.tracks)===h)})}else u.push({name:"top",a:c(r),b:c(o)});let d=f=>He(f,s,!!r.is_drop_frame),p=[];for(let f of u){let h=lo(r,f.a),g=lo(o,f.b),b=[...new Set([...h,...g].flatMap(w=>[w.s,w.e]))].sort((w,y)=>w-y),k=(w,y)=>w.find(_=>_.s<=y&&_.e>y);for(let w=0;w+1<b.length;w++){let[y,_]=[b[w],b[w+1]],v=k(h,y),T=k(g,y),$=v?Nv(v,y,r,a):null,x=T?Nv(T,y,o,l):null,R=I3($,x);if(!R)continue;let C=p[p.length-1];if(C&&C.lane===f.name&&C.rec_out===y&&C.kind===R.kind&&C.a?.item_id===$?.item_id&&C.b?.item_id===x?.item_id){C.rec_out=_,C.rec_out_tc=d(_),C.frames=_-C.rec_in;continue}p.push({lane:f.name,kind:R.kind,rec_in:y,rec_out:_,rec_in_tc:d(y),rec_out_tc:d(_),frames:_-y,a:$,b:x,note:R.note})}}return{ranges:p,ta:r,tb:o,lanes:u.map(f=>f.name),fps:s}}var jv=e=>e?`${e.file} @ ${e.src_tc} [${e.track} ${e.item_id}]`:"(nothing)";function Bv(e,t,n,r){let o=Zm.map(c=>[c,e.ranges.filter(u=>u.kind===c).length]).filter(([,c])=>c),s=e.ranges.length?`${e.ranges.length} record range${e.ranges.length===1?"":"s"} differ in source between A and B (${o.map(([c,u])=>`${u} ${c}`).join(", ")})`:`no source differences: A and B show the same source on every record frame (${e.lanes.join(", ")})`,i=e.ranges.slice(0,r),a=e.ranges.length>i.length?`TRUNCATED: showing ${i.length} of ${e.ranges.length} ranges \u2014 NOT the full list. Pass limit=${e.ranges.length}, or csv_path for all.
|
|
264
|
+
`:"",l=i.map(c=>`- ${c.lane==="top"?"":`${c.lane} `}${c.rec_in_tc}\u2013${c.rec_out_tc} (${c.frames} fr) ${c.kind}: A ${jv(c.a)} | B ${jv(c.b)} \u2014 ${c.note}`);return`${a}${s}
|
|
265
|
+
A: ${t} "${e.ta.name}"
|
|
266
|
+
B: ${n} "${e.tb.name}"
|
|
267
|
+
compared: ${e.lanes[0]==="top"?"topmost enabled video clip per record frame":`per video track (${e.lanes.join(", ")})`}; record frames and TC at the timelines' ${+e.fps.toFixed(3)} fps from each one's start TC (a side's src_frame counts at its media rate); out exclusive${l.length?`
|
|
268
|
+
${l.join(`
|
|
269
|
+
`)}`:""}`}var P3=e=>{let t=e==null?"":String(e);return/[",\r\n]/.test(t)?`"${t.replace(/"/g,'""')}"`:t};function qv(e){let t=["lane","kind","rec_in_tc","rec_out_tc","frames","a_file","a_src_tc","a_file_tc","a_track","a_item","a_path","b_file","b_src_tc","b_file_tc","b_track","b_item","b_path","note"],n=e.map(r=>[r.lane,r.kind,r.rec_in_tc,r.rec_out_tc,r.frames,r.a?.file,r.a?.src_tc,r.a?.file_tc,r.a?.track,r.a?.item_id,r.a?.path,r.b?.file,r.b?.src_tc,r.b?.file_tc,r.b?.track,r.b?.item_id,r.b?.path,r.note]);return[t,...n].map(r=>r.map(P3).join(",")).join(`
|
|
270
|
+
`)+`
|
|
271
|
+
`}function Uv(e,t){let n=Pt(e.tb),r=!!e.tb.is_drop_frame,o=i=>He(i,n,r),s=[`TITLE: ${t}`,`FCM: ${r?"DROP FRAME":"NON-DROP FRAME"}`];return e.ranges.forEach((i,a)=>{let l=String(a+1).padStart(3,"0");if(!i.b){s.push(`${l} ${"BL".padEnd(8)} V C ${o(0)} ${o(i.frames)} ${i.rec_in_tc} ${i.rec_out_tc}`,`* ${i.kind.toUpperCase()}: B HAS NO PICTURE HERE`);return}s.push(`${l} ${Ym(i.b.reel??i.b.file).padEnd(8)} V C ${i.b.src_tc} ${He(i.b.src_frame+Math.round(i.frames*i.b.rate/n),i.b.rate,i.b.src_tc.includes(";"))} ${i.rec_in_tc} ${i.rec_out_tc}`,`* FROM CLIP NAME: ${i.b.file}`,`* ${i.kind.toUpperCase()}: ${i.note.toUpperCase()}`)}),s.join(`\r
|
|
272
|
+
`)+`\r
|
|
273
|
+
`}function Gv(e,t){let n=structuredClone(e),r=n.timelines.find(s=>s.id===t.tb.id);n.timelines=[r];let o=new Set(t.ranges.map(s=>s.b?.item_id).filter(Boolean));for(let s of r.tracks)s.items=s.kind==="Video"?s.items.filter(i=>o.has(i.id)):[];return r.name=`${r.name} \u2014 source diff`,n}function F3(e,t){let n=(e.keyframes??[]).filter(i=>i.parameter_path==="speed"&&typeof i.time?.value=="number"&&typeof i.value=="number").map(i=>({x:i.time.value,y:i.value,t:Array.isArray(i.raw_extraction?.drtNativeTangent)?i.raw_extraction.drtNativeTangent:null,pre:!!i.raw_extraction?.speedPreRoll,g0:Array.isArray(i.raw_extraction?.speedGraphPoint)&&Math.abs(i.raw_extraction.speedGraphPoint[0])<1e-9})).sort((i,a)=>i.x-a.x);if(n.length<2)return null;let r=(n.find(i=>i.g0)??n.find(i=>!i.pre)??n[0]).x,o=(i,a)=>{let l=n[i].t;if(l&&l.length>=4){if(a==="in"&&l[0])return l[1]/l[0];if(a==="out"&&l[2])return l[3]/l[2]}let c=a==="out"?Math.min(i+1,n.length-1):Math.max(i-1,0),u=Math.min(i,c),d=Math.max(i,c);return n[d].x>n[u].x?(n[d].y-n[u].y)/(n[d].x-n[u].x):0},s=i=>{let a=n.length-1;if(i<=n[0].x)return n[0].y+(i-n[0].x)*o(0,"out");if(i>=n[a].x)return n[a].y+(i-n[a].x)*o(a,"in");for(let l=0;l<a;l++){let c=n[l],u=n[l+1];if(i>u.x)continue;let d=u.x-c.x;if(d<=0)return u.y;let p=(i-c.x)/d,f=p*p,h=f*p;return(2*h-3*f+1)*c.y+(h-2*f+p)*d*o(l,"out")+(-2*h+3*f)*u.y+(h-f)*d*o(l+1,"in")}return n[a].y};{let i=n[0].x-1,a=n[n.length-1].x+1;for(let l=0;l<80;l++){let c=(i+a)/2;s(c)<t?i=c:a=c}Math.abs(s(a)-t)<1e-4&&(r=a)}return i=>s(r+i)}function Hv(e,t,n,r=0,o=0){let s=e.source_range.start.rate||n,i=t?.source_fps||s,a=Math.round(e.timeline_range.duration.value),l=F3(e,e.source_range.start.value/s),c=e.source_range.start.value*(i/s),u=i/n*((e.speed??100)/100)*(e.speed_reverse?-1:1),d=[];for(let p=-r;p<a+o;p++)d.push(l?l(p/n)*i:c+p*u);return d}var Ks=e=>"a"in e;async function O3(){let e=[zt("CONFORM_MEDIA_GEN"),_o(new URL("../../rust/target/release/media-gen",import.meta.url)),(await Ar())?.runner],t=zt("CONFORM_RIFE_WEIGHTS")??re(tt(),"models","rife","rife_v4.22_lite.safetensors"),n;for(let r of e)if(r&&await On(r)){n=r;break}if(!n)throw new Error("the interpolation model's runner (media-gen) is not installed (Apple Silicon; cargo build --release -p media-gen)");if(!await On(t))throw new Error(`RIFE's weights are not installed at ${t} (scripts/rife/oracle.py --out writes them)`);return{runner:n,weights:t}}async function zv(e){if(e.kind==="retime"&&(e.speed??100)<=0&&!e.ramp?.length)throw new Error("retime: speed must be above 0 (a reverse or a freeze is an edit, not a fix)");let t=async g=>(await st(g)).available_range?.duration.value||void 0,n=await qt({op:"fix",kind:e.kind,path:e.path,frames:await t(e.path),includeFreezes:!!e.include_freezes,plate:e.plate,plateStart:e.plate_start??0,plateFrames:e.plate_frames,mask:e.mask,plateCount:e.plate?await t(e.plate):void 0,srcIn:e.src_in??0,outFrames:e.frames,speed:e.speed!=null?e.speed/100:void 0,ramp:e.ramp?.map(([g,b])=>[g,b/100])}),r=n.out,o=n.between,s={kind:e.kind,status:"planned",frames_in:n.frames,frames_out:r.length,between:o,found:n.found},i=n.found;if(e.kind==="cadence"&&i.repace?.detected&&!e.force)return{...s,status:"refused: re-pace detected"};if(e.plan_only)return s;if(!(o>0||r.length!==s.frames_in||r.some((g,b)=>!Ks(g)&&g.f!==b)))return{...s,status:"nothing to fix"};let l=e.out_path??e.path.replace(/(\.[^./]+)?$/,`_${e.kind}.mov`),c=async(g,b)=>{let k=await st(g),w=k.source_timecode?At(k.source_timecode,k.source_fps??k.available_range?.duration.rate??24):null;return{tc:w!=null?w+b:-1,df:!!k.source_timecode?.includes(";")}},u=e.kind==="cadence"?await c(e.plate,i.plate.start):await c(e.path,Ks(r[0])?r[0].a:r[0].f),[d,p]=String(n.rate??"24/1").split("/").map(Number),f=await Kv(e.path,r,l,d,p||1,u),h=e.kind==="cadence"?await qt({op:"cadence_check",out:l,plate:e.plate,plateStart:i.plate.start,plateFrames:i.plate.frames}).then(g=>({motion_flags:g.motion_flags})):await qt({op:"fix",kind:"duplicates",path:l,frames:r.length}).then(g=>({repeats_left:g.between}));return{...s,status:"fixed",wrote:l,between_output_frames:f,check:h}}async function Wv(e,t){let n=e.timelines.find(c=>c.kind==="primary")??e.timelines[0];if(!n)throw new Error("the session has no timeline");let r=Pt(n),o=Math.max(0,Math.floor(t.handles??12)),s=t.out_dir??re(tt(),"renders",t.session_id);t.plan_only||await Ve(s);let i=[],a=e.media_references??[],l=!1;for(let c of n.tracks.filter(u=>u.kind==="Video"))for(let u of c.items){if(u.kind!=="clip"||u.enabled===!1||!u.source_range||t.item_ids&&!t.item_ids.includes(u.id))continue;let d=u.speed??100,p=!!u.speed_ramped;if(!p&&Math.abs(d-100)<1e-6)continue;let f=u.name??u.id,h=p?"ramp":`${+d.toFixed(2)} %`;if(u.speed_reverse||!p&&d<=0){i.push({item:u.id,name:f,speed:h,skipped:"a reverse or a freeze is an edit, not a retime to smooth"});continue}let g=a.find(C=>C.id===u.media_reference_id),b=g?.local_path??g?.target_url?.replace(/^file:\/\//,"");if(!g||!b||!await On(b)){i.push({item:u.id,name:f,speed:h,skipped:"its media isn't linked on this machine (timeline_relink first)"});continue}let k=(await st(b)).available_range?.duration.value??0,w=Hv(u,g,r,o,o),y=o;for(;y>0&&(w[0]<0||w[0]>k-1);)w=w.slice(1),y--;for(;w.length>Math.round(u.timeline_range.duration.value)+y&&(w[w.length-1]<0||w[w.length-1]>k-1);)w=w.slice(0,-1);let _=await qt({op:"fix",kind:"retime",path:b,frames:k||void 0,positions:w}),v=_.out;if(t.plan_only){i.push({item:u.id,name:f,speed:h,frames:v.length,between:_.between});continue}let T=Math.round(u.timeline_range.start.value),$=(n.start_frame??0)+T-y,x=re(s,`${fe(b).replace(/\.[^.]+$/,"")}_flow_${He($,r,!!n.is_drop_frame).replace(/[:;]/g,"")}.mov`);await Kv(b,v,x,n.fps_num,n.fps_den||1,{tc:$,df:!!n.is_drop_frame});let R=await st(x);R.id=`flow-${u.id}`,e.media_references=[...a.filter(C=>C.id!==R.id),R],u.media_reference_id=R.id,u.source_range={start:{value:y,rate:r},duration:{value:Math.round(u.timeline_range.duration.value),rate:r}},u.speed=100,u.speed_ramped=!1,u.speed_reverse=!1,u.keyframes=(u.keyframes??[]).filter(C=>C.parameter_path!=="speed"),l=!0,i.push({item:u.id,name:f,speed:h,wrote:x,frames:v.length,between:_.between})}return{session:e,items:i,changed:l}}async function Kv(e,t,n,r,o,s){let i=await It("conform-fix-");try{let a=$=>`${$.a}_${$.b}_${$.t}`,l=new Map;for(let $ of t.filter(Ks)){let x=l.get(`${$.a}_${$.b}`)??{a:$.a,b:$.b,t:[]};x.t.includes($.t)||x.t.push($.t),l.set(`${$.a}_${$.b}`,x)}let c=new Set([...l.values()].flatMap($=>[$.a,$.b])),u=0,d=0,p=$=>{let x=new Uint8Array($.length/4*3);for(let R=0,C=0;R<$.length;R+=4,C+=3)x[C]=$[R],x[C+1]=$[R+1],x[C+2]=$[R+2];return x};if(c.size){let $=[];await bu(e,B=>{u=B.w,d=B.h},(B,L)=>{c.has(B)&&$.push(Gn(re(i,`${B}.bgr`),p(L)))}),await Promise.all($);let x=[...l.values()].map(B=>({a:re(i,`${B.a}.bgr`),b:re(i,`${B.b}.bgr`),t:B.t,out:B.t.map(L=>re(i,`${a({a:B.a,b:B.b,t:L})}.mid.bgr`))}));await Ke(re(i,"jobs.json"),JSON.stringify({w:u,h:d,pairs:x}));let R=await O3(),C=await sn(R.runner,["rife","--weights",R.weights,"--jobs",re(i,"jobs.json")]);if(!C.success)throw new Error(`the interpolation model (RIFE on media-gen) failed: ${C.stderr.trim().split(`
|
|
274
|
+
`).slice(-4).join(" | ")}`)}await Gr();let f=($,x)=>{let R=new Uint8Array(u*d*4);for(let C=0,B=0;B<R.length;C+=x,B+=4)R[B]=$[C+2],R[B+1]=$[C+1],R[B+2]=$[C],R[B+3]=255;return R},h=new Map;for(let $ of t.filter(Ks))h.has(a($))||h.set(a($),gu(f(await Ut(re(i,`${a($)}.mid.bgr`)),3),u,d));let g=new Map;t.forEach(($,x)=>{Ks($)||g.set($.f,x)});let b=new Map,k=[],w=[],y=0,_=$=>{for(;y<t.length;){let x=t[y];if(Ks(x))w.push(k.length),k.push(h.get(a(x)));else{if(x.f>$||!b.has(x.f))break;k.push(b.get(x.f)),g.get(x.f)===y&&b.delete(x.f)}y++}};if(await bu(e,$=>{u=$.w,d=$.h},($,x)=>{g.has($)&&b.set($,gu(f(x,4),u,d)),_($)}),y<t.length)throw new Error(`the source stopped decoding at output frame ${y} of ${t.length}`);let v=new Uint8Array(k.reduce(($,x)=>$+x.length,0)),T=0;for(let $ of k)v.set($,T),T+=$.length;return await Gn(n,$1(v,Uint32Array.from(k.map($=>$.length)),u,d,r,o,"apch",!1,BigInt(s.tc),s.df,1,1)),w}finally{await dn(i).catch(()=>{})}}function Vv(e){let n=[`${e.status}: ${e.kind} \u2014 ${e.frames_in} source frames \u2192 ${e.frames_out} out, ${e.between} remade between frames`];if(e.kind==="duplicates"){let r=e.found;n.push(r.length?`found (${r.length}): ${r.map(o=>`${o.check} ${o.start}\u2013${o.end}`).join(", ")}`:"found: no repeated frames QC calls a defect")}if(e.kind==="cadence"){let r=e.found;n.push(`held frames cut (${r.held_frames.length}): ${r.held_frames.join(", ")||"none"}`),r.real_pauses_kept.length&&n.push(`kept as real pauses (the plate pauses too): ${r.real_pauses_kept.join(", ")}`),n.push(`skipped source frames: ${r.gaps.map(o=>`after render ${o.after_render_frame} \u2192 plate ${o.plate_frames.join("/")}`).join("; ")||"none"}`),r.repace.detected&&n.push(`RE-PACE: render frames ${r.repace.runs.fast.map(([o,s])=>`${o}\u2013${s}`).join(", ")} race ahead of the plate. ${r.repace.note}`)}return e.wrote&&n.push(`wrote ${e.wrote}; between frames at output ${e.between_output_frames?.join(", ")||"none"}`),e.check&&n.push(`check: ${JSON.stringify(e.check)}`),n.join(`
|
|
275
|
+
`)}async function co(e){let t=await or();if(!t)throw new P("unsupported","media_patch needs the native engine (conformtools-decode), which is not installed here. From a source checkout build it once: cd rust && cargo build --release -p media-native --bin conformtools-decode (or set CONFORM_NATIVE_DECODE to the binary); the npm package ships it.");let n=await sn(t,["patch",JSON.stringify(e)]);if(n.code!==0){let r=di(n.stderr),o=/not supported|does not match|refus|outside|disagrees|no timecode|timecode mismatch|exists/.test(r);throw new P(o?"refused":"engine",r)}return JSON.parse(n.stdout.trim().split(`
|
|
276
|
+
`).pop())}var rf=()=>re(tt(),"patches.jsonl"),bc=e=>`${(e/1e9).toFixed(e<1e10?2:1)} GB`;function L3(e,t){return[`layout: ${e.top_level.map(n=>n.type).join(" ")} (index at the ${e.moov_at}), ${bc(e.master_bytes)}`,` in_place grows the file by ${bc(e.in_place_grows_by)}; new needs ${bc(e.new_needs_free)} free${t!=null?` (${bc(t)} free here${t<e.new_needs_free?": NOT enough for new, in_place only if the user asks to modify the master":""})`:""}`,` chunk offsets after the write: ${e.chunk_offsets_after}; bitrate box (btrt): ${e.btrt?"present, refreshed":"none"}`,` changes: ${e.changes}`].join(`
|
|
277
|
+
`)}async function N3(e){if(e.in==null||e.out==null)throw new P("invalid_args","plan needs in and out (the fixed range on the master, frames or TC)");let t=await st(e.path),n=t.source_fps??t.streams?.find(c=>c.kind==="video")?.rate??0,r=t.source_timecode??null,o=yr(e.in,n,r),s=yr(e.out,n,r);if(o<0||s<o)throw new P("invalid_args","in/out must be inside the master, in before out");let i=await co({mode:"plan",master:e.path,master_in:o,frames:s-o+1}),a=c=>He((i.master_tc_start_frame??0)+c,n),l=i.frames-(s-o+1);return{text:[`${i.codec}: render master frames ${i.span[0]}\u2013${i.span[1]} (${i.frames} frames, ${a(i.span[0])}\u2013${a(i.span[1])}) for the fix at ${o}\u2013${s}${l?` (+${l} to whole GOPs)`:""}`,`GOP ${i.gop??"?"}${i.fixed_gop?" (fixed)":" (varies)"}, ${i.b_frames?"B-frames":"no B-frames"}${i.open_gop_after?"; the GOP after the fix is open, so it is included":""}`,i.swappable?`then: ${i.render}`:`the master's GOP at ${a(i.span[0])} is open: a swap there needs a re-encode across the seam; ask before rendering`].join(`
|
|
278
|
+
`),data:{...i,fixed:[o,s],tc_in:a(i.span[0]),tc_out:a(i.span[1])}}}async function j3(){try{return(await ct(rf())).split(`
|
|
279
|
+
`).filter(Boolean).map(e=>JSON.parse(e))}catch{return[]}}var ef=e=>`${((Number(e)||0)/1e6).toFixed(1)} MB`;async function of(e,t){let n=e.mode??"new";if(n==="undo")return D3(e.path);if(e.patches?.length){if(n!=="in_place"&&n!=="check")throw new P("invalid_args","patches (several at once) is for mode in_place or check; one patch per new/section file");if(e.patch||e.in!=null||e.out!=null||e.patch_in!=null)throw new P("invalid_args","with patches, each is placed by its own TC: leave patch/in/out/patch_in out");let h=[];for(let[k,w]of e.patches.entries())t?.(k,e.patches.length,`check ${fe(w)}`),h.push(await co({mode:"check",master:e.path,patch:w}));let g=h.map(k=>[k.master_in,k.master_in+k.frames-1]).sort((k,w)=>k[0]-w[0]);for(let k=1;k<g.length;k++)if(g[k][0]<=g[k-1][1])throw new P("refused",`patches overlap at master frames ${g[k][0]}\u2013${g[k-1][1]}; nothing written`);if(n==="check")return{text:`all ${h.length} patches fit: ${h.map(k=>`${k.frames} frames at ${k.master_in}`).join(", ")}
|
|
280
|
+
nothing written (mode=check)`,data:{plans:h}};let b=[];for(let[k,w]of e.patches.entries())t?.(k,e.patches.length,`patch ${k+1}/${e.patches.length}: ${fe(w)}`),b.push(await of({path:e.path,patch:w,mode:n,verify:e.verify}));return t?.(e.patches.length,e.patches.length,"done"),{text:b.map(k=>k.text).join(`
|
|
281
|
+
|
|
282
|
+
`),data:{mode:n,path:e.path,patches:b.map(k=>k.data)}}}if(n==="plan")return N3(e);if(!e.patch)throw new P("invalid_args","patch (the render of the fixed range, with record TC) is required");let r,o;if(e.in!=null||e.out!=null){let h=await st(e.path),g=h.source_fps??h.streams?.find(k=>k.kind==="video")?.rate??0,b=h.source_timecode??null;if(e.in!=null&&(r=yr(e.in,g,b)),e.out!=null){if(r==null)throw new P("invalid_args","out needs in");if(o=yr(e.out,g,b)-r+1,o<1)throw new P("invalid_args","out is before in")}if(r!=null&&r<0)throw new P("invalid_args",`in is before the master's start TC (${b})`)}let s=await co({mode:"check",master:e.path,patch:e.patch,master_in:r,frames:o,patch_in:e.patch_in}),i=`${s.master_in}\u2013${s.master_in+s.frames-1}`,a=Hn(e.path),l=fe(e.path,a),c=async h=>{let g=e.out_path??re(xn(e.path),h);if(await Jv(g)&&(g=re(g,h)),await Ye(g))throw new P("refused",`${g} already exists; not overwriting (pass another out_path)`);return g},u=`${s.frames} frame${s.frames===1?"":"s"} of ${s.codec} cut in by timecode at master frames ${i} (patch frames ${s.patch_in}\u2013${s.patch_in+s.frames-1})`;if(n==="check"){let h=s.layout,g=await Th(xn(e.path)).catch(()=>null);return{text:`patch fits: ${u}, no re-encode
|
|
283
|
+
${h?L3(h,g)+`
|
|
284
|
+
`:""}nothing written (mode=check)`,data:{...s,free_bytes:g}}}let d={patch_in:s.patch_in,frames:s.frames};if(n==="section"){let h=await c(`${l}_patch_${i.replace("\u2013","-")}${a}`),g=await It("conform-patch-");try{let b=re(g,`range${a}`);await Ia({path:e.path,in:s.master_in,out:s.master_in+s.frames-1,out_path:b});let k=await co({mode:"new",master:b,patch:e.patch,out_path:h,...d}),w=await st(h);return{text:`wrote section ${h}: ${u}, with the master's TC and audio, no re-encode
|
|
285
|
+
verified: ${tf(k)}; start TC ${w.source_timecode??"none"}`,data:{...d,master_in:s.master_in,mode:n,path:h,start_tc:w.source_timecode??null,verify:k.verify,cost:k.cost}}}finally{await dn(g)}}if(n==="in_place"){t?.(0,1,`write + verify ${fe(e.patch)}`);let h=await co({mode:"in_place",master:e.path,patch:e.patch,...d,verify:e.verify??"index"}),g={...h.undo,patch:e.patch,at:new Date().toISOString()};await Ve(tt()),await Ke(rf(),JSON.stringify(g)+`
|
|
286
|
+
`,{append:!0});let b=h.cost??{};return{text:`patched ${fe(e.path)} in place: ${u}, no re-encode
|
|
287
|
+
verified: ${tf(h)}
|
|
288
|
+
cost: the file grew ${ef(b.grew_bytes)}; ${ef(b.dead_bytes)} stay as dead bytes (the replaced frames + old index, kept so undo works); the patched span now sits at the end of the file, away from its audio (mode=new rewrites the file contiguously)${b.btrt_refreshed?"; bitrate box refreshed":""}
|
|
289
|
+
undo: media_patch mode=undo path=${e.path} restores the original byte for byte`,data:{...d,master_in:s.master_in,mode:n,path:e.path,verify:h.verify,cost:h.cost,undo:g}}}let p=await c(`${l}_patched${a}`),f=await co({mode:"new",master:e.path,patch:e.patch,out_path:p,...d});return{text:`wrote ${p}: ${fe(e.path)} with ${u}, no re-encode
|
|
290
|
+
verified: ${tf(f)}
|
|
291
|
+
rewritten contiguously in the master's interleave order (${ef(f.cost?.bytes)}); the master was not touched`,data:{...d,master_in:s.master_in,mode:n,path:p,verify:f.verify,cost:f.cost}}}function tf(e){let t=e.verify??{},n=t.other_tracks_check==="index"?`${t.other_tracks} other tracks (audio/TC) untouched: every sample at its original offset and size, and the write never reached them (verify=full re-reads and hashes them)`:`${t.other_tracks} other tracks (audio/TC) hash-identical`;return`${t.frames} frames, the master's TC track unchanged, ${t.patched_frames_identical} frames at the patch's TC byte-identical to the patch (ends decode to the patch's pixels), frames either side are the master's (${(t.splice??[]).filter(r=>!r.is.startsWith("patch")).map(r=>r.frame).join(", ")||"none: the span is the whole file"}), ${n}`}async function D3(e){let t=await j3(),n=(await Bt(e)).size,r=t.findLastIndex(s=>s.path===e&&s.size_after===n);if(r<0){let s=t.some(i=>i.path===e);throw new P(s?"refused":"not_found",s?`${fe(e)} changed since its last in-place patch (size ${n}); nothing undone`:`no in-place patch of ${fe(e)} on record`)}let o=t[r];return await co({mode:"undo",record:o}),t.splice(r,1),await Ke(rf(),t.map(s=>JSON.stringify(s)+`
|
|
292
|
+
`).join("")),{text:`undid the in-place patch of ${fe(e)} (master frames ${o.master_in}\u2013${o.master_in+o.frames-1}): the file is byte-identical to before it`,data:{mode:"undo",path:e,undone:o}}}var B3={rec709:1,bt709:1,rec2020:9,bt2020:9,"dci-p3":11,p3dci:11,p3d65:12,"display-p3":12},q3={rec709:1,bt709:1,g24:1,bt1886:1,pq:16,st2084:16,g26:17,st428:17,hlg:18},U3={rec709:1,bt709:1,rec2020:9,bt2020:9};function nf(e,t,n){if(typeof t=="number")return t;let r=n[t.toLowerCase().replace(/[\s_.]/g,"")];if(r==null)throw new P("invalid_args",`unknown ${e} '${t}' (use ${Object.keys(n).join(", ")} or an H.273 code)`);return r}async function Jv(e){let t=await Bt(e).then(n=>n.isDirectory).catch(()=>null);return t!==null?t:!/[\\/]$/.test(e)&&Hn(e)?!1:(await Ve(e),!0)}async function Xv(e){if(!e.out_path&&!e.in_place)throw new P("invalid_args","give out_path (a retagged copy) or in_place=true (only when the user asks to change this file itself)");let t=e.out_path;t&&await Jv(t)&&(t=re(t,fe(e.path)));let n=[nf("primaries",e.primaries,B3),nf("transfer",e.transfer,q3),nf("matrix",e.matrix,U3)],r=await co({mode:"retag",master:e.path,out_path:t,in_place:e.in_place??!1,primaries:n[0],transfer:n[1],matrix:n[2]}),o=r.retag,s=o.frames_before.map(i=>`${i.tags.join("/")} \xD7${i.frames}`).join(", ");return{text:`retagged ${r.path} (${r.codec}, no re-encode)
|
|
293
|
+
colr ${o.colr.kind}: ${o.colr.before.join("/")} \u2192 ${o.colr.after.join("/")} (primaries/transfer/matrix)
|
|
294
|
+
frame headers: ${o.frames} frames, ${s} \u2192 ${o.colr.after.join("/")}
|
|
295
|
+
read back: all match`,data:r}}async function sf(e,t,n,r){let o=await or();if(!o)throw new P("unsupported",`media_${e==="dcp"?"dcp":"dcp_kdm"} needs the native engine (conformtools-decode), which is not installed here. From a source checkout: cd rust && cargo build --release -p media-native --bin conformtools-decode (or set CONFORM_NATIVE_DECODE); the npm package ships it.`);let s="",i="",a=new TextDecoder,l=await br(o,[e,JSON.stringify(t)],c=>{s+=a.decode(c,{stream:!0});let u=s.split(`
|
|
296
|
+
`);s=u.pop();for(let d of u){if(!d.trim())continue;let p=d.startsWith('{"progress"')?JSON.parse(d).progress:null;p?n?.(p[0],p[1],"encoding"):i=d}},{signal:r});if(s.trim()&&(i=s),l.code!==0){let c=di(l.stderr);throw new P(/exists|is required|not ProRes|integer rate|mix is|Hz|not integer PCM|unknown|encrypted|no key|do not fit|fps|not a date|must be after|signing identity|CPL|VF|subtitles/.test(c)?"refused":"engine",c)}return i}async function Qv(e,t,n){let r={...e,path:void 0,movie:e.path,out_dir:e.out_dir??xn(e.path)};return JSON.parse(await sf("dcp",r,t,n))}async function Yv(e){return JSON.parse(await sf("kdm",e))}function af(e){let t=r=>`${(r/1e6).toFixed(1)} MB`,n=[`wrote ${e.path}`];if(e.source_dcp)n.push(`from ${e.source_dcp.path}${e.source_dcp.encrypted?" (encrypted)":""}: ${e.frames} frames @ ${e.fps} fps, ${e.reels} reel(s)`),e.patch&&n.push(`patched frames ${e.patch.at}\u2013${e.patch.at+e.patch.count-1} from ${e.patch.movie} (its frames ${e.patch.from}\u2013${e.patch.from+e.patch.count-1}); every other codestream re-wrapped byte-for-byte`),e.carried_reels?.length&&n.push(`reel(s) ${e.carried_reels.join(", ")} carried unchanged`),e.sound_replaced&&n.push("sound replaced from the new mix");else if(e.source&&e.container&&e.audio){let[r,o]=e.container.picture,s=r!==e.container.width||o!==e.container.height?` (picture ${r}x${o}, rest black)`:"";n.push(`${e.frames} frames @ ${e.fps} fps, ${e.container.width}x${e.container.height}${s} from ${e.source.codec} ${e.source.width}x${e.source.height}`,`sound: ${e.audio.channels} ch ${e.audio.rate/1e3} kHz 24-bit (mix was ${e.audio.bits_in}-bit)`),e.reclock&&n.push(`reclocked ${e.reclock.from_fps.toFixed(3)} \u2192 ${e.reclock.to_fps} frame-for-frame; sound ${e.reclock.audio}`)}return n.push(...e.assets.map(r=>` ${r.file} ${t(r.size)} sha1 ${r.hash}`)),e.encrypted?(n.push(`CPL ${e.cpl}; ENCRYPTED (AES-128 + HMAC), CPL/PKL signed by ${e.signer?.subject}`,`content key: ${e.keys} \u2014 the ONLY copy. Keep it with the job; without it this DCP can never play or get a KDM. Do not ship it with the DCP.`),e.signer?.created&&n.push(`new facility signing identity created at ${e.signer.path} (back it up; KDMs are signed with it)`),n.push("next: media_dcp_kdm with keys + the venue's projector certificate")):n.push(`CPL ${e.cpl}; unencrypted OV, unsigned`),n.push(e.valid?`validation: PASS${e.findings.length?` with ${e.findings.length} note(s)`:""}`:"validation: FAIL",...e.findings.map(r=>` ${r.severity} ${r.code}: ${r.message}`)),n.join(`
|
|
297
|
+
`)}function Zv(e){return[`wrote ${e.path}`,`${e.title} (CPL ${e.cpl_id}), ${e.keys} key(s)`,`for ${e.recipient.cn} (${e.recipient.o}, thumbprint ${e.recipient.thumbprint})`,`plays ${e.not_valid_before} \u2192 ${e.not_valid_after} (UTC); signature self-checked`].join(`
|
|
298
|
+
`)}async function eT(e,t,n){if(e.patches?.length||e.mode==="vf"||e.mode==="check"||e.reel!==void 0||typeof e.at=="string"||e.start_tc!==void 0)throw new P("refused","an encrypted patch takes one fix: path + at (a composition frame number), as a new OV; patches=, mode=vf/check, reel= and timecode placement need an unencrypted source");if(!e.title)throw new P("refused","title is required for an encrypted patch (the new package's ContentTitleText)");let{dcp:r,keys:o,encrypt:s,path:i,at:a,color:l,from:c,count:u,wav:d,title:p,out_dir:f,issuer:h}=e,g={dcp:r,keys:o,encrypt:s,movie:i,at:a,color:l,from:c,count:u,wav:d,title:p,issuer:h,out_dir:f??xn(r.replace(/\/+$/,""))};return JSON.parse(await sf("dcp",g,t,n))}async function tT(e,t,n){let r=await or();if(!r)throw new P("unsupported","media_dcp_patch needs the native engine (conformtools-decode), which is not installed here. From a source checkout: cd rust && cargo build --release -p media-native --bin conformtools-decode (or set CONFORM_NATIVE_DECODE); the npm package ships it.");let{path:o,at:s,reel:i,color:a,from:l,count:c,patches:u,...d}=e,p=u?.length?u:o?[{path:o,at:s,reel:i,color:a,from:l,count:c}]:[];if(!p.length)throw new P("refused","give the fix as path= (with at=), or several as patches=[{path, at}, \u2026]");let f="",h="",g=new TextDecoder,b=await br(r,["dcp-patch",JSON.stringify({...d,patches:p})],k=>{f+=g.decode(k,{stream:!0});let w=f.split(`
|
|
299
|
+
`);f=w.pop();for(let y of w){if(!y.trim())continue;let _=y.startsWith('{"progress"')?JSON.parse(y).progress:null;_?t?.(_[0],_[1],"encoding the fix"):h=y}},{signal:n});if(f.trim()&&(h=f),b.code!==0){let k=di(b.stderr);throw new P(/did not verify/.test(k)?"engine":"refused",k)}return JSON.parse(h)}function nT(e){let t=r=>`${(r/1e6).toFixed(1)} MB`,n=e.mode==="check"?[`check: ${e.ok?"OK":"REFUSED"}, nothing written (would write ${e.would_write}, ${e.package})`]:[`wrote ${e.path} (${e.package}${e.package==="VF"?": plays only with the OV ingested":""})`];n.push(`${e.frames} frames @ ${e.fps} fps, ${e.reels} reel(s); re-wrapped: reel ${e.rewrap_reels.join(", ")||"none"}`);for(let r of e.patches)n.push(` ${r.essence} ${r.frames} frame(s) at ${r.at} (${r.tc}, reel ${r.reel} frame ${r.reel_frame}) from ${r.source} ${r.path?.split("/").pop()??""}`);e.encoded_frames&&n.push(`encoded ${e.encoded_frames} frame(s) of the fix to DCI J2K`);for(let r of e.assets??[])n.push(` ${r.file} ${t(r.size)} ${r.carried?"carried (same bytes)":"new"} sha1 ${r.hash}`);for(let r of e.verify??[])n.push(`${r.code==="VERIFY_OK"?"verified":r.code}: ${r.message}`);return e.decoded_frames&&n.push(`decoded: ${e.decoded_frames} patch and seam frame(s) decode cleanly (our J2K decoder)`),e.valid!==void 0&&n.push(e.valid?`validation: PASS${e.hashes_checked?" (every hash recomputed)":""}${e.findings.length?` with ${e.findings.length} warning(s)`:""}`:"validation: FAIL"),n.push(...e.findings.map(r=>` ${r.severity} ${r.code}: ${r.message}`)),n.join(`
|
|
300
|
+
`)}function yc(e,t){let n=[...e].sort((r,o)=>r[0]-o[0]);if(t<=n[0][0])return n[0][1];for(let r=1;r<n.length;r++)if(t<=n[r][0])return n[r-1][1]+(n[r][1]-n[r-1][1])*(t-n[r-1][0])/Math.max(1e-9,n[r][0]-n[r-1][0]);return n[n.length-1][1]}function aa(e,t,n,r,o,s,i=0){let a=e.map(([b,k])=>[b,k*o/r]),l=[0,...a.map(b=>b[0]).filter(b=>b>1e-9&&b<t-1e-9),t].filter((b,k,w)=>w.indexOf(b)===k).sort((b,k)=>b-k),c=l.map(b=>yc(a,b)/100),u=n/o,d=l.map(b=>u+b/r),p=[u];for(let b=1;b<l.length;b++)p.push(p[b-1]+(c[b-1]+c[b])*.5*(l[b]-l[b-1])/o);let f=b=>c[b]*r/o,h=[],g=(b,k,w)=>h.push({id:`${s}-${h.length}`,parameter_path:"speed",time:{value:b,rate:r},value:k,interp:"bezier",tangent_in:null,tangent_out:null,order_index:h.length,raw_extraction:w});if(u>1e-9){let b=u/3;g(0,0,{drtNativeTangent:[0,0,b,b,0,0],speedPreRoll:!0})}for(let b=0;b<l.length;b++){let k=[0,0,0,0,0,0];if(b>0){let y=(d[b]-d[b-1])/3;k[0]=-y,k[1]=-f(b)*y}else if(u>1e-9){let y=u/3;k[0]=-y,k[1]=-y}if(b+1<l.length){let y=(d[b+1]-d[b])/3;k[2]=y,k[3]=f(b)*y}let w=a.find(y=>Math.abs(y[0]-l[b])<1e-9);g(d[b],p[b],w?{drtNativeTangent:k,speedGraphPoint:[l[b],w[1]]}:{drtNativeTangent:k,speedGraphPoint:[l[b],c[b]*100],speedGraphSynth:!0})}return{keyframes:h,sourceFrames:(p[p.length-1]-u)*o}}var la=class{constructor(t,n,r=100){this.channels=t;this.sampleRate=n;this.hz=r;this.counted=0;this.binSamples=Math.max(1,Math.round(n/r)),this.sums=new Float64Array(t),this.bins=Array.from({length:t},()=>[])}push(t){let n=this.channels,r=Math.floor(t.length/n);for(let o=0;o<r;o++){let s=o*n;for(let i=0;i<n;i++){let a=t[s+i];this.sums[i]+=a*a}++this.counted===this.binSamples&&this.flush()}}flush(){for(let t=0;t<this.channels;t++)this.bins[t].push(Math.sqrt(this.sums[t]/this.counted)),this.sums[t]=0;this.counted=0}finish(){return this.counted>0&&this.flush(),this.bins.map(t=>Float32Array.from(t))}};var W9=typeof process<"u"&&!!process.env?.CONFORM_PROFILE;function ca(e,t,n,r){if(!n||!r||!(e>0)||!(t>0))return{w:e,h:t};let o=Math.min(e/n,t/r);return{w:n*o,h:r*o}}var iq=180/Math.PI;var ua=(e,t)=>`conform-${e}-${t}`,H3=4,z3="1",W3=.025,K3=.005,V3=.5,J3=.001,X3=.5,Q3=.05;function Y3(e,t,n){let r=e.measuredBy==="sizing";if(e.flipH||e.flipV)return!1;let o=r?J3:W3,s=r?Q3:V3,i=(a,l)=>!l||(r?Math.abs(a)<X3:Math.abs(a/l)<K3);return Math.abs(e.scaleX-1)<o&&Math.abs(e.scaleY-1)<o&&Math.abs(e.rotationDeg)<s&&i(e.dxCenter,t)&&i(e.dyCenter,n)&&!e.perspective}function Z3(e,t,n,r){e.scale=t.scale*100,Math.abs(t.scaleX-t.scaleY)>.001&&(e.scale_x=t.scaleX*100,e.scale_y=t.scaleY*100),n>0&&(e.position_x=t.dxCenter/n),r>0&&(e.position_y=t.dyCenter/r),Math.abs(t.rotationDeg)>.001&&(e.rotation=t.rotationDeg);let o=e;t.flipH&&(o.flip_horizontal=!0),t.flipV&&(o.flip_vertical=!0)}function eL(e,t,n,r,o,s,i){let a=[],l=n.srcStart??0,c=0;for(let u of t.keyframes){let d=u.refFrame-n.refStart,p=n.srcEnd!=null&&n.refEnd>n.refStart?(n.srcEnd-l)/(n.refEnd-n.refStart):r/(o||r),h={value:l+d*p,rate:r},g=(b,k)=>{a.push({id:`${e}-kf-${c++}`,parameter_path:b,time:h,value:k})};g("scale",u.reframe.scale*100),s>0&&g("position.x",u.reframe.dxCenter/s),i>0&&g("position.y",u.reframe.dyCenter/i),Math.abs(u.reframe.rotationDeg)>.001&&g("rotation",u.reframe.rotationDeg)}return a}function rT(e,t={}){let n=[],r=e.refFps??24,o=og(r)??{num:24,den:1},s=new Map(e.clips.map(y=>[y.label,y])),i=new Set(e.timeline.filter(y=>y.kind!=="gap"&&y.clipLabel).map(y=>y.clipLabel)),a=[],l=new Map;for(let y of e.clips){if(!i.has(y.label))continue;let _=ua("media",y.clipIndex);l.set(y.label,_);let v=y.srcFps??r;a.push({id:_,kind:"external",content_kind:"video",target_url:y.label,display_name:y.label.replace(/\.[^.]+$/,""),source_fps:v,source_timecode:He(y.srcStartFrame,v,y.srcDropFrame??!1),available_range:{start:{value:0,rate:v},duration:{value:y.srcFrames,rate:v}},source_resolution_w:y.srcW??null,source_resolution_h:y.srcH??null,reel_name:null,raw_extraction:{},metadata:{codec:y.codec}}),y.srcFps&&e.refFps&&Math.abs(y.srcFps-e.refFps)>.01&&n.push({kind:"rate",message:`${y.label} is ${y.srcFps.toFixed(3)} fps against a ${e.refFps.toFixed(3)} fps reference. The cut is written at the reference rate with source ranges in the clip's own rate, but the MATCH was made frame-index to frame-index \u2014 check this clip's in-points before trusting them.`});for(let T of y.warnings)n.push({kind:"rate",message:`${y.label}: ${T}`})}let c=[],u=0,d=0,p=0,f=0,h=0,g=[];for(let y of e.timeline){if(y.kind==="gap"||!y.clipLabel||y.srcStart==null||y.srcStart>=0){g.push(y);continue}let _=s.get(y.clipLabel),v=y.srcEnd!=null&&y.refEnd>y.refStart?(y.srcEnd-y.srcStart)/(y.refEnd-y.refStart):(_?.srcFps??r)/(r||1),T=v>0?Math.ceil(-y.srcStart/v-1e-9):y.refEnd-y.refStart+1;if(T>y.refEnd-y.refStart){g.push({...y,kind:"gap",clipLabel:void 0});continue}n.push({kind:"source-range",refStart:y.refStart,refEnd:y.refStart+T-1,message:`${y.clipLabel}: placed from source frame ${y.srcStart}, before the clip's first frame \u2014 the first ${T} frame(s) are left empty and the clip starts at frame 0. Usually a speed or frame-rate conform (e.g. 25 fps played frame-for-frame); check the shot's timing.`}),g.push({kind:"gap",refStart:y.refStart,refEnd:y.refStart+T-1}),g.push({...y,refStart:y.refStart+T,srcStart:y.srcStart+T*v})}for(let y of g){let _=y.refEnd-y.refStart+1;if(y.kind==="gap"||!y.clipLabel){d+=_,n.push({kind:"gap",refStart:y.refStart,refEnd:y.refEnd,message:`${_} frame(s) with no matching source \u2014 left empty on the timeline.`+(y.nothingSimilar!=null?` Nothing in the media you supplied resembles these frames (best similarity ${y.nothingSimilar.toFixed(2)}) \u2014 stock, graphics, or media that was not in the bucket.`:"")+(y.unconfirmed?` Best guess: ${y.unconfirmed.clipLabel} from source frame ${y.unconfirmed.srcFrame}, but the picture did not confirm it (${y.unconfirmed.why??"often graphics or stock that resembles a camera shot"}) \u2014 check it by eye if a shot is expected here.`:"")});continue}y.kind==="composite"&&n.push({kind:"composite",refStart:y.refStart,refEnd:y.refEnd,message:`split-screen / composite of ${y.regions?.length??0} sources \u2014 emitted as the first region only; rebuild the layout by hand.`});let v=s.get(y.clipLabel),T=l.get(y.clipLabel);if(!v||!T)continue;let $=v.srcFps??r,x=y.speed&&(y.speed.kind==="retime"||y.speed.kind==="reverse")?y.speed.percent/100:1,R=(r>0?_*($/r):_)*x,C=y.speed?.kind==="reverse"?Math.min(y.srcStart??0,y.srcEnd??y.srcStart??0):y.srcStart??0;y.takeRival&&n.push({kind:"contested",refStart:y.refStart,refEnd:y.refEnd,message:`${y.clipLabel} or ${y.takeRival.clipLabel}? Two takes of one setup explain this shot almost equally (shot-sizing agreement ${y.takeRival.winnerAgreement.toFixed(2)} vs ${y.takeRival.agreement.toFixed(2)}). Conformed from ${y.clipLabel} \u2014 check the take against the offline.`}),y.contest?.settledBy==="label"&&n.push({kind:"contested",refStart:y.refStart,refEnd:y.refEnd,message:`${y.clipLabel} and ${y.contest.rivals.map(X=>X.clipLabel).join(", ")} explain these frames equally well (tied at ${y.contest.winnerScore?.toFixed(1)??"\u2014"} bits). Conformed from ${y.clipLabel} because it sorts first by name \u2014 verify the source timecode.`});let B=ua("item",h),L={id:B,kind:"clip",item_index:h++,name:y.clipLabel,enabled:!0,timeline_range:{start:{value:y.refStart,rate:r},duration:{value:_,rate:r}},source_range:{start:{value:C,rate:$},duration:{value:R,rate:$}},media_reference_id:T,raw_extraction:{},metadata:{}},Z=y.track;if(Z&&Z.kind!=="unresolved"&&Z.keyframes.length>0&&!(Z.kind==="static"&&Y3(Z.keyframes[Z.keyframes.length>>1].reframe,e.refW,e.refH))){let X=Z.keyframes[Z.keyframes.length>>1],O=ca(e.refW,e.refH,v.srcW,v.srcH);Z3(L,X.reframe,O.w,O.h),p++,Z.kind==="animated"&&(f++,L.keyframes=eL(B,{keyframes:Z.keyframes},y,$,r,O.w,O.h),n.push({kind:"reframe",refStart:y.refStart,refEnd:y.refEnd,message:`${y.clipLabel}: animated reframe (${Z.keyframes.length} keys: ${Z.label}) \u2014 measured, not declared; check the move against the reference.`}))}else Z?.kind==="unresolved"&&n.push({kind:"unresolved",refStart:y.refStart,refEnd:y.refEnd,message:`${y.clipLabel}: placed, but its reframe could not be recovered${Z.label&&!Z.label.startsWith("unresolved")?` (${Z.label})`:""} \u2014 the clip is full-frame on the timeline and may need resizing.`});if(y.ramp&&y.ramp.length>=2){let X=aa(y.ramp,_,C,r,$,`${B}-spd`);L.source_range={start:L.source_range.start,duration:{value:Math.max(1,Math.ceil(X.sourceFrames)+1),rate:$}},L.speed_ramped=!0,L.speed=Math.round(100*X.sourceFrames/_*(r/$)*100)/100;let O=L.keyframes??[];L.keyframes=[...O,...X.keyframes.map((ae,W)=>({...ae,order_index:O.length+W}))],n.push({kind:"retime",refStart:y.refStart,refEnd:y.refEnd,message:`${y.clipLabel}: SPEED RAMP read from the picture \u2014 ${y.ramp.map(([ae,W])=>`${W.toFixed(0)}%@${Math.round(ae)}`).join(" \u2192 ")}. Check the ramp against the reference.`})}y.speed&&y.speed.kind!=="normal"&&(L.speed=y.speed.percent,L.speed_ramped=!1,y.speed.kind==="reverse"&&(L.speed_reverse=!0),n.push({kind:"retime",refStart:y.refStart,refEnd:y.refEnd,message:y.speed.kind==="freeze"?`${y.clipLabel}: FREEZE FRAME \u2014 the source holds on one frame across ${_} reference frame(s). Emitted at 0% speed; a host may want an explicit freeze instead.`:y.speed.kind==="reverse"?`${y.clipLabel}: REVERSE at ${y.speed.percent.toFixed(1)}% \u2014 the source runs backwards across ${_} reference frame(s), read from the picture. Check the direction and speed against the reference.`:y.speed.basis==="frame-for-frame"?`${y.clipLabel}: plays FRAME FOR FRAME \u2014 one source frame per record frame, ${y.speed.percent.toFixed(1)}% of real time \u2014 measured from the picture at ${y.speed.samples} points. Usually the edit's rate-conform setting, not a retime.`:y.speed.basis==="convention"?`${y.clipLabel}: emitted at ${y.speed.percent.toFixed(1)}% to match the cut's other shots at this frame rate \u2014 this shot's own picture could not tell real time from frame-for-frame. Check its motion against the reference.`:`${y.clipLabel}: retimed to ${y.speed.percent.toFixed(1)}% (fitted over ${y.speed.samples} runs, residual ${y.speed.residual.toFixed(1)} frames). A speed RAMP would not fit one slope \u2014 check it if the residual is high.`})),y.inPointAmbiguity!=null&&y.inPointAmbiguity>=H3?n.push({kind:"ambiguous",refStart:y.refStart,refEnd:y.refEnd,message:`${y.clipLabel}: in-point uncertain \u2014 ${y.inPointAmbiguity} source frames match this shot equally well (the picture barely changes), so its source timecode may be out by up to \xB1${Math.ceil(y.inPointAmbiguity/2)} frames. Check it against the offline.`}):y.inPointUnconfirmed&&n.push({kind:"ambiguous",refStart:y.refStart,refEnd:y.refEnd,message:`${y.clipLabel}: in-point not confirmed \u2014 ${y.takeRival?"and the take itself is contested (see the red marker); ":"the take is right, but "}nothing in the shot (motion, difference mode) pinned the exact frame, so its source timecode may be off. Check it against the offline.`}),c.push(L),u++}let b={id:ua("track",1),kind:"Video",track_index:1,name:"V1",enabled:!0,items:c,source_element_id:null,raw_extraction:{},metadata:{}},k={id:ua("timeline",1),name:t.name??t.referenceName??"Auto-Conform",kind:"primary",timeline_index:0,fps_num:o.num,fps_den:o.den,resolution_w:e.refW||null,resolution_h:e.refH||null,start_frame:e.refStartFrame,is_drop_frame:e.refDropFrame,duration_frames:e.refFrames,tracks:[b],markers:[],source_element_id:null,raw_extraction:{},metadata:{}};return{session:{projects:[{id:ua("project",1),user_id:"",created_at:"",source_format:"auto-conform",source_filename:t.referenceName??null,source_file_sha256:null,source_file_bytes:null,parser_name:"conform-session",parser_version:z3,status:"ready",error_message:null,metadata:{}}],timelines:[k],media_references:a,source_format:"auto-conform",source_filename:t.referenceName??null},issues:n,stats:{placed:u,gapFrames:d,reframed:p,animated:f}}}var tL={gap:"Green",unresolved:"Red",contested:"Red",composite:"Yellow",rate:"Yellow",reframe:"Yellow",retime:"Yellow",ambiguous:"Yellow","source-range":"Yellow",vfx:"Cyan"},nL={gap:"NO SOURCE",unresolved:"REFRAME UNRESOLVED",contested:"CONTESTED SOURCE",composite:"COMPOSITE",rate:"RATE",reframe:"REFRAME",retime:"RETIME",ambiguous:"IN-POINT UNCERTAIN","source-range":"SOURCE RANGE",vfx:"VFX / CLEANUP"};function rL(e,t){return e.map((n,r)=>{let o=n.refStart??0,s=n.refEnd!=null&&n.refStart!=null?n.refEnd-n.refStart+1:1;return{id:`conform-marker-${r}`,name:nL[n.kind]??n.kind.toUpperCase(),color:tL[n.kind]??"Yellow",kind:null,note:n.message,time:{value:o,rate:t},duration:{value:Math.max(1,s),rate:t},item_id:null,raw_extraction:{},source_element_id:null,metadata:{}}})}function oT(e,t){let n=(e.timelines??[])[0];if(!n||t.length===0)return e;let r=Pt(n);return{...e,timelines:[{...n,markers:[...n.markers??[],...rL(t,r)]},...(e.timelines??[]).slice(1)]}}var oL=.02,cf=100,sL="the lowest enabled video track is read as the picture spine; anything on the tracks above it (titles, graphics, split-screens) is not hinted and falls to the pixel search";function sT(e){return e&&e.split(/[\\/]/).pop()||null}function jr(e,t){if(!e||!Number.isFinite(e.value))return 0;let n=e.rate&&Number.isFinite(e.rate)&&e.rate>0?e.rate:t;return Math.round(e.value*(t/n))}function iT(e){let t=e,n=(r,o)=>r!=null&&Number.isFinite(r)&&Math.abs(r-o)>1e-6;return n(t.scale,cf)||n(t.scale_x,cf)||n(t.scale_y,cf)||n(t.position_x,0)||n(t.position_y,0)||n(t.rotation,0)}var iL=3;function aL(e){let t=e;return(t.scale??100)>=100&&Math.abs(t.position_x??0)<1&&Math.abs(t.position_y??0)<1&&(t.opacity??100)>=100&&!(t.crop_left||t.crop_right||t.crop_top||t.crop_bottom)}function lL(e){let n=(e.tracks??[]).filter(r=>r.kind==="Video"&&r.enabled!==!1).sort((r,o)=>r.track_index-o.track_index).filter(r=>(r.items??[]).some(o=>o.kind==="clip"));return{track:n[0]??null,extraVideo:Math.max(0,n.length-1)}}function cL(e,t,n){return!n||n<=0||!e.length?0:Math.min(...e.map(o=>jr(o.timeline_range?.start,t)))>=n-1?n:0}function aT(e,t,n={}){let r=[],o=(e.timelines??[]).filter(v=>v.kind!=="compound"),s=(t?o.find(v=>v.name===t):null)??o[0]??(e.timelines??[])[0];if(!s)return{timelineName:"",timelineId:null,startOffset:0,fps:0,frames:0,shots:[],cuts:[],warnings:["no timeline in this file"]};o.length>1&&r.push(`this file holds ${o.length} sequences \u2014 hinting from "${s.name}". If that is not the cut you rendered, the claims below will disagree with the picture everywhere.`);let i=Pt(s),{track:a,extraVideo:l}=lL(s);if(!a)return{timelineName:s.name,timelineId:s.id??null,startOffset:0,fps:i,frames:s.duration_frames??0,shots:[],cuts:[],warnings:[...r,"no video track with clips \u2014 nothing to hint from"]};let c=n.allTracks?(s.tracks??[]).filter(v=>v.kind==="Video"&&v.enabled!==!1):[a];l>0&&r.push(n.allTracks?`${l} video track(s) above the spine \u2014 their clips are hinted too, each checked against the picture like any other claim.`:`${l} video track(s) above the spine \u2014 ${sL}.`);let u=c.flatMap(v=>v.items??[]).sort((v,T)=>jr(v.timeline_range?.start,i)-jr(T.timeline_range?.start,i)),d=cL(u,i,s.start_frame??0);d>0&&r.push(`item times carry the timeline's start timecode (${d} frames); removed so they line up with a render that begins at its first frame.`);let p=new Map((e.media_references??[]).map(v=>[v.id,v])),f=new Map;for(let v of c)for(let T of v.items??[])f.set(T,v.track_index);let h=[];for(let v of c)for(let T of v.items??[]){if(T.enabled===!1||T.kind!=="clip"||!aL(T))continue;let $=T.media_reference_id?p.get(T.media_reference_id):void 0;if($?.content_kind==="still"||/\.(png|webp|tiff?|psd|exr|dpx|gif|jpe?g)$/i.test($?.target_url??$?.display_name??""))continue;let x=jr(T.timeline_range?.start,i)-d,R=jr(T.timeline_range?.duration,i);R>0&&h.push({track:v.track_index,lo:x,hi:x+R-1})}let g=(v,T,$)=>{let x=[[v,T]];for(let R of h)R.track<=$||(x=x.flatMap(([C,B])=>{if(R.hi<C||R.lo>B)return[[C,B]];let L=[];return R.lo>C&&L.push([C,R.lo-1]),R.hi<B&&L.push([R.hi+1,B]),L}));return x.filter(([R,C])=>C-R+1>=iL)},b=[],k=0,w=0,y=0,_=0;for(let v of u){if(v.enabled===!1){w++;continue}if(v.kind==="nested"||v.nested_timeline_id){k++;continue}if(v.kind!=="clip"){y++;continue}let T=jr(v.timeline_range?.start,i)-d,$=jr(v.timeline_range?.duration,i);if($<=0){y++;continue}let x=v.media_reference_id?p.get(v.media_reference_id):void 0,R=sT(x?.local_path)??sT(x?.target_url)??x?.display_name??null,C=v.name??null,B=v.reel_name??x?.reel_name??null;if(!R&&!C&&!B){_++;continue}let L=v.source_range?.start?.rate||i,Z=jr(v.source_range?.start,L),X=jr(v.source_range?.duration,L),O=$>0&&X>0?X/$:1,ae=Math.abs(O-1)>oL?O:null,W=f.get(v)??0,ne=x?.source_timecode?Aa(x.source_timecode,L):null;for(let[z,q]of g(T,T+$-1,W)){let j=Math.round((z-T)*O);b.push({index:b.length,itemId:v.id??null,refStart:z,refEnd:q,clipName:C,reelName:B,sourceFilename:R,srcStart:Z+j,srcTimecode:ne?ne.frames+Z+j:null,srcRate:L,srcDropFrame:ne?.drop??!1,declaredReframe:iT(v),declaredTransform:iT(v)?{scale:v.scale,scale_x:v.scale_x,scale_y:v.scale_y,position_x:v.position_x,position_y:v.position_y,rotation:v.rotation}:null,declaredSpeed:ae})}}return k&&r.push(`${k} nested/compound clip(s) not expanded \u2014 their shots fall to the pixel search rather than being hinted from the wrapper's own range, which would be wrong.`),w&&r.push(`${w} disabled clip(s) ignored.`),y&&r.push(`${y} non-clip item(s) (transitions, gaps) ignored.`),_&&r.push(`${_} clip(s) name no source at all \u2014 no file, no reel, no clip name. Nothing to bind them to, so they go to the pixel search.`),{timelineName:s.name,timelineId:s.id??null,startOffset:d,fps:i,frames:s.duration_frames??(b.length?b[b.length-1].refEnd+1:0),shots:b,cuts:[...new Set(b.slice(1).map(v=>v.refStart))].sort((v,T)=>v-T),warnings:r}}var jq=8*1024*1024;var bL=new Set(["mov","mp4","m4v","r3d","mxf","braw","ari","arx","arri","crm"]),uf=e=>e.split(".").pop()?.toLowerCase()??"",df=e=>bL.has(uf(e)),lT=new Set(["mov","mp4","m4v"]),wc=e=>(e.split(/[\\/]/).pop()??e).replace(/\.[^.]+$/,"").toUpperCase();function cT(e,t){let n=new Set(e.map(t).filter(i=>!lT.has(uf(i))).map(wc)),r=new Set(e.map(t).map(wc)),o=[],s=[];for(let i of e){let a=t(i),l=/^(.*)_TRIM_\d+-\d+$/.exec(wc(a))?.[1];(lT.has(uf(a))&&n.has(wc(a))||l!=null&&r.has(l)?s:o).push(i)}return{kept:o,proxies:s}}var kc="autoconform",yL=new Set(["ambiguous","speed_unobservable"]),uT=["kind","clipLabel","srcStart","srcEnd","track","speed"],dT=(e,t)=>e.refStart<=t&&t<=e.refEnd;function Vs(e){return e.report.timeline.flatMap(t=>{let n={ref_start:t.refStart,ref_end:t.refEnd};if(t.kind==="gap"&&t.unconfirmed)return[{...n,kind:"gap_guess",clip:t.unconfirmed.clipLabel,src_frame:Math.round(t.unconfirmed.srcFrame),why:t.unconfirmed.why??"the picture did not confirm it"}];if(t.kind==="gap"||!t.clipLabel||t.srcStart==null)return[];if(e.alignIssues.some(s=>s.kind==="reviewed"&&s.refStart===t.refStart))return[];let o=e.alignIssues.find(s=>yL.has(s.kind)&&dT(t,s.refStart))?.message??(t.takeRival?`another take (${t.takeRival.clipLabel}) explains it nearly as well`:null);return o?[{...n,kind:"doubtful",clip:t.clipLabel,src_frame:Math.round(t.srcStart),why:o}]:[]})}async function wL(e,t,n){let r=e.pool.find(c=>fe(c)===t.clip);if(!r)throw new P("not_found",`${t.clip} is not in the pool this conform ran on`);let o=Math.max(1,Math.floor((t.ref_end-t.ref_start)/4)),s=t.ref_start+2*o,i=n.unconfirmed?.placed??n,a=i.srcEnd!=null&&i.srcStart!=null&&t.ref_end>t.ref_start?(i.srcEnd-i.srcStart)/(t.ref_end-t.ref_start):1;return(await Eo({path:e.reference,frame:s,around:2*o,step:o,b:r,b_frame:Math.max(0,Math.round(t.src_frame+(s-t.ref_start)*a)),width:192})).out_path}function kL(e,t,n){let r=Vs(e),o=[];for(let s of[...t,...n]){let i=t.includes(s)?"gap_guess":"doubtful";if(!r.some(a=>a.ref_start===s&&a.kind===i))throw new P("invalid_args",`${s} is not a ${i==="gap_guess"?"gap with a guess (accept)":"doubtful shot (reject)"}; review shots: ${r.map(a=>`${a.ref_start} ${a.kind}`).join(", ")||"none"}`)}for(let s of e.report.timeline)if(t.includes(s.refStart)&&s.unconfirmed){let i=s.unconfirmed;Object.assign(s,i.placed??{kind:"static",clipLabel:i.clipLabel,srcStart:i.srcFrame,srcEnd:i.srcFrame+(s.refEnd-s.refStart)}),delete s.unconfirmed,e.alignIssues.push({kind:"reviewed",refStart:s.refStart,refEnd:s.refEnd,message:`${i.clipLabel} from source frame ${Math.round(i.srcFrame)}: the engine could not confirm it; placed on review from the contact sheet; check the in-point.`}),o.push(`accepted ${s.refStart}-${s.refEnd} ${i.clipLabel}@${Math.round(i.srcFrame)}`)}else if(n.includes(s.refStart)&&s.clipLabel&&s.srcStart!=null){let i=Object.fromEntries(uT.map(a=>[a,s[a]]));s.unconfirmed={clipLabel:s.clipLabel,srcFrame:s.srcStart,why:"rejected on review",placed:i};for(let a of uT)a!=="kind"&&delete s[a];s.kind="gap",e.alignIssues=e.alignIssues.filter(a=>!dT(s,a.refStart)),o.push(`rejected ${s.refStart}-${s.refEnd} ${i.clipLabel}@${Math.round(i.srcStart)}`)}return o}async function pT(e){let t=await e1(e.session_id,kc);if(!t)throw new P("not_found",`session ${e.session_id} was not made by timeline_autoconform (0.6.4 or later), so there is nothing to review`);let n=[];if(e.accept?.length||e.reject?.length){n=kL(t,e.accept??[],e.reject??[]);let l=await ft(e.session_id);l.session=pf(t).session,await Ta(e.session_id,kc,t),await Yt(l,`autoconform review: ${n.join("; ")}`)}let r=Vs(t),o=e.offset??0,s=r.slice(o,o+(e.limit??4)),i=new Map(t.report.timeline.map(l=>[l.refStart,l])),a=[];for(let l of s)try{l.sheet=await wL(t,l,i.get(l.ref_start)),a.push({data:To(await Ut(l.sheet)),mimeType:"image/png"})}catch(c){l.why+=` (no contact sheet: ${c instanceof Error?c.message:c})`}return{settled:n,shots:r.length,from:o,review:s,images:a}}function mT(e){return[...e.settled,e.shots?`${e.shots} shot(s) to review${e.review.length?`; showing ${e.from+1}\u2013${e.from+e.review.length}`:""}`:"nothing left to review",...e.review.map(t=>`- ${t.ref_start}-${t.ref_end} ${t.kind==="gap_guess"?"GAP, guess":"PLACED, doubtful"}: ${t.clip} from source frame ${t.src_frame}: ${t.why}${t.sheet?`
|
|
301
|
+
image ${e.review.filter(n=>n.sheet).indexOf(t)+1}: ${t.sheet} (top row = reference, bottom = ${t.clip})`:""}`),...e.review.length?["Look at each sheet. Same shot, same moment? gap_guess \u2192 accept=[ref_start]; doubtful and clearly another shot or moment \u2192 reject=[ref_start]. Only decide when sure; otherwise leave it and tell the artist which shots to check (identical-looking takes of one setup are theirs to call)."]:[]].join(`
|
|
302
|
+
`)}async function mf(e,t=4e3){let n=[],r=new Set;async function o(i){let a=await pi(i).catch(()=>[i]);r.has(a[0])||(a.forEach(l=>r.add(l)),n.push(a[0]))}async function s(i,a){if(!(a>10||n.length>=t))for await(let l of Ct(i)){if(l.name.startsWith("."))continue;let c=re(i,l.name);if(l.isDirectory?await s(c,a+1):l.isFile&&df(l.name)&&await o(c),n.length>=t)return}}for(let i of e)if((await Bt(i)).isDirectory)await s(i,0);else if(df(fe(i)))await o(i);else throw new Error(`not a conformable media file: ${i}`);return cT(n,i=>i).kept}async function _c(e){let t=await mf(e.pool);if(!t.length)throw new Error("pool is empty \u2014 no mov/mp4/r3d/mxf/braw/ari/crm files found");let n=[...t].sort((l,c)=>fe(l).localeCompare(fe(c))),r=e.hints?(await u1(e.hints))?.session??e.hints:void 0,o=r?aT(r,void 0,{allTracks:!0}).shots:[],s=performance.now(),i=l=>console.error(`[time] ${l} ${((performance.now()-s)/1e3).toFixed(1)} s`),a=await _a({reference:e.reference,clips:n,lite:!0,display:!!e.display_transform});try{let l=await a.ask({op:"autoconform",claims:o,referenceAudio:e.reference_audio??e.reference,sizing:e.sizing!==!1,trust:!!e.trust},(g,b,k)=>{e.signal?.throwIfAborted(),e.onProgress?.(g,b,k==="index"?`index: ${g} of ${b} clips`:k)});if(!l.ok)throw new Error(`analysis engine: ${l.why??l.miss}`);for(let g of l.laps)i(`engine: ${g}`);zt("CONFORM_DEBUG_NOMINATIONS")&&l.soundLog.length&&console.error(`[sound] ${l.soundLog.join(" | ")}`);let c=l.report,u={...c,clips:c.clips.map(g=>({clipIndex:g.clip,label:g.label,shots:[],coverage:0,srcFps:g.srcFps,srcStartFrame:g.srcStartFrame,srcFrames:g.srcFrames,srcW:g.srcW,srcH:g.srcH,codec:g.codec,warnings:[]}))},d={reference:e.reference,name:e.name??`${fe(e.reference)} auto conform`,pool:n,rotated:l.rotated,alignIssues:l.issues,report:u},{session:p,issues:f,stats:h}=pf(d);return{session:p,report:u,rebuild:d,issues:f,stats:h,pool:n,unreadable:l.unreadable}}finally{a.close()}}function pf(e){let{report:t}=e,n=new Set(e.rotated),r=rT(t,{name:e.name,referenceName:fe(e.reference)});for(let i of r.session.timelines[0]?.tracks[0]?.items??[]){let a=Math.round(i.timeline_range?.start.value??-1);n.has(a)&&!t.timeline.find(l=>l.refStart===a)?.track&&(i.rotation=180)}r.issues.push(...e.alignIssues);let o=oT(r.session,r.issues),s=new Map(e.pool.map(i=>[fe(i),i]));for(let i of o.media_references??[]){let a=s.get(fe(i.target_url??""))??s.get(i.reel_name??"");a&&(i.target_url=a,i.local_path=a)}return{session:o,issues:r.issues,stats:r.stats}}function fT(e){let t=new Set(e.issues.map(n=>n.kind));return(e.report.timeline??[]).some(n=>n.kind==="gap")&&t.add("gap"),e.unreadable?.length&&t.add("unreadable"),Vs(e.rebuild).length&&t.add("review"),t}function hT(e){let t=e.report,n=t.timeline??[],r={};for(let i of n)r[i.kind??"?"]=(r[i.kind??"?"]??0)+1;let o=e.issues,s={};for(let i of o)s[i.kind]=(s[i.kind]??0)+1;return[`reference ${t.refFrames??"?"} frames @ ${t.refFps??"?"} fps; pool ${e.pool.length} clip(s)${t.triage?` (examined ${t.triage.examined??"?"}, skipped ${t.triage.skipped??0})`:""}`,...e.unreadable?.length?[`unreadable pool files (left out): ${e.unreadable.length} \u2014 ${e.unreadable.slice(0,5).map(i=>`${fe(i.path)}: ${i.error.slice(0,80)}`).join("; ")}${e.unreadable.length>5?"; \u2026":""}`]:[],`timeline segments: ${Object.entries(r).map(([i,a])=>`${a} ${i}`).join(", ")}`,`stats: ${JSON.stringify(e.stats)}`,`issues: ${o.length?Object.entries(s).map(([i,a])=>`${a} ${i}`).join(", "):"none"}`,...o.slice(0,25).map(i=>`- [${i.kind}] ${i.message??i.note??""}${i.refStart!=null?` @ ${i.refStart}${i.refEnd!=null?`\u2013${i.refEnd}`:""}`:""}`)].join(`
|
|
303
|
+
`)}var pa=["plain","short","jump","lookalike","punch_in","turned","animated","offrate","retime","ramp","pip","gap","lower_third","locator","title","frankenbite"],Js={plain:{plain:1},hard:{plain:2,short:3,jump:2,lookalike:3,punch_in:2,turned:1,animated:1,offrate:1,gap:1},all:{plain:2,short:3,jump:2,lookalike:3,punch_in:2,turned:1,animated:1,offrate:1,retime:1,ramp:1,pip:1,gap:1,lower_third:1,locator:1,title:1},speed:{plain:1,offrate:3,retime:3,ramp:3},sound:{plain:2,short:1,jump:2,lookalike:3,punch_in:1,frankenbite:2},graphics:{plain:1,lower_third:3,locator:3,title:2}},ff=new Set(["lower_third","locator","title"]),gT=["MARIA ALVAREZ","DR. JAMES OKAFOR","SARAH CHEN","TOM WHITFIELD","ANA LUCIA REYES","MARCUS BELL"],bT=["Small Business Owner","Emergency Physician","City Council Member","Rancher, 4th Generation","Teacher","Veteran, U.S. Army"],yT=["AUSTIN, TEXAS","LOCKHART, TX","SAN MARCOS","CALDWELL COUNTY","HOUSTON, TEXAS","WEST TEXAS"],wT=["STRONGER TOGETHER","THE ROAD AHEAD","PLANNING AHEAD","RIGHT HERE AT HOME","VOTE NOVEMBER 5"];var _L=(e,t)=>e.path<t.path?-1:e.path>t.path?1:0;function vL(e){let t=[],n=[],r=new Map;for(let{path:o,ref:s}of[...e].sort(_L)){let i=s.available_range?.duration?.value??0,a=s.available_range?.duration?.rate||s.source_fps||0;if(!a||i<a*5||!s.source_resolution_w){n.push({path:o,reason:"too short or no picture"});continue}let l=o.slice(0,o.lastIndexOf("/")),c=r.get(l)??0;r.set(l,c+1);let u=Jg(s);t.push({path:o,dir:l,idx:c,frames:i,rate:a,w:s.source_resolution_w,h:s.source_resolution_h??0,sound:u})}return{clips:t,skipped:n}}function TL(e){let t=e>>>0,n=()=>{t=t+1831565813>>>0;let r=t;return r=Math.imul(r^r>>>15,r|1),r^=r+Math.imul(r^r>>>7,r|61),((r^r>>>14)>>>0)/4294967296};return{next:n,int:(r,o)=>r+Math.floor(n()*(o-r+1)),pick:r=>r[Math.floor(n()*r.length)],range:(r,o)=>r+n()*(o-r)}}function kT(e){let t=typeof e=="object"&&e!==null?e:Js[e??"hard"];if(!t)throw new Error(`unknown mix '${e}' (presets: ${Object.keys(Js).join(", ")})`);return t}function vc(e){let t=kT(e),n=pa.filter(r=>(t[r]??0)>0);if(!n.length)throw new Error("the mix weights no class");return n}function xL(e,t){let n=TL(e.seed),r=e.fps_num??24e3,o=e.fps_den??1001,s=e.width??1920,i=e.height??1080,a=r/o,l=kT(e.mix),c=vc(e.mix),u=c.reduce((x,R)=>x+l[R],0),d=()=>{let x=n.next()*u;for(let R of c)if((x-=l[R])<0)return R;return c[c.length-1]};if(!t.length)throw new Error("no usable clips");let p=t.filter(x=>Math.abs(x.rate-a)>.01),f=[],h=e.shots??24,g=0,b=null,k=0,w=(x,R,C)=>Math.max(1,Math.round(R*(x.rate/a)*(C/100))),y=x=>Math.ceil(x.rate*Math.min(12,Math.max(2,.15*x.frames/x.rate))),_=(x,R,C)=>(e.avoid??[]).some(B=>B.path===x&&R<B.to&&R+C>B.from),v=(x,R)=>{let C=y(x),B=x.frames-Math.ceil(x.rate)-R;if(B<=C)return-1;for(let L=0;L<24;L++){let Z=n.int(C,B);if(!_(x.path,Z,R))return Z}return-1},T=(x,R,C)=>{let B=0;for(let L=0;L<R;L++)B+=yc(C,L+.5)/100;return Math.max(1,Math.ceil(B*(x.rate/a))+1)},$=[];for(let x=0;x<h;x++){let R=d(),C=[R];R==="gap"&&(g+=n.int(6,48));let B=R==="short"||R!=="plain"&&R!=="ramp"&&!ff.has(R)&&n.next()<.2;B&&R!=="short"&&C.push("short");let L=R==="ramp"?n.int(60,144):ff.has(R)?n.int(48,120):B?n.int(4,23):R==="plain"?n.int(24,120):24+Math.floor(n.next()**2*96),Z,X=n.pick(t),O=100,ae=-1,W={};if(R==="jump"&&b){X=b.clip;let I=b.srcOut+n.int(6,120);I+w(X,L,100)<X.frames-X.rate&&!_(X.path,I,w(X,L,100))&&(ae=I)}else if(R==="lookalike"&&b){let I=t.filter(S=>S.dir===b.clip.dir&&S!==b.clip).sort((S,A)=>Math.abs(S.idx-b.clip.idx)-Math.abs(A.idx-b.clip.idx));I.length&&(X=I[Math.min(I.length-1,n.int(0,2))])}else if(R==="offrate"&&p.length)X=n.pick(p),O=n.next()<.6?Math.round(a/X.rate*1e4)/100:100;else if(R==="retime")O=n.pick([25,50,150,200]);else if(R==="ramp"){let I=Math.round(L*n.range(.2,.4)),S=Math.round(L*n.range(.6,.8));Z=n.pick([[[I,100],[S,40]],[[I,40],[S,100]],[[I,100],[S,200]],[[I,200],[S,100]],[[0,100],[I,100],[Math.round((I+S)/2),30],[S,100]]])}R==="jump"&&ae<0&&(C[0]="plain"),R==="lookalike"&&(!b||X.dir!==b.clip.dir)&&(C[0]="plain"),R==="offrate"&&O===100&&Math.abs(X.rate-a)<.01&&(C[0]="plain");let ne=Z?T(X,L,Z):w(X,L,O);if(ae<0&&(ae=v(X,ne)),ae<0){if(++k>h*50)throw new Error("the clips are too short for this mix");x--;continue}let z=I=>(I/100-1)/2*.8;if(R==="punch_in"){let I=Math.round(n.range(110,200));Object.assign(W,{scale:I,position_x:Math.round(n.range(-1,1)*z(I)*s),position_y:Math.round(n.range(-1,1)*z(I)*i)})}else if(R==="turned")if(n.next()<.35)Object.assign(W,n.next()<.7?{flip_h:!0}:{flip_v:!0});else{let I=Math.round(n.range(1,6)*10)/10*(n.next()<.5?-1:1);Object.assign(W,{rotation:I,scale:Math.round(100+Math.abs(I)*4)})}else if(R==="animated")if(n.next()<.5)Object.assign(W,{scale:100,scale_end:Math.round(n.range(115,150))});else{let I=Math.round(n.range(125,150)),S=z(I)*s;Object.assign(W,{scale:I,position_x:Math.round(-S),position_x_end:Math.round(S)})}let q=e.audio&&X.sound&&O===100&&!Z&&Math.abs(X.rate-a)<.01,j;if(R==="frankenbite")if(!q)C[0]="plain";else{let I=t.filter(U=>U.dir===X.dir&&U!==X&&U.sound&&Math.abs(U.rate-a)<.01),S=I.length&&n.next()<.6?n.pick(I):X,A=v(S,ne);A>=0&&(S!==X||Math.abs(A-ae)>48)?j={path:S.path,source_in:A}:C[0]="plain"}if(f.push({path:X.path,source_in:ae,duration:L,at:g,track:1,...O!==100?{speed:O}:{},...Z?{ramp:Z}:{},...q?{audio:!0}:{},...j?{audio_from:j}:{},...W,classes:C,record_in:g,record_out:g+L}),ff.has(R)){let I=g+Math.floor(L*n.range(0,.2)),S=g+L-Math.floor(L*n.range(0,.15)),A=n.int(0,gT.length-1),U=R==="lower_third"?`${gT[A]}
|
|
304
|
+
${bT[n.int(0,bT.length-1)]}`:R==="locator"?yT[n.int(0,yT.length-1)]:wT[n.int(0,wT.length-1)];$.push({kind:R,text:U,at:I,duration:Math.max(12,S-I),track:3})}if(R==="pip"&&L>=12){let I=n.pick(t),S=Math.max(8,Math.floor(L*n.range(.5,1))),A=v(I,w(I,S,100));if(A>=0){let U=Math.round(n.range(25,45)),de=(1-U/100)/2*.85,te=g+Math.floor((L-S)*n.next());f.push({path:I.path,source_in:A,duration:S,at:te,track:2,scale:U,position_x:Math.round((n.next()<.5?-1:1)*de*s),position_y:Math.round((n.next()<.5?-1:1)*de*i),classes:["pip"],record_in:te,record_out:te+S})}}b={clip:X,srcOut:ae+ne},g+=L}return{shots:f,titles:$}}function da(e,t,n){let r=Qg(t);if(!r)throw new Error(`unknown operation '${t}'; known: ${Object.keys(Xg).join(", ")}`);return r(e,n)}function hf(e,t){let n={projects:[],timelines:[],media_references:[]},r="author-tl";da(n,"new_timeline",{timeline_id:r,name:e.name,fps_num:e.fps_num,fps_den:e.fps_den,resolution_w:e.width,resolution_h:e.height,start_frame:e.start_frame,is_drop_frame:e.drop_frame});let o=n.timelines.find(c=>c.id===r),s=e.fps_num/e.fps_den,i=()=>o.tracks.filter(c=>c.kind==="Video"),a=new Map,l=[];for(let[c,u]of e.shots.entries()){let d=Math.max(1,u.track??1);for(;i().length<d;)da(n,"add_track",{timeline_id:r,kind:"Video"});let p=i()[d-1],f=a.get(u.path);f||a.set(u.path,f=t(u.path));let h=f.available_range,g=h?.duration?.rate||f.source_fps||s,b=h?.duration?.value??1/0,k=u.speed??100,w=u.ramp?aa(u.ramp,u.duration,u.source_in,s,g,"spd"):null,y=w?Math.max(1,Math.ceil(w.sourceFrames)+1):Math.max(1,Math.round(u.duration*(g/s)*(k/100)));if(u.source_in<0||u.source_in+y>b)throw new Error(`shot ${c+1} (${f.id}): source ${u.source_in}+${y} is outside the clip (0\u2013${b-1})`);let _=da(n,"add_clip",{timeline_id:r,media_reference_id:f.id,media_reference:f,source_start:(h?.start?.value??0)+u.source_in,source_duration:u.duration,at_frame:u.at,track_id:p.id,without_audio:!u.audio}),v=_.meta?.item_id,T=p.items.find(L=>L.id===v);if(!T)throw new Error(`shot ${c+1}: ${_.summary}`);T.source_range={start:T.source_range.start,duration:{value:y,rate:g}};let $=_.meta?.audio_item_id;if($&&u.audio_from){let L=o.tracks.flatMap(X=>X.items).find(X=>X.id===$),Z=a.get(u.audio_from.path);if(Z||a.set(u.audio_from.path,Z=t(u.audio_from.path)),L){n.media_references.some(O=>O.id===Z.id)||n.media_references.push(Z),L.media_reference_id=Z.id,L.name=Z.id;let X=Z.available_range?.duration?.rate||Z.source_fps||s;L.source_range={start:{value:(Z.available_range?.start?.value??0)+u.audio_from.source_in,rate:X},duration:{value:u.duration*(X/s),rate:X}}}}w?(T.speed_ramped=!0,T.speed=Math.round(100*w.sourceFrames/u.duration*(s/g)*100)/100):k!==100&&(T.speed=k);let x=ca(e.width,e.height,f.source_resolution_w,f.source_resolution_h);(u.scale!=null||u.position_x!=null||u.position_y!=null||u.rotation!=null)&&da(n,"transform",{timeline_id:r,item_id:T.id,...u.scale!=null?{scale:u.scale}:{},...u.position_x!=null?{position_x:u.position_x/x.w}:{},...u.position_y!=null?{position_y:u.position_y/x.h}:{},...u.rotation!=null?{rotation:u.rotation}:{}});let R=[["scale",u.scale??100,u.scale_end,L=>L],["position.x",u.position_x??0,u.position_x_end,L=>L/x.w],["position.y",u.position_y??0,u.position_y_end,L=>L/x.h],["rotation",u.rotation??0,u.rotation_end,L=>L]],C=[];for(let[L,Z,X,O]of R)if(X!=null)for(let[ae,W]of[[0,Z],[y-1,X]])C.push({id:`${T.id}-kf-${C.length}`,parameter_path:L,time:{value:T.source_range.start.value+ae,rate:g},value:O(W),interp:"linear",order_index:C.length,raw_extraction:{}});if(w)for(let L of w.keyframes)C.push({...L,id:`${T.id}-${L.id}`,order_index:C.length});C.length&&(T.keyframes=C);let B=T;u.flip_h&&(B.flip_horizontal=!0),u.flip_v&&(B.flip_vertical=!0),l.push(`${c+1}. V${d} @${T.timeline_range.start.value} ${u.duration}f ${f.id} src+${u.source_in}${k!==100?` ${k}%`:""}${u.scale!=null?` scale ${u.scale}`:""}${u.rotation?` rot ${u.rotation}`:""}${u.flip_h?" flipH":""}${u.flip_v?" flipV":""}${u.audio?u.audio_from?` sound from ${u.audio_from.path.split("/").pop()}+${u.audio_from.source_in}`:" +sound":""}${w?` ramp ${u.ramp.map(([L,Z])=>`${Z}%@${L}`).join("\u2192")}`:""}${C.length&&!w?` animated (${C.length/2} params)`:""}`)}for(let[c,u]of(e.titles??[]).entries()){for(;i().length<u.track;)da(n,"add_track",{timeline_id:r,kind:"Video"});let d=i()[u.track-1],p=e.height/1080,f={font:"Arial",raster_w:e.width,raster_h:e.height,color:"#FFFFFF",opacity:1,shadow_color:"#000000",shadow_opacity:.6,shadow_dx:2*p,shadow_dy:2*p,shadow_blur:4*p,source_tool:"Resolve Text+"},h=u.kind==="lower_third"?{font_style:"Bold",size:52*p,align:"left",anchor_x:.08,anchor_y:.8,anchor_ref:"baseline"}:u.kind==="locator"?{font_style:"Regular",size:40*p,align:"left",anchor_x:.06,anchor_y:.1,anchor_ref:"baseline",tracking:.08}:{font_style:"Bold",size:110*p,align:"center",anchor_x:.5,anchor_y:.5,anchor_ref:"center"};d.items.push({id:`${r}-title-${c}`,kind:"clip",item_index:d.items.length,name:u.text.split(`
|
|
305
|
+
`)[0],enabled:!0,timeline_range:{start:{value:u.at,rate:s},duration:{value:u.duration,rate:s}},title:{text:u.text,...f,...h}}),l.push(`T${c+1}. V${u.track} @${u.at} ${u.duration}f ${u.kind} "${u.text.replace(`
|
|
306
|
+
`," / ")}"`)}return{session:n,summary:l}}function _T(e,t){vc(e.mix);let{clips:n,skipped:r}=vL(t);if(!n.length)throw new Error(`no usable clips (${r.length} skipped)`);let{shots:o,titles:s}=xL(e,n),i=e.fps_num??24e3,a=e.fps_den??1001,l=e.width??1920,c=e.height??1080,u=new Map(t.map(h=>[h.path,h.ref])),d=e.name??`generated ${e.seed}`,{session:p,summary:f}=hf({name:d,fps_num:i,fps_den:a,width:l,height:c,shots:o.map(({classes:h,record_in:g,record_out:b,...k})=>k),titles:s},h=>u.get(h));return{session:p,summary:f,shots:o,titles:s,pool:{used:n.length,skipped:r}}}async function ma(e){if(e.start_tc){let r=At(e.start_tc,e.fps_num/e.fps_den);if(r==null)throw new Error(`start_tc: cannot parse '${e.start_tc}' (HH:MM:SS:FF, ';' before FF for drop frame)`);e={...e,start_frame:r,drop_frame:e.drop_frame??e.start_tc.includes(";")}}let t=new Map;for(let r of e.shots)if(!t.has(r.path))try{t.set(r.path,await st(r.path))}catch(o){t.set(r.path,o instanceof Error?o:new Error(String(o)))}let n=new Set;for(let r of t.values()){if(r instanceof Error)continue;let o=r.id,s=2;for(;n.has(o);)o=`${r.id} (${s++})`;n.add(r.id=o)}return hf(e,r=>{let o=t.get(r);if(o instanceof Error)throw o;return o})}async function vT(e,t,n){let r=await _a({reference:e,clips:[]});try{let o=await r.ask(t,n);if(!o.ok)throw new Error(`${fe(e)}: ${o.why??"the analysis engine could not read it"}`);return o}finally{r.close()}}var TT=e=>t=>He(e.startFrame+t,e.fps||24,e.dropFrame);async function xT(e,t,n){let r=await vT(e,{op:"cuts"},n),o=TT(r),s=r.fps||24,[i,a]=Math.abs(s-Math.round(s))>.01?[Math.round(s*1001/1e3)*1e3,1001]:[Math.round(s),1],{session:l}=await ma({name:t??`${fe(e)} cuts`,fps_num:i,fps_den:a,width:r.w||1920,height:r.h||1080,start_tc:He(r.startFrame,s,r.dropFrame),shots:r.shots.map(([u,d])=>({path:e,source_in:u,duration:d-u+1,at:u}))}),c=[`${fe(e)}: ${r.frames} frames @ ${s.toFixed(3)} fps \u2014 ${r.shots.length} shot(s), ${r.cuts.length} cut(s)${r.flat.length?`, ${r.flat.length} black run(s)`:""}`,...r.shots.slice(0,200).map(([u,d],p)=>`${String(p+1).padStart(4)} ${o(u)} \u2013 ${o(d)} (${d-u+1} fr)${r.flat.some(([f,h])=>f<=u&&h>=d)?" black":""}`),...r.shots.length>200?[`\u2026 ${r.shots.length-200} more`]:[]];return{session:l,text:c.join(`
|
|
307
|
+
`),data:{frames:r.frames,fps:s,cuts:r.cuts,shots:r.shots,black:r.flat,cutsTc:r.cuts.map(o)}}}async function ST(e,t={},n){let r=await vT(e,{op:"qc",edgesEvery:t.edges_every??1},n),o=TT(r),s=(y,_)=>y===_?o(y):`${o(y)} \u2013 ${o(_)}`,i=r.temporal.findings.filter(y=>y.severity==="fail"),a=r.temporal.findings.filter(y=>y.severity==="warn"),[l,c]=r.matteRaster??[0,0],u=r.matte,d=r.format,p=["top","bottom","left","right"].flatMap(y=>r.edges[y].map(_=>({e:y,..._}))),f=r.audio??[],h=f.flatMap(y=>y.findings.map(_=>({track:y.track,..._}))),g=i.length||p.length||r.pixels.defects.length||h.some(y=>y.severity==="fail")?"FAIL":a.length||h.length?"CHECK":"PASS",b=[`${fe(e)}: ${g} \u2014 ${r.frames} frames, ${r.w}\xD7${r.h} @ ${(r.fps||0).toFixed(3)} fps`,`frames: ${i.length} fail, ${a.length} to check (motion p50 ${r.temporal.stats.motionP50}, p90 ${r.temporal.stats.motionP90})`,...r.temporal.findings.filter(y=>y.severity!=="info").map(y=>` ${y.severity.toUpperCase().padEnd(4)} ${y.check.padEnd(9)} ${s(y.start,y.end)} ${y.detail}`),...u&&d?[`picture: ${u.h<c?"letterbox":"pillarbox"} ${d} \u2014 active ${u.w}\xD7${u.h} of ${l}\xD7${c} (the format: edges are checked past it)`]:[],`edges${r.edgesEvery>1?` (every ${r.edgesEvery}th frame)`:""}: ${p.length?`worst top ${r.edges.worst.top}, bottom ${r.edges.worst.bottom}, left ${r.edges.worst.left}, right ${r.edges.worst.right} px${d?" past the picture":""}`:"clean"}`,...p.slice(0,40).map(y=>` FAIL ${y.e.padEnd(6)} ${y.thickness} px ${s(y.start,y.end)}`),...r.cardFrames?.length?[` INFO picture on black (a card, logo or graphic) on ${r.cardFrames.length} frame(s) checked, first ${o(r.cardFrames[0])}: not blanking`]:[],...r.edges.cornerFrames.length?[` CHECK black corners on ${r.edges.cornerFrames.length} frame(s), first ${o(r.edges.cornerFrames[0])}`]:[],`pixels: ${r.pixels.measurable?r.pixels.defects.length?`${r.pixels.defects.length} defect(s)`:"clean":"not measurable (the picture barely moves across the frames sampled)"} (${r.pixels.frames} frames)`,...r.pixels.defects.map(y=>` FAIL ${y.kind.padEnd(4)} pixel at ${y.x},${y.y}${y.pixels>1?` (${y.pixels} px)`:""}, value ${y.value}, ${y.contrast>0?"+":""}${y.contrast} vs its neighbours`),`sound: ${f.length?f.map(y=>`track ${y.track} ${y.channels}ch ${y.lufs??"\u2014"} LUFS ${y.truePeak??"\u2014"} dBTP`).join("; "):"no audio track"}`,...h.slice(0,40).map(y=>` ${y.severity.toUpperCase().padEnd(4)} ${y.check.padEnd(14)} track ${y.track}${y.channel?` ch ${y.channel}`:""}${y.start!=null?` at ${o(Math.floor(y.start*(r.fps||24)))}`:""} ${y.detail}`)],k=r.temporal.findings.filter(y=>y.check==="duplicate"||y.check==="retime"),w=k.length?[{verb:"media_fix",args:{kind:"duplicates",path:e},why:`${k.length} repeated-frame finding(s): remade as the motion between their neighbours`}]:[];return w.length&&b.push(`fix: media_fix kind=duplicates \u2014 ${w[0].why} (plan_only first)`),{verdict:g,text:b.join(`
|
|
308
|
+
`),data:{verdict:g,...r,fixes:w}}}async function SL(e){let t=[];async function n(r,o){if(!(await Bt(r)).isDirectory){if(/\.wav$/i.test(r))t.push(r);else throw new Error(`not a WAV: ${r}`);return}if(!(o>10))for await(let i of Ct(r))!i.name.startsWith(".")&&(i.isDirectory||/\.wav$/i.test(i.name))&&await n(re(r,i.name),o+1)}for(let r of e)await n(r,0);return t.sort((r,o)=>fe(r).localeCompare(fe(o)))}async function $T(e,t){let n=(await mf(e.picture)).sort((y,_)=>fe(y).localeCompare(fe(_))),r=await SL(e.sound);if(!n.length)throw new Error("no picture files found");if(!r.length)throw new Error("no recorder WAVs found");let o=await qt({op:"sync",picture:n,sound:r},t),s=o.synced,i=await Promise.all(n.map(y=>st(y))),a=y=>y.available_range?.duration.rate||24,l=a(i[0]),c=y=>(y.source_timecode?At(y.source_timecode,a(y)):null)??0,u=n.map((y,_)=>_).sort((y,_)=>c(i[y])-c(i[_])||fe(n[y]).localeCompare(fe(n[_]))),[d,p]=Math.abs(l-Math.round(l))>.01?[Math.round(l*1001/1e3)*1e3,1001]:[Math.round(l),1],f=0,h=u.map(y=>{let _=Math.round(i[y].available_range?.duration.value??0),v={path:n[y],source_in:0,duration:_,at:f};return f+=_,v}),{session:g}=await ma({name:e.name??`${fe(r[0])} dailies`,fps_num:d,fps_den:p,width:i[0].source_resolution_w||1920,height:i[0].source_resolution_h||1080,shots:h});$L(g,s,u,h,r,await Promise.all(r.map(y=>st(y))),l);let b=y=>He(y,l,!1),k=(y,_)=>{let v=o.sound[y];return v.start!=null?b(Math.round((v.start+_)*l)):`+${_.toFixed(3)} s`},w=[`${n.length} picture file(s), ${r.length} recorder file(s): ${s.filter(y=>y.by==="sound").length} synced by sound, ${s.filter(y=>y.by==="timecode").length} by timecode only, ${s.filter(y=>y.by==="none").length} not found`,...u.map(y=>{let _=s[y];return` ${fe(n[y]).padEnd(32)} ${_.sound==null?"\u2014".padEnd(24):fe(r[_.sound]).padEnd(24)} ${_.by.padEnd(8)} ${_.offset==null?"":`at ${k(_.sound,_.offset)}`}${_.tcOffFrames!=null?` TC ${_.tcOffFrames>=0?"+":""}${_.tcOffFrames} fr`:""}${_.note?` \u2014 ${_.note}`:""}`})];return{session:g,text:w.join(`
|
|
309
|
+
`),data:{picture:n.map((y,_)=>({path:y,...s[_],sound:s[_].sound==null?null:r[s[_].sound]}))}}}function $L(e,t,n,r,o,s,i){let a=e.timelines[0],l=p=>p.streams?.find(f=>f.kind==="audio")?.channels??1,c=Math.max(1,...t.filter(p=>p.sound!=null).map(p=>l(s[p.sound]))),u=new Map;for(let[p,f]of s.entries())e.media_references?.some(h=>h.id===f.id)||e.media_references?.push(f),u.set(p,f.id);let d=p=>({value:p,rate:i});for(let p=0;p<c;p++){let f=[];n.forEach((h,g)=>{let b=t[h],k=r[g];b.sound==null||b.offset==null||p>=l(s[b.sound])||f.push({id:`sync-a${p+1}-${g+1}`,kind:"clip",item_index:f.length,name:fe(o[b.sound]),enabled:!0,timeline_range:{start:d(k.at),duration:d(k.duration)},source_range:{start:d(b.offset*i),duration:d(k.duration)},media_reference_id:u.get(b.sound),channel_map:{routing:{[p]:0}}})}),a.tracks.push({id:`sync-a${p+1}`,kind:"Audio",track_index:p,name:`A${p+1}`,enabled:!0,items:f,audio_channel_count:1})}}var RL=2.5;async function CL(e,t){let n=t.map(s=>{let i=Math.max(1,Math.round(s.duration*((s.speed??100)/100)));return{s,need:i,frames:[s.source_in,s.source_in+(i>>1),s.source_in+i-1]}}),r=await e.ask({op:"detail",frames:n.flatMap(s=>s.frames.map(i=>[s.s.path,i]))});if(!r.ok)throw new Error(`the analysis engine could not read the planned shots: ${r.why}`);let o=r.detail;return n.flatMap((s,i)=>o.slice(3*i,3*i+3).filter(a=>a!=null&&a<RL).length>=2?[{path:s.s.path,from:s.s.source_in-24,to:s.s.source_in+s.need+24}]:[])}var AL=/\.(mov|mxf|mp4|m4v|mts|braw|r3d|ari)$/i,EL=/prox(y|ies)|^cache$/i;async function RT(e,t,n=!0){if((await Bt(e)).isFile){AL.test(e)&&!e.split("/").pop().startsWith("._")&&t.push(e);return}if(!(!n&&EL.test(e.split("/").pop())))for await(let o of Ct(e))o.name.startsWith(".")||await RT(`${e}/${o.name}`,t,!1)}async function CT(e){vc(e.mix);let t=[];for(let c of e.media)await RT(c,t);if(t.sort(),!t.length)throw new Error("no video files under the media given");let n=[],r=new Map;for(let c of t)try{n.push({path:c,ref:await st(c)})}catch(u){r.set(c,u instanceof Error?u.message:String(u))}let o=[...e.avoid??[]],s,i=e.look===!1?null:await Ih();try{for(let c=0;c<(e.look===!1?1:5);c++){try{s=_T({...e,avoid:o},n)}catch(d){throw d instanceof Error&&d.message.startsWith("no usable clips")?new Error(`no usable clips (${t.length} skipped)`):d}if(e.look===!1)break;let u=await CL(i,s.shots);if(!u.length)break;o.push(...u)}}finally{i?.close()}if(!s)throw new Error("no cut");let a=new Map([...r,...s.pool.skipped.map(c=>[c.path,c.reason])]),l=t.filter(c=>a.has(c)).map(c=>`${c} (${a.get(c)})`);return{session:s.session,summary:s.summary,shots:s.shots,titles:s.titles,pool:{used:s.pool.used,skipped:l}}}var ML=new Set(["aaf","avb","drt","prproj","xml","fcpxml","otio","otioz","edl","json"]);function IL(e){let t=e.split(/[/\\]/).pop()??"",n=t.lastIndexOf(".");return n>0?t.slice(n+1).toLowerCase():""}function AT(e){return e?/\.flame-archive\.zip$/i.test(e)?!0:ML.has(IL(e)):!1}async function PL(e,t){let n=await st(e).catch(()=>null),r=n?.streams?.find(i=>i.kind==="video");if(!n)return{...t,frames:0,label:""};let o=n.source_fps??t.fps,s=n.source_timecode?Aa(n.source_timecode,Math.round(o??24)):null;return{fps:o,frames:n.available_range?.duration?.value??0,startFrame:s?.frames??0,dropFrame:!!s?.drop,w:r?.width??t.w,h:r?.height??t.h,label:r?.codec??""}}async function ET(e){let t=[e.a,e.b].filter(h=>AT(h));if(t.length)throw new P("invalid_args",`Compare Cuts compares two renders of the cut (movies); ${t.map(h=>fe(h)).join(" and ")} ${t.length>1?"are timelines":"is a timeline"}. Two timelines: Reconform (Compare) or timeline_diff.`);let n=await _c({reference:e.b,pool:[e.a],name:`${fe(e.b)} rebuilt from ${fe(e.a)}`,onProgress:e.onProgress,signal:e.signal}),r=n.report,o=r.clips[0],s={fps:r.refFps,frames:r.refFrames,startFrame:r.refStartFrame,dropFrame:r.refDropFrame,w:r.refW,h:r.refH,label:""},i=o?{fps:o.srcFps??r.refFps,frames:o.srcFrames,startFrame:o.srcStartFrame,dropFrame:r.refDropFrame,w:o.srcW,h:o.srcH,label:o.codec}:await PL(e.a,s),a=h=>i.fps?He(i.startFrame+h,i.fps,i.dropFrame):"",l=h=>s.fps?He(s.startFrame+h,s.fps,s.dropFrame):"",c=n.issues,u=[],d=(h,g)=>{let b=u[u.length-1];b?.kind==="hole"&&b.recordOut===h?(b.count+=g-h,b.recordOut=g,b.recordOutTc=l(g)):u.push({index:0,kind:"hole",count:g-h,recordIn:h,recordOut:g,recordInTc:l(h),recordOutTc:l(g)})},p=0;for(let h of[...r.timeline].sort((g,b)=>g.refStart-b.refStart)){h.refStart>p&&d(p,h.refStart);let g=h.refEnd-h.refStart+1;if(!h.clipLabel||h.srcStart==null){d(h.refStart,h.refEnd+1),p=h.refEnd+1;continue}let b=h.speed?.slope??1,k=h.ramp?null:Array.from({length:g},(T,$)=>h.srcStart+Math.floor($*b+.001)),w=k?Math.min(...k):h.srcStart,y=k?Math.max(...k):h.srcStart+g-1,_={index:0,kind:"a-source",count:g,recordIn:h.refStart,recordOut:h.refEnd+1,recordInTc:l(h.refStart),recordOutTc:l(h.refEnd+1),aIn:w,aOut:y+1,aInTc:a(w),aOutTc:a(y+1)};h.ramp?_.motion={percent:100,ramp:!0,entry:h.srcStart,entryTc:a(h.srcStart)}:h.speed&&h.speed.kind!=="normal"&&(_.motion={percent:h.speed.kind==="freeze"?0:(h.speed.kind==="reverse"?-1:1)*h.speed.percent,entry:h.srcStart,entryTc:a(h.srcStart)});let v=c.find(T=>T.refStart<=h.refEnd&&T.refEnd>=h.refStart&&T.kind!=="retime");v&&(_.unreproducible={checked:0,failed:0,note:v.message}),u.push(_),p=h.refEnd+1}p<s.frames&&d(p,s.frames),u.forEach((h,g)=>h.index=g+1);let f={...s,codec:"",kind:"unknown"};return{a:i,b:s,events:u,summary:Fv(u),check:u.filter(h=>h.unreproducible),edl:Ov(u,f,{title:`${fe(e.b)} FROM ${fe(e.a)}`.toUpperCase().slice(0,70),aReel:fe(e.a)}),csv:Lv(u),session:n.session,stats:n.stats}}function MT(e,t){let n=(s,i)=>`${fe(i)}: ${s.label?`${s.label} `:""}${s.w}x${s.h} @ ${s.fps?.toFixed(3)??"?"} fps, ${s.frames} frames`,r=e.summary.hole===0&&e.events.length===1&&!e.events[0].motion&&e.events[0].aIn===0&&e.events[0].count===e.a.frames,o=s=>s.motion?s.motion.ramp?" SPEED RAMP":s.motion.percent===0?" FREEZE":s.motion.percent<0?` REVERSE ${-s.motion.percent.toFixed(1)}%`:` SPEED ${s.motion.percent.toFixed(1)}%`:"";return[r?"B is A, picture for picture (one event covers the whole cut).":`B rebuilt from A in ${e.events.length} event(s): ${e.events.filter(s=>s.kind!=="hole").length} from A (${e.summary.aSource} frames), ${e.events.filter(s=>s.kind==="hole").length} hole(s) of new material (${e.summary.hole} frames)`,`A (old) ${n(e.a,t.a)}`,`B (new) ${n(e.b,t.b)}`,"",...e.events.map(s=>`${String(s.index).padStart(4)} ${s.recordInTc}\u2013${s.recordOutTc} ${s.kind==="hole"?`NEW MATERIAL (${s.count} fr)`:`A ${s.aInTc}\u2013${s.aOutTc} (${s.count} fr)${o(s)}`}${s.unreproducible?` CHECK: ${s.unreproducible.note}`:""}`)].join(`
|
|
310
|
+
`)}import{basename as Yo}from"node:path";var IT=48e3*30;function gf(e){return(t,n)=>e.slice(t,t+n).arrayBuffer().then(r=>new Uint8Array(r))}var FL=async e=>{let t=globalThis.OfflineAudioContext;if(!t)return null;let r=await new t(1,1,48e3).decodeAudioData(await e.arrayBuffer()),o=new Float32Array(r.length);for(let s=0;s<r.numberOfChannels;s++){let i=r.getChannelData(s);for(let a=0;a<i.length;a++)o[a]+=i[a]/r.numberOfChannels}return{sampleRate:r.sampleRate,channels:1,chunks:(async function*(){yield o})()}},OL=FL;async function LL(e){let t=await OL(e).catch(()=>null);if(!t)return null;let n=new la(t.channels,t.sampleRate,100),r=0;for await(let o of t.chunks)n.push(o),r+=o.length/t.channels;return r?{sampleRate:t.sampleRate,channels:t.channels,sampleFrames:r,durationSec:r/t.sampleRate,envelopes:n.finish(),codec:"platform"}:null}async function PT(e){await Gr();let t=gf(e),n=await Sa(t,e.size),r=JSON.parse(n);if(!r||r.aac)return LL(e);let o=r.sample_rate??0,s=r.channels??0,i=r.sample_frames??0;if(!o||!s||!i)return null;let a=new la(s,o,100);for(let l=0;l<i;l+=IT){let c=Math.min(IT,i-l),u=await $a(t,e.size,l,c);if(!u||u.length<12)break;let d=new DataView(u.buffer,u.byteOffset,u.byteLength),p=d.getUint32(8,!0),f=d.getUint32(4,!0);if(!p||!f)break;let h=u.byteOffset+12,g=h%4===0?new Float32Array(u.buffer,h,p*f):new Float32Array(u.slice(12).buffer,0,p*f);a.push(g)}return{sampleRate:o,channels:s,sampleFrames:i,durationSec:i/o,envelopes:a.finish(),codec:r.codec}}function NL(e){let t=1681.974450955533,n=3.999843853973347,r=.7071752369554196,o=Math.tan(Math.PI*t/e),s=Math.pow(10,n/20),i=Math.pow(s,.4996667741545416),a=1+o/r+o*o,l={b0:(s+i*o/r+o*o)/a,b1:2*(o*o-s)/a,b2:(s-i*o/r+o*o)/a,a1:2*(o*o-1)/a,a2:(1-o/r+o*o)/a},c=38.13547087602444,u=.5003270373238773,d=Math.tan(Math.PI*c/e),p=1+d/u+d*d,f={b0:1,b1:-2,b2:1,a1:2*(d*d-1)/p,a2:(1-d/u+d*d)/p};return{shelf:l,highpass:f}}function jL(e){switch(e){case 1:return[1];case 2:return[1,1];case 6:return[1,1,1,0,1.41,1.41];case 8:return[1,1,1,0,1.41,1.41,1.41,1.41];default:return new Array(e).fill(1)}}var DL=-.691,BL=-70,qL=10,UL=.4,GL=.75;var xc=class{constructor(t,n){this.channels=t;this.sampleRate=n;this.blockFilled=0;this.historyAt=0;this.sinceLastBlock=0;this.totalSamples=0;this.blockPower=[];let r=NL(n);this.shelf=r.shelf,this.highpass=r.highpass,this.weights=jL(t),this.state=Array.from({length:t},()=>({s1:[0,0,0,0],s2:[0,0,0,0]})),this.blockSize=Math.round(UL*n),this.hop=Math.max(1,Math.round(this.blockSize*(1-GL))),this.blockSums=new Array(t).fill(0),this.history=Array.from({length:t},()=>new Float32Array(this.blockSize))}step(t,n,r){let o=t.b0*r+t.b1*n[0]+t.b2*n[1]-t.a1*n[2]-t.a2*n[3];return n[1]=n[0],n[0]=r,n[3]=n[2],n[2]=o,o}push(t){let n=Math.floor(t.length/this.channels);for(let r=0;r<n;r++){for(let o=0;o<this.channels;o++){let s=this.state[o],i=this.step(this.highpass,s.s2,this.step(this.shelf,s.s1,t[r*this.channels+o])),a=i*i;this.blockSums[o]+=a-this.history[o][this.historyAt],this.history[o][this.historyAt]=a}if(this.historyAt=(this.historyAt+1)%this.blockSize,this.totalSamples++,this.blockFilled<this.blockSize&&this.blockFilled++,this.blockFilled>=this.blockSize&&(this.sinceLastBlock++,this.sinceLastBlock>=this.hop||this.blockPower.length===0)){this.sinceLastBlock=0;let o=0;for(let s=0;s<this.channels;s++){let i=this.weights[s]??1;i!==0&&(o+=i*(this.blockSums[s]/this.blockSize))}this.blockPower.push(o)}}}finish(){return HL(this.blockPower)}get samplesSeen(){return this.totalSamples}};function HL(e){let t=a=>a>0?DL+10*Math.log10(a):-1/0,n=e.filter(a=>t(a)>BL);if(n.length===0)return{integratedLufs:null,gatedBlocks:0,totalBlocks:e.length};let r=n.reduce((a,l)=>a+l,0)/n.length,o=t(r)-qL,s=n.filter(a=>t(a)>o);if(s.length===0)return{integratedLufs:null,gatedBlocks:0,totalBlocks:e.length};let i=s.reduce((a,l)=>a+l,0)/s.length;return{integratedLufs:t(i),gatedBlocks:s.length,totalBlocks:e.length}}var zL=4,Tc=32;function WL(e=zL,t=Tc){let n=[],r=t/2;for(let o=0;o<e;o++){let s=new Float32Array(t),i=0;for(let a=0;a<t;a++){let l=a-r+1-o/e,c=l===0?1:Math.sin(Math.PI*l)/(Math.PI*l),u=.42-.5*Math.cos(2*Math.PI*a/(t-1))+.08*Math.cos(4*Math.PI*a/(t-1));s[a]=c*u,i+=s[a]}if(i!==0)for(let a=0;a<t;a++)s[a]/=i;n.push(s)}return n}var FT=1024;var Sc=class{constructor(t){this.channelCount=t;this.base=0;this.next=0;this.peak=0;this.phases=WL(),this.half=Tc/2;let n=1;for(let r=1;r<this.phases.length;r++){let o=0;for(let s=0;s<Tc;s++)o+=Math.abs(this.phases[r][s]);o>n&&(n=o)}this.l1=n,this.buffers=Array.from({length:t},()=>new Float32Array(0))}push(t){let n=Math.floor(t.length/this.channelCount);if(n<=0)return;for(let o=0;o<this.channelCount;o++){let s=this.buffers[o],i=new Float32Array(s.length+n);i.set(s,0);for(let a=0;a<n;a++){let l=t[a*this.channelCount+o];i[s.length+a]=l;let c=l<0?-l:l;c>this.peak&&(this.peak=c)}this.buffers[o]=i}let r=this.base+this.buffers[0].length;this.evaluate(r-this.half,!1),this.trim()}finish(){let t=this.base+this.buffers[0].length;return this.evaluate(t,!0),this.peak>0?20*Math.log10(this.peak):-1/0}evaluate(t,n){if(!(t<=this.next)){for(let r=0;r<this.channelCount;r++){let o=this.buffers[r],s=this.base,i=this.base+o.length;for(let a=this.next;a<t;a+=FT){let l=Math.min(a+FT,t),c=Math.max(s,a-this.half),u=Math.min(i,l+this.half),d=0;for(let p=c;p<u;p++){let f=o[p-s]<0?-o[p-s]:o[p-s];f>d&&(d=f)}if(!(d*this.l1<=this.peak))for(let p=a;p<l;p++)for(let f=1;f<this.phases.length;f++){let h=this.phases[f],g=0;for(let k=0;k<Tc;k++){let w=p+k-this.half+1;w>=s&&w<i&&(g+=o[w-s]*h[k])}let b=g<0?-g:g;b>this.peak&&(this.peak=b)}}}this.next=t,n&&(this.next=Math.max(this.next,this.base+this.buffers[0].length))}}trim(){let t=Math.max(this.base,this.next-this.half+1),n=t-this.base;if(!(n<=0)){for(let r=0;r<this.channelCount;r++)this.buffers[r]=this.buffers[r].slice(n);this.base=t}}};var KL={fps:24,minTonality:.7,minIsolationDb:20,maxFrameMultiple:3};function VL(e,t,n,r,o){let s=Math.round(n*r/o),i=2*Math.PI*s/n,a=2*Math.cos(i),l=0,c=0;for(let u=0;u<n;u++){let d=e[t+u]+a*l-c;c=l,l=d}return Math.sqrt(l*l+c*c-a*l*c)/(n/2)}function JL(e,t,n){let r=0;for(let o=0;o<n;o++){let s=e[t+o];r+=s*s}return Math.sqrt(r/n)}var $c=e=>e>0?20*Math.log10(e):-1/0;function OT(e,t,n={}){let r={...KL,...n};if(t<=0||e.length===0)return null;let o=1e3/r.fps,s=Math.max(64,Math.round(20/1e3*t)),i=Math.max(1,Math.round(s/2)),a=Math.min(e.length,Math.round(12*t));if(a<s*4)return null;let l=[],c=[];for(let g=0;g+s<=a;g+=i){let b=JL(e,g,s);l.push(b),c.push(b>1e-6?Math.min(1,VL(e,g,s,1e3,t)/(b*Math.SQRT2)):0)}if(l.length<4)return null;let u=[...l].sort((g,b)=>g-b),d=u[Math.floor(u.length/2)],p=g=>c[g]>=r.minTonality&&$c(l[g])-$c(Math.max(d,1e-9))>=r.minIsolationDb,f=null,h=0;for(;h<l.length;){if(!p(h)){h++;continue}let g=h;for(;g+1<l.length&&p(g+1);)g++;let b=g-h+1,k=((b-1)*i+s)*1e3/t;if(k<=o*r.maxFrameMultiple){let w=(h*i+(g*i+s))/2,y=Math.max(...l.slice(h,g+1)),_=c.slice(h,g+1).reduce((T,$)=>T+$,0)/b,v={atSeconds:w/t,durationMs:k,tonality:_,isolationDb:$c(y)-$c(Math.max(d,1e-9))};(!f||v.isolationDb>f.isolationDb)&&(f=v)}h=g+1}return f}function LT(e,t){if(t<=1)return e;let n=Math.floor(e.length/t),r=new Float32Array(n);for(let o=0;o<n;o++){let s=0;for(let i=0;i<t;i++)s+=e[o*t+i];r[o]=s/t}return r}var NT=1<<18;async function jT(e,t={}){await Gr();let n=gf(e),r=await Sa(n,e.size),o=JSON.parse(r);if(!o||o.aac)return{loudness:null,twoPop:null,truePeakDb:null};let s=o.sample_rate??0,i=o.channels??0,a=o.sample_frames??0;if(!s||!i||!a)return{loudness:null,twoPop:null,truePeakDb:null};let l=new xc(i,s),c=new Sc(i),u=Math.min(a,Math.round(12*s)),d=new Float32Array(u*i),p=0;for(let b=0;b<a;b+=NT){if(t.signal?.aborted)return{loudness:null,twoPop:null,truePeakDb:null};let k=Math.min(NT,a-b),w=await $a(n,e.size,b,k);if(!w||w.length<12)break;let y=new DataView(w.buffer,w.byteOffset,w.byteLength),_=y.getUint32(8,!0),v=y.getUint32(4,!0);if(!_||!v)break;let T=w.byteOffset+12,$=T%4===0?new Float32Array(w.buffer,T,_*v):new Float32Array(w.slice(12).buffer,0,_*v);if(l.push($),c.push($),p<d.length){let x=Math.min($.length,d.length-p);d.set($.subarray(0,x),p),p+=x}t.onProgress?.(Math.min(b+k,a),a)}let f=l.finish(),h=p>0?OT(LT(d.subarray(0,p),i),s,{fps:t.fps&&t.fps>0?t.fps:void 0}):null,g=c.finish();return{loudness:f.integratedLufs===null?null:f,twoPop:h,truePeakDb:Number.isFinite(g)?g:null}}var QL={apco:"ProRes 422 Proxy",apcs:"ProRes 422 LT",apcn:"ProRes 422",apch:"ProRes 422 HQ",ap4h:"ProRes 4444",ap4x:"ProRes 4444 XQ",aprn:"ProRes RAW",aprh:"ProRes RAW HQ"};function DT(e){let t=(e??"").toLowerCase().trim(),n=E1(t);return{family:n,label:QL[t]??n??t,bitDepth:M1(t),chroma:I1(t)}}function bf(e){return e.toLowerCase().replace(/\b(apple|avid|sony|panasonic)\b/g,"").replace(/[\s_-]+/g,"")}function BT(e,t){let n=bf(e),r=bf(t.label);return!n||!r?!1:r===n||r.startsWith(n)?!0:t.family!=null&&bf(t.family)===n}var qU={"23.98":24e3/1001,"23.976":24e3/1001,"29.97":3e4/1001,"59.94":6e4/1001,"47.95":48e3/1001,"119.88":12e4/1001};function qT(e,t,n,r=255){let o=e instanceof Int32Array?-13110.4:r*.1,s=Math.floor(n*.45),i=Math.floor(t*.45),a=f=>{let h=0,g=f*t;for(let b=0;b<t;b++)e[g+b]<=o&&h++;return h>=t*.95},l=f=>{let h=0;for(let g=0;g<n;g++)e[g*t+f]<=o&&h++;return h>=n*.95},c=0;for(;c<s&&a(c);)c++;let u=0;for(;u<s&&a(n-1-u);)u++;let d=0;for(;d<i&&l(d);)d++;let p=0;for(;p<i&&l(t-1-p);)p++;return{top:c,bottom:u,left:d,right:p}}function UT(e,t,n){if(e.length===0)return null;let r=(c,u)=>{let d=Math.floor(u*.02),p=e.filter(f=>f[c]>d);return p.length<e.length*.8?0:Math.min(...p.map(f=>f[c]))},o=r("top",n),s=r("bottom",n),i=r("left",t),a=r("right",t);if(o+s+i+a===0)return null;let l={x:i,y:o,w:t-i-a,h:n-o-s};return l.w<t*.3||l.h<n*.3?null:l}function GT(e,t=16){if(e<=0)return[];let n=Math.min(t,e);if(n===1)return[e>>1];let r=[];for(let o=0;o<n;o++)r.push(Math.min(e-1,Math.floor((o+.5)*e/n)));return[...new Set(r)]}function HT(e,t,n){if(!e)return null;let r=Math.round(e.y),o=Math.round(n-e.h-e.y),s=Math.round(e.x),i=Math.round(t-e.w-e.x),a=[];return(r||o)&&a.push(`letterboxed ${r===o?`${r} px top and bottom`:`${r} px top, ${o} px bottom`}`),(s||i)&&a.push(`pillarboxed ${s===i?`${s} px each side`:`${s} px left, ${i} px right`}`),a.length?a.join(", "):null}function YL(e){let t=new DataView(e.buffer,e.byteOffset,8);return{w:t.getUint32(0,!0),h:t.getUint32(4,!0)}}function yf(e){let t=y1(e),{w:n,h:r}=YL(t),o=new Int32Array(n*r),s=new DataView(t.buffer,t.byteOffset+8,n*r*4);for(let i=0;i<n*r;i++)o[i]=s.getInt32(i*4,!0);return{y:o,w:n,h:r}}function Xo(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getUint32(0,!0),r=t.getUint32(4,!0),o=n*r;if(e.byteLength<8+o*4)throw new Error(`decoded frame short: ${e.byteLength} B for ${n}x${r}`);let s=new Uint8Array(o);for(let i=0,a=8;i<o;i++,a+=4)s[i]=54*e[a]+183*e[a+1]+19*e[a+2]+128>>8;return{y:s,w:n,h:r}}function Qo(e,t){let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=n.getUint32(0,!0),o=n.getUint32(4,!0),s=r*o;if(e.byteLength<8+s*2)throw new Error(`decoded luma short: ${e.byteLength} B for ${r}x${o}`);let i=new Uint16Array(s);for(let a=0,l=8;a<s;a++,l+=2)i[a]=n.getUint16(l,!0);return{y:i,w:r,h:o,peak:t}}function JT(e,t){switch(t.codec){case"prores":return Qo(fu(e),1023);case"r3d":return Qo(w1(e),255);case"arriraw":return Qo(p1(e,t.w,t.h),255);case"xocn":return Qo(T1(e),255);case"vc3":return Qo(k1(e),255);case"braw":return Qo(f1(e),4095);case"proresraw":return Qo(g1(e),255)}}var zT={gpu:0,wasm:0},wf=null;function eN(){return wf||(wf=!!0||typeof navigator>"u"||!("gpu"in navigator)?Promise.resolve(null):import("./prores-CFX64NME.js").catch(()=>null)),wf}function tN(e,t,n,r){if(r===t&&e.length===t*n)return e;let o=new Uint16Array(t*n);for(let s=0;s<n;s++)o.set(e.subarray(s*r,s*r+t),s*t);return o}async function nN(e){try{let t=await eN();if(!t||!await t.proresGpuAvailable())return null;let n=await t.decodeProResFrameGpu(e);return n?{y:tN(n.y,n.width,n.height,n.strideY),w:n.width,h:n.height,peak:1023}:null}catch{return null}}async function rN(e,t){if(t.codec==="prores"){let n=await nN(e);if(n)return zT.gpu++,n;zT.wasm++}return JT(e,t)}function XT(e){let t=e.y.length,n=new Uint8Array(t);if(e.peak===255){for(let o=0;o<t;o++)n[o]=e.y[o]>255?255:e.y[o];return n}let r=255/e.peak;for(let o=0;o<t;o++){let s=Math.round(e.y[o]*r);n[o]=s>255?255:s}return n}function oN(e,t,n="coarse"){if(n==="exact"){let r=JT(e,t);return{y:XT(r),w:r.w,h:r.h}}if(n==="index"&&t.codec==="prores"){let r=yf(e),o=e.length>20?e[18]<<8|e[19]:0,s=o>0?Math.min(r.h,Math.max(1,Math.round(o/8))):r.h,i=new Uint8Array(r.w*s);for(let a=0;a<i.length;a++)i[a]=Math.max(0,Math.min(255,Math.round(r.y[a]/128+128)));return{y:i,w:r.w,h:s}}if(n==="index"&&t.codec==="r3d")return Xo(hu(e,0));if(n==="index"&&t.codec==="xocn"){let r=v1(e),o=new DataView(r.buffer,r.byteOffset,r.byteLength),s=o.getUint32(0,!0),i=o.getUint32(4,!0);return{y:r.subarray(8,8+s*i),w:s,h:i}}switch(t.codec){case"prores":{let r=yf(e);return{y:r.y,w:r.w,h:r.h}}case"r3d":return Xo(hu(e,t.subbands));case"arriraw":return Xo(m1(e,t.w,t.h,t.scale));case"xocn":return Xo(t.display==="rec709"?S1(e):x1(e,t.scale));case"vc3":return Xo(_1(e,t.scale));case"braw":return Xo(h1(e,t.scale));case"proresraw":return Xo(b1(e,t.scale))}}var WT=512*1024,KT=160*1024,VT=16*1024;async function QT(e,t,n,r,o="coarse"){let s=async i=>new Uint8Array(await e.slice(t,t+i).arrayBuffer());if(o==="index"&&r?.codec==="xocn"&&n>KT){let i=await s(KT),a=C1(i.subarray(0,128));if(a>0&&a<=n)return a<=i.length?i.subarray(0,a):await s(a)}if(o!=="exact"&&r?.codec==="r3d"&&n>VT){let i=await s(VT),a=R1(i,n,o==="index"?0:Math.min(3,r.subbands)),l=new Uint8Array(n);if(l.set(i),!a.length)return l.set(new Uint8Array(await e.slice(t+i.length,t+n).arrayBuffer()),i.length),l;let c=a[0];await Promise.all(Array.from({length:c},async(u,d)=>{let p=a[1+2*d],f=p+a[2+2*d];p<i.length&&(p=i.length),p<f&&l.set(new Uint8Array(await e.slice(t+p,t+f).arrayBuffer()),p)}));for(let u=1+2*c;u<a.length;u++){let d=a[u];l[d]=255,l[d+1]=144,l[d+2]=0,l[d+3]=10,l[d+12]=255,l[d+13]=147}return l}if(o!=="exact"&&r?.codec==="xocn"&&n>WT){let i=await s(WT),a=A1(i.subarray(0,128));if(a>0&&a<=n)return a<=i.length?i.subarray(0,a):await s(a)}return await s(n)}async function YT(e,t,n="coarse"){if(n!=="exact")return oN(e,t,n);let r=await rN(e,t);return{y:XT(r),w:r.w,h:r.h}}async function sN(e,t,n,r,o,s){let i=await YT(e,t,n),a={idx:o,ok:!0,w:i.w,h:i.h,black:tx(i.y)};if(r.diff&&s&&(a.diff=nx(s.y,i.y)),r.hash){let l=Pv(i.y,i.w,i.h);a.bits=Array.from(l.bits),a.q=l.quality,a.my=l.meanY??0}return r.bars&&(a.bars=qT(i.y,i.w,i.h)),{result:a,plane:i}}var ZT=e=>({idx:e,ok:!1,w:0,h:0,black:!1});async function iN(e,t,n,r,o,s,i){let a=[],l=null;for(let c=0;c<t.length;c++){let u=t[c],d=c<n,p;try{let f=await QT(e,u.offset,u.size,r,o),h=await sN(f,r,o,s,u.idx,l);l=h.plane,p=h.result}catch{p=ZT(u.idx)}d||a.push(p),i?.(d?null:p)}return a}function aN(e,t){let n=[],r=Math.min(t,e.length);if(r===0)return n;let o=Math.ceil(e.length/r);for(let s=0;s<e.length;s+=o){let i=e.slice(s,s+o);s===0?n.push({jobs:i,primers:0}):n.push({jobs:[e[s-1],...i],primers:1})}return n}async function ex(e,t,n,r,o,s={}){let{signal:i,onProgress:a}=s;if(t.length===0)return[];let l=t.length,c=0,u=()=>a?.(++c,l);if(typeof Worker>"u")return await iN(e,t,0,n,r,o,g=>{if(i?.aborted)throw new DOMException("aborted","AbortError");g&&u()});let d=Math.max(1,Math.min(navigator.hardwareConcurrency||4,16,t.length)),p=o.diff?aN(t,d):Array.from({length:d},(h,g)=>({jobs:t.filter((b,k)=>k%d===g),primers:0})),f=new Map;return await new Promise((h,g)=>{let b=p.filter(_=>_.jobs.length>0).length;if(b===0){h();return}let k=[],w=()=>{for(let _ of k)_.terminate();i?.removeEventListener("abort",y)};function y(){w(),g(new DOMException("aborted","AbortError"))}if(i?.aborted){y();return}i?.addEventListener("abort",y,{once:!0});for(let _ of p){if(_.jobs.length===0)continue;let v=new Worker(new URL("./workers/picture-worker.ts",import.meta.url),{type:"module"});k.push(v),v.onmessage=$=>{let x=$.data;if(x.progress)for(let R=0;R<x.progress;R++)u();if(x.results){for(let R of x.results)f.set(R.idx,R);--b===0&&(w(),h())}},v.onerror=$=>{w(),g(new Error(`picture worker error: ${$.message}`))};let T={file:e,jobs:_.jobs,primers:_.primers,spec:n,tier:r,want:o};v.postMessage(T)}}),t.map(h=>f.get(h.idx)??ZT(h.idx))}var lN=16,cN=.075,uN=.12;function tx(e){let t=0,n=0;for(let r=0;r<e.length;r++){let o=e[r];t+=o,o>n&&(n=o)}return t/e.length<=255*cN&&n<=255*uN}function nx(e,t){let n=Math.min(e.length,t.length);if(n===0)return 0;let r=0;for(let o=0;o<n;o++)r+=Math.abs(e[o]-t[o]);return r/n}var dN=1.5,pN=1,mN=30;function fN(e,t){let n=[];for(let r of t){let o=e.frames[r];o&&n.push({idx:r,offset:o.offset,size:o.size})}return n}async function Rc(e,t,n,r,o,s){if(!t.spec)return null;try{return await ex(e,fN(t,n),t.spec,r,o,{signal:s.signal,onProgress:s.onProgress})}catch(i){if(i instanceof DOMException&&i.name==="AbortError")return null;throw i}}async function rx(e,t,n={}){let r;try{r=t??await Ro(e)}catch{return null}if(!r.spec||r.frames.length===0)return null;let o=GT(r.frames.length,lN),s=await Rc(e,r,o,"exact",{bars:!0},n);if(!s)return null;let i=s.filter(w=>w.ok&&w.bars);if(i.length===0)return null;let{w:a,h:l}=i[0],c=UT(i.map(w=>w.bars),a,l),u=r.h>0&&l>0?r.h/l:1,d=r.w>0&&a>0?r.w/a:1,p=c?{x:Math.round(c.x*d),y:Math.round(c.y*u),w:Math.round(c.w*d),h:Math.round(c.h*u)}:null,f=p?HT(p,Math.round(a*d),Math.round(l*u)):null,h=Math.max(1,Math.round(u)),g=h>1?` (\xB1${h} px, measured at 1/${h} scale)`:"",b=`across ${i.length} sampled frame${i.length===1?"":"s"}`;return c==null||c.x===0&&c.y===0&&c.w===a&&c.h===l?{hasBlanking:!1,note:`none found ${b}`}:{hasBlanking:!0,note:`${f??"bars detected"}${g} ${b}`}}async function ox(e,t,n,r={}){let o;try{o=n??await Ro(e)}catch{return null}if(!o.spec||o.frames.length===0)return null;let s=o.frames.length,i=Math.min(t,s),a=Math.max(i,s-t);if(a<=i)return null;let l=[];for(let h=i;h<a;h++)l.push(h);let c=await Rc(e,o,l,"exact",{},r);if(!c)return null;let u=[],d=0;for(let h of c)h.ok&&(d++,h.black&&u.push(h.idx));if(d===0)return null;let p=`${d} of ${a-i} interior frames`;if(u.length===0)return{hasBlackFrames:!1,note:`none found in ${p}`};let f=u.slice(0,5).join(", ");return{hasBlackFrames:!0,note:`${u.length} black frame${u.length===1?"":"s"} at ${f}${u.length>5?", \u2026":""} (${p})`}}function kf(e,t){let n=e/t,r=Math.floor(n/60);return`${r}:${(n-r*60).toFixed(2).padStart(5,"0")}`}async function sx(e,t,n={}){let r;try{r=t??await Ro(e)}catch{return null}if(!r.spec||r.frames.length===0)return null;let o=r.fps&&r.fps>0?r.fps:24,s=Math.min(r.frames.length,Math.round(o*mN)),i=[];for(let d=0;d<s;d++)i.push(d);let a=await Rc(e,r,i,"exact",{diff:!0},n);if(!a)return null;let l=[],c=[],u=0;for(let d=0;d<a.length;d++){let p=a[d];if(!p.ok){l.push(l[d-1]??!1),c.push(!1);continue}u++,l.push(p.black),c.push(p.diff==null?!1:p.diff>dN)}return u===0?null:hN(l,c,o)}function hN(e,t,n){let r=e.length,o=Math.max(2,Math.round(n*pN)),s=0;for(;s<r&&e[s];)s++;let i=s,a=-1,l=-1;for(;s<r;){if(e[s]){s++;continue}let d=s,p=s+1;for(;p<r&&!e[p]&&!t[p];)p++;if(p-d>=o){a=d,l=p;break}s=Math.max(p,s+1)}let c=null;for(let d=l>=0?l:i;d<r;d++)if(!e[d]){c=d;break}let u=[];return i>0&&u.push(`${(i/n).toFixed(2)} s black at head`),a>=0?u.push(`a static card ${kf(a,n)}\u2013${kf(l,n)} (${((l-a)/n).toFixed(2)} s)`):u.push(`no static card in the first ${(r/n).toFixed(0)} s`),c!=null&&u.push(`picture from ${kf(c,n)}`),{hasSlate:a>=0,programmeStart:c,note:u.join(", ")}}var gN=1200,bN=.5,yN=.6,wN=.7,kN=3;function _N(e,t,n){let r=e.length;for(let o=n;o<r;o++){if(!e[o]||t[o])continue;let s=0,i=0;for(let a=o;a<r;a++)t[a]||(s++,e[a]&&i++);if(s>=3&&i>=s*wN)return o}return-1}async function ix(e,t,n={}){let r;try{r=t??await Ro(e)}catch{return null}if(!r.spec||r.frames.length===0)return null;let o=r.fps&&r.fps>0?r.fps:24,s=r.frames.length,i=Math.max(1,Math.round(o*bN),Math.ceil(s/gN)),a=[];for(let w=0;w<s;w+=i)a.push(w);let l=await Rc(e,r,a,"coarse",{hash:!0},n);if(!l)return null;let c=[],u=[],d=[];for(let w of l)!w.ok||!w.bits||(c.push(w.idx),u.push({bits:Uint32Array.from(w.bits),quality:w.q??0,meanY:w.my}),d.push(w.black));let p=u.length,f=`sampled every ${(i/o).toFixed(2)} s`;if(p<8)return null;let h=Math.floor(p*yN);if(h<2)return null;let g=new Array(p).fill(!1);for(let w=h;w<p;w++)if(!d[w]){for(let y=0;y<h;y++)if(gc(u[w],u[y])<=Qm){g[w]=!0;break}}let b=_N(g,d,h);if(b<0)return{hasTextlessTail:!1,note:`no repeated material at the tail (${f})`};let k=(c[p-1]-c[b])/o;return k<kN?{hasTextlessTail:!1,note:`only ${k.toFixed(1)} s of repeated material at the tail, too short to be textless (${f})`}:{hasTextlessTail:!0,note:`${k.toFixed(1)} s from ${(c[b]/o/60).toFixed(0)}:${(c[b]/o%60).toFixed(2).padStart(5,"0")} repeats earlier picture (${f})`}}function vN(e){let t=e.toLowerCase().match(/\.([a-z0-9]{2,4})$/);return t?t[1]:void 0}function TN(e){if(e===1)return"mono";if(e===2)return"stereo";if(e===6)return"5.1"}async function ax(e,t={}){let n={name:e.name,sizeBytes:e.size,wrapper:vN(e.name)},r;try{let o=await Ro(e);r=o,n.width=o.w||void 0,n.height=o.h||void 0,n.fps=o.fps??void 0,n.durationFrames=o.frames.length||void 0;let s=o.index?.codec,i=DT(s??o.label);n.codec=s?i.label:o.label,n.bitDepth=i.bitDepth??void 0,n.chroma=i.chroma??void 0,o.fps&&Number.isFinite(o.startFrame)&&(n.startTimecode=He(o.startFrame,o.fps,o.dropFrame))}catch{}if(t.audio!==!1){try{let o=await PT(e);o&&(n.audioChannels=o.channels,n.audioSampleRate=o.sampleRate,n.audioLayout=TN(o.channels))}catch{}if(t.loudness!==!1)try{let o=await jT(e,{signal:t.signal,fps:n.fps});o.loudness?.integratedLufs!=null&&(n.loudnessLufs=o.loudness.integratedLufs),o.truePeakDb!=null&&(n.truePeakDb=o.truePeakDb),n.hasTwoPop=o.twoPop!==null}catch{}}if(t.picture?.blanking){let o=await rx(e,r,{signal:t.signal});o&&(n.hasBlanking=o.hasBlanking,n.blankingNote=o.note)}if(t.picture?.headStructure){let o=await sx(e,r,{signal:t.signal});o&&(n.hasSlate=o.hasSlate,n.slateNote=o.note)}if(t.picture?.textlessTail){let o=await ix(e,r,{signal:t.signal});o&&(n.hasTextlessTail=o.hasTextlessTail,n.textlessNote=o.note)}if(t.picture?.blackFrames){let o=n.fps&&n.fps>0?Math.round(n.fps):24,s=await ox(e,o,r,{signal:t.signal});s&&(n.hasBlackFrames=s.hasBlackFrames,n.blackFramesNote=s.note)}return n}function Xs(e,t,n,r,o,s){let i=hn(e,t,n,r,(a,l)=>a===l,o);return s&&i.outcome!=="unstated"?{...i,note:s}:i}function _f(e,t){let n=t.plusMinus??0;return Math.abs(e-t.target)<=n+1e-9}function xN(e){return e.plusMinus?`${e.target} \xB1${e.plusMinus}`:String(e.target)}function hn(e,t,n,r,o,s){if(n==null)return{field:e,label:t,outcome:"unstated"};let i=s.required(n.value);return r==null||typeof r=="number"&&!Number.isFinite(r)?{field:e,label:t,outcome:"unmeasurable",required:i,note:"not reported by the probe"}:{field:e,label:t,outcome:o(n.value,r)?"pass":"fail",required:i,measured:s.measured(r)}}var fa={required:e=>e,measured:e=>e},Qs={required:e=>String(e),measured:e=>String(e)},vf={required:xN,measured:e=>String(e)};function lx(e,t){let n=e.video??{},r=e.audio??{},o=e.content??{};return[hn("video.codec","Codec",n.codec,t.codec,(s,i)=>BT(s,{family:null,label:i}),fa),hn("video.wrapper","Wrapper",n.wrapper,t.wrapper,(s,i)=>s.toLowerCase()===i.toLowerCase(),fa),hn("video.width","Width",n.width,t.width,(s,i)=>s===i,Qs),hn("video.height","Height",n.height,t.height,(s,i)=>s===i,Qs),hn("video.fps","Frame rate",n.fps,t.fps,(s,i)=>_f(i,s),vf),hn("video.durationFrames","Duration (frames)",n.durationFrames,t.durationFrames,(s,i)=>_f(i,s),vf),hn("video.startTimecode","Start timecode",n.startTimecode,t.startTimecode,(s,i)=>s===i,fa),hn("video.par","Pixel aspect ratio",n.par,t.par,(s,i)=>Math.abs(s-i)<=.005,Qs),hn("video.bitDepth","Bit depth",n.bitDepth,t.bitDepth,(s,i)=>s===i,Qs),hn("video.chroma","Chroma",n.chroma,t.chroma,(s,i)=>Ra(s)===Ra(i),fa),hn("audio.channels","Audio channels",r.channels,t.audioChannels,(s,i)=>s===i,Qs),hn("audio.layout","Audio layout",r.layout,t.audioLayout,(s,i)=>s.toLowerCase()===i.toLowerCase(),fa),hn("audio.sampleRate","Sample rate",r.sampleRate,t.audioSampleRate,(s,i)=>s===i,Qs),hn("audio.loudnessLufs","Loudness (LUFS)",r.loudnessLufs,t.loudnessLufs,(s,i)=>_f(i,s),vf),hn("audio.truePeakDb","True peak (dBTP)",r.truePeakDb,t.truePeakDb,(s,i)=>i<=s+1e-9,{required:s=>`\u2264 ${s}`,measured:s=>s.toFixed(2)}),Xs("content.twoPop","2-pop",o.twoPop,t.hasTwoPop,{required:s=>s?"present":"absent",measured:s=>s?"present":"absent"}),Xs("content.slate","Slate",o.slate,t.hasSlate,{required:s=>s?"present":"absent",measured:s=>s?"present":"absent"},t.slateNote),Xs("content.textlessAtTail","Textless at tail",o.textlessAtTail,t.hasTextlessTail,{required:s=>s?"present":"absent",measured:s=>s?"present":"absent"},t.textlessNote),Xs("content.noBlanking","Free of blanking",o.noBlanking,t.hasBlanking==null?void 0:!t.hasBlanking,{required:s=>s?"no blanking":"blanking allowed",measured:s=>s?"none found":"blanking found"},t.blankingNote),Xs("content.noBlackFrames","Free of black frames",o.noBlackFrames,t.hasBlackFrames==null?void 0:!t.hasBlackFrames,{required:s=>s?"no black frames":"black frames allowed",measured:s=>s?"none found":"black frames found"},t.blackFramesNote),Xs("content.matchesMaster","Matches approved master",o.matchesMaster,t.matchesMaster,{required:s=>s?"must match":"need not match",measured:s=>s?"matches":"differs"})]}async function cx(e){let n=(await qt({op:"audio",path:e}).catch(()=>null))?.tracks??[];if(n.length===1){let o=(await st(e).catch(()=>null))?.streams?.filter(s=>s.kind==="audio").reduce((s,i)=>s+(i.channels??0),0)??0;o>n[0].channels&&(n[0].channels=o)}return n.map(r=>({track:r.track,channels:r.channels,rate:r.rate,lufs:r.lufs,peak_db:r.truePeak,findings:r.findings}))}var po=e=>e==null?"\u2014":`${e.toFixed(1)}`;function SN(e,t){if(!t.length)return[];let n=[],r=new Set;for(let o of e){if(o.lufs==null)continue;let s=t.map((l,c)=>({x:l,i:c,d:l.lufs==null?1/0:o.lufs-l.lufs})).sort((l,c)=>Math.abs(l.d)-Math.abs(c.d)),i=s.find(l=>Math.abs(l.d)<=.5&&l.x.channels===o.channels)??s.find(l=>Math.abs(l.d)<=.5),a=s.find(l=>l.d>=5&&l.d<=7);i&&r.add(i.i),n.push(i?{check:`Track ${o.track} vs mix`,outcome:i.x.channels===o.channels?"pass":"warn",measured:`= ${i.x.file} (${i.x.channels}ch, ${po(i.x.lufs)} LUFS, \u0394 ${i.d.toFixed(1)} LU)`,note:i.x.channels!==o.channels?"loudness matches but the channel count differs (downmix or wrong bus)":void 0}:{check:`Track ${o.track} vs mix`,outcome:"fail",measured:`${po(o.lufs)} LUFS`,note:a?`\u2248 +6 LU over ${a.x.file}: summed twice (two buses into one output, or a doubled track)`:`no mix file within 0.5 LU (nearest ${s[0]?.x.file??"\u2014"}: ${po(s[0]?.x.lufs??null)} LUFS)`})}return t.forEach((o,s)=>{r.has(s)||n.push({check:`Mix ${o.file}`,outcome:"warn",measured:`${o.channels}ch, ${po(o.lufs)} LUFS`,note:"no output track carries this mix (missing bus?)"})}),n}var uo=e=>({value:e,source:"operator"});async function ux(e){let t=await Jo.open(e.path),n=await ax(t,{loudness:!1}),r=e.fps??n.fps??24,o=w=>w==null?null:typeof w=="number"?w:At(w,r),s=o(e.mark_in),i=o(e.mark_out),a=await Co(),l=s!=null?He(s,r):e.start_tc??a.conventions?.program_start,c=e.end_on_picture??a.conventions?.end_on_picture,u=e.frames??(s!=null&&i!=null?i-s+1:void 0),d={label:Yo(e.path),video:{...e.codec?{codec:uo(e.codec)}:{},...e.width?{width:uo(e.width)}:{},...e.height?{height:uo(e.height)}:{},...e.fps?{fps:uo({target:e.fps,plusMinus:.001})}:{},...e.bit_depth?{bitDepth:uo(e.bit_depth)}:{},...e.chroma?{chroma:uo(e.chroma)}:{},...l?{startTimecode:uo(l)}:{},...u?{durationFrames:uo({target:u})}:{}}},p=lx(d,n).filter(w=>w.outcome!=="unstated").map(w=>({check:w.label,outcome:w.outcome==="pass"||w.outcome==="fail"?w.outcome:"unchecked",expected:w.required,measured:w.measured,note:w.note}));if(l||p.push({check:"Start timecode",outcome:"unchecked",measured:n.startTimecode,note:"no start TC stated and none in the artist's profile: confirm it (artist_profile action=remember convention program_start)"}),p.push({check:"Picture",outcome:"pass",measured:[n.codec,n.width&&`${n.width}x${n.height}`,n.fps&&`${+n.fps.toFixed(3)} fps`,n.bitDepth&&`${n.bitDepth}-bit`,n.chroma].filter(Boolean).join(", ")}),e.name!==!1)try{let w=Fa(a,Yo(e.path),{probe:await st(e.path)}),y=w.issues.filter(v=>v.level==="error"),_=w.issues.filter(v=>v.level==="warn");p.push({check:"Name",outcome:y.length?"fail":_.length?"warn":"pass",measured:Yo(e.path),note:w.issues.map(v=>`${v.element}: ${v.message}`).join("; ")||void 0})}catch(w){p.push({check:"Name",outcome:"unchecked",note:String(w.message??w)})}try{let w=await qt({op:"ends",path:e.path,cap:Math.round(5*r),frames:n.durationFrames||void 0}),[y,_,v,T]=[w.first,w.last,w.head,w.tail],$=x=>x>=Math.round(5*r)?"5 s or more":`${x} frame(s)`;p.push({check:"First frame",outcome:y==null?"unchecked":y?"warn":"pass",measured:y==null?void 0:y?`black (${$(v)})`:"picture"}),p.push({check:"Last frame",outcome:_==null?"unchecked":_?c?"fail":"warn":"pass",measured:_==null?void 0:_?`black (last ${$(T)})`:"picture",note:_?c?"the job ends on picture: Mark Out past the end card, or a gap at the tail":"black tail: confirm the delivery spec pads with black":void 0})}catch{p.push({check:"First/last frame",outcome:"unchecked"})}let f=await cx(e.path),h=f.reduce((w,y)=>w+y.channels,0);e.channels!=null&&p.push({check:"Audio channels",outcome:h===e.channels?"pass":"fail",expected:String(e.channels),measured:`${h} (${f.map(w=>`track ${w.track}: ${w.channels}ch`).join(", ")||"no audio"})`});for(let w of f){let y=e.loudness_lufs==null||w.lufs==null?null:Math.abs(w.lufs-e.loudness_lufs)<=(e.loudness_tolerance??1),_=e.true_peak==null||w.peak_db==null?null:w.peak_db<=e.true_peak;p.push({check:`Audio track ${w.track}`,outcome:y===!1||_===!1?"fail":w.lufs==null?"unchecked":"pass",expected:[e.loudness_lufs!=null&&`${e.loudness_lufs} LUFS \xB1${e.loudness_tolerance??1}`,e.true_peak!=null&&`\u2264 ${e.true_peak} dBTP`].filter(Boolean).join(", ")||void 0,measured:`${w.channels}ch${w.rate?` ${w.rate/1e3} kHz`:""}, ${po(w.lufs)} LUFS, ${po(w.peak_db)} dBTP`})}for(let w of f)for(let y of w.findings)p.push({check:`Audio track ${w.track} ${y.check}`,outcome:y.severity==="fail"?"fail":"warn",measured:`${y.channel?`ch ${y.channel} `:""}${y.start!=null?`at ${y.start.toFixed(3)} s: `:""}${y.detail}`});let g=f.find(w=>w.channels===2)??f[0],b=a.conventions?.theatrical_tag;if(b&&g?.lufs!=null&&e.name!==!1){let w=new RegExp(`[_\\-. ]${b.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}([_\\-. ]|$)`,"i").test(Yo(e.path));w&&g.lufs>-20&&p.push({check:`${b} tag`,outcome:"warn",measured:`${po(g.lufs)} LUFS on track ${g.track}`,note:`tagged ${b} (theatrical) but measures at a web/nearfield level`}),!w&&g.lufs<-27&&p.push({check:`${b} tag`,outcome:"warn",measured:`${po(g.lufs)} LUFS on track ${g.track}`,note:`measures at a theatrical level: add _${b} to the audio config? ask`})}f.length||p.push({check:"Audio",outcome:e.channels===0?"pass":e.channels||e.mix?.length?"fail":"warn",measured:"no audio tracks"});let k=[];for(let w of e.mix??[]){let y=await cx(w);y.length||p.push({check:`Mix ${Yo(w)}`,outcome:"unchecked",measured:"no audio read from this file"});for(let{findings:_,...v}of y)k.push({...v,file:Yo(w)})}if(p.push(...SN(f,k)),e.ref)try{let w=await Da({a:e.path,b:e.ref,b_in:e.ref_in??n.startTimecode??l}),y=w.overall;p.push({check:"Picture vs REF",outcome:y.verdict==="exact"?"pass":y.verdict==="unverifiable"?"warn":"fail",measured:y.verdict==="offset"?`offset ${y.offset>0?"+":""}${y.offset} frame(s)`:y.verdict,expected:`exact at ${w.b_tc}`,note:[...w.shots.filter(_=>_.verdict!=="exact").slice(0,5).map(_=>`shot ${_.a_tc}: ${_.verdict}${_.offset?` ${_.offset>0?"+":""}${_.offset}`:""}`),...w.flash].join("; ")||void 0})}catch(w){p.push({check:"Picture vs REF",outcome:"unchecked",note:String(w.message??w)})}return{file:Yo(e.path),verdict:p.some(w=>w.outcome==="fail")?"FAIL":"PASS",rows:p,tracks:f,mix:k}}function dx(e){let t={pass:"PASS",fail:"FAIL",warn:"WARN",unchecked:"----"};return[`${e.verdict}: ${e.file}`,...e.rows.map(n=>` ${t[n.outcome]} ${n.check}: ${n.measured??"could not measure"}${n.expected?` (expected ${n.expected})`:""}${n.note?` \u2014 ${n.note}`:""}`)].join(`
|
|
311
|
+
`)}import{basename as px}from"node:path";async function $N(e,t){let r=(await st(e).catch(()=>null))?.vendor_metadata?.bext,o=await qt({op:"mix",path:e,fps:t}).catch(()=>null);if(!o)return null;let[s,i,a,l,c]=[o.rate,o.channels,o.samples,o.lastSound,o.pop],u=G1(r?.time_reference??0,r?.sample_rate||s,a,t),d=At(u.tc,t)??0,p=f=>d+Math.floor(f*u.frames/Math.max(a,1));return{file:px(e),channels:i,start:d,end:d+u.frames,last_sound:l<0?d:p(l)+1,pop:c?p(c.atSeconds*s):null}}function RN(e){let t=e.toUpperCase().split(/[_.]/),n=[];for(let o of t)o==="5-1"?n.push({label:"5.1",channels:6}):o==="7-1"?n.push({label:"7.1",channels:8}):o==="STEREO"||o==="LORO"?n.push({label:o==="LORO"?"LoRo":"stereo",channels:2}):o==="MONO"&&n.push({label:"mono",channels:1});let r=t.map(o=>/^(\d+)CH$/.exec(o)).find(Boolean);return{total:r?Number(r[1]):null,parts:n}}async function mx(e,t){let n=Ws(e,t.timeline_id),r=Pt(n),o=!!n.is_drop_frame,s=v=>He(v,r,o),i=n.tracks.filter(v=>v.kind==="Video"),a=lo(n,i),l=[];if(!a.length)throw new Error("the timeline has no enabled video");let c=a[0].s,u=a[a.length-1].e,d=[];for(let v of t.mix??[]){let T=await $N(v,r);T?d.push(T):l.push({check:`Mix ${px(v)}`,outcome:"unchecked",measured:"no audio read from this file"})}let p=d[0],f=t.program_start??(await Co()).conventions?.program_start,h=f?At(f,r):null,g=p?.pop!=null?p.pop+Math.round(2*r):null,b=g??(h!=null&&h>=c-Math.round(10*r)?h:c);p&&l.push(p.pop!=null?{check:"2-pop",outcome:h==null||g===h?"pass":"warn",measured:`${s(p.pop)} in ${p.file} \u2192 program starts ${s(g)}`,note:h!=null&&g!==h?`the stated start is ${s(h)}`:void 0}:{check:"2-pop",outcome:"warn",measured:`none found in the first 15 s of ${p.file}`,note:`program start taken as ${s(b)}`});let k=p?p.last_sound:u;if(p){let v=u-p.last_sound;l.push({check:"Picture end vs mix end",outcome:v===0?"pass":"fail",measured:`picture ends ${s(u-1)} (last frame), sound ends ${s(p.last_sound-1)}`,note:v===0?void 0:v<0?`picture stops ${-v} frame(s) before the mix: ${-v} frame(s) of black under sound. EDIT ERROR: extend the last shot/card, or ask`:`picture runs ${v} frame(s) past the mix: picture with no sound at the end. EDIT ERROR: ask before trimming`});for(let T of d.slice(1))T.last_sound!==p.last_sound&&l.push({check:`Mix ${T.file} end`,outcome:"warn",measured:`sound ends ${s(T.last_sound-1)}`,note:`${p.file} ends ${s(p.last_sound-1)}`});p.start>b&&l.push({check:"Mix start",outcome:"fail",measured:`${p.file} starts ${s(p.start)}`,note:`after the program start ${s(b)}: no sound under the first frames`})}c>b&&l.push({check:"Picture start",outcome:"fail",measured:`first picture ${s(c)}`,note:`${c-b} frame(s) of black after the program start ${s(b)}`});let w=a.find(v=>v.s<=k-1&&v.e>=k);l.push({check:"Last program frame",outcome:w?"pass":"fail",measured:w?`${s(k-1)}: ${w.it.name??"clip"} (${w.track})`:`${s(k-1)}: no picture`,note:w?"confirm it is the end card, not black inside the clip":"the program ends on a gap"});let y=[],_=b;for(let v of a)if(!(v.e<=b)){if(v.s>=k)break;v.s>_&&y.push([_,Math.min(v.s,k)]),_=Math.max(_,v.e)}_<Math.min(k,u)&&y.push([_,Math.min(k,u)]),l.push(y.length?{check:"Gaps in the program",outcome:"warn",measured:y.map(([v,T])=>`${s(v)}\u2013${s(T-1)} (${T-v} fr)`).join(", "),note:"black in the render: check each against the REF (intentional or an edit error)"}:{check:"Gaps in the program",outcome:"pass",measured:"none"});for(let v of i){if(v.enabled===!1)continue;let T=v.items.filter(x=>x.kind==="clip"&&x.enabled!==!1).map(x=>(n.start_frame??0)+x.timeline_range.start.value+x.timeline_range.duration.value),$=Math.max(...T,-1/0);$>Math.min(k,u)-Math.round(r)&&$<Math.min(k,u)&&l.push({check:`Track ${Sn(v,n.tracks)}`,outcome:"warn",measured:`ends ${Math.min(k,u)-$} frame(s) before the picture ends`,note:"an effect/adjustment layer should cover the whole program"})}if(t.name){let v=RN(t.name),T=v.parts.reduce(($,x)=>$+x.channels,0);if(v.total!=null&&v.parts.length&&T!==v.total)l.push({check:"Name audio",outcome:"fail",measured:t.name,note:`${v.total}CH but ${v.parts.map($=>$.label).join(" + ")} = ${T} channels`});else if(v.parts.length&&d.length){let $=[...d],x=v.parts.filter(R=>{let C=$.findIndex(B=>B.channels===R.channels);return C<0?!0:($.splice(C,1),!1)});l.push({check:"Name audio vs mix",outcome:x.length?"fail":"pass",measured:`${v.parts.map(R=>`${R.label} (${R.channels}ch)`).join(" + ")} = ${T}ch`,note:x.length?`no ${x.map(R=>`${R.channels}ch mix for ${R.label}`).join(", ")} among ${d.map(R=>`${R.file} (${R.channels}ch)`).join(", ")}`:"route each to an output track in this order (host_render audio_tracks), then qc_deliverable the render"})}}return{verdict:l.some(v=>v.outcome==="fail"||v.outcome==="unchecked"&&v.check.startsWith("Mix "))?"STOP":"READY",rows:l,mark_in:s(b),mark_out:s(k-1),program:[b,k],mix:d}}function fx(e){let t={pass:"PASS",fail:"FAIL",warn:"WARN",unchecked:"----"};return[`${e.verdict==="READY"?"READY to render":"STOP: fix before rendering"} \u2014 Mark In ${e.mark_in}, Mark Out ${e.mark_out} (inclusive, ${e.program[1]-e.program[0]} frames)`,...e.rows.map(n=>` ${t[n.outcome]} ${n.check}: ${n.measured??"could not measure"}${n.note?` \u2014 ${n.note}`:""}`)].join(`
|
|
312
|
+
`)}import{basename as Mc}from"node:path";var Sf=["dialogue","music","sfx","other"],$f=["hits","seams","gaps","edges","sync","titles","levels","keys"],Cc=-60,hx=-35,Ac=-30,CN=.5,AN=.5,gx=.12,Ec=2,$r=e=>Math.round(e*10)/10;function EN(e,t,n){if(!e||e.activity<.05||e.flatness>=.46)return null;let r=e.activity*n;return e.onset_rate>=3&&e.pause_rate>=.2&&r>=6?"dialogue":e.onset_rate>=2&&e.pause_rate<.05&&(t?.confidence??0)>=2.5&&r>=6?"music":null}function bx(e,t){for(let i of e){let a=Object.keys(t??{}).find(l=>l.toLowerCase()===i.toLowerCase());if(a)return t[a]}let[n,...r]=e.map(i=>i.toLowerCase().replace(/[_\-.]+/g," ").trim());if(/^(vo|v o|dx|dial(og|ogue)?|dialog(ue)? \d+|voice ?over|narration|narr)( \d+)?$/.test(n))return"dialogue";if(/^(mx|music|score|mus)( \d+)?$/.test(n))return"music";if(/^(fx|sfx|efx|effects?|sound effects?|foley|amb(ience)?|atmos)( \d+)?$/.test(n))return"sfx";let o=[n,...r].join(" "),s=i=>i.test(o);return s(/\b(vo|voice ?over|dial(og|ogue)?|narr(ation|ator)?|interview|lav|boom|speech|sot|pickups?)\b/)?"dialogue":s(/\b(music|score|bed|song|stem|cue|theme|instrumental|epidemic|artlist|premiumbeat|musicbed|audiojungle|soundstripe)\b/)?"music":s(/\b(sfx|whoosh|hit|riser|impact|foley|stinger|swoosh|transitions?|ambience|atmos|room ?tone|cinetransitions?)\b/)?"sfx":null}function MN(e){if(!e)return null;let[t,...n]=e.split("."),r=t.trim().toLowerCase();return r==="dialogue"?"dialogue":r==="music"?"music":r==="effects"?"sfx":bx([t,n.join(" ")])}var IN=-60;function PN(e){let t=e?.local_path??e?.target_url?.replace(/^file:\/\//,"");return t?decodeURIComponent(t):null}function FN(e,t,n,r){let o=t.start_frame??0,s=new Map((e.media_references??[]).map(a=>[a.id,a])),i=[];for(let a of t.tracks??[]){if(a.kind!=="Audio"||a.enabled===!1)continue;let l=Sn(a,t.tracks);for(let c of a.items??[]){if(c.kind!=="clip"||c.enabled===!1||!c.timeline_range?.duration?.value)continue;let u=c.media_reference_id?s.get(c.media_reference_id):void 0,d=PN(u),p=c.name??(d?Mc(d):c.id),f=c.source_range?.start.rate||n,h=(c.speed??100)/100*(c.speed_reverse?-1:1),g=o+c.timeline_range.start.value,b=g+c.timeline_range.duration.value,k=bx([l,p,d?Mc(d):""],r),w=MN(c.audio_role),y=k??w,_=k==null&&w!=null&&/^dialogue(\.dialogue-\d+)?$/i.test(c.audio_role??"");i.push({it:c,track:a,label:l,role:y??"other",named:y!=null,hostDefault:_,muted:(c.audio_gain_db??0)<=IN,path:d,name:p,s:g,e:b,src0:(c.source_range?.start.value??0)/f,speed:h||1,gain:c.audio_gain_db??0,fade_in:c.fade_in?.duration_frames??0,fade_out:c.fade_out?.duration_frames??0})}}return i.sort((a,l)=>a.s-l.s)}var ur=(e,t,n)=>e.src0+(t-e.s)/n*e.speed,ha=(e,t,n)=>e.s+(t-e.src0)/e.speed*n;function mo(e,t,n){let r=e.sound;if(!r)return-120;let o=ur(e,t,n),s=ur(e,t+1,n);o>s&&([o,s]=[s,o]);let i=Math.max(0,Math.floor(o/r.hop)),a=Math.min(r.rms_db.length,Math.max(i+1,Math.ceil(s/r.hop))),l=-120;for(let c=i;c<a;c++)r.rms_db[c]>l&&(l=r.rms_db[c]);return l+e.gain}function Tf(e,t,n){let r=e.sound;if(!r)return[];let[o,s]=[Math.min(ur(e,e.s,t),ur(e,e.e,t)),Math.max(ur(e,e.s,t),ur(e,e.e,t))];return r.onsets.filter(([i,a])=>a>=n&&i>=o&&i<s).map(([i,a])=>({frame:Math.round(ha(e,i,t)),strength:a}))}function xf(e,t,n){let r=[],o=-1;for(let s=0;s<=e.length;s++){let i=s<e.length&&e[s]===1;i&&o<0&&(o=s),!i&&o>=0&&(s-o>=n&&r.push([t+o,t+s]),o=-1)}return r}async function yx(e,t={}){let n=Ws(e,t.timeline_id),r=Pt(n),o=!!n.is_drop_frame,s=W=>He(Math.round(W),r,o),i=n.start_frame??0,a=new Set(t.checks?.length?t.checks:$f),l=t.hit_tolerance??4,c=Math.max(1,Math.round((t.dead_air??.5)*r)),u=t.level_spread??6,d=FN(e,n,r,t.roles),p=new Map((e.media_references??[]).map(W=>[W.id,W])),f=new Map;for(let W of d)W.path&&(f.get(W.path)??f.set(W.path,[]).get(W.path)).push(W);let h=[],g=[],b=[...f.keys()],k=0,w=async()=>{for(;k<b.length;){let W=b[k++],ne=f.get(W),z=a.has("levels")?ne.map(q=>{let[j,I]=[ur(q,q.s,r),ur(q,q.e,r)];return[Math.max(0,Math.min(j,I)),Math.abs(I-j)]}):[];try{let q=await qt({op:"sound",path:W,windows:z});ne.forEach((j,I)=>{if(j.sound=q,j.window=z.length?I:void 0,j.muted)return;let S=EN(q.profile,q.tempo,q.duration);j.named?j.hostDefault&&(S==="music"||q.profile&&(q.profile.flatness>=.46||q.profile.activity<.05))&&(j.role=S??"other"):j.role=S??"other"}),q.tempo&&ne.some(j=>j.role==="music"&&!j.muted)&&g.push({file:Mc(W),bpm:q.tempo.bpm,confidence:q.tempo.confidence})}catch(q){h.push(`${Mc(W)}: ${q instanceof Error?q.message:String(q)}`)}}};await Promise.all(Array.from({length:Math.min(3,b.length)},w));let y=d.filter(W=>W.sound&&!W.muted),_=(n.tracks??[]).filter(W=>W.kind==="Video"),v=lo(n,_),T=[],$=new Set;for(let W of _){if(W.enabled===!1)continue;let ne=q=>!!q.title||(q.media_reference_id?p.get(q.media_reference_id)?.kind==="generator":!1),z=(W.items??[]).filter(q=>q.kind==="clip"&&q.enabled!==!1&&q.timeline_range.duration.value>0&&!ne(q)).sort((q,j)=>q.timeline_range.start.value-j.timeline_range.start.value);z.forEach((q,j)=>{let I=i+q.timeline_range.start.value,S=I+q.timeline_range.duration.value;$.has(I)||($.add(I),T.push({frame:I,kind:"cut",name:q.name??q.id}));let A=z[j+1];!$.has(S)&&(!A||i+A.timeline_range.start.value>S)&&v.some(U=>U.s===S)&&($.add(S),T.push({frame:S,kind:"cut",name:`out of ${q.name??q.id}`}))})}let x=[];for(let W of _)for(let ne of W.items??[]){if(ne.kind!=="clip"||ne.enabled===!1)continue;let z=ne.media_reference_id?p.get(ne.media_reference_id):void 0;if(ne.title||z?.kind==="generator"){let q=i+ne.timeline_range.start.value;x.push({s:q,e:q+ne.timeline_range.duration.value,name:ne.title?.text?.split(`
|
|
313
|
+
`)[0]??ne.name??ne.id}),$.has(q)||($.add(q),T.push({frame:q,kind:"title",name:ne.title?.text?.split(`
|
|
314
|
+
`)[0]??ne.name??ne.id}))}}T.sort((W,ne)=>W.frame-ne.frame);let R=Math.min(...d.map(W=>W.s),...v.map(W=>W.s),i),B=Math.max(...d.map(W=>W.e),...v.map(W=>W.e),i+1)-R,L=[],Z=[],X={verdict:"CLEAN",timeline:n.name??n.id,fps:r,files:b.length,clips:d.length,unreadable:h,roles:{dialogue:0,music:0,sfx:0,other:0},muted:0,tempo:g,rows:L,findings:Z,cuts:[],hits:[],seams:[],sync:[],titles:[],levels:[],ops:[]};for(let W of d)X.roles[W.role]++;X.muted=d.filter(W=>W.muted).length;let O=W=>Z.push({...W,record_tc:s(W.frame)}),ae=(W,ne,z,q)=>L.push({check:W,outcome:ne,measured:z,note:q});if(a.has("hits")){let W=[];for(let S of y)if(S.role==="music"||S.role==="sfx"){let A=Tf(S,r,CN),U=A.length/Math.max(1,(S.e-S.s)/r)<=AN;for(let de of A)W.push({record_tc:s(de.frame),frame:de.frame,track:S.label,clip:S.name,strength:Math.round(de.strength*100)/100,nearest_cut:null,sparse:U})}W.sort((S,A)=>S.frame-A.frame);let ne=S=>{let A=null;for(let U of y)if(U.role==="music"&&U.s<=S&&S<U.e&&U.sound.beats.length)for(let de of U.sound.beats){let te=ha(U,de,r);(A==null||Math.abs(te-S)<Math.abs(A))&&(A=te-S)}return A},z=0,q=0,j=0,I=0;for(let S of T){let A=null;for(let _e of W)(!A||Math.abs(_e.frame-S.frame)<Math.abs(A.frame-S.frame))&&(A=_e);let U=A?A.frame-S.frame:null,de=U==null?"none":Math.abs(U)<=1?"on":Math.abs(U)<=l&&A.sparse?"near":"none",te=ne(S.frame);te!=null&&(j++,Math.abs(te)<=1&&I++),X.cuts.push({record_tc:s(S.frame),frame:S.frame,kind:S.kind,name:S.name,hit_tc:A?A.record_tc:null,delta:U,verdict:de,beat:te==null?null:Math.round(te*10)/10}),de==="on"&&z++,de==="near"&&(q++,O({check:"hits",severity:"warn",frame:S.frame,frames:1,track:A.track,clip:A.clip,note:`${S.kind==="title"?"title":"cut"} "${S.name}" is ${Math.abs(U)} fr ${U>0?"before":"after"} the hit at ${A.record_tc}`}))}for(let S of W){let A=null;for(let U of T){let de=Math.abs(U.frame-S.frame);(A==null||de<A)&&(A=de)}S.nearest_cut=A}X.hits=W.filter(S=>S.sparse&&(S.nearest_cut==null||S.nearest_cut>l)).sort((S,A)=>A.strength-S.strength).slice(0,12).sort((S,A)=>S.frame-A.frame).map(({sparse:S,...A})=>A),ae("Hits on cuts",q?"warn":"pass",`${z} of ${T.length} cut(s)/title(s) on a hit, ${q} near miss(es), ${W.length} hit(s) in music/SFX${j?`; ${I} of ${j} cut(s) under music on the beat`:""}`,X.hits.length?`${X.hits.length} strong hit(s) no cut uses`:void 0)}if(a.has("seams")){let W=y.filter(z=>z.role==="music").sort((z,q)=>z.s-q.s),ne=0;for(let z of W)for(let q of W){if(q===z||z.s>q.e+1||z.s<q.e-2*r||z.s<=q.s)continue;let j=z.s<q.e-1||q.fade_out>=Ec||z.fade_in>=Ec,I=Math.round(r),S=pe=>10*Math.log10(pe.reduce((xe,ve)=>xe+Math.pow(10,ve/10),0)/Math.max(1,pe.length)),A=S(Array.from({length:Math.min(I,q.e-q.s)},(pe,xe)=>mo(q,q.e-1-xe,r))),U=S(Array.from({length:Math.min(I,z.e-z.s)},(pe,xe)=>mo(z,z.s+xe,r))),de=A>Cc&&U>Cc?$r(U-A):null,te=null,_e=q.sound.beats.map(pe=>ha(q,pe,r)).filter(pe=>pe>=q.s&&pe<q.e),Se=z.sound.beats.map(pe=>ha(z,pe,r)).filter(pe=>pe>=z.s&&pe<z.e);if(q.sound.tempo&&z.sound.tempo&&_e.length>=2&&Se.length){let pe=60/q.sound.tempo.bpm*r/Math.abs(q.speed),xe=_e[_e.length-1],ve=Se[0],Oe=Math.round((ve-xe)/pe);te=$r(ve-(xe+Oe*pe))}let H={record_tc:s(z.s),track:z.label,out:q.name,in:z.name,level_jump_db:de,beat_offset_frames:te,bpm_out:q.sound.tempo?.bpm??null,bpm_in:z.sound.tempo?.bpm??null,crossfade:j};X.seams.push(H);let le=[];de!=null&&Math.abs(de)>=6&&!j&&le.push(`level ${de>0?"jumps up":"drops"} ${Math.abs(de)} dB across the join (no crossfade)`),te!=null&&Math.abs(te)>Math.max(2,.25*(60/(q.sound.tempo?.bpm??120))*r)&&le.push(`join is ${Math.abs(te)} fr ${te>0?"late":"early"} of the beat`),H.bpm_out&&H.bpm_in&&Math.abs(H.bpm_out-H.bpm_in)/H.bpm_out>.03&&le.push(`tempo ${H.bpm_out} \u2192 ${H.bpm_in} BPM`),le.length&&(ne++,O({check:"seams",severity:"warn",frame:z.s,frames:1,track:z.label,clip:`${q.name} \u2192 ${z.name}`,note:le.join("; ")}))}ae("Music seams",ne?"warn":"pass",`${X.seams.length} join(s), ${ne} flagged`)}if(a.has("gaps")){let W=new Uint8Array(B),ne=new Uint8Array(B),z=new Uint8Array(B);for(let te of v)for(let _e=te.s;_e<te.e;_e++)z[_e-R]=1;for(let te of y)for(let _e=te.s;_e<te.e;_e++)mo(te,_e,r)>Cc&&(W[_e-R]=1,te.role==="music"&&(ne[_e-R]=1));let q=new Uint8Array(B);for(let te=0;te<B;te++)q[te]=z[te]&&!W[te]?1:0;let j=y.length?xf(q,R,c):[];for(let[te,_e]of j)O({check:"gaps",severity:"warn",frame:te,frames:_e-te,track:"",clip:"",note:`dead air: ${_e-te} fr of picture with no sound (${s(te)}\u2013${s(_e-1)})`});let I=-1,S=-1;for(let te=0;te<B;te++)ne[te]&&(I<0&&(I=te),S=te);let A=new Uint8Array(B);if(I>=0)for(let te=I;te<=S;te++)A[te]=ne[te]?0:1;let U=xf(A,R,Math.round(r));for(let[te,_e]of U)O({check:"gaps",severity:"warn",frame:te,frames:_e-te,track:"",clip:"",note:`music drops out for ${_e-te} fr (${s(te)}\u2013${s(_e-1)})`});let de=0;for(let te of y)if(te.role==="dialogue"){let _e=new Uint8Array(te.e-te.s);for(let Se=te.s;Se<te.e;Se++)_e[Se-te.s]=mo(te,Se,r)<=Cc+10?1:0;for(let[Se,H]of xf(_e,te.s,Math.round(1.5*r)))de++,O({check:"gaps",severity:"info",frame:Se,frames:H-Se,track:te.label,clip:te.name,note:`${$r((H-Se)/r)} s of silence inside the dialogue clip`})}ae("Dead air and holes",j.length||U.length?"warn":"pass",`${j.length} dead air run(s) \u2265 ${c} fr, ${U.length} music hole(s) \u2265 1 s, ${de} long pause(s) in dialogue`)}if(a.has("edges")){let W=0,ne=0;for(let z of new Set(y.map(q=>q.track.id))){let q=y.filter(j=>j.track.id===z).sort((j,I)=>j.s-I.s);for(let j=0;j<q.length;j++){let I=q[j],S=q[j-1],A=q[j+1],U=(_e,Se)=>!!_e&&!!Se&&_e.path===Se.path&&_e.e===Se.s&&Math.abs(ur(_e,_e.e,r)-ur(Se,Se.s,r))*r<1,de=mo(I,I.s,r),te=mo(I,I.e-1,r);de>hx&&I.fade_in<Ec&&!U(S,I)&&(W++,O({check:"edges",severity:"warn",frame:I.s,frames:1,track:I.label,clip:I.name,note:`starts inside sound (${$r(de)} dBFS) with no fade in`})),te>hx&&I.fade_out<Ec&&!U(I,A)&&(W++,O({check:"edges",severity:I.role==="dialogue"&&te>Ac?"fail":"warn",frame:I.e-1,frames:1,track:I.label,clip:I.name,note:I.role==="dialogue"&&te>Ac?`ends inside speech (${$r(te)} dBFS): a word is cut on the frame`:`ends inside sound (${$r(te)} dBFS) with no fade out`})),I.role==="dialogue"&&Tf(I,r,gx).find(Se=>Se.frame-I.s<=1&&Se.frame>=I.s)&&(ne++,O({check:"edges",severity:"info",frame:I.s,frames:1,track:I.label,clip:I.name,note:"speech starts on the cut (no breath before the first word)"}))}}ae("Clip edges",W?"warn":"pass",`${W} hard edge(s) in sound, ${ne} dialogue clip(s) starting on a word`)}if(a.has("sync")){let W=[];for(let z of _)for(let q of z.items??[])if(q.kind==="clip"&&q.enabled!==!1&&q.media_reference_id){let j=q.source_range?.start.rate||r,I=(q.speed??100)/100*(q.speed_reverse?-1:1)||1,S=i+q.timeline_range.start.value;W.push({it:q,s:S,e:S+q.timeline_range.duration.value,ref:q.media_reference_id,src0:(q.source_range?.start.value??0)/j,speed:I,name:q.name??q.id})}let ne=0;for(let z of d){if(!z.it.media_reference_id)continue;let q=W.filter(A=>A.ref===z.it.media_reference_id&&A.s<z.e&&z.s<A.e).sort((A,U)=>Math.abs(A.s-z.s)-Math.abs(U.s-z.s))[0];if(!q||(z.it.speed_ramped||q.it.speed_ramped)&&q.s!==z.s)continue;let j=Math.max(z.s,q.s),I=ur(z,j,r)-(q.src0+(j-q.s)/r*q.speed),S=Math.round(I*r);X.sync.push({record_tc:s(z.s),track:z.label,clip:z.name,picture:q.name,lead_frames:q.s-z.s,trail_frames:z.e-q.e,source_offset_frames:S}),S!==0&&z.speed===q.speed&&(ne++,O({check:"sync",severity:"fail",frame:j,frames:Math.min(z.e,q.e)-j,track:z.label,clip:z.name,note:`sound is ${Math.abs(S)} fr ${S>0?"ahead of":"behind"} its picture "${q.name}" (source offset)`}))}ae("Sound vs picture",ne?"fail":"pass",`${X.sync.length} clip(s) with their own picture, ${ne} out of sync`,X.sync.some(z=>z.lead_frames||z.trail_frames)?`${X.sync.filter(z=>z.lead_frames>0).length} J-cut(s), ${X.sync.filter(z=>z.trail_frames>0).length} L-cut(s)`:void 0)}if(a.has("titles")){let W=y.filter(q=>q.role==="dialogue"),ne=W.flatMap(q=>Tf(q,r,gx).map(j=>j.frame)).sort((q,j)=>q-j),z=q=>W.some(j=>j.s<=q&&q<j.e&&mo(j,q,r)>Ac);for(let q of x){let j=null;for(let I of ne){let S=I-q.s;(j==null||Math.abs(S)<Math.abs(j))&&(j=S)}X.titles.push({record_tc:s(q.s),end_tc:s(q.e-1),name:q.name,words_at_start:z(q.s),words_at_end:z(q.e-1),nearest_word:j})}x.length&&ae("Titles vs dialogue","pass",`${x.length} title(s); ${X.titles.filter(q=>q.nearest_word!=null&&Math.abs(q.nearest_word)<=2).length} start on a word, ${X.titles.filter(q=>q.words_at_end).length} end mid-speech`)}if(a.has("levels")){let W=y.map(z=>{let q=z.window!=null?z.sound.windows[z.window]:void 0;return{record_tc:s(z.s),track:z.label,clip:z.name,role:z.role,lufs:q?.lufs!=null?$r(q.lufs+z.gain):null,gain_db:z.gain,peak_db:q?.peak_db!=null?$r(q.peak_db+z.gain):null,vs_role:null}}),ne=0;for(let z of Sf){let q=W.filter(I=>I.role===z&&I.lufs!=null).map(I=>I.lufs).sort((I,S)=>I-S);if(q.length<3)continue;let j=q[Math.floor(q.length/2)];for(let I of W)if(I.role===z&&I.lufs!=null&&(I.vs_role=$r(I.lufs-j),Math.abs(I.vs_role)>=u)){ne++;let S=y.find(A=>A.name===I.clip&&s(A.s)===I.record_tc);O({check:"levels",severity:"warn",frame:S.s,frames:S.e-S.s,track:S.label,clip:S.name,note:`${I.lufs} LUFS, ${Math.abs(I.vs_role)} LU ${I.vs_role>0?"above":"below"} the ${z} median (${j})`})}}X.levels=W,ae("Clip levels",ne?"warn":"pass",`${W.filter(z=>z.lufs!=null).length} clip(s) measured, ${ne} \u2265 ${u} LU from their role`)}if(a.has("keys")){let W=0;for(let ne of y)if(ne.role==="dialogue")for(let z of ne.it.keyframes??[]){if(!/gain|volume|level/i.test(z.parameter_path))continue;let q=Math.round(ha(ne,z.time.value/(z.time.rate||r),r));q<ne.s||q>=ne.e||mo(ne,q,r)>Ac&&(W++,O({check:"keys",severity:"info",frame:q,frames:1,track:ne.label,clip:ne.name,note:`gain keyframe (${z.parameter_path}) sits inside speech`}))}ae("Gain keys in speech","pass",`${W} key(s) inside speech`)}if(Z.sort((W,ne)=>W.frame-ne.frame),h.length&&ae("Files read",y.length?"warn":"fail",`${b.length-h.length} of ${b.length} file(s)`,h.join("; ")),X.verdict=Z.some(W=>W.severity!=="info")||L.some(W=>W.outcome==="fail")?"CHECK":"CLEAN",t.markers??!0){let W={fail:"Red",warn:"Yellow",info:"Blue"};for(let ne of Z)X.ops.push({op:"marker_add",frame:ne.frame,...ne.frames>1?{duration:ne.frames}:{},color:W[ne.severity],name:`Sound: ${ne.check}${ne.clip?` ${ne.clip}`:""}`,note:ne.note,data:"ConformTools:sound"})}return X}function wx(e){let t=`${e.verdict}: ${e.timeline} @ ${$r(e.fps)} \u2014 ${e.clips} audio clip(s) in ${e.files} file(s) (dialogue ${e.roles.dialogue}, music ${e.roles.music}, sfx ${e.roles.sfx}, other ${e.roles.other}${e.muted?`; ${e.muted} muted`:""})${e.tempo.length?`; tempo ${e.tempo.map(a=>`${a.file} ${a.bpm} BPM`).join(", ")}`:""}`,n={pass:"\u2713",warn:"!",fail:"\u2717"},r=[t,...e.rows.map(a=>` ${n[a.outcome]} ${a.check}: ${a.measured??""}${a.note?` \u2014 ${a.note}`:""}`)],o=e.findings.filter(a=>a.severity!=="info");o.length&&r.push("findings:",...o.slice(0,40).map(a=>` ${a.record_tc} ${a.severity.toUpperCase()} [${a.check}]${a.track?` ${a.track}`:""}${a.clip?` ${a.clip}`:""}: ${a.note}`)),o.length>40&&r.push(` \u2026 ${o.length-40} more in the structured result`);let s=e.findings.length-o.length;s&&r.push(`${s} informational finding(s) in the structured result`);let i=e.cuts.filter(a=>a.verdict!=="none");return i.length&&r.push("cuts and hits:",...i.slice(0,24).map(a=>` ${a.record_tc} ${a.kind} ${a.name}: hit ${a.delta===0?"on the frame":`${Math.abs(a.delta)} fr ${a.delta>0?"after":"before"}`}${a.verdict==="near"?" (near miss)":""}`)),e.hits.length&&r.push("strong hits no cut uses:",...e.hits.map(a=>` ${a.record_tc} ${a.track} ${a.clip} (${a.strength})`)),e.sync.some(a=>a.lead_frames||a.trail_frames)&&r.push("split edits:",...e.sync.filter(a=>a.lead_frames||a.trail_frames).slice(0,24).map(a=>` ${a.record_tc} ${a.track} ${a.clip}: ${a.lead_frames>0?`J-cut, sound leads ${a.lead_frames} fr`:a.lead_frames<0?`sound in ${-a.lead_frames} fr after picture`:"head together"}; ${a.trail_frames>0?`L-cut, sound trails ${a.trail_frames} fr`:a.trail_frames<0?`sound out ${-a.trail_frames} fr before picture`:"tail together"}`)),e.titles.length&&r.push("titles:",...e.titles.map(a=>` ${a.record_tc}\u2013${a.end_tc} "${a.name}": ${a.nearest_word==null?"no words near":a.nearest_word===0?"a word starts on its first frame":`nearest word ${Math.abs(a.nearest_word)} fr ${a.nearest_word>0?"after":"before"} it`}${a.words_at_start?", speech under its start":""}${a.words_at_end?", speech under its end":""}`)),e.ops.length&&r.push(`host_apply ops ready: ${e.ops.length} markers (data "ConformTools:sound")`),r.join(`
|
|
315
|
+
`)}import{basename as kx}from"node:path";async function _x(e,t=16){let n=await st(e),r=n.streams?.find(_=>_.kind==="video"),o=r?.width??0,s=r?.height??0,i=n.available_range?.duration.value??0;if(!o||!s)throw new Error(`${kx(e)}: no raster in the probe`);let a=await qt({op:"aspect",path:e,samples:t,frames:i||void 0}),l=a.w,c=a.h,u=a.active??{x:0,y:0,w:l,h:c},d=o/l,p=s/c,f={x:Math.round(u.x*d),y:Math.round(u.y*p),w:Math.round(u.w*d),h:Math.round(u.h*p)},h=f.h<s-2,g=f.w<o-2,b=h&&g?"windowbox":h?"letterbox":g?"pillarbox":"none",k=f.w/f.h,w=_=>2*Math.round(_/2),y=b==="pillarbox"?`${w(s*k)}x${s}`:`${o}x${w(o/k)}`;return{file:kx(e),width:o,height:s,frames_sampled:a.sampled,active:f,boxing:b,aspect:+k.toFixed(4),aspect_name:a.name??k.toFixed(2),oar_raster:b==="none"?`${o}x${s}`:y}}function vx(e){return`${e.boxing==="none"?`${e.file}: full ${e.width}x${e.height} raster is picture \u2192 OAR ${e.aspect_name}, no boxing`:`${e.file}: ${e.boxing}: active picture ${e.active.w}x${e.active.h} at (${e.active.x},${e.active.y}) inside ${e.width}x${e.height} \u2192 OAR ${e.aspect_name}; OAR raster ${e.oar_raster}`}
|
|
316
|
+
(${e.frames_sampled} frames sampled across the clip; a bar counts only when \u226580% of them carry it)`}var Rx=/lower ?thirds?|\bLTs?\b|titles?|subtitles?|\bsubs\b|captions?|graphics?|\bgfx\b|\btext\b|supers?/i,_n=e=>[e.timeline_range.start.value,e.timeline_range.start.value+e.timeline_range.duration.value],Tx=e=>Rx.test(e.name??"")||e.items.some(t=>t.kind!=="gap")&&e.items.every(t=>t.kind==="gap"||!!t.title),ga=e=>e.enabled!==!1&&(e.kind==="clip"||e.kind==="nested"),xx=e=>`V${e.track_index}${e.name?` "${e.name}"`:""}`,ON=/\b(TEXTED|TEXTLESS|MASTER|MEZZ(ANINE)?)(\b|_)/i,Sx=300,LN=60;function Cx(e,t,n={}){let r=e.timelines.filter(O=>O.kind!=="compound"),o=n.timeline_id?r.find(O=>O.id===n.timeline_id):r.find(O=>O.tracks.some(ae=>ae.kind==="Video"&&ae.items.length));if(!o)throw new P("not_found",n.timeline_id?`no timeline ${n.timeline_id} in this session`:"the session has no timeline with video");if(!t.length)throw new P("invalid_args","changes is empty: give clip ids or record ranges");let s=Pt(o),i=o.start_frame??0,a=!!o.is_drop_frame,l=O=>He(O+i,s,a),c=[],u=o.tracks.filter(O=>O.kind==="Video"&&O.enabled!==!1).sort((O,ae)=>ae.track_index-O.track_index),d=new Set,p=(O,ae)=>u.some(W=>W.track_index<O.track_index&&W.items.some(ne=>ga(ne)&&_n(ne)[0]<_n(ae)[1]&&_n(ne)[1]>_n(ae)[0]));for(let O of u)for(let ae of O.items)!ga(ae)||ae.title||(ON.test(ae.name??"")||ae.timeline_range.duration.value>=Sx*s&&p(O,ae))&&d.add(ae);d.size&&c.push(`baked picture (a laid-back master, or a clip of ${Sx/60} min or more) left out of the cut points, the edits under it decide: ${[...d].map(O=>`"${O.name??O.id}" ${l(_n(O)[0])}\u2013${l(_n(O)[1]-1)}`).join(", ")}`);let f=O=>ga(O)&&!d.has(O),h=u.filter(Tx),g=u.filter(O=>!Tx(O));for(let O of o.tracks)O.kind==="Video"&&O.enabled===!1&&Rx.test(O.name??"")&&O.items.some(ga)&&c.push(`${xx(O)} is a graphics track but disabled: left out of TEXTED too; enable it if the master carries it`);let b=Math.max(0,...u.flatMap(O=>O.items.filter(ga).map(ae=>_n(ae)[1]))),k=new Set([0,b]);for(let O of g)for(let ae of O.items)f(ae)&&_n(ae).forEach(W=>k.add(W));let w=[...k].filter(O=>O>=0&&O<=b).sort((O,ae)=>O-ae),y=[];for(let O=0;O+1<w.length;O++){let[ae,W]=[w[O],w[O+1]],ne={start:ae,end:W,item:null,track:null};for(let q of g){let j=q.items.find(I=>f(I)&&_n(I)[0]<=ae&&_n(I)[1]>=W);if(j){ne={start:ae,end:W,item:j,track:q};break}}let z=y[y.length-1];z&&z.item===ne.item?z.end=W:y.push(ne)}let _=[...h.flatMap(O=>O.items.filter(f).map(_n)),...u.flatMap(O=>O.items.filter(ae=>ae.kind==="transition").map(_n))],v=new Set([0,b,...y.map(O=>O.start)].filter(O=>!_.some(([ae,W])=>ae<O&&O<W))),T=O=>Math.max(...[...v].filter(ae=>ae<=O)),$=O=>Math.min(...[...v].filter(ae=>ae>=O)),x=O=>y.find(ae=>ae.start<=O&&O<ae.end),R=new Map(o.tracks.flatMap(O=>O.items.map(ae=>[ae.id,ae]))),C=O=>{if(typeof O=="number")return O-i;let ae=At(O,s);if(ae==null){if(/^\d+$/.test(O))return Number(O)-i;throw new P("invalid_args",`cannot read '${O}' as a record timecode`)}return ae-i},B=t.map(O=>{if(typeof O=="string"){let ne=R.get(O);if(!ne)throw new P("not_found",`no clip ${O} on ${o.name} (item ids come from timeline_query)`);return[..._n(ne)]}let[ae,W]=[C(O.in),C(O.out)+1];if(W<=ae)throw new P("invalid_args",`range ${O.in}..${O.out} is empty or backwards`);return[ae,W]}).sort((O,ae)=>O[0]-ae[0]);for(let[O,ae]of B)if(O<0||ae>b)throw new P("invalid_args",`change ${l(O)}\u2013${l(ae-1)} is outside the timeline (${l(0)}\u2013${l(b-1)})`);let L=[];for(let[O,ae]of B){let W=O>0?x(O-1):void 0,ne=ae<b?x(ae):void 0,z=T(W?.item?W.start:O),q=$(ne?.item?ne.end:ae),j=L[L.length-1];j&&z<=j.tail?(j.tail=Math.max(j.tail,q),j.changes.push([O,ae])):L.push({head:z,tail:q,changes:[[O,ae]]})}let Z=O=>O.item?O.item.name??O.item.reel_name??O.item.id:"(black)",X=L.map((O,ae)=>{let W=y.filter(A=>A.end>O.head&&A.start<O.tail),ne=A=>O.changes.some(([U,de])=>A.end>U&&A.start<de),z=W.findIndex(ne),q=W.length-1-[...W].reverse().findIndex(ne),j=W.map((A,U)=>({role:ne(A)?"changed":U===z-1?"before":U===q+1?"after":"inside",name:Z(A),track:A.track?xx(A.track):"-",rec_in_tc:l(A.start),frames:A.end-A.start})),I=h.filter(A=>A.items.some(U=>f(U)&&_n(U)[1]>O.head&&_n(U)[0]<O.tail)),S=[];for(let A of j)(A.role==="before"||A.role==="after")&&A.frames>LN*s&&S.push(`the ${A.role} clip "${A.name}" runs ${Math.round(A.frames/s)} s: check it is a real shot, not baked picture`);return j.some(A=>A.role==="before")||S.push("no clip before the change (timeline head or black): starts on the change"),j.some(A=>A.role==="after")||S.push("no clip after the change (timeline tail or black): ends on the change"),I.length||S.push("no graphics in range: one render serves TEXTED and TEXTLESS"),{nn:(n.first_patch??1)+ae,range:{in:O.head+i,out:O.tail-1+i},frames:O.tail-O.head,rec_in_tc:l(O.head),rec_out_tc:l(O.tail-1),start_tc:l(O.head),versions:I.length?["TEXTED","TEXTLESS"]:["TEXTED"],textless_exclude_tracks:I.map(A=>({index:A.track_index,name:A.name??null})),audio:!1,neighbours:j,notes:S}});return{timeline:o.name,fps:s,start_tc:l(0),patches:X,warnings:c}}function Ax(e){let t=`${e.patches.length} patch${e.patches.length===1?"":"es"} on ${e.timeline}: `+e.patches.map(r=>`PATCH${String(r.nn).padStart(2,"0")} ${r.rec_in_tc}\u2013${r.rec_out_tc} (${r.frames} fr, ${r.versions.join("+")})`).join("; "),n=e.patches.flatMap(r=>[`PATCH${String(r.nn).padStart(2,"0")}: record ${r.rec_in_tc}\u2013${r.rec_out_tc} inclusive, ${r.frames} frames; host_render range {in:${r.range.in}, out:${r.range.out}}; file TC ${r.start_tc}; picture only`,...r.neighbours.map(o=>` ${o.role.padEnd(7)} ${o.rec_in_tc} ${String(o.frames).padStart(5)} fr ${o.track} ${o.name}`),r.textless_exclude_tracks.length?` TEXTLESS: leave out ${r.textless_exclude_tracks.map(o=>`V${o.index}${o.name?` "${o.name}"`:""}`).join(", ")}`:"",...r.notes.map(o=>` note: ${o}`)].filter(Boolean));return[t,...n,...e.warnings.map(r=>`warning: ${r}`)].join(`
|
|
317
|
+
`)}function $x(e){let t=e.streams?.find(r=>r.kind==="video"),n=t?.codec_specific??{};return{codec:t?.codec,fourcc:n.fourcc,profile:n.profile,pixel_format:n.pixel_format,bit_depth:t?.bit_depth,raster:t?.width?`${t.width}x${t.height}`:void 0,fps:Math.round((e.source_fps??t?.rate??0)*1e3)/1e3,colour:n.colr?`${n.colr.primaries}/${n.colr.transfer}/${n.colr.matrix}`:void 0}}async function Rf(e,t,n){return(await qt({op:"hashes",path:e,from:t,count:n})).hashes.map(o=>o??void 0)}async function NN(e){let t=Math.max(2,Math.round(e.fps*2)),n=[];for(let[r,o]of[["head",e.offset],["tail",e.offset+e.frames]]){let s=Math.max(0,o-t),i=Math.min(e.mframes,o+t),a=i-s;if(a<=0)continue;let l=await Rf(e.master,s,a),c=Math.max(s,e.offset),u=Math.min(i,e.offset+e.frames),d=u>c?await Rf(e.patch,c-e.offset,u-c):[],p=e.original?await Rf(e.original,s,a):null,f=0,h=0,g=0,b=0;l.forEach((w,y)=>{let _=s+y;_>=c&&_<u?(h++,(!w||w!==d[_-c])&&f++):p&&(b++,(!w||w!==p[y])&&g++)});let k=l.filter(w=>!w).length;n.push({seam:r,tc:He(e.master_tc+o,e.fps),frames:[s,i-1],inside:h?f?`${f}/${h} frames differ from the patch`:`${h} frames = the patch`:"\u2014",outside:p?g?`${g}/${b} frames differ from the original`:`${b} frames = the original`:"no original given (pass original= a backup to prove the neighbours)",undecoded:k,ok:!f&&!g&&!k})}return n}async function Ex(e,t){let[n,r]=await Promise.all([st(e.patch),st(e.master)]),o=$x(n),s=$x(r),i=Object.keys(o).map(_=>({field:_,patch:o[_],master:s[_],ok:o[_]===s[_]})),a=n.available_range?.duration.value??n.declared_duration?.value??0,l=r.available_range?.duration.value??r.declared_duration?.value??0,c=o.fps||s.fps,u=[];e.expected_frames!=null&&u.push({what:"frames",ok:a===e.expected_frames,detail:`${a} frames, expected ${e.expected_frames}`});let d=n.source_timecode??null,p=r.source_timecode??null;e.expected_tc&&u.push({what:"start TC",ok:d!=null&&At(d,c)===At(e.expected_tc,c),detail:`starts ${d??"with no TC"}, expected ${e.expected_tc}`});let f=n.streams?.filter(_=>_.kind==="audio").length??0;u.push({what:"picture only",ok:f===0,detail:f?`${f} audio track(s)`:"no audio"});let h=null,g=[],b=[],k=d?At(d,c):null,w=p?At(p,c):null;if(k==null||w==null)u.push({what:"position in master",ok:!1,detail:"no start TC on the patch or the master: cannot place it"});else if(k-w<0||k-w+a>l)u.push({what:"position in master",ok:!1,detail:`${d} + ${a} fr is outside the master (${p}, ${l} fr)`});else{h=k-w,u.push({what:"position in master",ok:!0,detail:`master frames ${h}\u2013${h+a-1}`});let _=await qt({op:"patch",patch:e.patch,master:e.master,offset:h,frames:a,tolerance:e.tolerance??10},t);for(let T of _.mismatches)g.push({...T,tc:He((k??0)+T.frame,c)});for(let T of _.shotChanges)b.push(He((k??0)+T,c));let v=_.undecoded;v&&u.push({what:"decode",ok:!1,detail:`${v} patch frame(s) did not decode`}),u.push({what:"picture vs master",ok:!g.length,detail:g.length?`${g.length}/${a} frames differ (first ${g[0].tc})`:`all ${a} frames match at the same TC`})}let y;if(h!=null)try{y=await NN({master:e.master,patch:e.patch,original:e.original,offset:h,frames:a,mframes:l,fps:c,master_tc:w??0});let _=y.filter(T=>!T.ok);y.length&&y.every(T=>/^(\d+)\/\1 frames differ from the patch$/.test(T.inside)&&!T.undecoded)?(u.push({what:"seam decode",ok:!0,detail:"not spliced yet: the master still has its own frames in the span; run patch_verify again after media_patch"}),y=void 0):u.push({what:"seam decode",ok:!_.length,detail:_.length?_.map(T=>`${T.seam} ${T.tc}: ${[T.inside,T.outside,T.undecoded?`${T.undecoded} undecoded`:""].filter(Boolean).join("; ")}`).join(" | "):`${y.length} seam(s): every frame decodes and matches${e.original?"":" the patch (neighbours unchecked: no original)"}`})}catch(_){if(!/not installed|missing/.test(String(_)))throw _}return{ok:i.every(_=>_.ok)&&u.every(_=>_.ok),spec:i,frames:a,start_tc:d,master_offset:h,checks:u,mismatches:g,shot_changes:b,seams:y}}function Mx(e,t){let n=[...e.spec.filter(r=>!r.ok).map(r=>r.field),...e.checks.filter(r=>!r.ok).map(r=>r.what)];return[`${e.ok?"PASS":"FAIL"}: ${fe(t.patch)} vs ${fe(t.master)}${n.length?` (${n.join(", ")})`:""}`,...e.spec.map(r=>` ${r.ok?"ok ":"DIFF"} ${r.field}: ${r.patch??"-"}${r.ok?"":` (master ${r.master??"-"})`}`),...e.checks.map(r=>` ${r.ok?"ok ":"FAIL"} ${r.what}: ${r.detail}`),...e.mismatches.slice(0,40).map(r=>` frame ${r.frame} @ ${r.tc}: mean diff ${r.mean}, max ${r.max}`),e.mismatches.length>40?` \u2026 ${e.mismatches.length-40} more`:"",e.shot_changes.length?` shot changes in the patch at ${e.shot_changes.join(", ")}`:"",...(e.seams??[]).map(r=>` seam ${r.seam} ${r.tc} (master frames ${r.frames[0]}\u2013${r.frames[1]}): ${r.ok?"ok":"FAIL"} \u2014 inside: ${r.inside}; outside: ${r.outside}${r.undecoded?`; ${r.undecoded} undecoded`:""}`)].filter(Boolean).join(`
|
|
318
|
+
`)}import{createHash as jN}from"node:crypto";var Cf=e=>_o(new URL(e,import.meta.url)),Fc=e=>/^__version__\s*=\s*["']([^"']+)["']/m.exec(e)?.[1]??"";async function Ix(e,t=""){let n={};for await(let r of Ct(e))r.name==="__pycache__"||/\.py[co]$/.test(r.name)||(r.isDirectory?Object.assign(n,await Ix(re(e,r.name),`${t}${r.name}/`)):r.isFile&&(n[`${t}${r.name}`]=re(e,r.name)));return n}async function DN(){let e=Cf("./peer-kit/ctpeer/"),t=[];for await(let s of Ct(e))s.isFile&&s.name.endsWith(".py")&&t.push(s.name);t.sort();let n={},r=jN("sha256");for(let s of t)n[s]=await Ut(re(e,s)),r.update(s),r.update(n[s]);let o={ctpeer_version:Fc(new TextDecoder().decode(n["__init__.py"])),ctpeer_sha256:r.digest("hex")};return n["VENDORED.json"]=new TextEncoder().encode(JSON.stringify(o,null,2)),n}var Ic="conformtools_flame_hook.py",Pc="conformtools_flame.zip";function Px(e=Xt()){return e==="darwin"?re(ai(),"Library","Preferences","Autodesk","flame","python"):re(ai(),"flame","python")}async function BN(e=Px()){let t=Cf("./flame/hook/"),n={};for(let[r,o]of Object.entries(await Ix(re(t,"conformtools_flame"))))n[`conformtools_flame/${r}`]=await Ut(o);for(let[r,o]of Object.entries(await DN()))n[`ctpeer/${r}`]=o;return await Ve(e),await wa(re(t,Ic),re(e,Ic)),await Gn(re(e,Pc),o1(n)),{version:Fc(await ct(re(t,"conformtools_flame","__init__.py"))),dest:e,files:[re(e,Ic),re(e,Pc)]}}async function qN(e=Px()){if(!await Ye(re(e,Ic))||!await Ye(re(e,Pc)))return{installed:!1,dest:e};let t=cs(await Ut(re(e,Pc)),{filter:n=>n.name==="conformtools_flame/__init__.py"})["conformtools_flame/__init__.py"];return{installed:!0,dest:e,...t?{version:Fc(new TextDecoder().decode(t))}:{}}}async function UN(){return Fc(await ct(Cf("./flame/hook/conformtools_flame/__init__.py")))}var Af={flame:{install:()=>BN(),installed:()=>qN(),version:UN,what:"hook",next:"In Flame: Flame menu > Python > Rescan Python Hooks (or restart Flame), then Flame menu > CONFORM.TOOLS > Connect to CONFORM.TOOLS."}};function Ef(e,t,n){let r=t*n,o=new Float32Array(r*3);for(let s=0;s<r;s++)o[s*3]=e[s*4]/255,o[s*3+1]=e[s*4+1]/255,o[s*3+2]=e[s*4+2]/255;return{data:o,w:t,h:n}}function Dr(e){return e<0?0:e>1?1:e}var Mf="srgb";function Fx(e){Mf=e}function Br(e){return Mf==="g24"?Math.pow(Math.max(e,0),2.4):e<=.04045?e/12.92:Math.pow((e+.055)/1.055,2.4)}function If(e){return Mf==="g24"?Math.pow(Math.max(e,0),1/2.4):e<=.0031308?e*12.92:1.055*Math.pow(e,1/2.4)-.055}function Oc(e,t){let n=Math.min(1,t/Math.max(e.w,e.h));if(n>=1)return e;let r=Math.max(1,Math.round(e.w*n)),o=Math.max(1,Math.round(e.h*n)),s=new Float32Array(r*o*3),i=e.w/r,a=e.h/o;for(let l=0;l<o;l++){let c=Math.floor(l*a),u=Math.min(e.h,Math.max(c+1,Math.floor((l+1)*a)));for(let d=0;d<r;d++){let p=Math.floor(d*i),f=Math.min(e.w,Math.max(p+1,Math.floor((d+1)*i))),h=0,g=0,b=0,k=0;for(let y=c;y<u;y++)for(let _=p;_<f;_++){let v=(y*e.w+_)*3;h+=e.data[v],g+=e.data[v+1],b+=e.data[v+2],k++}let w=(l*r+d)*3;s[w]=h/k,s[w+1]=g/k,s[w+2]=b/k}}return{data:s,w:r,h:o}}function gn(e,t){let n=new Float64Array(9);for(let r=0;r<3;r++)for(let o=0;o<3;o++){let s=0;for(let i=0;i<3;i++)s+=e[r*3+i]*t[i*3+o];n[r*3+o]=s}return n}function Of(e){let t=new Float64Array(9);for(let n=0;n<3;n++)for(let r=0;r<3;r++)t[n*3+r]=e[r*3+n];return t}function Lc(e){let t=new Float64Array(9);return t[0]=e[0],t[4]=e[1],t[8]=e[2],t}function Lf(e){let t=Float64Array.from(e),n=new Float64Array([1,0,0,0,1,0,0,0,1]);for(let i=0;i<24;i++){let a=0;for(let[l,c]of[[0,1],[0,2],[1,2]])a+=t[l*3+c]**2;if(a<1e-30)break;for(let[l,c]of[[0,1],[0,2],[1,2]]){let u=t[l*3+c];if(Math.abs(u)<1e-300)continue;let d=(t[c*3+c]-t[l*3+l])/(2*u),p=Math.sign(d||1)/(Math.abs(d)+Math.sqrt(d*d+1)),f=1/Math.sqrt(p*p+1),h=p*f;for(let g=0;g<3;g++){let b=t[g*3+l],k=t[g*3+c];t[g*3+l]=f*b-h*k,t[g*3+c]=h*b+f*k}for(let g=0;g<3;g++){let b=t[l*3+g],k=t[c*3+g];t[l*3+g]=f*b-h*k,t[c*3+g]=h*b+f*k}for(let g=0;g<3;g++){let b=n[g*3+l],k=n[g*3+c];n[g*3+l]=f*b-h*k,n[g*3+c]=h*b+f*k}}}let r=[0,1,2].sort((i,a)=>t[i*3+i]-t[a*3+a]),o=new Float64Array(3),s=new Float64Array(9);return r.forEach((i,a)=>{o[a]=t[i*3+i];for(let l=0;l<3;l++)s[l*3+a]=n[l*3+i]}),{values:o,vectors:s}}function Ox(e){let t=new Float64Array(9);for(let n=0;n<3;n++)for(let r=0;r<=n;r++){let o=e[n*3+r];for(let s=0;s<r;s++)o-=t[n*3+s]*t[r*3+s];if(n===r){if(o<=0)return null;t[n*3+r]=Math.sqrt(o)}else t[n*3+r]=o/t[r*3+r]}return t}function GN(e){let t=new Float64Array(9);for(let n=0;n<3;n++){t[n*3+n]=1/e[n*3+n];for(let r=0;r<n;r++){let o=0;for(let s=r;s<n;s++)o+=e[n*3+s]*t[s*3+r];t[n*3+r]=-o/e[n*3+n]}}return t}function Pf(e){let{values:t,vectors:n}=Lf(e),r=1e-12*Math.max(...Array.from(t).map(Math.abs),1e-30),o=new Float64Array(3);for(let s=0;s<3;s++)o[s]=Math.abs(t[s])>r?1/t[s]:0;return gn(gn(n,Lc(o)),Of(n))}function HN(e){let{values:t,vectors:n}=Lf(e),r=new Float64Array(3);for(let o=0;o<3;o++)r[o]=Math.sqrt(Math.max(t[o],0));return gn(gn(n,Lc(r)),Of(n))}function Lx(e){let t=e.w*e.h,n=new Float64Array(3);for(let s=0;s<t;s++)for(let i=0;i<3;i++)n[i]+=e.data[s*3+i];for(let s=0;s<3;s++)n[s]/=t;let r=new Float64Array(9);for(let s=0;s<t;s++){let i=e.data[s*3]-n[0],a=e.data[s*3+1]-n[1],l=e.data[s*3+2]-n[2];r[0]+=i*i,r[1]+=i*a,r[2]+=i*l,r[4]+=a*a,r[5]+=a*l,r[8]+=l*l}let o=Math.max(1,t-1);for(let s of[0,1,2,4,5,8])r[s]/=o;return r[3]=r[1],r[6]=r[2],r[7]=r[5],{mean:n,cov:r}}function zN(e,t,n,r){let o=e.w*e.h,s=new Float32Array(o*3);for(let i=0;i<o;i++){let a=e.data[i*3]-n[0],l=e.data[i*3+1]-n[1],c=e.data[i*3+2]-n[2];s[i*3]=t[0]*a+t[1]*l+t[2]*c+r[0],s[i*3+1]=t[3]*a+t[4]*l+t[5]*c+r[1],s[i*3+2]=t[6]*a+t[7]*l+t[8]*c+r[2]}return{data:s,w:e.w,h:e.h}}function WN(e,t){let{values:n,vectors:r}=Lf(e),o=new Float64Array(3),s=new Float64Array(3);for(let d=0;d<3;d++){let p=Math.max(n[d],0);o[d]=Math.sqrt(p),s[d]=o[d]>1e-12?1/o[d]:0}let i=Lc(o),a=Lc(s),l=Of(r),c=gn(gn(gn(gn(i,l),t),r),i),u=HN(c);return gn(gn(gn(gn(r,a),u),a),l)}function KN(e,t){let r=Float64Array.from(e),o=Float64Array.from(t);for(let a of[0,4,8])r[a]+=1e-5,o[a]+=1e-5;let s=Ox(r),i=Ox(o);if(!s||!i){let a=new Float64Array(9);for(let l=0;l<3;l++){let c=Math.sqrt(Math.max(e[l*3+l],0)),u=Math.sqrt(Math.max(t[l*3+l],0));a[l*3+l]=c>1e-12?u/c:1}return a}return gn(i,GN(s))}function VN(e,t,n,r){let o=Pf(n.cov),s=Pf(r.cov),i=e.w*e.h,a=new Float64Array(9);for(let c=0;c<i;c++){let u=t.data[c*3]-r.mean[0],d=t.data[c*3+1]-r.mean[1],p=t.data[c*3+2]-r.mean[2],f=e.data[c*3]-n.mean[0],h=e.data[c*3+1]-n.mean[1],g=e.data[c*3+2]-n.mean[2];a[0]+=u*f,a[1]+=u*h,a[2]+=u*g,a[3]+=d*f,a[4]+=d*h,a[5]+=d*g,a[6]+=p*f,a[7]+=p*h,a[8]+=p*g}let l=Math.max(1,i-1);for(let c=0;c<9;c++)a[c]/=l;return gn(gn(Pf(s),s),gn(a,o))}var dr=4096;function Ff(e,t){let n=e.w*e.h,r=t.w*t.h,o=i=>Math.min(dr-1,Math.max(0,Math.round(Dr(i)*(dr-1)))),s=[];for(let i=0;i<3;i++){let a=new Float64Array(dr),l=new Float64Array(dr);for(let h=0;h<n;h++)a[o(e.data[h*3+i])]++;for(let h=0;h<r;h++)l[o(t.data[h*3+i])]++;let c=0;for(let h=0;h<dr;h++)c+=a[h],a[h]=c/n;let u=[],d=[];c=0;for(let h=0;h<dr;h++)l[h]!==0&&(c+=l[h],u.push(h/(dr-1)),d.push(c/r));let p=new Float32Array(dr),f=0;for(let h=0;h<dr;h++){let g=a[h];for(;f<d.length-1&&d[f]<g;)f++;if(f===0||d[f]<=g)p[h]=u[f]??0;else{let b=d[f-1],k=d[f],w=k>b?(g-b)/(k-b):0;p[h]=u[f-1]+(u[f]-u[f-1])*w}}s.push(p)}return s}var Ys=1/Math.sqrt(3),Zs=1/Math.sqrt(6),Nc=1/Math.sqrt(2),uH=[Ys,Ys,Ys,Zs,Zs,-2*Zs,Nc,-Nc,0],dH=[Ys,Zs,Nc,Ys,Zs,-Nc,Ys,-2*Zs,0];function jc(e,t,n="mvgd"){let r=e.w*e.h,o=b=>Math.min(dr-1,Math.max(0,Math.round(Dr(b)*(dr-1)))),s=(b,k)=>{let w=new Float32Array(r*3);for(let y=0;y<3;y++){let _=k[y];for(let v=0;v<r;v++)w[v*3+y]=_[o(b.data[v*3+y])]}return{data:w,w:b.w,h:b.h}},i=Ff(e,t),a=s(e,i),l=Lx(a),c=Lx(t),u;if(n==="mkl")u=WN(l.cov,c.cov);else if(n==="coral")u=KN(l.cov,c.cov);else if(n==="adain"){let b=new Float64Array(9);for(let k=0;k<3;k++){let w=Math.sqrt(Math.max(l.cov[k*3+k],0)),y=Math.sqrt(Math.max(c.cov[k*3+k],0));b[k*3+k]=w>1e-12?y/w:1}u=b}else u=VN(a,t,l,c);let d=zN(a,u,l.mean,c.mean),p={data:Float32Array.from(d.data,Dr),w:e.w,h:e.h},f=Ff(p,t),h=s(p,f),g=[c.mean[0]-(u[0]*l.mean[0]+u[1]*l.mean[1]+u[2]*l.mean[2]),c.mean[1]-(u[3]*l.mean[0]+u[4]*l.mean[1]+u[5]*l.mean[2]),c.mean[2]-(u[6]*l.mean[0]+u[7]*l.mean[1]+u[8]*l.mean[2])];return{hm1:i,matrix:Array.from(u),offset:g,mid:p,hm2:f,image:h}}function jx(e,t,n=1){let r=e.w*e.h,o=new Float32Array(r*3),s=[Math.pow(t[0],n),Math.pow(t[1],n),Math.pow(t[2],n)];for(let i=0;i<r;i++)for(let a=0;a<3;a++){let l=Br(Math.min(1,Math.max(0,e.data[i*3+a])))*s[a];o[i*3+a]=If(l<0?0:l>1?1:l)}return{data:o,w:e.w,h:e.h}}function Nx(e){let t=Math.hypot(e[0],e[1],e[2]);return t>0?[e[0]/t,e[1]/t,e[2]/t]:[1/Math.sqrt(3),1/Math.sqrt(3),1/Math.sqrt(3)]}function Dx(e,t){let n=Nx(e),r=Nx(t),o=n[0]*r[0]+n[1]*r[1]+n[2]*r[2],s=[n[1]*r[2]-n[2]*r[1],n[2]*r[0]-n[0]*r[2],n[0]*r[1]-n[1]*r[0]],i=Math.hypot(s[0],s[1],s[2]);return Math.atan2(i,o)*180/Math.PI}var Dc={note:"Measured from DaVinci Resolve Studio 21 EXR renders of a 16-bit ramp chart (drt-color-re/render_grade.py batch 5, 2026-08-11). Absolute per-amplitude deltas vs the neutral render; regenerate with gen_wheel_basis.py.",x:[0,.033351,.066701,.100052,.133403,.166754,.200104,.233455,.266806,.300156,.333507,.366858,.400208,.433559,.46691,.500261,.533611,.566962,.600313,.633663,.667014,.700365,.733715,.767066,.800417,.833768,.867118,.900469,.93382,.96717,1],controls:{shadow:{amps:[-.4,-.2,-.1,.05,.1,.2,.3,.4],curves:{"-0.40":[-.4,-.361005,-.320961,-.28089,-.240827,-.200775,-.160651,-.119559,-.084823,-.054151,-.028079,-.007759,-487e-6,-487e-6,-493e-6,-492e-6,-49e-5,-49e-5,-488e-6,-49e-5,-488e-6,-487e-6,-489e-6,-488e-6,-49e-5,-488e-6,-491e-6,-489e-6,-488e-6,-49e-5,-489e-6],"-0.20":[-.2,-.180746,-.160725,-.140689,-.120659,-.100632,-.08057,-.060049,-.042665,-.027551,-.014705,-.004394,-487e-6,-487e-6,-493e-6,-492e-6,-49e-5,-49e-5,-488e-6,-49e-5,-488e-6,-487e-6,-489e-6,-488e-6,-49e-5,-488e-6,-491e-6,-489e-6,-488e-6,-49e-5,-489e-6],"-0.10":[-.1,-.090617,-.080607,-.070588,-.060574,-.05056,-.040529,-.030279,-.021573,-.014076,-.007709,-.002511,-487e-6,-487e-6,-493e-6,-492e-6,-49e-5,-49e-5,-488e-6,-49e-5,-488e-6,-487e-6,-489e-6,-488e-6,-49e-5,-488e-6,-491e-6,-489e-6,-488e-6,-49e-5,-489e-6],"+0.05":[.01665,.014519,.01285,.011184,.009514,.007848,.006178,.004433,.003088,.001785,631e-6,-218e-6,-487e-6,-487e-6,-493e-6,-492e-6,-49e-5,-49e-5,-488e-6,-49e-5,-488e-6,-487e-6,-489e-6,-488e-6,-49e-5,-488e-6,-491e-6,-489e-6,-488e-6,-49e-5,-489e-6],"+0.10":[.0333,.029526,.02619,.022856,.019518,.016185,.012843,.009357,.006657,.004041,.00172,24e-6,-487e-6,-487e-6,-493e-6,-492e-6,-49e-5,-49e-5,-488e-6,-49e-5,-488e-6,-487e-6,-489e-6,-488e-6,-49e-5,-488e-6,-491e-6,-489e-6,-488e-6,-49e-5,-489e-6],"+0.20":[.0666,.059539,.052869,.046199,.039526,.032859,.026174,.019208,.013791,.008561,.003926,527e-6,-487e-6,-487e-6,-493e-6,-492e-6,-49e-5,-49e-5,-488e-6,-49e-5,-488e-6,-487e-6,-489e-6,-488e-6,-49e-5,-488e-6,-491e-6,-489e-6,-488e-6,-49e-5,-489e-6],"+0.30":[.0999,.089552,.079548,.069542,.059534,.049533,.039505,.029067,.020915,.013093,.006169,.001059,-487e-6,-487e-6,-493e-6,-492e-6,-49e-5,-49e-5,-488e-6,-49e-5,-488e-6,-487e-6,-489e-6,-488e-6,-49e-5,-488e-6,-491e-6,-489e-6,-488e-6,-49e-5,-489e-6],"+0.40":[.1332,.119565,.106227,.092886,.079542,.066207,.052837,.038936,.028026,.017634,.008453,.001622,-487e-6,-487e-6,-493e-6,-492e-6,-49e-5,-49e-5,-488e-6,-49e-5,-488e-6,-487e-6,-489e-6,-488e-6,-49e-5,-488e-6,-491e-6,-489e-6,-488e-6,-49e-5,-489e-6]}},midtone:{amps:[-.4,-.2,-.1,.1,.2,.4],curves:{"-0.40":[0,-487e-6,-489e-6,-488e-6,-49e-5,-489e-6,-451e-6,263e-6,-.003632,-.010819,-.020501,-.032238,-.047185,-.059943,-.066296,-.060685,-.040876,-.017385,-303e-6,-447e-6,-488e-6,-487e-6,-489e-6,-488e-6,-49e-5,-488e-6,-491e-6,-489e-6,-488e-6,-49e-5,-489e-6],"-0.20":[0,-487e-6,-489e-6,-488e-6,-49e-5,-489e-6,-466e-6,-57e-6,-.002523,-.007541,-.014006,-.020949,-.027712,-.032192,-.033342,-.029182,-.019455,-.008585,-391e-6,-467e-6,-488e-6,-487e-6,-489e-6,-488e-6,-49e-5,-488e-6,-491e-6,-489e-6,-488e-6,-49e-5,-489e-6],"-0.10":[0,-487e-6,-489e-6,-488e-6,-49e-5,-489e-6,-476e-6,-266e-6,-.001602,-.004451,-.00808,-.011811,-.014895,-.016618,-.016765,-.014464,-.00969,-.004462,-438e-6,-478e-6,-488e-6,-487e-6,-489e-6,-488e-6,-49e-5,-488e-6,-491e-6,-489e-6,-488e-6,-49e-5,-489e-6],"+0.10":[0,-487e-6,-489e-6,-488e-6,-49e-5,-489e-6,-509e-6,-938e-6,.001249,.004662,.008518,.012261,.014922,.015752,.01505,.012601,.007936,.002742,-514e-6,-496e-6,-488e-6,-487e-6,-489e-6,-488e-6,-49e-5,-488e-6,-491e-6,-489e-6,-488e-6,-49e-5,-489e-6],"+0.20":[0,-487e-6,-489e-6,-488e-6,-49e-5,-489e-6,-53e-5,-.001381,.00303,.010093,.018105,.0258,.030902,.031857,.029403,.023831,.014993,.005523,-542e-6,-502e-6,-488e-6,-487e-6,-489e-6,-488e-6,-49e-5,-488e-6,-491e-6,-489e-6,-488e-6,-49e-5,-489e-6],"+0.40":[0,-487e-6,-489e-6,-488e-6,-49e-5,-489e-6,-571e-6,-.002236,.006718,.021856,.039117,.055211,.063967,.062345,.052975,.039586,.02427,.009349,-592e-6,-514e-6,-488e-6,-487e-6,-489e-6,-488e-6,-49e-5,-488e-6,-491e-6,-489e-6,-488e-6,-49e-5,-489e-6]}},highlight:{amps:[-.4,-.2,-.1,.1,.2,.4],curves:{"-0.40":[0,-487e-6,-489e-6,-488e-6,-49e-5,-489e-6,-487e-6,-49e-5,-484e-6,-475e-6,-464e-6,-461e-6,-487e-6,-487e-6,-49e-6,-.001378,-.005676,-.012124,-.02034,-.033741,-.0471,-.060436,-.073779,-.087121,-.100459,-.1138,-.127144,-.14048,-.153821,-.167165,-.180293],"-0.20":[0,-487e-6,-489e-6,-488e-6,-49e-5,-489e-6,-487e-6,-49e-5,-484e-6,-475e-6,-464e-6,-461e-6,-487e-6,-487e-6,-285e-6,-921e-6,-.003101,-.006371,-.010411,-.017115,-.023794,-.030461,-.037134,-.043804,-.050474,-.057144,-.063817,-.070484,-.077154,-.083827,-.090391],"-0.10":[0,-487e-6,-489e-6,-488e-6,-49e-5,-489e-6,-487e-6,-49e-5,-484e-6,-475e-6,-464e-6,-461e-6,-487e-6,-487e-6,-392e-6,-703e-6,-.001797,-.003442,-.005449,-.008802,-.012141,-.015474,-.018812,-.022146,-.025482,-.028816,-.032154,-.035487,-.038821,-.042159,-.04544],"+0.10":[0,-487e-6,-489e-6,-488e-6,-49e-5,-489e-6,-487e-6,-49e-5,-484e-6,-475e-6,-464e-6,-461e-6,-487e-6,-487e-6,-913e-6,207e-6,.002501,.005682,.010558,.017987,.025407,.032818,.040228,.047642,.055048,.062463,.069872,.077283,.084698,.092108,.099403],"+0.20":[0,-487e-6,-489e-6,-488e-6,-49e-5,-489e-6,-487e-6,-49e-5,-484e-6,-475e-6,-464e-6,-461e-6,-487e-6,-487e-6,-.001308,875e-6,.005478,.011902,.021601,.036463,.051302,.066123,.080944,.095772,.110587,.125414,.140236,.155056,.169883,.184705,.199294],"+0.40":[0,-487e-6,-489e-6,-488e-6,-49e-5,-489e-6,-487e-6,-49e-5,-484e-6,-475e-6,-464e-6,-461e-6,-487e-6,-487e-6,-.002028,.002127,.011361,.024415,.043682,.073414,.103093,.132732,.162378,.192031,.221663,.251316,.280962,.310601,.340254,.3699,.399077]}}},contrast:{cs:[.5,.8,1.25,1.5,1.8],curves:{"0.50":[.2175,.200578,.183907,.167229,.15055,.13388,.117203,.100531,.083854,.067175,.050505,.033828,.017148,479e-6,-.016201,-.032878,-.049548,-.066227,-.082897,-.099576,-.116253,-.132923,-.149602,-.16628,-.182951,-.199629,-.216308,-.232978,-.249655,-.266334,-.282745],"0.80":[.087,.079939,.073269,.066599,.059926,.053259,.046589,.039919,.033249,.026576,.019909,.013239,.006566,-101e-6,-.006775,-.013445,-.020112,-.026785,-.033452,-.040125,-.046795,-.053462,-.060135,-.066805,-.073475,-.080145,-.086818,-.093485,-.100155,-.106828,-.113392],"1.25":[0,-.010727,-.021735,-.032532,-.042279,-.050126,-.055135,-.056541,-.054061,-.047509,-.037623,-.025716,-.013116,-.001136,.010563,.023076,.035617,.047411,.057676,.06563,.070555,.072344,.071151,.067141,.060599,.052178,.042386,.031729,.020695,.009783,-345e-6],"1.50":[0,-.021136,-.043244,-.065419,-.086537,-.105469,-.121116,-.131949,-.135345,-.128698,-.109132,-.077071,-.039172,-.002436,.033276,.07165,.108539,.139821,.161382,.172335,.174591,.16969,.159165,.144656,.12727,.107658,.086487,.064431,.042132,.020262,-196e-6],"1.80":[0,-.030247,-.061752,-.093815,-.125632,-.1564,-.185357,-.21169,-.23463,-.254734,-.26386,-.247374,-.163569,-.008383,.14496,.280152,.328288,.341546,.334832,.316817,.295588,.272004,.245823,.217525,.18759,.15646,.124616,.09254,.060672,.029492,-59e-6]}},pivot_probes:{pivot02_c15:[0,.011586,.023617,.041223,.072432,.128713,.199237,.267856,.339119,.410913,.481153,.547825,.60882,.662121,.707868,.747147,.780708,.809347,.833813,.8549,.873465,.889957,.904721,.918081,.93036,.941903,.953031,.964073,.975367,.987238,.999804],pivot08_c15:[0,.012599,.024474,.035774,.04682,.057941,.069476,.081743,.095087,.109829,.126295,.144829,.165876,.190289,.218866,.252371,.29155,.337202,.39039,.451293,.517901,.588105,.659892,.731177,.799843,.87034,.927,.958466,.976191,.988267,.999805],pivot02_c07:[.06,.083008,.106345,.129696,.153044,.176383,.199734,.223071,.246421,.269769,.293109,.316459,.339807,.363147,.386494,.409845,.433184,.456532,.479872,.50322,.52657,.54991,.573258,.596608,.619945,.643295,.666643,.689983,.713333,.736681,.759657],pivot08_c07:[.24,.263008,.286345,.309696,.333044,.356383,.379734,.403071,.426421,.449769,.473109,.496459,.519807,.543146,.566494,.589845,.613184,.636532,.659872,.68322,.70657,.72991,.753258,.776608,.799945,.823295,.846643,.869983,.893333,.916681,.939657]}};var pr=.435;var Hx={shadow:[0,0,0],midtone:[0,0,0],highlight:[0,0,0],contrast:1,pivot:pr};function ei(e){if(!e)return!0;let t=n=>n.every(r=>Math.abs(r)<1e-9);return t(e.shadow)&&t(e.midtone)&&t(e.highlight)&&Math.abs(e.contrast-1)<1e-9}var bn=Dc.x,fo=bn.length;function jf(e){let t=Dc.controls[e],n=[],r=[];for(let s of t.amps)n.push(s),r.push(t.curves[`${s>=0?"+":""}${s.toFixed(2)}`]);let o=n.findIndex(s=>s>0);return o<0&&(o=n.length),n.splice(o,0,0),r.splice(o,0,new Array(fo).fill(0)),{amps:n,curves:r}}var XN=jf("shadow"),QN=jf("midtone"),YN=jf("highlight");function Zo(e,t){if(t<=bn[0])return e[0];let n=fo-1;if(t>=bn[n])return e[n];let r=0,o=n;for(;o-r>1;){let i=r+o>>1;bn[i]<=t?r=i:o=i}let s=(t-bn[r])/(bn[o]-bn[r]);return e[r]+(e[o]-e[r])*s}function Nf(e,t,n){if(t===0)return 0;let{amps:r,curves:o}=e,s=r.length-1;if(t<=r[0])return Zo(o[0],n)*(t/r[0]);if(t>=r[s])return Zo(o[s],n)*(t/r[s]);let i=0,a=s;for(;a-i>1;){let c=i+a>>1;r[c]<=t?i=c:a=c}let l=(t-r[i])/(r[a]-r[i]);return Zo(o[i],n)+(Zo(o[a],n)-Zo(o[i],n))*l}var Bc=(()=>{let e=Dc.contrast,t=e.cs.filter(n=>n>1).map(n=>({c:n,y:e.curves[n.toFixed(2)].map((r,o)=>bn[o]+r)}));return t.unshift({c:1,y:[...bn]}),t})();function Bx(e,t){if(t<=e[0])return bn[0];let n=fo-1;if(t>=e[n])return bn[n];let r=0,o=n;for(;o-r>1;){let i=r+o>>1;e[i]<=t?r=i:o=i}let s=(t-e[r])/(e[o]-e[r]);return bn[r]+(bn[o]-bn[r])*s}function ZN(e,t){let n=0;for(;n<Bc.length-2&&Bc[n+1].c<=e;)n++;let r=Bc[n],o=Bc[n+1],s=(e-r.c)/(o.c-r.c),i=pr,a=new Array(fo);for(let u=0;u<fo;u++){let d=bn[u],p=0,f=1;for(let h=0;h<30;h++){let g=(p+f)/2;Bx(r.y,g)*(1-s)+Bx(o.y,g)*s<d?p=g:f=g}a[u]=(p+f)/2}let l=a;if(Math.abs(t-i)>1e-6){l=new Array(fo);for(let u=0;u<fo;u++){let d=bn[u],p=d<t?i*(d/t):i+(1-i)*((d-t)/(1-t)),f=Zo(a,p);l[u]=f<i?t*(f/i):t+(1-t)*((f-i)/(1-i))}}let c=0;for(let u=0;u<fo;u++){let d=l[u]<c?c:l[u];l[u]=d<0?0:d>1?1:d,c=l[u]}return l}var qx=NaN,Ux=NaN,Gx=null;function ej(e,t,n){return t<1?n+t*(e-n):((t!==qx||n!==Ux)&&(Gx=ZN(t,n),qx=t,Ux=n),Zo(Gx,e))}function ho(e,t,n){let r=e+Nf(XN,t.shadow[n],e)+Nf(QN,t.midtone[n],e)+Nf(YN,t.highlight[n],e);return t.contrast!==1&&(r=ej(r,t.contrast,t.pivot)),r}var zx=[.2126,.7152,.0722];function Wx(e,t){let n=t.wheels??Hx,r=Df({...t,wheels:void 0,saturation:void 0,mixer:void 0}),o=!ei(t.wheels),s=e.w*e.h,i=new Float32Array(s*3),a=(c,u)=>{let d=c*r.slope[u]+r.offset[u],p=r.power[u];return p!==1&&(d=d<0?-Math.pow(-d,p):Math.pow(d,p)),o?ho(d,n,u):d};if(s*3>=32768){let u=new Float32Array(12288);for(let d=0;d<3;d++)for(let p=0;p<4096;p++)u[d*4096+p]=a(p/4095,d);for(let d=0;d<s;d++)for(let p=0;p<3;p++){let f=e.data[d*3+p];if(f>=0&&f<=1){let h=f*4095,g=h|0,b=h-g,k=u[p*4096+g];i[d*3+p]=b>0?k+(u[p*4096+g+1]-k)*b:k}else i[d*3+p]=a(f,p)}}else for(let c=0;c<s;c++)for(let u=0;u<3;u++)i[c*3+u]=a(e.data[c*3+u],u);let l=t.saturation??1;if(l!==1)for(let c=0;c<s;c++){let u=.21*i[c*3]+.7*i[c*3+1]+.09*i[c*3+2];for(let d=0;d<3;d++)i[c*3+d]=u+(i[c*3+d]-u)*l}if(!ti(t.mixer)){let c=qc(t.mixer);for(let u=0;u<s;u++){let d=i[u*3],p=i[u*3+1],f=i[u*3+2];i[u*3]=c[0]*d+c[1]*p+c[2]*f,i[u*3+1]=c[3]*d+c[4]*p+c[5]*f,i[u*3+2]=c[6]*d+c[7]*p+c[8]*f}}return{data:i,w:e.w,h:e.h}}function ti(e){if(!e)return!0;let t=[1,0,0,0,1,0,0,0,1];return e.every((n,r)=>Math.abs(n-t[r])<1e-9)}function qc(e){let t=e.slice();for(let n=0;n<3;n++){let r=-zx[n];for(let o=0;o<3;o++)r+=zx[o]*e[o*3+n];for(let o=0;o<3;o++)t[o*3+n]-=r}return t}function Kx(e,t){if(!ei(t.wheels)||t.saturation!==void 0&&t.saturation!==1||!ti(t.mixer)){let c=Wx(e,t);for(let u=0;u<c.data.length;u++)c.data[u]=Dr(c.data[u]);return c}let n=t.blackPointOffset,r=Math.pow(2,t.exposureStops),o=[t.wbGain[0]*r,t.wbGain[1]*r,t.wbGain[2]*r],s=e.w*e.h,i=new Float32Array(s*3);for(let c=0;c<s;c++)i[c*3]=Dr(e.data[c*3]+n[0]),i[c*3+1]=Dr(e.data[c*3+1]+n[1]),i[c*3+2]=Dr(e.data[c*3+2]+n[2]);let a=jx({data:i,w:e.w,h:e.h},o,1),l=t.power;if(!l||l[0]===1&&l[1]===1&&l[2]===1)return a;for(let c=0;c<s;c++)for(let u=0;u<3;u++){let d=a.data[c*3+u];a.data[c*3+u]=d<=0?0:Math.pow(d,l[u])}return a}function Df(e){let t=Math.pow(2,e.exposureStops),n=e.wbGain.map(i=>Math.pow(i*t,1/2.4)),r=e.blackPointOffset.map((i,a)=>i*n[a]),o=e.power??[1,1,1],s={slope:n,offset:r,power:o};return ei(e.wheels)||(s.wheels=e.wheels),e.saturation!==void 0&&Math.abs(e.saturation-1)>1e-6&&(s.saturation=e.saturation),ti(e.mixer)||(s.mixer=e.mixer),s}function Vx(e,t,n){return .2126*e+.7152*t+.0722*n}function tj(e,t){let n=e.length;if(n===0)return 0;if(n===1)return e[0];let r=Math.min(n-1,Math.max(0,t*(n-1))),o=Math.floor(r),s=Math.min(n-1,o+1),i=r-o;return e[o]+i*(e[s]-e[o])}function Jx(e,t,n=4,r=6e4){let o=e.w*e.h,s=Math.max(1,Math.floor(o/r)),i=new Float32Array(Math.ceil(o/s)),a=0;for(let c=0;c<o;c+=s){let u=Br(Math.max(0,Math.min(1,e.data[c*3]))),d=Br(Math.max(0,Math.min(1,e.data[c*3+1]))),p=Br(Math.max(0,Math.min(1,e.data[c*3+2]))),f=Vx(u,d,p);if(f<=1e-5||Math.max(u,d,p)>=.99)continue;let h=Br(Math.max(0,Math.min(1,t.data[c*3]))),g=Br(Math.max(0,Math.min(1,t.data[c*3+1]))),b=Br(Math.max(0,Math.min(1,t.data[c*3+2]))),k=Vx(h,g,b)/f;!Number.isFinite(k)||k<=0||(i[a++]=Math.max(-n,Math.min(n,Math.log2(k))))}if(a===0)return 0;let l=i.subarray(0,a);return l.sort(),tj(l,.5)}function nj(e,t,n,r,o,s,i){let l=new Float64Array(1024),c=new Float64Array(1024),u=new Float64Array(1024),d=0;for(let C=0;C<n;C+=r){let B=e[C*3+o],L=t[C*3+o];if(!(B>.004&&B<.996)||!(L>5e-4&&L<.9995))continue;let Z=B*1023+.5|0,X=s?s[C]:1;l[Z]+=B*X,c[Z]+=L*X,u[Z]+=X,d++}let p=[],f=[],h=[];for(let C=0;C<1024;C++)u[C]!==0&&(p.push(l[C]/u[C]),f.push(c[C]/u[C]),h.push(u[C]));let g=p.length;if(d<32||g<8)return{slope:1,offset:0,power:1,residual:0,samples:d};let b=0;for(let C=0;C<g;C++)b+=h[C];let k=(C,B,L)=>{let Z=0;for(let X=0;X<g;X++){let O=p[X]*C+B,ae=O<=0?0:Math.pow(O,L);Z+=h[X]*Math.abs((ae>1?1:ae)-f[X])}return Z/b},w=C=>{let B=0,L=0,Z=0,X=0,O=0;for(let z=0;z<g;z++){let q=C===1?f[z]:Math.pow(Math.max(f[z],1e-9),1/C),j=h[z];B+=j,L+=j*p[z],Z+=j*p[z]*p[z],X+=j*q,O+=j*p[z]*q}let ae=B*Z-L*L;if(Math.abs(ae)<1e-12)return null;let W=(B*O-L*X)/ae,ne=(Z*X-L*O)/ae;for(let z=0;z<3;z++){let q=0,j=0,I=0,S=0,A=0;for(let de=0;de<g;de++){let te=p[de]*W+ne;if(te<=1e-9)continue;let _e=Math.pow(te,C),Se=(_e>1?1:_e)-f[de],H=C*Math.pow(te,C-1),le=H*p[de],pe=h[de];q+=pe*le*le,j+=pe*le*H,I+=pe*H*H,S+=pe*le*Se,A+=pe*H*Se}let U=q*I-j*j;if(!(Math.abs(U)>1e-12))break;if(W-=(I*S-j*A)/U,ne-=(q*A-j*S)/U,ne>0&&(ne=0),!(W>.02&&W<200)||!Number.isFinite(ne))return null}return!(W>.02&&W<200)||!Number.isFinite(ne)||ne>0?null:{s:W,o:ne}},y=i?Math.min(Math.max(1,i[0]),i[1]):1,_=w(y),v=_?{slope:_.s,offset:_.o,power:y,residual:k(_.s,_.o,y),samples:d}:{slope:1,offset:0,power:1,residual:k(1,0,1),samples:d},T=.02,$=160,x=Math.log(i?i[0]:.1),R=Math.log(i?i[1]:5);for(let C=0;C<$;C++){let B=Math.exp(x+(R-x)*C/($-1)),L=w(B);if(!L)continue;let Z=k(L.s,L.o,B);Z<v.residual*(1-T)&&(v={slope:L.s,offset:L.o,power:B,residual:Z,samples:d})}return v}function Uc(e,t,n=4e4,r,o){if(e.w!==t.w||e.h!==t.h)throw new Error(`fitShotAnalysis: size mismatch \u2014 ${e.w}x${e.h} vs ${t.w}x${t.h}`);let s=e.w*e.h;if(r&&r.length!==s)throw new Error(`fitShotAnalysis: weights length ${r.length} != ${s} pixels`);let i=Math.max(1,Math.floor(s/n)),a=[1,1,1],l=[0,0,0],c=[1,1,1],u=[0,0,0],d=0;for(let b=0;b<3;b++){let k=nj(e.data,t.data,s,i,b,r,o?.[b]);a[b]=k.slope,l[b]=k.offset,c[b]=k.power,u[b]=k.residual,d=Math.max(d,k.samples)}let p=a.map(b=>Math.pow(b,2.4)),f=[p[0]/p[1],1,p[2]/p[1]],h=Math.log2(p[1]);return{analysis:{blackPointOffset:[l[0]/a[0],l[1]/a[1],l[2]/a[2]],wbGain:f,exposureStops:h,power:c,castDeg:Dx(f,[1,1,1])},lumaStops:Jx(e,t),slope:a,offset:l,power:c,residual:u,maxResidual:Math.max(u[0],u[1],u[2]),samples:d}}function Xx(e,t,n,r=2e4,o,s){let i=e.w*e.h;if(o&&o.length!==i)throw new Error(`fitLogWheels: weights length ${o.length} != ${i} pixels`);let a=Math.max(1,Math.floor(i/r)),l=1024,c=[[],[],[]],u=[[],[],[]],d=[[],[],[]];for(let x=0;x<3;x++){let R=new Float64Array(l),C=new Float64Array(l),B=new Float64Array(l);for(let L=0;L<i;L+=a){let Z=e.data[L*3+x];if(!(Z>.002&&Z<.998))continue;let X=Z*(l-1)+.5|0,O=o?o[L]:1;R[X]+=Z*O,C[X]+=t.data[L*3+x]*O,B[X]+=O}for(let L=0;L<l;L++)B[L]!==0&&(c[x].push(R[L]/B[L]),u[x].push(C[L]/B[L]),d[x].push(B[L]))}let p=(x,R)=>R?Math.min(R[1],Math.max(R[0],x)):x,f={shadow:[0,0,0],midtone:[0,0,0],highlight:[0,0,0],contrast:p(1,s?.contrast),pivot:p(pr,s?.pivot)},h=n.wbGain,g=Math.pow(2,n.exposureStops),b=[0,1,2].map(x=>Math.pow(h[x]*g,1/2.4)),k=n.blackPointOffset,w=n.power??[1,1,1],y=[[],[],[]];for(let x=0;x<3;x++)for(let R=0;R<c[x].length;R++){let C=(c[x][R]+k[x])*b[x];w[x]!==1&&(C=C<0?-Math.pow(-C,w[x]):Math.pow(C,w[x])),y[x].push(C)}let _=0;for(let x=0;x<3;x++)for(let R of d[x])_+=R;let v=()=>{let x=0;for(let R=0;R<3;R++)for(let C=0;C<y[R].length;C++){let B=ho(y[R][C],f,R);x+=d[R][C]*Math.abs((B<0?0:B>1?1:B)-u[R][C])}return _?x/_:0},T=(x,R,C)=>{let B=.6180339887,L=R,Z=C,X=Z-B*(Z-L),O=L+B*(Z-L);x(X);let ae=v();x(O);let W=v(),ne=ae,z=W;for(let j=0;j<18&&Z-L>1e-4;j++)ne<z?(Z=O,O=X,z=ne,X=Z-B*(Z-L),x(X),ne=v()):(L=X,X=O,ne=z,O=L+B*(Z-L),x(O),z=v());let q=ne<z?X:O;x(q)},$=v();for(let x=0;x<3;x++){T(C=>{f.contrast=C},Math.max(.4,s?.contrast[0]??.4),Math.min(2.2,s?.contrast[1]??2.2)),T(C=>{f.pivot=C},Math.max(.15,s?.pivot[0]??.15),Math.min(.85,s?.pivot[1]??.85));for(let C=0;C<3;C++)T(B=>{f.shadow[C]=B},-.4,.4),T(B=>{f.midtone[C]=B},-.4,.4),T(B=>{f.highlight[C]=B},-.4,.4);let R=v();if($-R<1e-5)break;$=R}return Math.abs(f.contrast-1)<1e-4&&(f.contrast=1,f.pivot=pr),{wheels:f,residual:v()}}var An=e=>e<0?0:e>1?1:e;function Yx(e){let t=e[0]*(e[4]*e[8]-e[5]*e[7])-e[1]*(e[3]*e[8]-e[5]*e[6])+e[2]*(e[3]*e[7]-e[4]*e[6]);return[(e[4]*e[8]-e[5]*e[7])/t,(e[2]*e[7]-e[1]*e[8])/t,(e[1]*e[5]-e[2]*e[4])/t,(e[5]*e[6]-e[3]*e[8])/t,(e[0]*e[8]-e[2]*e[6])/t,(e[2]*e[3]-e[0]*e[5])/t,(e[3]*e[7]-e[4]*e[6])/t,(e[1]*e[6]-e[0]*e[7])/t,(e[0]*e[4]-e[1]*e[3])/t]}function rj(e,t){let n=e.w*e.h,r=new Float32Array(n*3);for(let o=0;o<3;o++){let s=t[o],i=s.length-1;for(let a=0;a<n;a++){let l=Math.min(i,Math.max(0,Math.round(An(e.data[a*3+o])*i)));r[a*3+o]=s[l]}}return{data:r,w:e.w,h:e.h}}function Qx(e,t,n=1){let r=0,o=0;for(let s=0;s<e.w*e.h;s+=n){for(let i=0;i<3;i++)r+=Math.abs(An(e.data[s*3+i])-An(t.data[s*3+i]));o+=3}return r/o}var OH=.8/255;function Zx(e,t,n,r){let o=n??jc(e,t,r?.inner??"mvgd"),s=r?.tone1Contrast??null,i=r?.enableTone2??!0,a=r?.trimContrast??null,l=o.matrix,c=C=>({data:Float32Array.from(C.data,An),w:C.w,h:C.h}),u=rj(e,o.hm1),d=qf(e,u),p=o.offset,f=Yx(l),h=[f[0]*p[0]+f[1]*p[1]+f[2]*p[2],f[3]*p[0]+f[4]*p[1]+f[5]*p[2],f[6]*p[0]+f[7]*p[1]+f[8]*p[2]],g=e.w*e.h,b=new Float32Array(g*3);for(let C=0;C<g;C++){let B=d.out.data[C*3],L=d.out.data[C*3+1],Z=d.out.data[C*3+2];b[C*3]=An(l[0]*B+l[1]*L+l[2]*Z+p[0]),b[C*3+1]=An(l[3]*B+l[4]*L+l[5]*Z+p[1]),b[C*3+2]=An(l[6]*B+l[7]*L+l[8]*Z+p[2])}let k={data:b,w:e.w,h:e.h},w=qf(k,o.image);if(s==null&&i&&a==null){let C=Qx(c(w.out),o.image);return{tone1:d.tone,offset:h,matrix:l,tone2:w.tone,tone2Enabled:!0,trim:null,residual:C}}let y=s==null?d.tone:{...d.tone,contrast:s,pivot:d.tone.pivot??.435},_=a==null?null:{slope:[1,1,1],offset:[0,0,0],power:[1,1,1],contrast:a,pivot:.435},v=Bf(e,y),T=new Float32Array(g*3);for(let C=0;C<g;C++){let B=v.data[C*3],L=v.data[C*3+1],Z=v.data[C*3+2];T[C*3]=An(l[0]*B+l[1]*L+l[2]*Z+p[0]),T[C*3+1]=An(l[3]*B+l[4]*L+l[5]*Z+p[1]),T[C*3+2]=An(l[6]*B+l[7]*L+l[8]*Z+p[2])}let $={data:T,w:e.w,h:e.h},x=i?Bf($,w.tone):$;_&&(x=Bf(x,_));let R=Qx(x,o.image);return{tone1:y,offset:h,matrix:l,tone2:w.tone,tone2Enabled:i,trim:_,residual:R}}function Bf(e,t){let r=t.shadow||t.midtone||t.highlight||t.contrast!==void 0&&Math.abs(t.contrast-1)>1e-9?{shadow:t.shadow??[0,0,0],midtone:t.midtone??[0,0,0],highlight:t.highlight??[0,0,0],contrast:t.contrast??1,pivot:t.pivot??.435}:null,o=new Float32Array(3*4096);for(let i=0;i<3;i++){let a=t.power?.[i]??1;for(let l=0;l<4096;l++){let c=l/4095*t.slope[i]+t.offset[i];a!==1&&(c=c<0?-Math.pow(-c,a):Math.pow(c,a)),r&&(c=ho(c,r,i)),o[i*4096+l]=An(c)}}let s=new Float32Array(e.data.length);for(let i=0;i<e.w*e.h;i++)for(let a=0;a<3;a++)s[i*3+a]=o[a*4096+Math.min(4095,Math.max(0,Math.round(An(e.data[i*3+a])*4095)))];return{data:s,w:e.w,h:e.h}}function qf(e,t,n){let r=Uc(e,t,void 0,n),o=r.analysis,s=Xx(e,t,o,void 0,n);s.residual<r.maxResidual&&(o={...o,wheels:s.wheels});let i=Kx(e,o),a={data:Float32Array.from(i.data,An),w:e.w,h:e.h},l=Df(o);return{tone:{slope:l.slope,offset:l.offset,power:l.power,...l.wheels?{shadow:l.wheels.shadow,midtone:l.wheels.midtone,highlight:l.wheels.highlight,contrast:l.wheels.contrast,pivot:l.wheels.pivot}:{}},out:a}}function Uf(e,t,n=16){let{w:r,h:o}=e,s=(a,l)=>.2126*a[l*3]+.7152*a[l*3+1]+.0722*a[l*3+2],i=new Float32Array(r*o);for(let a=0;a<o;a+=n)for(let l=0;l<r;l+=n){let c=0,u=0,d=0,p=0,f=0,h=0,g=Math.min(o,a+n),b=Math.min(r,l+n);for(let v=a;v<g;v++)for(let T=l;T<b;T++){let $=v*r+T,x=s(e.data,$),R=s(t.data,$);c++,u+=x,d+=R,p+=x*x,f+=R*R,h+=x*R}let k=p/c-(u/c)**2,w=f/c-(d/c)**2,y=2e-5,_=k<y&&w<y?1:k<y||w<y?.1:Math.min(1,Math.max(0,((h/c-u/c*(d/c))/Math.sqrt(k*w)-.2)/.6));for(let v=a;v<g;v++)for(let T=l;T<b;T++){let $=v*r+T,x=Math.max(e.data[$*3],e.data[$*3+1],e.data[$*3+2])>.99||Math.max(t.data[$*3],t.data[$*3+1],t.data[$*3+2])>.99;i[$]=x?0:_}}return i}function oj(e,t){let n=[0,1,2,3].map(r=>[e[r*4],e[r*4+1],e[r*4+2],e[r*4+3],t[r]]);for(let r=0;r<4;r++){let o=r;for(let s=r+1;s<4;s++)Math.abs(n[s][r])>Math.abs(n[o][r])&&(o=s);if([n[r],n[o]]=[n[o],n[r]],Math.abs(n[r][r])<1e-12)return r<3?[r===0?1:0,r===1?1:0,r===2?1:0,0]:[0,0,0,0];for(let s=0;s<4;s++)if(s!==r){let i=n[s][r]/n[r][r];for(let a=r;a<5;a++)n[s][a]-=i*n[r][a]}}return n.map((r,o)=>r[4]/r[o])}var sj=0;function eS(e,t,n){if(e.w!==t.w||e.h!==t.h)throw new Error(`pixelFitStages: size mismatch ${e.w}x${e.h} vs ${t.w}x${t.h}`);let r=e.w*e.h,o=n?.weights??Uf(e,t),s=new Float64Array(16),i=new Float64Array(12),a=0;for(let T=0;T<r;T++){let $=o[T];if(!$)continue;a+=$;let x=[e.data[T*3],e.data[T*3+1],e.data[T*3+2],1];for(let R=0;R<4;R++){for(let C=0;C<4;C++)s[R*4+C]+=$*x[R]*x[C];for(let C=0;C<3;C++)i[R*3+C]+=$*x[R]*t.data[T*3+C]}}let l=(n?.ridge??sj)*a;for(let T=0;T<3;T++)s[T*4+T]+=l,i[T*3+T]+=l;let c=[0,1,2].map(T=>oj(s,[0,1,2,3].map($=>i[$*3+T]))),u=c.flatMap(T=>T.slice(0,3)),d=c.map(T=>T[3]),p=Yx(u),f=[p[0]*d[0]+p[1]*d[1]+p[2]*d[2],p[3]*d[0]+p[4]*d[1]+p[5]*d[2],p[6]*d[0]+p[7]*d[1]+p[8]*d[2]],h=new Float32Array(r*3);for(let T=0;T<r;T++){let $=e.data[T*3],x=e.data[T*3+1],R=e.data[T*3+2];for(let C=0;C<3;C++)h[T*3+C]=An(u[C*3]*$+u[C*3+1]*x+u[C*3+2]*R+d[C])}let g={data:h,w:e.w,h:e.h},b=T=>{let $=0,x=0;for(let R=0;R<r;R++){let C=o[R];C&&($+=C*(Math.abs(T.data[R*3]-t.data[R*3])+Math.abs(T.data[R*3+1]-t.data[R*3+1])+Math.abs(T.data[R*3+2]-t.data[R*3+2])),x+=3*C)}return x?$/x:0},k=qf(g,t,o),w=b(g),y=b(k.out),_=y<w-.5/255;return{tone1:{slope:[1,1,1],offset:[0,0,0],power:[1,1,1]},offset:f,matrix:u,tone2:k.tone,tone2Enabled:_,trim:null,residual:_?y:w,trustedShare:a/r}}function tS(e){let{wheels:t,...n}=e;return{...n,...t?{shadow:t.shadow,midtone:t.midtone,highlight:t.highlight,contrast:t.contrast,pivot:t.pivot}:{}}}function nS(e){if(e.mixerLumaLock!==!1||ti(e.mixer))return!1;let t=(s,i)=>Math.abs(s-i)<1e-9,n=e.power??[1,1,1],r=e.curves,o=!!r&&[r.r,r.g,r.b].some(s=>s&&s.length>=2);return[0,1,2].every(s=>t(n[s],1))&&rS(e)===null&&!o}function ij(e,t){if(t<=e[0][0])return e[0][1];let n=e[e.length-1];if(t>=n[0])return n[1];let r=0,o=e.length-1;for(;o-r>1;){let c=r+o>>1;e[c][0]<=t?r=c:o=c}let[s,i]=e[r],[a,l]=e[o];return a>s?i+(l-i)*(t-s)/(a-s):i}var qr=[.21,.7,.09];function rS(e){if(!e.shadow&&!e.midtone&&!e.highlight&&e.contrast===void 0)return null;let t=r=>[r?.[0]??0,r?.[1]??0,r?.[2]??0],n={shadow:t(e.shadow),midtone:t(e.midtone),highlight:t(e.highlight),contrast:e.contrast??1,pivot:e.pivot??pr};return ei(n)?null:n}function oS(e,t){if(nS(e))return i=>i;let n=rS(e),r=e.power??[1,1,1],o=[e.curves?.r,e.curves?.g,e.curves?.b].map(i=>i&&i.length>=2?i:null),s=i=>i<0?0:i>1?1:i;return(i,a)=>{let l=i*e.slope[a]+e.offset[a],c=r[a];c!==1&&(l=l<0?-Math.pow(-l,c):Math.pow(l,c)),n&&(l=ho(l,n,a));let u=o[a];return u&&(l=ij(u,s(l))),t?s(l):l}}function sS(e){let t=e.saturation??1,n=Math.abs(t-1)>1e-9,r=!ti(e.mixer),o=nS(e);if(!n&&!r&&!o)return null;let s=[t+(1-t)*qr[0],(1-t)*qr[1],(1-t)*qr[2],(1-t)*qr[0],t+(1-t)*qr[1],(1-t)*qr[2],(1-t)*qr[0],(1-t)*qr[1],t+(1-t)*qr[2]];if(r){let a=e.mixerLumaLock===!1?e.mixer:qc(e.mixer),l=new Array(9);for(let c=0;c<3;c++)for(let u=0;u<3;u++)l[c*3+u]=a[c*3]*s[u]+a[c*3+1]*s[3+u]+a[c*3+2]*s[6+u];s=l}let i=[0,0,0];if(o){let a=e.slope,l=e.offset;for(let c=0;c<3;c++){i[c]=s[c*3]*l[0]+s[c*3+1]*l[1]+s[c*3+2]*l[2];for(let u=0;u<3;u++)s[c*3+u]*=a[u]}}return{m:s,add:i}}var ba=-1,go=-1,aS=!1,Hf=.35,aj=[.25,-.5,Math.log(.25)],lj=[4,.5,Math.log(4)],Rr=-1;function Gf(e){let t={slope:[e[0],e[1],e[2]],offset:[e[3],e[4],e[5]],power:[Math.exp(e[6]),Math.exp(e[7]),Math.exp(e[8])],contrast:e[9],pivot:ba>=0?e[ba]:pr,saturation:e[10]};if(Rr>=0&&(t.master={slope:e[Rr],offset:e[Rr+1],power:Math.exp(e[Rr+2])}),go>=0){let n=e.slice(go,go+6);t.mixer=[1,n[0],n[1],n[2],1,n[3],n[4],n[5],1],aS&&(t.mixerLumaLock=!1)}return e.length-(ba>=0?1:0)-(go>=0?6:0)-(Rr>=0?3:0)>11&&(t.shadow=[e[11],e[12],e[13]],t.midtone=[e[14],e[15],e[16]],t.highlight=[e[17],e[18],e[19]]),t}var cj=[.25,.25,.25,-.5,-.5,-.5,Math.log(.25),Math.log(.25),Math.log(.25),.5,0,...Array(9).fill(-.3)],uj=[4,4,4,.5,.5,.5,Math.log(4),Math.log(4),Math.log(4),2,2,...Array(9).fill(.3)],dj=e=>e.map((t,n)=>n===ba?Math.min(.9,Math.max(.1,t)):Rr>=0&&n>=Rr?Math.min(lj[n-Rr],Math.max(aj[n-Rr],t)):go>=0&&n>=go&&n<go+6?Math.min(Hf,Math.max(-Hf,t)):Math.min(uj[n],Math.max(cj[n],t))),Gc=(e,t)=>t===1?e:e<0?-Math.pow(-e,t):Math.pow(e,t);function iS(e,t,n,r){let o=e.master,s=o?{...e,slope:[1,1,1],offset:[0,0,0],power:[1,1,1]}:{...e},i=oS(s,!1),a=sS(s);for(let l=0;l<t.length;l+=3){let c,u,d;if(o){let p=t[l],f=t[l+1],h=t[l+2],g=Gc(p*e.slope[0]+e.offset[0],e.power[0]),b=Gc(f*e.slope[1]+e.offset[1],e.power[1]),k=Gc(h*e.slope[2]+e.offset[2],e.power[2]),w=.2126*g+.7152*b+.0722*k,y=.2126*p+.7152*f+.0722*h,_=Gc(y*o.slope+o.offset,o.power);c=i(g-w+_,0),u=i(b-w+_,1),d=i(k-w+_,2)}else c=i(t[l],0),u=i(t[l+1],1),d=i(t[l+2],2);if(a){let p=a.m,f=a.add,h=p[0]*c+p[1]*u+p[2]*d+f[0],g=p[3]*c+p[4]*u+p[5]*d+f[1],b=p[6]*c+p[7]*u+p[8]*d+f[2];c=h,u=g,d=b}n[l]=c,n[l+1]=u,n[l+2]=d}r?.(n);for(let l=0;l<n.length;l++)n[l]=n[l]<0?0:n[l]>1?1:n[l]}function pj(e,t,n){let r=e.slice(),o=t.slice();for(let i=0;i<n;i++){let a=i;for(let c=i+1;c<n;c++)Math.abs(r[c*n+i])>Math.abs(r[a*n+i])&&(a=c);if(a!==i){for(let c=0;c<n;c++)[r[i*n+c],r[a*n+c]]=[r[a*n+c],r[i*n+c]];[o[i],o[a]]=[o[a],o[i]]}let l=r[i*n+i]||1e-12;for(let c=i+1;c<n;c++){let u=r[c*n+i]/l;if(u){for(let d=i;d<n;d++)r[c*n+d]-=u*r[i*n+d];o[c]-=u*o[i]}}}let s=new Array(n).fill(0);for(let i=n-1;i>=0;i--){let a=o[i];for(let l=i+1;l<n;l++)a-=r[i*n+l]*s[l];s[i]=a/(r[i*n+i]||1e-12)}return s}function zf(e,t,n={}){if(n.matchChroma&&n.matchStats===void 0&&(n={...n,matchStats:1}),e.w!==t.w||e.h!==t.h)throw new Error(`fitPrimaries: size mismatch ${e.w}x${e.h} vs ${t.w}x${t.h}`);let r=e.w*e.h,o=n.samples??6e3;if(n.skinBoost&&n.skinBoost>1){let H=n.weights??new Float32Array(r).fill(1),le=new Float32Array(r);for(let pe=0;pe<r;pe++){if(le[pe]=H[pe],!H[pe])continue;let xe=t.data[pe*3]*255,ve=t.data[pe*3+1]*255,Oe=t.data[pe*3+2]*255,ue=.299*xe+.587*ve+.114*Oe,me=128-.168736*xe-.331264*ve+.5*Oe,ge=128+.5*xe-.418688*ve-.081312*Oe;(n.skinRegion===void 0||n.skinRegion!==null&&n.skinRegion[pe]>1)&&me>=77&&me<=127&&ge>=133&&ge<=173&&ue>40&&ue<235&&(le[pe]=H[pe]*n.skinBoost)}n={...n,weights:le}}let s=[];for(let H=0;H<r;H++)(!n.weights||n.weights[H]>0)&&s.push(H);let i=[],a=Math.max(1,s.length/o);for(let H=0;H<s.length&&i.length<o;H+=a)i.push(s[Math.floor(H)]);let l=i.length,c=new Float64Array(l*3),u=new Float64Array(l*3),d=new Float64Array(l);i.forEach((H,le)=>{for(let pe=0;pe<3;pe++)c[le*3+pe]=e.data[H*3+pe],u[le*3+pe]=t.data[H*3+pe];d[le]=Math.sqrt(n.weights?n.weights[H]:1)});let p=(n.wheels?20:11)+(n.freePivot?1:0)+(n.mixer||n.mixerRaw?6:0)+(n.lumMix100?3:0),f=[1,1,1,0,0,0,0,0,0,1,1,...n.wheels?Array(9).fill(0):[],...n.freePivot?[pr]:[],...n.mixer||n.mixerRaw?Array(6).fill(0):[]];Rr=n.lumMix100?p-3:-1,n.lumMix100&&(f=[...f,1,0,0]),go=n.mixer||n.mixerRaw?p-6-(n.lumMix100?3:0):-1,aS=!!n.mixerRaw,Hf=n.mixerRaw?1.5:.35,ba=n.freePivot?p-1-(n.mixer||n.mixerRaw?6:0)-(n.lumMix100?3:0):-1;let h=[.2126,.7152,.0722],g=n.keepTone;g&&(f=[...g.slope,...g.offset,...g.power.map(Math.log),g.contrast,g.saturation,...f.slice(11)]);let b=H=>{if(n.balanceOnly&&(H[7]=H[6],H[8]=H[6]),g){let le=h[0]*H[0]+h[1]*H[1]+h[2]*H[2],pe=h[0]*g.slope[0]+h[1]*g.slope[1]+h[2]*g.slope[2];for(let Oe=0;Oe<3;Oe++)H[Oe]*=pe/le;let xe=h[0]*H[3]+h[1]*H[4]+h[2]*H[5],ve=h[0]*g.offset[0]+h[1]*g.offset[1]+h[2]*g.offset[2];for(let Oe=3;Oe<6;Oe++)H[Oe]+=ve-xe}return H};if(n.lumMix100){let H=b;b=le=>{H(le);let pe=h[0]*le[0]+h[1]*le[1]+h[2]*le[2];for(let ve=0;ve<3;ve++)le[ve]/=pe;let xe=h[0]*le[3]+h[1]*le[4]+h[2]*le[5];for(let ve=3;ve<6;ve++)le[ve]-=xe;return le[6]=le[7]=le[8]=0,le}}let k=new Set([...n.balanceOnly?[7,8]:[],...g?[6,7,8,9]:[],...n.lumMix100?[6,7,8]:[],...n.noContrastSat?[9,10]:[]]),w=[1,1,1,0,0,0,0,0,0,1,1,...n.wheels?Array(9).fill(0):[],...n.freePivot?[pr]:[],...n.mixer||n.mixerRaw?Array(6).fill(0):[],...n.lumMix100?[1,0,0]:[]],y=[6,7,8,9],_=0;for(let H=0;H<l;H++)_+=d[H]*d[H];let v=Math.sqrt((n.prior??0)*_),T=[.02,.1,.25,.5,.75,.9,.98],$=H=>{let le=new Float64Array(l),pe=0,xe=0;for(let ge=0;ge<l;ge++){let Re=H[ge*3],Le=H[ge*3+1],Ne=H[ge*3+2],We=d[ge]*d[ge];xe+=We,pe+=We*(Math.max(Re,Le,Ne)-Math.min(Re,Le,Ne)),le[ge]=.2126*Re+.7152*Le+.0722*Ne}let ve=new Float64Array(9),Oe=[0,0,0];B.forEach((ge,Re)=>{for(let Le of ge){for(let Ne=0;Ne<3;Ne++)ve[Re*3+Ne]+=H[Le*3+Ne];Oe[Re]++}});let ue=new Float64Array(6),me=[0,0];return X.forEach((ge,Re)=>{for(let Le of ge){for(let Ne=0;Ne<3;Ne++)ue[Re*3+Ne]+=H[Le*3+Ne];me[Re]++}}),le.sort(),[...T.map(ge=>le[Math.floor(ge*(l-1))]),pe/xe,...Array.from(ve,(ge,Re)=>Oe[Re/3|0]?ge/Oe[Re/3|0]:0),...[0,1].flatMap(()=>Array.from(ue,(ge,Re)=>me[Re/3|0]?ge/me[Re/3|0]:0))]},x=[];for(let H=0;H<l;H++){let le=u[H*3],pe=u[H*3+1],xe=u[H*3+2],ve=.2126*le+.7152*pe+.0722*xe;Math.max(le,pe,xe)-Math.min(le,pe,xe)<.06&&ve>.04&&ve<.96&&x.push(H)}let R=H=>.2126*u[H*3]+.7152*u[H*3+1]+.0722*u[H*3+2];x.sort((H,le)=>R(H)-R(le));let C=Math.floor(x.length/3),B=C>=20?[x.slice(0,C),x.slice(C,2*C),x.slice(2*C)]:[[],[],[]],L=[];for(let H=0;H<l;H++){let le=u[H*3]*255,pe=u[H*3+1]*255,xe=u[H*3+2]*255,ve=.299*le+.587*pe+.114*xe,Oe=128-.168736*le-.331264*pe+.5*xe,ue=128+.5*le-.418688*pe-.081312*xe;Oe>=77&&Oe<=127&&ue>=133&&ue<=173&&ve>40&&ve<235&&L.push(H)}L.sort((H,le)=>R(H)-R(le));let Z=Math.floor(L.length/2),X=Z>=15?[L.slice(0,Z),L.slice(Z)]:[[],[]],O=$(u),ae=n.matchStats?O.length:0,W=Math.sqrt((n.matchStats??0)*_*3/Math.max(1,ae)),ne=l*3+ae+y.length,z=new Float64Array(l*3),q=H=>{iS(Gf(H),c,z,n.post);let le=new Float64Array(ne);for(let pe=0;pe<l*3;pe++)le[pe]=(z[pe]-u[pe])*d[pe/3|0];if(ae){let pe=$(z);for(let xe=0;xe<ae;xe++)le[l*3+xe]=W*(pe[xe]-O[xe])}return y.forEach((pe,xe)=>{le[l*3+ae+xe]=v*(H[pe]-w[pe])}),le},j=H=>{let le=0;for(let pe of H)le+=pe*pe;return le},I=q(f),S=j(I),A=.001,U=0,de=n.iterations??80,te=new Float64Array(ne*p);for(;U<de;U++){for(let ve=0;ve<p;ve++){if(k.has(ve)){for(let ge=0;ge<ne;ge++)te[ge*p+ve]=0;continue}let Oe=1e-4,ue=f.slice();ue[ve]+=Oe,b(ue);let me=q(ue);for(let ge=0;ge<ne;ge++)te[ge*p+ve]=(me[ge]-I[ge])/Oe}let H=new Array(p*p).fill(0),le=new Array(p).fill(0);for(let ve=0;ve<ne;ve++){let Oe=I[ve];for(let ue=0;ue<p;ue++){let me=te[ve*p+ue];if(me){le[ue]+=me*Oe;for(let ge=ue;ge<p;ge++)H[ue*p+ge]+=me*te[ve*p+ge]}}}for(let ve of k)H[ve*p+ve]+=1;for(let ve=0;ve<p;ve++)for(let Oe=0;Oe<ve;Oe++)H[ve*p+Oe]=H[Oe*p+ve];let pe=!1,xe=!1;for(let ve=0;ve<8;ve++){let Oe=H.slice();for(let Le=0;Le<p;Le++)Oe[Le*p+Le]*=1+A;let ue=pj(Oe,le.map(Le=>-Le),p),me=b(dj(f.map((Le,Ne)=>k.has(Ne)?Le:Le+ue[Ne]))),ge=q(me),Re=j(ge);if(Re<S){xe=(S-Re)/Math.max(S,1e-12)<1e-7,f=me,S=Re,I=ge,A=Math.max(A/3,1e-7),pe=!0;break}A*=4}if(!pe||xe)break}iS(Gf(f),c,z,n.post);let _e=0,Se=0;for(let H=0;H<l*3;H++){let le=d[H/3|0]**2;_e+=le*Math.abs(z[H]-u[H]),Se+=le}return{cdl:Gf(f),residual:Se?_e/Se:0,iterations:U}}var mj="yunet.safetensors";async function lS(e){let t=await Ar(),n=t&&re(t.model,mj);if(!t||!n||!await On(n))return[];let r=new Uint8Array(e.w*e.h*3);for(let s=0;s<r.length;s++)r[s]=Math.max(0,Math.min(255,Math.round(e.data[s]*255)));let o=await It("conform-faces-");try{let s=re(o,"in.rgb");await Gn(s,r);let i=[],a=await br(t.runner,["faces","--weights",n,"--input-rgb",`${s}:${e.w}x${e.h}`],c=>i.push(c));if(a.code!==0)throw new Error(`face detection failed (exit ${a.code}): ${a.stderr.trim().slice(-300)}`);return JSON.parse(new TextDecoder().decode(fj(i)).trim()).faces.map(c=>({x0:Math.max(0,c.x/e.w),y0:Math.max(0,c.y/e.h),x1:Math.min(1,(c.x+c.w)/e.w),y1:Math.min(1,(c.y+c.h)/e.h),score:c.score}))}finally{await Wt(o).catch(()=>{})}}function fj(e){let t=new Uint8Array(e.reduce((r,o)=>r+o.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t}function cS(e,t,n=8){let r=t.filter(i=>i.x1>i.x0&&i.y1>i.y0&&i.score>0);if(r.length===0)return null;let o=e.w*e.h,s=new Float32Array(o).fill(1);for(let i of r){let a=(i.x0+i.x1)/2*e.w,l=(i.y0+i.y1)/2*e.h,c=Math.max(1,(i.x1-i.x0)/2*e.w),u=Math.max(1,(i.y1-i.y0)/2*e.h),d=Math.max(0,Math.floor(a-2.5*c)),p=Math.min(e.w,Math.ceil(a+2.5*c)),f=Math.max(0,Math.floor(l-2.5*u)),h=Math.min(e.h,Math.ceil(l+2.5*u));for(let g=f;g<h;g++){let b=(g-l)/u;for(let k=d;k<p;k++){let w=(k-a)/c,y=w*w+b*b,_=1+(n-1)*i.score*Math.exp(-y/(2*.45)),v=g*e.w+k;_>s[v]&&(s[v]=_)}}}return s}var uS=()=>({slope:[1,1,1],offset:[0,0,0],power:[1,1,1]});function Wf(e,t){let n=Hc(t),r="engine"in e&&e.engine==="ai"?e:null,o=r?r.transferred?"Color Transfer":"Autobalance":"Auto Balance",s={source:r?r.transferred?"ai_color_transfer_v1":"ai_balance_v1":"auto_balance_v1",castDeg:e.analysis.castDeg,exposureStops:e.analysis.exposureStops,wbGain:e.analysis.wbGain,blackPointOffset:e.analysis.blackPointOffset,framesUsed:e.framesUsed,transfer:e.transfer,...r?{seed:r.seed,prompt:r.prompt,fitResidual:r.fitResidual,inferenceMs:r.inferenceMs,matchMethod:r.matchMethod,gradeStyle:r.gradeStyle,usesLogWheels:e.cdl.wheels!==void 0,usesSaturation:e.cdl.saturation!==void 0,facesDetected:r.facesDetected,skinWeighted:r.skinWeighted}:{}};if(r?.fold){let a=r.fold;return[{id:n[0],kind:"cdl",label:`${o} \xB7 tone 1`,enabled:!0,cdl:{...a.tone1},meta:s},{id:n[1],kind:"cdl",label:`${o} \xB7 match matrix`,enabled:!0,cdl:{...uS(),offset:a.offset,mixer:a.matrix,mixerLumaLock:!1},meta:{source:s.source,part:"2/4"}},{id:n[2],kind:"cdl",label:`${o} \xB7 tone 2`,enabled:a.tone2Enabled??!0,cdl:{...a.tone2},meta:{source:s.source,part:"3/4"}},...a.trim?[{id:n[3],kind:"cdl",label:`${o} \xB7 trim`,enabled:!0,cdl:{...uS(),contrast:a.trim.contrast,pivot:a.trim.pivot},meta:{source:s.source,part:"4/4"}}]:[]]}let i=tS(e.cdl);return[{id:n[0],kind:"cdl",label:o,enabled:!0,cdl:i,meta:s}]}function Hc(e){let t=e?`@${e}`:"";return[`auto-balance${t}`,`auto-balance${t}-2`,`auto-balance${t}-3`,`auto-balance${t}-4`]}function dS(e,t,n,r){let o=Wf(e,r),s=new Set(o.map(a=>a.id)),i=r?[...Hc(r),...Hc()]:Hc();return[...o.map(a=>({timeline_id:t,item_id:n,entry:a})),...i.filter(a=>!s.has(a)).map(a=>({timeline_id:t,item_id:n,remove_id:a}))]}var pS={inputColorSpace:"REC709_COLORSPACE",inputGamma:"TWOPOINTFOUR_GAMMA",outputColorSpace:"REC709_COLORSPACE",outputGamma:"TWOPOINTFOUR_GAMMA"};function mS(e){let t=String(e.outputGamma??pS.outputGamma);return t==="TWOPOINTFOUR_GAMMA"||t==="REC709_GAMMA"?"g24":t==="SRGB_GAMMA"?"srgb":null}function Kf(e){let t=n=>String(e[n]??pS[n]).replace(/_(COLORSPACE|GAMMA)$/,"");return`${t("inputColorSpace")}/${t("inputGamma")} \u2192 ${t("outputColorSpace")}/${t("outputGamma")}`}async function es(e,t){await Gr();let n=Float32Array.from(e.data);return d1(JSON.stringify(t),n),{data:n,w:e.w,h:e.h}}var bS=["primaries","pixel","hm-mkl-hm","hm-coral-hm","hm-adain-hm","hm-mvgd-hm"],fS=1024;async function hj(e){let t=await tb(e);return Ef(t.rgba,t.width,t.height)}async function gj(e,t){let n=await st(e),r=n.streams?.find(u=>u.kind==="video"),o=(r?.codec??"").toLowerCase(),s=n.source_fps??r?.rate??24,i=n.available_range?.duration?.value??0;if(["r3d","braw","crm","canon","arriraw","ari","xocn","prores_raw","prores raw","aprn","aprh"].some(u=>o.includes(u)))throw new Error(`${fe(e)} is camera-native raw (${o}): the engine decodes it as log, so a display-referred match would be wrong \u2014 match on a proxy or a rendered frame`);let l=t==null?Math.floor(i/2):yr(t,s,n.source_timecode??null);if(i&&(l<0||l>=i))throw new Error(`frame ${l} is outside ${fe(e)} (0\u2013${i-1})`);let c=await Ma(e,l,o);return{image:Ef(c.rgba,c.width,c.height),frame:l,codec:o,transfer:"g24",fps:s}}async function hS(e,t){let n=Hn(e).toLowerCase();if(Yg.has(n)||Zg.has(n))return{image:await hj(e),frame:0,codec:"still",transfer:"srgb",fps:0};if(Ea.has(n))return gj(e,t);throw new Error(`unsupported file for color match: ${fe(e)}`)}async function yS(e){let t=Date.now(),n=e.reference==="auto"||e.reference==="ai";if(n&&!Ln())throw new P("unsupported",`reference "auto": ${wi}; match to a still or a frame of another clip`);let r=e.method??(n?"primaries":"hm-mkl-hm"),o=r.split("-")[1],s=await hS(e.source,e.frame);if(e.cst){let _=mS(e.cst);if(!_)throw new Error(`the clip's Color Space Transform (${Kf(e.cst)}) does not end on a display; balance needs Rec.709/sRGB out`);s.image=await es(s.image,e.cst),s.transfer=_}let i,a=n?await(async()=>{let _=ki();if(_)throw new Error(_);let v=await Ar();if(!v&&!e.download)throw new Error("the Autocolor model is not installed yet: run again with download: true to fetch it once (~4.3 GB, stays on this machine)");v??=await Xa({onProgress:e.onProgress});let T=await _y(v,Oc(s.image,1024)),$=vy(gS(s.image,T.w,T.h),T);return i={ms:T.ms,askedStops:$.askedStops,appliedStops:$.appliedStops},{image:$.image,frame:0,codec:"ai",transfer:s.transfer,fps:0}})():await hS(e.reference,e.reference_frame),l=e.transfer??s.transfer;Fx(l);let c=Oc(s.image,fS),u=Oc(a.image,fS);(o==="mvgd"||r==="pixel"||r==="primaries")&&(u.w!==c.w||u.h!==c.h)&&(u=gS(u,c.w,c.h));let d,p,f,h,g=0,b=0;if(r==="primaries"){let _=Uf(c,u),v=0;for(let C of _)v+=C;let T,$=e.skinBoost??3;if($>1){let C=await lS(u);g=C.length,T=cS(u,C);let B=C.reduce((L,Z)=>L+Math.max(0,Z.x1-Z.x0)*Math.max(0,Z.y1-Z.y0)*Z.score,0);b=Math.min(1,B/.05)}let x={weights:_,balanceOnly:!0,mixerRaw:e.mixer===!0};h=zf(c,u,x);let R=1+($-1)*b;T&&R>1.05&&(h=zf(c,u,{...x,skinBoost:R,skinRegion:T,keepTone:h.cdl})),p=u,f=v/_.length}else if(r==="pixel"){let _=eS(c,u);d=_,p=u,f=_.trustedShare}else{let _=jc(c,u,o);d=Zx(c,u,_,{tone1Contrast:null,enableTone2:!1,trimContrast:null}),p=_.image}let k=Uc(c,p),w={itemId:e.item_id??"color-match",averaged:c,balanced:p,report:{},analysis:k.analysis,cdl:{slope:[1,1,1],offset:[0,0,0],power:[1,1,1]},framesUsed:[s.frame],issues:[],transfer:l,sourceW:s.image.w,sourceH:s.image.h,totalMs:Date.now()-t,engine:"ai",transferred:!0,reference:u,seed:n?376436993:0,prompt:n?"balance (FLUX.2 klein, local)":"",matchMethod:r,fitResidual:h?.residual??d.residual,lumaStops:k.lumaStops,inferenceMs:i?.ms??0,facesDetected:g,skinWeighted:g>0,gradeStyle:h?"primaries":"fold",fold:d};if(h){let _=h.cdl;w.cdl={slope:_.slope,offset:_.offset,power:_.power,saturation:_.saturation,..._.mixer?{mixer:_.mixer,mixerLumaLock:_.mixerLumaLock}:{},wheels:{shadow:[0,0,0],midtone:[0,0,0],highlight:[0,0,0],contrast:_.contrast,pivot:_.pivot}}}let y=Wf(w);return{run:w,entries:y,method:r,transfer:l,source:{path:e.source,frame:s.frame,codec:s.codec,w:s.image.w,h:s.image.h},reference:{path:n?"FLUX.2 klein (local)":e.reference,w:a.image.w,h:a.image.h},residual:h?.residual??d.residual,lumaStops:k.lumaStops,ai:i,trustedShare:f,cst:e.cst?Kf(e.cst):void 0}}function wS(e,t,n){return dS(e.run,t,n)}function kS(e,t){for(let n of e.timelines)for(let r of n.tracks)for(let o of r.items){if(o.id!==t)continue;return(o.effects??[]).find(i=>i.kind==="color_space_transform")?.parameters}}function _S(e,t){let n=[];for(let r of e.timelines)for(let o of r.tracks)for(let s of o.items)(s.id===t||s.name===t)&&n.push({timelineId:r.id??"",itemId:s.id,name:s.name??""});return n.length===1?n[0]:n.length>1?n.find(o=>o.itemId===t)??n[0]:null}var bo=e=>(Math.round(e*1e3)/1e3).toString(),ts=e=>e?`[${e.map(bo).join(", ")}]`:"\u2014";function vS(e){let t=[`source ${fe(e.source.path)} frame ${e.source.frame} (${e.source.codec}, ${e.source.w}x${e.source.h}, ${e.cst?`after the clip's CST ${e.cst}, `:""}${e.transfer}) \u2192 reference ${fe(e.reference.path)} (${e.reference.w}x${e.reference.h})`,`method ${e.method}; fit residual ${bo(e.residual)} (mean |chain \u2212 match|, 0\u20131 codes); luma ${e.lumaStops>=0?"+":""}${bo(e.lumaStops)} stops`,...e.ai?[`Autobalance: FLUX.2 klein on this machine in ${(e.ai.ms/1e3).toFixed(1)} s; exposure held (model asked ${e.ai.askedStops>=0?"+":""}${bo(e.ai.askedStops)} stops, applied ${e.ai.appliedStops>=0?"+":""}${bo(e.ai.appliedStops)})`]:[],...e.method==="primaries"?[(n=>n.facesDetected?`skin: ${n.facesDetected} face${n.facesDetected>1?"s":""} found \u2014 skin protected (color only, contrast kept)`:"skin: no faces in the frame \u2014 plain balance")(e.run)]:[],"grade (Resolve node order \u2014 timeline_write resolve-drt emits them as corrector nodes):"];for(let n of e.entries){let r=n.cdl??{},o=n.enabled===!1?" (bypassed)":"",s=[r.slope?`slope ${ts(r.slope)}`:"",r.offset?`offset ${ts(r.offset)}`:"",r.power?`power ${ts(r.power)}`:"",r.mixer?`mixer ${ts(r.mixer)}`:"",r.saturation!=null?`sat ${bo(r.saturation)}`:"",r.contrast!=null?`contrast ${bo(r.contrast)} @ pivot ${bo(r.pivot??.435)}`:"",r.shadow?`wheels lift ${ts(r.shadow)} gamma ${ts(r.midtone)} gain ${ts(r.highlight)}`:""].filter(Boolean);t.push(`- ${n.label??n.id}${o}: ${s.join("; ")}`)}return t.join(`
|
|
319
|
+
`)}function gS(e,t,n){let r=new Float32Array(t*n*3);for(let o=0;o<n;o++){let s=Math.min(e.h-1,Math.floor((o+.5)*e.h/n));for(let i=0;i<t;i++){let a=Math.min(e.w-1,Math.floor((i+.5)*e.w/t)),l=(s*e.w+a)*3,c=(o*t+i)*3;r[c]=e.data[l],r[c+1]=e.data[l+1],r[c+2]=e.data[l+2]}}return{data:r,w:t,h:n}}var Vf=960,bj=187.5/1023,TS={lift:100663320,gain:100663325,gamma:100663330,offset:100663421,contrast:2248147137,pivot:2248147136,shadow:2248147138,temp:2248147221,tint:2248147222};function yj(e){let t=[];for(let n of["lift","gain","gamma","offset","shadow"])e[n].forEach((r,o)=>t.push([TS[n]+o,r]));for(let n of["contrast","pivot","temp","tint"])t.push([TS[n],e[n]]);return t.sort((n,r)=>n[0]-r[0])}function wj(e,t=`(3, ${e.h}, ${e.w})`){let n=`{'descr': '<f4', 'fortran_order': False, 'shape': ${t}, }`;for(;(10+n.length+1)%64;)n+=" ";n+=`
|
|
320
|
+
`;let r=e.w*e.h,o=new Uint8Array(10+n.length+12*r);o.set([147,78,85,77,80,89,1,0,n.length&255,n.length>>8]),o.set(new TextEncoder().encode(n),10);let s=new Float32Array(3*r);for(let i=0;i<r;i++)for(let a=0;a<3;a++)s[a*r+i]=e.data[i*3+a];return o.set(new Uint8Array(s.buffer),10+n.length),o}var kj=["H","Q1","M","Q3","T"],zc=["clip","group_pre","group_post","adjustment_clips","timeline","output"],_j=`How do you build your grade? (color_prep look_levels=[...] lut_dirs=[...])
|
|
321
|
+
look_levels: where your look lives, any of: clip (nodes after your balance node in this tree), group_pre, group_post, adjustment_clips, timeline, output (an output LUT in project settings)
|
|
322
|
+
lut_dirs: the folders your LUTs and DCTLs live in (so I can read your DCTLs and find your LUTs; anything encrypted I bake through Resolve in a scratch project)`;function Wc(e){return[e.space!=null?`colour space ${e.space_name??`#${e.space}`}`:"",e.gamma!=null?`gamma ${e.gamma_name??`#${e.gamma}`}`:""].filter(Boolean).join(", ")}async function SS(e){if(!e||!/\.(drt|drp)$/i.test(e)||!await Ye(e))return null;try{let t=cs(await Ut(e),{filter:n=>n.name==="project.xml"})["project.xml"];return t?await s1(new TextDecoder().decode(t)):null}catch{return null}}function vj(e,t){return!!t?.timeline_space&&t.timeline_space===e.working.space&&t.timeline_gamma===e.working.gamma}function $S(e,t){return e.working}function Tj(e,t){let n=e.nodes.find(o=>o.id===e.balance_node),r=$S(e,t);return{working:[r.space,r.gamma],...n?.space!=null?{node_space:n.space}:{},...n?.gamma!=null?{node_gamma:n.gamma}:{}}}async function RS(e,t,n,r,o,s){if(!await Ye(e))throw new P("not_found",`tree: no file at ${e} (the colourist's .drx, exported from a clip's node graph)`);let i=await i1(await ct(e));if(!i.ok)throw new P("invalid_args",`${fe(e)}: ${i.why}`);let a=i.nodes.map(f=>` node ${f.id}${f.label?` "${f.label}"`:""}${f.cst?` (Color Space Transform: ${f.cst_params?.inputColorSpace??"?"}/${f.cst_params?.inputGamma??"?"} -> ${f.cst_params?.outputColorSpace??"?"}/${f.cst_params?.outputGamma??"?"})`:""}${Wc(f)?` (grades in its own ${Wc(f)})`:""}`).join(`
|
|
323
|
+
`);if(t==null||n==null&&!s||!r?.length)return{ask:`${fe(e)} has ${i.nodes.length} nodes:
|
|
324
|
+
${a}
|
|
325
|
+
Which node is the BALANCE node, and which is the input Color Space Transform? (color_prep tree=\u2026 balance_node=<id> cst_node=<id>; if their input CST is not in this tree \u2014 in a group pre-clip grade or color management \u2014 give working="<SPACE>_COLORSPACE/<CURVE>_GAMMA" for the space this tree works in instead of cst_node)
|
|
326
|
+
${_j}`};if(!i.nodes.find(f=>f.id===t))throw new P("invalid_args",`${fe(e)} has no node ${t}:
|
|
327
|
+
${a}`);let c;if(n!=null){let f=i.nodes.find(h=>h.id===n);if(!f?.cst){let h=i.nodes.filter(b=>b.cst).map(b=>b.id),g=h.length?`The Color Space Transform node${h.length===1?"":"s"} in this tree: ${h.join(", ")}. Ask the user which is their input CST; do not try ids.`:"This tree has NO Color Space Transform node: their input transform is outside it (group pre-clip, color management). Ask the user which space the tree works in and pass working=<SPACE>_COLORSPACE/<CURVE>_GAMMA instead of cst_node.";throw new P("invalid_args",`node ${n} is not a Color Space Transform node. ${g}
|
|
328
|
+
${a}`)}if(c=f.cst_params??{},!c.outputColorSpace||!c.outputGamma)throw new P("invalid_args",`node ${n}'s CST does not say its output (working) space; set it in Resolve and export the still again`)}else{let[f,h]=s.split("/").map(g=>g.trim());if(!f?.endsWith("_COLORSPACE")||!h?.endsWith("_GAMMA"))throw new P("invalid_args",`working '${s}': give <SPACE>_COLORSPACE/<CURVE>_GAMMA (Resolve CST names, e.g. DWG_COLORSPACE/DAV_INTER_OETF_GAMMA)`);c={outputColorSpace:f,outputGamma:h}}let u=r.filter(f=>!zc.includes(f));if(u.length)throw new P("invalid_args",`look_levels ${u.join(", ")}: use ${zc.join(", ")}`);let d={name:fe(e),body_hex:i.body_hex,nodes:i.nodes,balance_node:t,...n!=null?{cst_node:n}:{},working:{space:String(c.outputColorSpace),gamma:String(c.outputGamma)},look_levels:r,lut_dirs:o},p=await mi();return await J1({...p,color_tree:d}),{tree:d}}async function CS(){return(await mi()).color_tree??null}async function AS(e){let t=await or();if(!t)throw new P("unsupported","the native decoder (conformtools-decode) is not installed");let n=[],r=await br(t,e,i=>n.push(i)),o=new Uint8Array(n.reduce((i,a)=>i+a.length,0)),s=0;for(let i of n)o.set(i,s),s+=i.length;return{out:o,...r}}async function xS(e){let t=await AS(["colour",e]).catch(n=>({code:1,out:new Uint8Array,stderr:String(n?.message??n)}));return t.code!==0?{kind:"unknown",evidence:`could not read it (${t.stderr.trim().slice(0,200)})`,confident:!1}:JSON.parse(new TextDecoder().decode(t.out))}async function xj(e){let t=[],n=e.split("/").slice(-3).reverse().find(s=>/prox(y|ies)/i.test(s));n&&t.push(`its ${n===fe(e)?"name":"folder"} says proxy ("${n}")`);let r=(await st(e).catch(()=>null))?.streams?.find(s=>s.kind==="video"),o=r?.codec_specific?.profile??"";return/^ProRes (Proxy|LT)$/i.test(o)&&t.push(`it is ${o}, a proxy codec${r?.width?` at ${r.width}x${r.height}`:""}`),t}function Jf(e,t){let n=e?.find(i=>t.some(a=>a.toLowerCase().includes(i.match.toLowerCase())));if(!n)return null;let r=n.as.trim();if(/^(graphic|none|skip)$/i.test(r))return{kind:"graphic",evidence:`you said: ${r}`,confident:!0};if(/^rec\.?709$/i.test(r))return{kind:"display",color_space:"REC709_COLORSPACE",gamma:"TWOPOINTFOUR_GAMMA",evidence:"you said: Rec.709",confident:!0};let[o,s]=r.split("/").map(i=>i.trim());if(!o?.endsWith("_COLORSPACE")||!s?.endsWith("_GAMMA"))throw new P("invalid_args",`color answer '${r}' for '${n.match}': give graphic, rec709, or <SPACE>_COLORSPACE/<CURVE>_GAMMA (Resolve CST names)`);return{kind:/709|SRGB|2020/.test(s)||s==="TWOPOINTFOUR_GAMMA"?"display":"log",color_space:o,gamma:s,evidence:`you said: ${r}`,confident:!0}}function Sj(e,t){let n=t.tracks.filter(u=>u.kind==="Video"),r=lo(t,n),o=new Map(e.media_references.map(u=>[u.id,u])),s=t.fps_den?t.fps_num/t.fps_den:t.fps_num,i=new Map;for(let u of r){let d=u.it,p=d.media_reference_id?o.get(d.media_reference_id):void 0,f=p?.local_path??p?.target_url?.replace(/^file:\/\//,"");if(!f||!d.source_range)continue;let h=(t.start_frame??0)+d.timeline_range.start.value,g=i.get(d.id);if(g){g.rec1=Math.max(g.rec1,u.e);continue}let b=p.source_timecode,k=b?b.split(/[:;]/).map(Number).reduce((w,y,_)=>_<3?w*60+y:w*Math.round(s)+y,0):0;i.set(d.id,{item:d,path:f,name:d.name??fe(f),colour:{kind:"unknown",evidence:"",confident:!1},rec0:u.s,rec1:u.e,src0:d.source_range.start.value+(u.s-h),camFrame:k+d.source_range.start.value,fps:s})}let a=[...i.values()].sort((u,d)=>u.rec0-d.rec0),l=new Set(a.map(u=>u.item.id)),c=n.flatMap(u=>u.items).filter(u=>u.kind==="clip"&&!l.has(u.id)&&u.media_reference_id);return{shots:a,hidden:c}}function $j(e,t){let n=e.start_frame??0,r=e.tracks.flatMap(a=>a.items).filter(a=>a.kind==="transition").map(a=>({s:n+a.timeline_range.start.value,e:n+a.timeline_range.start.value+a.timeline_range.duration.value})),o=a=>r.some(l=>a>=l.s-1&&a<=l.e),s=0,i=t.rec1-t.rec0-1;for(;s<i&&o(t.rec0+s);)s++;for(;i>s&&o(t.rec0+i);)i--;return kj.map((a,l)=>({key:a,src:t.src0+Math.round(s+(i-s)*l/4)}))}async function Rj(e,t,n){let r={outputColorSpace:n.space,outputGamma:n.gamma,doFwdOOTF:0},o="";if(/\.mxf$/i.test(e.path)){let s=await AS(["logframe",e.path,String(t),String(Vf)]);if(s.code!==0&&/not an X-OCN/.test(s.stderr)&&(o="h264"),s.code===0){let i=s.out.indexOf(10),a=JSON.parse(new TextDecoder().decode(s.out.subarray(0,i))),l=new Float32Array(s.out.slice(i+1).buffer);return await es({data:l,w:a.w,h:a.h},{inputColorSpace:a.color_space,inputGamma:a.gamma,...r,doInvOOTF:0})}}if(e.colour.kind==="log"&&/\.(r3d|braw|ari|arx|crm)$/i.test(e.path))return null;try{let s=await Ma(e.path,t,o,Vf),i=new Float32Array(s.width*s.height*3);for(let l=0,c=0;l<i.length;l+=3,c+=4)i[l]=s.rgba[c]/255,i[l+1]=s.rgba[c+1]/255,i[l+2]=s.rgba[c+2]/255;let a=Cj({data:i,w:s.width,h:s.height},Vf);return await es(a,{inputColorSpace:e.colour.color_space,inputGamma:e.colour.gamma,...r,doInvOOTF:e.colour.kind==="display"?1:0})}catch{return null}}function Cj(e,t){let n=Math.min(1,t/Math.max(e.w,e.h));if(n>=1)return e;let r=Math.round(e.w*n),o=Math.round(e.h*n),s=new Float32Array(r*o*3);for(let i=0;i<o;i++){let a=Math.floor(i*e.h/o),l=Math.max(a+1,Math.floor((i+1)*e.h/o));for(let c=0;c<r;c++){let u=Math.floor(c*e.w/r),d=Math.max(u+1,Math.floor((c+1)*e.w/r));for(let p=0;p<3;p++){let f=0;for(let h=a;h<l;h++)for(let g=u;g<d;g++)f+=e.data[(h*e.w+g)*3+p];s[(i*r+c)*3+p]=f/((l-a)*(d-u))}}}return{data:s,w:r,h:o}}async function ES(e,t){let n=vj(t.tree,t.project),r=n?t.project??null:null,o=r?.science==="davinciYRGBColorManagedv2",s=r?.science==="acescc"||r?.science==="acescct",i=$S(t.tree,r),a=[];!n&&t.project?.science&&a.push(`this timeline was exported from a project set to ${t.project.science}${t.project.timeline_space?`, timeline ${t.project.timeline_space}/${t.project.timeline_gamma}`:""} \u2014 not your color setup (your tree works in ${t.tree.working.space}/${t.tree.working.gamma}), so it was not used`),o&&t.tree.cst_node!=null&&a.push(`your project is DaVinci YRGB Color Managed: Resolve converts each clip into ${i.space}/${i.gamma} itself, so the CST node (${t.tree.cst_node}) is left as it is, not set per clip`);let l=t.progress??(()=>{}),c=e.timelines.find(x=>!t.timeline||x.id===t.timeline||x.name===t.timeline)??e.timelines[0];if(!c)throw new P("not_found","no timeline in this session");let{shots:u,hidden:d}=Sj(e,c),p=new Map,f=new Map;for(let x of u){if(Jf(t.answers,[x.name,x.path]))continue;let R=x.path.split("/").slice(0,-1).join("/");f.has(R)||f.set(R,await xj(x.path));let C=f.get(R);C.length&&p.set(R,{shots:[...p.get(R)?.shots??[],x],why:C})}if(p.size)return{text:`These clips look like editorial proxies, not camera originals (nothing is written):
|
|
329
|
+
${[...p.entries()].map(([R,C])=>` ${R.split("/").slice(-2).join("/")}: ${C.shots.length} clip(s), e.g. ${C.shots[0].name} \u2014 ${C.why.join("; ")}`).join(`
|
|
330
|
+
`)}
|
|
331
|
+
Autobalance needs the camera originals: conform the timeline to them, then run color prep again. If a clip really is an original, answer it with answers=[{match:"<part of the name>", as:"<SPACE>_COLORSPACE/<CURVE>_GAMMA"}].`,data:{proxies:[...p.values()].flatMap(R=>R.shots.map(C=>({item:C.item.id,name:C.name,path:C.path,why:R.why})))},ops:[]};let h=new Map;for(let x of u)l(`reading color metadata: ${x.name}`),x.colour=Jf(t.answers,[x.name,x.path])??h.get(x.path)??await xS(x.path),h.set(x.path,x.colour);let g=u.filter(x=>x.colour.kind==="unknown"||!x.colour.confident);if(g.length){let x=new Map;for(let C of g){let B=C.path.split("/").slice(-3,-1).join("/");x.set(B,[...x.get(B)??[],C])}return{text:`Before I build the color prep I need to know what these clips are (nothing is written until then):
|
|
332
|
+
${[...x.entries()].map(([C,B])=>` ${C}: ${B.length} clip(s), e.g. ${B[0].name} \u2014 ${B[0].colour.evidence}${B[0].colour.color_space?` (tags say ${B[0].colour.color_space}/${B[0].colour.gamma})`:""}`).join(`
|
|
333
|
+
`)}
|
|
334
|
+
Answer with answers=[{match:"<part of the file or folder name>", as:"rec709" | "graphic" | "<SPACE>_COLORSPACE/<CURVE>_GAMMA"}].`,data:{questions:g.map(C=>({item:C.item.id,name:C.name,path:C.path,...C.colour}))},ops:[]}}let b=u.filter(x=>x.colour.kind!=="graphic"),k=[];if(t.balance!==!1&&b.length&&!Ln())k.push(`balance: ${wi}; the tree and CSTs only`);else if(t.balance!==!1&&b.length&&s)k.push(`balance: your project uses ${r.science} color science, where the balance is not verified yet; the tree and CSTs only`);else if(t.balance!==!1&&b.length&&!await gy())k.push(`balance: ${Gu}; the tree and CSTs only`);else if(t.balance!==!1&&b.length){let x=ki();if(x)throw new P("unsupported",`${x}; run with balance=false for the tree and CSTs only`);let R=await Ar(),C=R&&await yy(R)&&await ky(R);if(!C&&!t.download)throw new P("refused",R?"Autobalance needs the Autocolor pack's new models (~0.3 GB): ask the user, then download=true; or balance=false for the tree and CSTs only":"Autobalance needs the Autocolor pack (one-time download, ~4.6 GB, runs on this machine): ask the user, then download=true; or balance=false for the tree and CSTs only");let B=C?R:await Xa({onProgress:l}),L=await It("conform-prep-"),Z=[i.space,i.gamma],X=await Ty(B,null,void 0,Z,Tj(t.tree,r));try{let O=S=>Rj(S,$j(c,S).find(A=>A.key==="M").src,i),W=b.slice(0,3).map(O),ne=async S=>{try{S.s.knobs=(await S.ai).values}catch(A){k.push(`${S.s.name}: Autobalance failed, CST set, no balance: ${A.message.slice(0,200)}`)}},z=null,q=zt("CONFORM_PREP_TIMING")?(S,A)=>console.error(`prep-timing ${S} ${Math.round(performance.now()-A)}`):()=>{};for(let[S,A]of b.entries()){l(`balance ${S+1}/${b.length}: ${A.name}`);let U=performance.now(),de=await W.shift();if(q("decode_wait",U),U=performance.now(),S+3<b.length&&W.push(O(b[S+3])),!de){k.push(`${A.name}: could not decode to its log here (raw developer missing); CST set, no balance`);continue}A.npy=re(L,`${A.item.id}.npy`),A.npyShape=`${de.w}x${de.h}`,await Gn(A.npy,wj(de));let te={s:A,ai:X.step1(A.npy)};te.ai.catch(()=>{}),q("npy_view",U),U=performance.now(),z&&await ne(z),q("finish_prev",U),z=te}z&&await ne(z);let j=b.filter(S=>S.knobs&&S.npy);if(j.length>=4){l(`balance: shots side by side, ${j.length} shots in 2x2 grids`);try{let S=await X.p2(j.map(A=>({frame:A.npy,node:A.knobs})));j.forEach((A,U)=>{S[U]&&(A.knobs=S[U])})}catch(S){k.push(`side-by-side pass failed, each shot balanced on its own: ${S.message.slice(0,300)}`)}}let I=new Map;for(let S of j){let A=S.npy&&S.knobs?S.npyShape??"":"";I.set(A,[...I.get(A)??[],S])}for(let S of I.values())if(!(S.length<2)){l(`balance: matching each person's skin colour across ${S.length} shots`);try{let A=await X.faces(S.map(de=>({frame:de.npy,node:de.knobs})));S.forEach((de,te)=>{A.values[te]&&(de.knobs=A.values[te])});let U=A.report.people?.length??0;U&&k.push(`faces: ${U} people matched across ${A.report.fitted} shots`)}catch(A){k.push(`face step failed, p2 kept: ${A.message.slice(0,300)}`)}}for(let S of j)S.raw=yj(S.knobs),S.step1=S.offset=S.knobs.offset.map(A=>A*bj)}finally{X.close(),await dn(L).catch(()=>{})}}let w=[],y=(x,R,C)=>({timeline_id:c.id,item_id:x.item.id,entry:{id:"color-prep",kind:"tree",label:"Color prep",enabled:!0,meta:{tree:t.tree.body_hex,balance_node:t.tree.balance_node,...t.tree.cst_node!=null&&!o?{cst_node:t.tree.cst_node,cst:{inputColorSpace:x.colour.color_space,inputGamma:x.colour.gamma,doInvOOTF:x.colour.kind==="display"?1:0}}:{},...C?{raw:C}:R?{printer:R}:{}}}}),_=x=>(x.finish_ops??[]).some(R=>R.id==="color-prep");for(let x of u)x.colour.kind!=="graphic"?w.push(y(x,x.offset,x.raw)):_(x.item)&&w.push({timeline_id:c.id,item_id:x.item.id,remove_id:"color-prep"});for(let x of d){let R=(c.start_frame??0)+x.timeline_range.start.value+x.timeline_range.duration.value/2,C=u.find(X=>X.rec0<=R&&R<X.rec1),B=e.media_references.find(X=>X.id===x.media_reference_id),L=B?.local_path??B?.target_url?.replace(/^file:\/\//,"")??"",Z=Jf(t.answers,[x.name??"",L])??h.get(L)??(L?await xS(L):null);!Z||Z.kind==="graphic"||Z.kind==="unknown"||!Z.confident||w.push(y({item:x,colour:Z},C?.offset,C?.raw))}let v=x=>u.filter(R=>R.colour.kind===x).length,T=[...new Set(b.map(x=>`${x.colour.color_space}/${x.colour.gamma}`))];return{text:[`color prep on ${c.name}: your tree "${t.tree.name}" (balance node ${t.tree.balance_node}${(()=>{let x=t.tree.nodes.find(R=>R.id===t.tree.balance_node);return x&&Wc(x)?` grading in its own ${Wc(x)}`:""})()}, ${o?"Color Managed project: Resolve's input transforms, no CST written":t.tree.cst_node!=null?`CST node ${t.tree.cst_node}`:"input CST outside the tree: not written, yours stays"}, working ${i.space}/${i.gamma}${r?.science?`, project ${r.science}`:""})`,...a,`${v("log")} log, ${v("display")} Rec.709-type, ${v("graphic")} graphics/stills left ungraded`,`input CSTs: ${T.join(", ")||"none"}`,...t.balance===!1?["balance: skipped (balance=false)"]:k,"nothing written yet: timeline_write target=resolve-drt writes the .drt (a separate file; the user's project is untouched)"].join(`
|
|
335
|
+
`),data:{shots:u.map(x=>({item:x.item.id,name:x.name,colour:x.colour,offset:x.offset}))},ops:w}}async function IS(e,t){let n=mt(e.endsWith(".cube")?e:`${e}.cube`);if(await Ye(n))throw new P("refused",`${n} exists; conform.tools never writes over a file \u2014 give a new name`);return await Ve(xn(n)),await Ke(n,t),n}var Kc={slog3:{space:"SGAMUT3_COLORSPACE",gamma:"SONY_SLOG3_GAMMA"},"slog3-sgamut3":{space:"SGAMUT3_COLORSPACE",gamma:"SONY_SLOG3_GAMMA"},"slog3-sgamut3cine":{space:"SGAMUT3CINE_COLORSPACE",gamma:"SONY_SLOG3_GAMMA"},"slog3-sgamut3.cine":{space:"SGAMUT3CINE_COLORSPACE",gamma:"SONY_SLOG3_GAMMA"},"venice-slog3":{space:"VENICE_SGAMUT3_COLORSPACE",gamma:"SONY_SLOG3_GAMMA"},"venice-slog3-sgamut3cine":{space:"VENICE_SGAMUT3CINE_COLORSPACE",gamma:"SONY_SLOG3_GAMMA"},slog2:{space:"SGAMUT_COLORSPACE",gamma:"SONY_SLOG2_GAMMA"},logc3:{space:"ALEXA3_COLORSPACE",gamma:"LOGC_EI800_GAMMA"},logc:{space:"ALEXA3_COLORSPACE",gamma:"LOGC_EI800_GAMMA"},"alexa-wide-gamut":{space:"ALEXA3_COLORSPACE",gamma:"LOGC_EI800_GAMMA"},logc4:{space:"ARRI_LOGC4_COLORSPACE",gamma:"LOGC4_EI800_GAMMA"},"red-log3g10":{space:"RWG_COLORSPACE",gamma:"RED_LOG3G10_GAMMA"},log3g10:{space:"RWG_COLORSPACE",gamma:"RED_LOG3G10_GAMMA"},redwidegamut:{space:"RWG_COLORSPACE",gamma:"RED_LOG3G10_GAMMA"},"canon-log3":{space:"CANONLOG3_COLORSPACE",gamma:"CANONLOG3_GAMMA"},"canon-log2":{space:"CANONLOG2_COLORSPACE",gamma:"CANONLOG2_GAMMA"},"canon-log":{space:"CANONLOG_COLORSPACE",gamma:"CANONLOG_GAMMA"},vlog:{space:"VLOG_COLORSPACE",gamma:"PANASONIC_VLOG_GAMMA"},"v-log":{space:"VLOG_COLORSPACE",gamma:"PANASONIC_VLOG_GAMMA"},"bmd-film-gen5":{space:"DWG_COLORSPACE",gamma:"BMDFILMV5_GAMMA"},"blackmagic-gen5":{space:"DWG_COLORSPACE",gamma:"BMDFILMV5_GAMMA"},"dwg-intermediate":{space:"DWG_COLORSPACE",gamma:"DAV_INTER_OETF_GAMMA"},"davinci-intermediate":{space:"DWG_COLORSPACE",gamma:"DAV_INTER_OETF_GAMMA"},dlog:{space:"DGAMUT_COLORSPACE",gamma:"DJI_DLOG_GAMMA"},"d-log":{space:"DGAMUT_COLORSPACE",gamma:"DJI_DLOG_GAMMA"},flog:{space:"FGAMUT_C_COLORSPACE",gamma:"FLOG_OETF_GAMMA"},"f-log":{space:"FGAMUT_C_COLORSPACE",gamma:"FLOG_OETF_GAMMA"},flog2:{space:"FGAMUT_C_COLORSPACE",gamma:"FLOG2_OETF_GAMMA"},"f-log2":{space:"FGAMUT_C_COLORSPACE",gamma:"FLOG2_OETF_GAMMA"},nlog:{space:"REC2020_COLORSPACE",gamma:"NLOG_OETF_GAMMA"},"n-log":{space:"REC2020_COLORSPACE",gamma:"NLOG_OETF_GAMMA"},"apple-log":{space:"APPLE_WG_COLORSPACE",gamma:"APPLE_LOG_GAMMA"},acescct:{space:"ACES_AP1_COLORSPACE",gamma:"ACESCCT_GAMMA"},acescc:{space:"ACES_AP1_COLORSPACE",gamma:"ACESCC_GAMMA"},"aces-ap0-linear":{space:"ACES_AP0_COLORSPACE",gamma:"LINEAR_GAMMA"},rec709:{space:"REC709_COLORSPACE",gamma:"REC709_GAMMA"},"rec709-gamma24":{space:"REC709_COLORSPACE",gamma:"TWOPOINTFOUR_GAMMA"},"rec709-2.4":{space:"REC709_COLORSPACE",gamma:"TWOPOINTFOUR_GAMMA"},"rec709-gamma22":{space:"REC709_COLORSPACE",gamma:"TWOPOINTTWO_GAMMA"},rec2020:{space:"REC2020_COLORSPACE",gamma:"REC709_GAMMA"},"p3d65-gamma26":{space:"P3D65_COLORSPACE",gamma:"TWOPOINTSIX_GAMMA"},p3d65:{space:"P3D65_COLORSPACE",gamma:"TWOPOINTSIX_GAMMA"},p3dci:{space:"P3DCI_COLORSPACE",gamma:"TWOPOINTSIX_GAMMA"},srgb:{space:"SRGB_COLORSPACE",gamma:"SRGB_GAMMA"},cineon:{space:"CINEON_COLORSPACE",gamma:"CINEON_GAMMA"},"linear-rec709":{space:"REC709_COLORSPACE",gamma:"LINEAR_GAMMA"}},MS=Object.keys(Kc);function Xf(e){let t=e.trim(),n=t.toUpperCase().split(/[\s/,+]+/).filter(Boolean),r=n.find(a=>a.endsWith("_COLORSPACE")),o=n.find(a=>a.endsWith("_GAMMA"));if(r&&o)return{space:r,gamma:o};if(r||o)throw new P("invalid_args",`${e}: give both tokens (SPACE_COLORSPACE and CURVE_GAMMA), or a name: ${MS.join(", ")}`);let s=t.toLowerCase().replace(/[\s_/]+/g,"-").replace(/^sony-/,"").replace(/^arri-/,"").replace(/\.cine$/,"cine").replace(/-s-?gamut/,"-sgamut").replace(/^s-log/,"slog"),i=Kc[s]??Kc[s.replace(/-/g,"")]??Object.entries(Kc).find(([a])=>a.replace(/[-.]/g,"")===s.replace(/[-.]/g,""))?.[1];if(!i)throw new P("invalid_args",`${e}: not a space I know. Names: ${MS.join(", ")}; or Resolve's own tokens, e.g. SGAMUT3CINE_COLORSPACE/SONY_SLOG3_GAMMA`);return i}var Qf=[17,33,65];async function PS(e,t,n){let r=n,o=new Float32Array(r*r*r*3),s=0;for(let l=0;l<r;l++)for(let c=0;c<r;c++)for(let u=0;u<r;u++)o[s++]=u/(r-1),o[s++]=c/(r-1),o[s++]=l/(r-1);let i={inputColorSpace:e.space,inputGamma:e.gamma,outputColorSpace:t.space,outputGamma:t.gamma},a;try{a=(await es({data:o,w:r*r,h:r},i)).data}catch(l){throw new P("invalid_args",`the transform ${e.space}/${e.gamma} \u2192 ${t.space}/${t.gamma} is not one Resolve's CST knows: ${l instanceof Error?l.message:l}`)}for(let l=0;l<a.length;l++)a[l]=Math.min(1,Math.max(0,a[l]));return a}function FS(e,t,n){let r=[`TITLE "${n.replace(/"/g,"'")}"`,"# written by conform.tools (Resolve Color Space Transform, exact)",`LUT_3D_SIZE ${t}`,"DOMAIN_MIN 0.0 0.0 0.0","DOMAIN_MAX 1.0 1.0 1.0",""];for(let o=0;o<e.length;o+=3)r.push(`${e[o].toFixed(6)} ${e[o+1].toFixed(6)} ${e[o+2].toFixed(6)}`);return r.join(`
|
|
336
|
+
`)+`
|
|
337
|
+
`}var Aj=(e,t)=>`${e}::${t}`,Yf=()=>re(tt(),"qc-decisions.json");async function Ej(){return await Ye(Yf())?JSON.parse(await ct(Yf())):{}}async function OS(e,t,n,r,o){let s=await Ej(),i=Aj(e,t),a={...s[i]};r==="open"?delete a[n]:a[n]={status:r,...o?{note:o}:{},at:new Date().toISOString()},s[i]=a,await Ve(tt()),await Ke(Yf(),JSON.stringify(s,null,1))}var LS=e=>e?`${sl.find(([t])=>t===e.status)?.[1]??e.status}${e.note?`: ${e.note}`:""}`:"";import{execFile as YS,execFileSync as ZS,spawn as Xj}from"node:child_process";import{appendFileSync as Qj}from"node:fs";import{createServer as Yj}from"node:http";import{open as Zj,readdir as eD,rename as tD,rm as nD,stat as uh}from"node:fs/promises";import{basename as e$,join as rD,relative as oD}from"node:path";import{spawn as DS}from"node:child_process";import{createWriteStream as Mj,readdirSync as Ij,rmSync as NS}from"node:fs";import{link as Pj,mkdtemp as Fj,open as Oj,rm as Lj,writeFile as Nj}from"node:fs/promises";import{tmpdir as Zf}from"node:os";import{basename as BS,dirname as jj,join as Vc}from"node:path";var Dj=200,Bj=250,qS=48,qj=48,Uj=4294967295,Gj=1280,Hj=720,zj=/\.(mov|mp4|m4v|mxf|mts|avi|mkv|r3d|braw|crm)$/i,Wj=e=>{let t=jj(e),n=BS(e).replace(/\.[^.]+$/,"");return`${t==="."?"":`${t}/`}${n}_proxy.mov`};function nh(e,t,n,r,o,s){let i=DS(e,["proxy",t,"--width",String(n),"--from",String(r),"--count",String(o)],{stdio:["ignore","pipe","pipe"]}),a=Buffer.alloc(0),l=null,c="";i.stderr.on("data",d=>{c+=d.toString()}),i.stdout.on("data",d=>{if(a=a.length?Buffer.concat([a,d]):d,!l){let p=a.indexOf(10);if(p<0)return;let f=JSON.parse(a.subarray(0,p).toString());l={w:f.w,h:f.h},a=a.subarray(p+1)}for(;a.length>=8;){let p=a.readUInt32LE(0),f=a.readUInt32LE(4);if(a.length<8+f)break;s(p,a.subarray(8,8+f)),a=a.subarray(8+f)}});let u=new Promise((d,p)=>{i.on("error",p),i.on("close",(f,h)=>{f===0||h?d(l):p(new Error(`proxy encode failed (${f}): ${c.trim().split(`
|
|
338
|
+
`).pop()}`))})});return{child:i,done:u}}async function rh(e,t=0){let n=await or();if(!n)return[];let r=[];for(let o=0;o<e.length;o++){let s=e[o];if(zj.test(s.name))try{let i=await U1(s.path);if(!i.w||!i.h||!(i.frames>1)||!(i.fps>0))continue;let a=Math.max(2,Math.min(Gj,Math.round(Hj*i.w/i.h/2)*2,i.w)),l=await nh(n,s.path,a,0,1,()=>{}).done;if(!l)continue;let c=Kj(i.fps),u=await Jj(n,s.path,c);r.push({of:t+o,name:Wj(s.name),width:l.w,height:l.h,fps:i.fps,duration_ms:i.frames/i.fps*1e3,frames:i.frames,has_audio:u,audio_sample_rate:u?c:0,audio_channels:u?1:0})}catch{}}return r}var Kj=e=>[48e3,6e4].find(t=>Math.abs(t/e-Math.round(t/e))<1e-6)??48e3,Vj=e=>{let t=e.audio_sample_rate/e.fps;return Math.abs(t-Math.round(t))<1e-6?Math.round(t):Math.ceil(t)},th,jS="conform-p2p-",US=()=>th??=(async()=>{for(let t of Ij(Zf()).filter(n=>n.startsWith(jS))){let n=Number(/^conform-p2p-(\d+)-/.exec(t)?.[1]),r=!1;try{r=!!n&&process.kill(n,0)}catch{}r||NS(Vc(Zf(),t),{recursive:!0,force:!0})}let e=await Fj(Vc(Zf(),`${jS}${process.pid}-`));process.once("exit",()=>NS(e,{recursive:!0,force:!0}));for(let t of["SIGINT","SIGTERM","SIGHUP"])process.listenerCount(t)||process.once(t,()=>process.exit(128+{SIGHUP:1,SIGINT:2,SIGTERM:15}[t]));return e})(),Jc=new Map;function Jj(e,t,n){let r,o=new Promise(i=>{r=i}),s=Jc.size;return Jc.set(`${t}@${n}`,US().then(i=>new Promise(a=>{let l=Vc(i,`${s}.pcm`),c=Mj(l),u=DS(e,["audio",t,"--rate",String(n)],{stdio:["ignore","pipe","ignore"]}),d=Buffer.alloc(0),p=!1;u.stdout.on("data",f=>{if(!d)return void c.write(f);d=Buffer.concat([d,f]);let h=d.indexOf(10);if(!(h<0)){try{p=JSON.parse(d.subarray(0,h).toString()).ok===!0}catch{p=!1}r(p),c.write(d.subarray(h+1)),d=null}}),u.on("error",()=>{r(!1),c.end(),a(null)}),u.on("close",f=>{r(p),c.end(()=>a(p&&f===0?l:null))})}))),o}async function GS(e,t,n){if(!t.has_audio)return Buffer.alloc(0);let r=await Jc.get(`${e}@${t.audio_sample_rate}`);if(!r)return Buffer.alloc(0);let o=Vj(t)*t.audio_channels*2,s=Buffer.alloc(o),i=await Oj(r);try{let{bytesRead:a}=await i.read(s,0,o,n*o);return s.subarray(0,a)}finally{await i.close()}}var ni=new Map,eh=Promise.resolve();function oh(e,t){for(let n of t){let r=e[n.of];!r||ni.has(r.path)||(eh=eh.then(async()=>{let o=await or();if(!o)return;let s=[],i=[];await nh(o,r.path,n.width,0,Math.min(qS,n.frames),(l,c)=>{i.push([l,Buffer.from(c)])}).done;for(let[l,c]of i){let u=await GS(r.path,n,l),d=Buffer.alloc(8);d.writeUInt32LE(c.length,0),d.writeUInt32LE(u.length,4),s.push(d,c,u)}let a=Vc(await US(),`prefill-${ni.size}-${BS(r.path)}.bin`);await Nj(a,Buffer.concat(s)),ni.set(r.path,a)}).catch(()=>{}))}return eh}async function HS(e,t){let n=[],r=new Set;for(let o of t){let s=e[o.of],i=s&&ni.get(s.path);if(!i)continue;let a=`${i}.${Date.now()}.${o.of}`;try{await Pj(i,a)}catch{continue}n.push({path:a,source_path:s.path}),r.add(o.of)}return{list:n,sent:r}}async function zS(){let e=th;th=void 0,Jc.clear(),ni.clear();let t=e&&await e;t&&await Lj(t,{recursive:!0,force:!0})}var WS=(e,t)=>new Set(t.filter(n=>e[n.of]&&ni.has(e[n.of].path)).map(n=>n.of));function KS(e,t,n,r=()=>new Set,o=()=>!1){let s=new Map,i=new Set,a,l=Promise.resolve(),c=new Set,u=p=>{let f=r().has(p)?qS:0;l=l.then(()=>i.has(p)?void 0:d(p,f,Bj)).catch(()=>{})},d=async(p,f,h)=>{a??=await or();let g=t().find(v=>v.of===p),b=e()[p];if(!a||!g||!b)return n({type:"nfs-proxy-push-done",file_index:p});s.get(p)?.kill();let k=Math.max(0,Math.min(h,g.frames-f));if(!k)return n({type:"nfs-proxy-push-done",file_index:p});let w=Promise.resolve(),y=nh(a,b.path,g.width,f,k,(v,T)=>{let $=Buffer.from(T);w=w.then(async()=>{let x=await GS(b.path,g,v);s.get(p)===y.child&&n({type:"nfs-proxy-push-frame",file_index:p,frame_number:v,data:$.toString("base64"),pcm_data:x.toString("base64")})})});s.set(p,y.child);let _=await y.done.then(()=>!y.child.killed,()=>!1);await w,s.get(p)===y.child&&s.delete(p),_&&n({type:"nfs-proxy-push-done",file_index:p})};return{handle(p){let f=Number(p.file_index);if(p.type==="nfs-proxy-push-req")return i.delete(f),o()?(c.add(f),!0):(u(f),!0);if(p.type==="nfs-proxy-push-seek"){i.add(f);let h=Number(p.frame_number);return h>=Uj||h<0?(s.get(f)?.kill(),s.delete(f),!0):(d(f,h,o()?qj:Dj),!0)}return!1},direct(){for(let p of c)u(p);c.clear()},stop(){for(let p of s.values())p.kill();s.clear(),c.clear()}}}var mr=2048,ri=1<<20,sD=32<<20,iD=3e3,VS=6e4,dh=e=>e?e.direct?`direct (${e.addr}, ${e.rtt_ms} ms)`:`through a relay (${e.addr.replace(/^Relay\((.*)\)$/,"$1")}, ${e.rtt_ms} ms): slower`:"connecting";async function aD(){let e=Xt()==="win32"?"i2o-transfer.exe":"i2o-transfer",t=[zt("CONFORM_P2P"),wh(e),_o(new URL(`./${e}`,import.meta.url)),_o(new URL(`../../native-host/i2o-transfer/target/release/${e}`,import.meta.url))].filter(Boolean);for(let n of t)if(await On(n))return n;return null}var lD=e=>Buffer.from(JSON.stringify(e)).toString("base64url");function fr(e){let t=JSON.parse(Buffer.from(e.trim(),"base64url").toString());if(t.v!==1||!t.node_id||!Array.isArray(t.files))throw new Error("not a conform.tools peer-to-peer ticket");return t}async function ph(e,t){let n=await aD();if(!n)throw new Error(kh("the peer-to-peer engine (i2o-transfer)"));let r=Xj(n,[],{stdio:["pipe","pipe","pipe"]}),o="";r.stdout.on("data",l=>{o+=l.toString();for(let c;(c=o.indexOf(`
|
|
339
|
+
`))>=0;){let u=o.slice(0,c).trim();if(o=o.slice(c+1),u)try{t(JSON.parse(u))}catch{}}});let s=zt("CONFORM_P2P_LOG"),i=`${e.type==="start-sender"?"S":"R"}${r.pid}`;r.stderr.on("data",l=>{if(s)try{Qj(s,l.toString().split(`
|
|
340
|
+
`).filter(Boolean).map(c=>`${new Date().toISOString().slice(11,23)} ${i} ${c}
|
|
341
|
+
`).join(""))}catch{}}),r.stdin.on("error",()=>{});let a=l=>{r.exitCode===null&&!r.stdin.destroyed&&r.stdin.write(JSON.stringify(l)+`
|
|
342
|
+
`)};return a(e),{child:r,send:a,stop:()=>r.kill()}}var sh=0;async function t$(e){return(await uh(e)).isDirectory()?(await eD(e,{recursive:!0,withFileTypes:!0})).filter(n=>n.isFile()&&!n.name.startsWith(".")).map(n=>rD(n.parentPath,n.name)).sort().map(n=>({path:n,name:oD(e,n).split("\\").join("/")})):[{path:e,name:e$(e)}]}async function mh(e,t={}){let n=v=>Promise.all(v.map(T=>typeof T=="string"?{path:T,name:e$(T)}:T).map(async T=>({...T,size:(await uh(T.path)).size}))),r=await n(e),o=t.proxies?await rh(r):[];o.length&&sh++;let s=!1,i=!1,a=()=>{f||!h||!i||s||[...WS(r,o)].some(v=>!l.has(v))&&h.stop()};oh(r,o).then(a);let l=new Set,c=!1,u=KS(()=>r,()=>o,v=>h?.send(v),()=>l,()=>!c),d=(v,T)=>({...v,proxy:o.find($=>$.of===T)}),p=Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("hex"),f=!1,h,g,b={},k=new Promise(v=>{g=v}),w=async()=>{let v,T,$=new Promise((B,L)=>{v=B,T=L}),x=o.length?await HS(r,o):{list:[],sent:new Set};l=x.sent,s=!1,c=!1;let R=await ph({type:"start-sender",files:r.map(d),secret_key:p,...b,...x.list.length?{prefill_files:x.list}:{}},B=>{if(B.type==="endpoint-ready"){if(b.port_v4===void 0&&b.port_v6===void 0){let L=B.addrs??[],Z=X=>X?Number(X.slice(X.lastIndexOf(":")+1)):void 0;b={port_v4:Z(L.find(X=>!X.startsWith("["))),port_v6:Z(L.find(X=>X.startsWith("[")))}}v(lD({v:1,node_id:String(B.node_id),relay_url:B.relay_url??null,addrs:B.addrs??[],files:r.map(({name:L,size:Z})=>({name:L,size:Z})),...r.length===1&&/\.iso$/i.test(r[0].name)?{iso:!0}:{},...t.label?{label:t.label}:{},...o.length?{proxies:o}:{}}))}else B.type==="connected"?s=!0:B.type==="path"?(c=!!B.direct,c&&u.direct(),t.onPath?.(B)):u.handle(B)||B.type==="error"&&!String(B.error).startsWith("[debug]")&&T(new Error(String(B.error)))});h=R,i=!1,R.child.on("exit",B=>{if(f)return g();if(!i)return T(new Error(`peer-to-peer sender exited (${B}) before its endpoint was ready`));w().catch(()=>g())});let C=await $;return i=!0,queueMicrotask(a),C};return{ticket:await w(),stop:()=>{f=!0,u.stop(),h?.stop(),o.length&&--sh===0&&zS()},closed:k,add:async v=>{let T=(await n(v)).filter(R=>!r.some(C=>C.name===R.name));if(!T.length)return 0;let $=r.length,x=t.proxies?await rh(T,$):[];return x.length&&!o.length&&sh++,o.push(...x),r.push(...T),h?.send({type:"add-sender-files",files:T.map((R,C)=>d(R,$+C))}),oh(r,x).then(a),T.length}}}var ih=257,cD=4096,uD=2e4,dD=3e3,JS=e=>{let t=[];for(let n of[...e].sort((r,o)=>r[0]-o[0])){let r=t[t.length-1];r&&n[0]<=r[1]?r[1]=Math.max(r[1],n[1]):t.push([n[0],n[1]])}return t},ah=(e,t,n)=>{let r=[],o=e;for(let[s,i]of n)if(!(i<=o)){if(s>=t)break;s>o&&r.push([o,s]),o=Math.max(o,i)}return o<t&&r.push([o,t]),r};async function fh(e,t,n={}){let r=fr(e),o=n.volume??"CONFORM_P2P",s=r.files.map(S=>({name:S.name,size:S.size}));if(n.proxies&&!r.iso&&r.proxies?.length){let S=await XS(r.proxies);r.proxies.forEach((A,U)=>s.push({name:A.name,size:S[U],proxy:A}))}let i=()=>s.filter(S=>!S.proxy),a=await Zj(t,"w+"),l=[],c=[],u=[],d=0,p=0,f=async S=>{for(let U of S)u[U]=d,d+=Math.ceil(s[U].size/mr);let A;try{A=await sa(s.map((U,de)=>({name:U.name,totalSize:U.size,fixedPartSector:u[de]})),o)}catch(U){throw new Error(`can't add ${S.length} more file(s) to this mount: ${U.message}. Mount it again to see them`)}(await a.stat()).size<A.totalBytes&&await a.truncate(A.totalBytes);for(let U of A.structuralRegions)await a.write(U.data,0,U.data.length,U.sectorStart*mr);for(let U of S)l[U]=(ih+u[U])*mr;c.push({regions:A.structuralRegions,totalBytes:A.totalBytes,files:s.length})};if(r.iso)await a.truncate(s[0].size),l.push(0),c.push({regions:[],totalBytes:s[0].size,files:1});else{let S=await sa(s.map(U=>({name:U.name,totalSize:U.size})),o);d=2*(Math.min(S.totalSectors-1,...S.fileDataRegions.map(U=>U.sectorStart))-ih)+cD,p=(ih+d)*mr,await f(s.map((U,de)=>de))}let h=()=>s.reduce((S,A)=>S+A.size,0),g=S=>[l[S],l[S]+s[S].size],b=[],k=(S,A,U=s.length)=>{let de=0;for(let te=0;te<U;te++){let[_e,Se]=g(te),H=Math.max(_e,S),le=Math.min(Se,A);if(le>H)for(let[pe,xe]of ah(H,le,b))de+=xe-pe}return de},w=[],y=!1,_=0,v,T=new Promise((S,A)=>{v=U=>U?A(U):S()});h()===0&&v();let $=(S,A)=>{b=JS([...b,[S,A]]),_=h()-k(0,1/0),n.onProgress?.(_,h());for(let U of[...w])k(U.a,U.b,U.n)||(w.splice(w.indexOf(U),1),U.ready());_>=h()&&v()},x=!1,R,C=null,B=[],L=(S,A,U=!1)=>{if(!R)return;let de=Date.now();B=B.filter(([,,te])=>de-te<uD);for(let[te,_e]of ah(S,A,JS([...b,...B.map(([Se,H])=>[Se,H])]))){for(let Se=te;Se<_e;Se+=U?ri:_e-te){let H=U?Math.min(_e,Se+ri):_e;R.send({type:"need-bytes",offset:Se,length:H-Se,...U?{ahead:!0}:{}})}B.push([te,_e,de])}},Z=new Map,X=(S,A,U=s.length)=>{for(let de=0;de<U;de++){let[te,_e]=g(de),Se=Math.max(te,S);if(Math.min(_e,A)<=Se)continue;let H=Z.get(de),pe=!!H&&Se>=H.end-ri&&Se<=H.end+ri&&C?.direct?Math.min(H.ahead*2,sD):ri;Z.set(de,{end:Math.min(_e,A),ahead:pe});let xe=Math.min(_e,Math.max(A,Se+ri)),ve=Math.min(_e,Math.max(A,Se+pe));if(s[de].proxy){L(Se,Math.min(_e,A));continue}L(Se,xe),ve>xe&&L(xe,ve,!0)}return y&&k(S,A,U)?Promise.reject(new Error("the mount is being stopped")):k(S,A,U)?new Promise((de,te)=>{let _e=[...Array(U).keys()].filter(xe=>s[xe].proxy&&Math.max(g(xe)[0],S)<Math.min(g(xe)[1],A)),Se=_e.length?setInterval(()=>{for(let xe of _e)for(let[ve,Oe]of ah(Math.max(g(xe)[0],S),Math.min(g(xe)[1],A),b))R?.send({type:"need-bytes",offset:ve,length:Oe-ve})},dD):void 0,H=()=>{clearTimeout(pe),clearInterval(Se)},le={a:S,b:A,n:U,ready:()=>{H(),de()},fail:xe=>{H(),te(xe)}},pe=setTimeout(()=>{clearInterval(Se),w.splice(w.indexOf(le),1),te(new Error(`bytes ${S}-${A} didn't arrive in ${VS/1e3} s`))},VS);w.push(le)}):Promise.resolve()},O=Yj((S,A)=>void ae(S,A).catch(()=>{A.headersSent||(A.statusCode=503),A.end()})),ae=async(S,A)=>{if(x)return A.writeHead(503).end();let U=new URL(S.url??"/","http://x");if(S.method==="POST"){let le=Number(U.searchParams.get("offset")),pe=[];for await(let ve of S)pe.push(ve);let xe=Buffer.concat(pe);return await a.write(xe,0,xe.length,le),$(le,le+xe.length),A.end("ok")}let de=c[Number(/^\/disk(?:_v(\d+))?\.iso$/.exec(U.pathname)?.[1]??(U.pathname==="/disk.iso"?1:0))-1];if(!de)return A.writeHead(404).end();let te=/bytes=(\d+)-(\d*)/.exec(S.headers.range??""),_e=te?Number(te[1]):0,Se=te&&te[2]?Math.min(Number(te[2])+1,de.totalBytes):de.totalBytes;if(S.method==="GET"&&await X(_e,Se,de.files),A.writeHead(te?206:200,{"Accept-Ranges":"bytes","Content-Length":Se-_e,...te?{"Content-Range":`bytes ${_e}-${Se-1}/${de.totalBytes}`}:{}}),S.method==="HEAD")return A.end();let H=Buffer.alloc(Se-_e);await a.read(H,0,H.length,_e),_e<p&&H.fill(0,0,Math.min(Se,p)-_e);for(let le of de.regions){let pe=le.sectorStart*mr,xe=Math.max(_e,pe),ve=Math.min(Se,pe+le.data.length);ve>xe&&H.set(le.data.subarray(xe-pe,ve-pe),xe-_e)}A.end(H)};await new Promise(S=>O.listen(0,"127.0.0.1",S));let W=O.address().port,ne=Promise.resolve(),z=S=>{r.iso||S.length<=i().length||i().some((A,U)=>S[U]?.name!==A.name)||(ne=ne.then(async()=>{let A=s.length,U=i().length;if(S.length<=U)return;let de=S.slice(U);s.push(...de.map(H=>({name:H.name,size:H.size})));let te=n.proxies?de.flatMap((H,le)=>H.proxy?[{...H.proxy,of:A+le}]:[]):[],_e=te.length?await XS(te):[];te.forEach((H,le)=>s.push({name:H.name,size:_e[le],proxy:H}));let Se=s.map((H,le)=>le).slice(A);await f(Se),R.send({type:"update-file-offsets",fileOffsets:l,fileSizes:s.map(H=>H.size),senderMapping:s.map((H,le)=>le<A?-2:H.proxy?-1:-3)}),te.length&&R.send({type:"add-proxy-files",proxy_files:Se.filter(H=>s[H].proxy).map(H=>lh(s[H].proxy,H))}),n.onGrow?.(c.length,Se)}).catch(A=>{q=A.message}))},q=null;R=await ph({type:"start-receiver",http_port:W,iso_path:t,file_offsets:l,proxy_files:s.flatMap((S,A)=>S.proxy?[lh(S.proxy,A)]:[]),peer_node_id:r.node_id,peer_relay_url:r.relay_url,peer_addrs:r.addrs},S=>{S.type==="path"?C=S:S.type==="manifest"?z(S.files):S.type==="error"&&!String(S.error).startsWith("[debug]")&&v(new Error(String(S.error)))}),R.send({type:"volume-mounted"}),R.child.on("exit",S=>{!x&&_<h()&&v(new Error(`peer-to-peer receiver exited (${S}) with ${_} of ${h()} bytes`))});let j=async()=>{if(x=!0,R&&R.child.exitCode===null){let S=new Promise(A=>R.child.once("exit",()=>A()));R.send({type:"cancel"}),await Promise.race([S,new Promise(A=>setTimeout(A,2e3))]),R.stop()}O.close(),await a.close()};T.catch(()=>{});let I=`http://127.0.0.1:${W}`;return{t:r,files:s,offsets:l,done:T,close:j,daemon:R,ensure:X,fh:a,ask:L,url:(S=1)=>`${I}/${S===1?"disk":`disk_v${S}`}.iso`,get version(){return c.length},get size(){return c[c.length-1].totalBytes},get total(){return h()},get have(){return _},get path(){return C},get grewError(){return q},get covered(){return b},set draining(S){if(y=S,S)for(let A of w.splice(0))A.fail(new Error("the mount is being stopped"))}}}var lh=(e,t)=>({iso_file_index:t,original_file_index:e.of,width:e.width,height:e.height,fps:e.fps,duration_ms:e.duration_ms,has_audio:e.has_audio??!1,audio_sample_rate:e.audio_sample_rate??0,audio_channels:e.audio_channels??0});async function XS(e){return await new Promise((t,n)=>{ph({type:"proxy-sizes",proxies:e.map(r=>lh(r,0))},r=>{r.type==="proxy-sizes"&&t(r.sizes)}).then(r=>r.child.on("exit",()=>n(new Error("the peer-to-peer engine gave no proxy sizes (an older i2o-transfer?)"))),n)})}async function n$(e,t,n={}){let r=n.chunk??8388608,o,s=a=>{let[l,c]=[o.offsets[a],o.files[a]];for(let u=0;u<c.size;u+=r)o.ask(l+u,l+Math.min(u+r,c.size))};o=await fh(e,t,{onProgress:n.onProgress,onGrow:(a,l)=>{o&&l.forEach(s)}});let i=new Promise((a,l)=>{let c=()=>l(new DOMException("receive aborted","AbortError"));n.signal?.aborted?c():n.signal?.addEventListener("abort",c,{once:!0})});i.catch(()=>{});try{return o.files.forEach((a,l)=>s(l)),await Promise.race([o.done,i]),{path:t,bytes:o.have,files:o.files.length}}finally{await o.close()}}var oi=(e,t)=>new Promise((n,r)=>YS(e,t,(o,s,i)=>o?r(new Error(String(i||o.message).trim())):n(String(s)))),ch=e=>new Promise(t=>YS("/usr/bin/hdiutil",["detach",e,"-force"],t)),Xc=new Map,QS=!1;function pD(e,t){if(Xc.set(e,t),!QS){QS=!0,process.on("exit",()=>{for(let n of Xc.values())for(let r of[...n].reverse())try{ZS("/usr/bin/hdiutil",["detach",r,"-force"],{stdio:"ignore",timeout:5e3})}catch{}});for(let n of["SIGINT","SIGTERM","SIGHUP"])process.once(n,()=>process.exit(128+{SIGHUP:1,SIGINT:2,SIGTERM:15}[n]))}}async function mD(){let e;try{e=JSON.parse(ZS("/bin/sh",["-c","/usr/bin/hdiutil info -plist | /usr/bin/plutil -convert json -o - -"],{encoding:"utf8",timeout:1e4}))}catch{return[]}let t=new Set([...Xc.values()].flat()),n=[],r=o=>Number(/disk_v(\d+)\.iso$/.exec(o??"")?.[1]??1);for(let o of[...e.images??[]].sort((s,i)=>r(i["image-path"])-r(s["image-path"]))){let s=o["image-path"]??"";if(!/^http:\/\/127\.0\.0\.1:\d+\/disk(_v\d+)?\.iso$/.test(s))continue;let i=o["system-entities"]??[],a=i.find(u=>u["mount-point"])?.["mount-point"],l=i[0]?.["dev-entry"];!l||t.has(l)||await fetch(s,{method:"HEAD",signal:AbortSignal.timeout(1500)}).then(()=>!0,()=>!1)||(await ch(l),a&&(await oi("/sbin/mount",[]).catch(()=>"")).includes(` on ${a} (`)&&await oi("/sbin/umount",["-f",a]).catch(()=>{}),n.push(a??l))}return n}async function fD(e,t,n){let r=async(u,d)=>{let p=new Uint8Array(d),{bytesRead:f}=await e.read(p,0,d,u);return f===d?p:p.subarray(0,f)},o=await zn({read:r,write:()=>Promise.reject(new Error("read-only")),getSize:async()=>(await e.stat()).size}),s=new Map,i=[],a=0;for(let u of o.files){let d=Wn(u).map(h=>({...h,at:(o.partitionStartSector+h.imageSector)*mr})),p=[];for(let h of d)for(let[g,b]of t){let k=Math.max(g,h.at),w=Math.min(b,h.at+h.length);if(w<=k)continue;let y=Math.ceil((k-h.at+h.offset)/mr)*mr,_=w-h.at+h.offset,v=_>=u.totalSize?u.totalSize:Math.floor(_/mr)*mr;v>y&&(p.push({offset:y,length:v-y}),a+=v-y)}let f=h=>{let g=d.find(b=>h>=b.offset&&h<b.offset+b.length);if(!g)throw new Error(`${u.name}: byte ${h} isn't in the image`);return g.at+(h-g.offset)};s.set(u.name,{name:u.name,size:u.totalSize,slice:(h=0,g=u.totalSize)=>({arrayBuffer:async()=>(await r(f(h),g-h)).slice().buffer})}),i.push({path:u.name,sourceBasename:u.name,keptRanges:p})}let l=await lc({session:{timelines:[],media_references:[]},files:s,handles:0,perFile:{mode:"sparse",populate:{structural:!0,segments:!0}},volumeName:o.volumeName,entries:i,...o.iuvdPayload?{iuvd:o.iuvdPayload}:{}}),c=`${n}.part`;try{await cc(l,s,await dc(c)),await tD(c,n)}catch(u){throw await nD(c,{force:!0}),u}return{path:n,image:l.totalBytes,kept:a,files:i.length}}async function hD(e){let t=r=>uh(r).then(()=>!0,()=>!1);if(!await t(e))return e;let n=e.replace(/\.iso$/i,"");for(let r=2;;r++)if(!await t(`${n}_${r}.iso`))return`${n}_${r}.iso`}var hh=e=>e.normalize("NFKD").replace(/[^A-Za-z0-9_-]+/g,"_").replace(/^_+|_+$/g,"").slice(0,30)||"CONFORM_P2P";async function r$(e,t,n={}){if(Xt()!=="darwin")throw new Error("live mount needs macOS (hdiutil attaches the image over HTTP); use p2p_receive elsewhere");await mD();let r=0,o="",s=null,i,a=[],l=new Promise(k=>{i=k}),c=async k=>{if(k<=r)return;let w=/\/dev\/disk\d+/.exec(await oi("/usr/bin/hdiutil",["attach",u.url(k),"-nomount","-readonly","-noverify","-noautoopen"]))?.[0];if(!w)throw new Error("hdiutil attached nothing");try{await oi("/sbin/mount",["-t","udf","-r","-o","nobrowse,noowners",w,o])}catch(y){throw await ch(w),y}a.push(w)},u=await fh(e,t,{proxies:n.proxies??!0,volume:hh(n.volume??"CONFORM_P2P"),onGrow:k=>{l=l.then(()=>c(k)).catch(w=>{s=`files added, but not shown: ${w.message}`})}});try{for(let y=Date.now();!u.path?.direct&&Date.now()-y<iD;)await new Promise(_=>setTimeout(_,100));r=u.version;let k=await oi("/usr/bin/hdiutil",["attach",u.url(r),"-readonly","-noverify","-noautoopen"]);o=k.trim().split(`
|
|
343
|
+
`).map(y=>y.split(" ").pop().trim()).filter(y=>y.startsWith("/")).pop()??"";let w=/\/dev\/disk\d+/.exec(k)?.[0];if(!o||!w)throw new Error(`hdiutil attached nothing: ${k}`);a.push(w)}catch(k){throw await u.close(),k}pD(o,a),i();let d=null,p=setInterval(()=>{d||oi("/sbin/mount",[]).then(k=>{d||k.split(`
|
|
344
|
+
`).filter(w=>w.includes(` on ${o} (`)).length>=a.length||(clearInterval(p),f().finally(()=>n.onEjected?.()))},()=>{})},2e3),f=()=>d??=(async()=>{clearInterval(p),await l.catch(()=>{}),u.draining=!0;for(let w of[...a].reverse())await ch(w);u.draining=!1,Xc.delete(o);let k=null;try{if(n.keep){if(u.t.iso){let w=await zn({read:async(y,_)=>{await u.ensure(y,y+_);let v=new Uint8Array(_);return await u.fh.read(v,0,_,y),v},write:()=>Promise.reject(new Error("read-only")),getSize:async()=>u.size});for(let y of w.files.filter(_=>_.name.startsWith(".conform/")||_.name===".i2o-manifest.json"))for(let _ of Wn(y)){let v=(w.partitionStartSector+_.imageSector)*mr;await u.ensure(v,v+_.length).catch(()=>{})}}k=await fD(u.fh,u.covered,await hD(n.keep))}}finally{await u.close()}return k})(),g={at:Date.now(),have:u.have},b=0;return{mountpoint:o,path:t,status:()=>{let k=Date.now();return k-g.at>=1e3&&(b=(u.have-g.have)/((k-g.at)/1e3),g={at:k,have:u.have}),{path:u.path,files:u.files.length,fetched:u.have,total:u.total,rate:b,error:u.grewError??s}},stop:f,get stopped(){return!!d}}}async function o$(e,t){if(!fr(e).iso)throw new Error("this ticket serves files, not a delivery .iso \u2014 use mount, or receive it whole");let n=await fh(e,t),r=n.size;return{read:async(o,s)=>{let i=Math.max(0,Math.min(s,r-o));await n.ensure(o,o+i);let a=new Uint8Array(i);return await n.fh.read(a,0,i,o),a},write:()=>Promise.reject(new Error("a peer's .iso is read-only")),getSize:async()=>r,size:()=>r,close:()=>n.close()}}var gD=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function gh(e){let t=e.trim();if(t.startsWith("bucket:"))return{kind:"bucket",session_id:t.slice(7)};if(gD.test(t))return{kind:"bucket",session_id:t};if(/\.iso$/i.test(t)||t.includes("/")||t.includes("\\"))return{kind:"file",path:mt(t)};try{return fr(t),{kind:"peer",ticket:t}}catch{}throw new Error(`"${e.slice(0,40)}\u2026" is not a .iso path, a bucket delivery (bucket:<id>) or a p2p_send ticket`)}async function bh(e){let{files:t}=await Qt("v1-sessions",`/v1/sessions/${e}/files`),n=t.find(r=>r.chunks?._format==="iso"&&r.chunks.b2FileName);if(!n)throw new Error(`delivery ${e} has no .iso in its bucket`);return n}async function Qc(e,t){if(e.kind==="file")return Object.assign(await Vo(e.path),{name:fe(e.path)});if(e.kind==="peer"){let o=fr(e.ticket);return Object.assign(await o$(e.ticket,re(t,o.files[0]?.name??"peer.iso")),{name:o.files[0]?.name??"peer.iso"})}let n=await bh(e.session_id),r=ui(e.session_id);return Object.assign(await Vm(()=>r.readUrl(n.chunks.b2FileName)),{name:n.file_name})}async function bD(){let{storage:e}=await Qt("v1-me","/v1/me/storage");if(!e)throw new Error("your org has no bucket set up \u2014 the org owner adds one on conform.tools (Settings \u2192 Storage) or PUT /v1/me/storage");return e}var s$=()=>re(tt(),"bucket-index");async function yD(e,t,n=50){let{sessions:r}=await Qt("v1-sessions",`/v1/sessions?limit=${n}`),o=[];await Ve(s$());let s=r.filter(i=>i.id!==t);return await Promise.all(Array.from({length:6},async()=>{for(let i=s.shift();i;i=s.shift())try{let l=(await bh(i.id)).chunks;if(!l.blocksKey||l.bucket!==e)continue;let c=re(s$(),`${i.id}-${l.isoSize}.json`),u;try{u=JSON.parse(await ct(c))}catch{let d=await ui(i.id).readUrl(l.blocksKey),p=await fetch(d);if(!p.ok)continue;u=await p.json(),await Ke(c,JSON.stringify(u))}u.size===l.isoSize&&o.push({key:l.b2FileName,index:u})}catch{}})),o}async function i$(e,t,n){let r=await Qt("v1-sessions",`/v1/sessions/${e}/storage/upload-url`,{body:{key:t,content_type:"application/json",content_length:n.length}}),o=await fetch(r.upload_url,{method:r.method,headers:r.headers,body:n});if(!o.ok)throw new Error(`saving ${t}: ${o.status} ${(await o.text()).slice(0,200)}`)}async function a$(e,t,n){let r=await _v(t,n);r.timelines.length&&await Qt("v1-sessions",`/v1/sessions/${e}/contents`,{body:{projects:[],timelines:r.timelines,media:r.media,delivery_intent:{format:"folder",folder_layout:"canonical-i2o",per_file_mode:{mode:"trim"},handles:r.handles}}})}async function l$(e,t={}){let n=await bD(),r=await Vo(e),o=Jh(e);try{let s=await zn(r),i=fe(e);t.onProgress?.(0,r.size(),"indexing the image");let a=0,l=await uu(r,s,r.size(),w=>t.onProgress?.(a+=w,r.size(),"indexing the image")),{session:c}=await Qt("v1-sessions","/v1/sessions",{body:{destination:"b2",storage:"org",status:"ready",label:t.label??i.replace(/\.iso$/i,""),...t.recipients?.length?{recipient_emails:t.recipients}:{}}}),u=c.id,d=`sessions/${u}/${i}`,p=t.dedupe===!1?[]:await yD(n.bucket,u),f=Vh(l,p),h=cu(r.size(),f),g=(t.bucket??ui)(u),b=await du(g,d,h,o.read,{onProgress:(w,y)=>t.onProgress?.(w,y,"uploading"),signal:t.signal}),k=`${d}.blocks.json`;return await i$(u,k,new TextEncoder().encode(JSON.stringify(l))),await Qt("v1-sessions",`/v1/sessions/${u}/files`,{body:{files:[{file_name:i,file_size:r.size(),status:"completed",chunks:{_format:"iso",b2FileName:d,isoSize:r.size(),blocksKey:k,bucket:n.bucket,files:s.files.filter(w=>!w.name.startsWith(`${ao}/`)).map(w=>({name:w.name,size:w.totalSize}))}}]}}),await a$(u,r,s),await Qt("v1-sessions",`/v1/sessions/${u}`,{method:"PATCH",body:{status:"completed"}}),{session_id:u,key:d,image:r.size(),uploaded:b.uploaded,copied:b.copied,reused_from:new Set(f.map(w=>w.key)).size}}finally{await o.close(),await r.close()}}async function c$(e,t,n={}){if(e.kind==="peer")throw new Error("a peer's delivery is read-only \u2014 add_to a .iso on disk or a bucket delivery");if(e.kind==="file"){let u=await Xm(e.path,t),d=await Vo(e.path),p=d.size();return await d.close(),{...u,image:p}}let r=e.session_id,o=await bh(r),s=o.chunks.b2FileName,i=(n.bucket??ui)(r),a=await Vm(()=>i.readUrl(s)),l=await It("conform-grow-"),c=await Tv(a,re(l,"overlay"));try{n.onProgress?.(0,0,"patching");let u=await Xm(c,t);if(!c.writes().length)return{...u,uploaded:0,copied:0,image:a.size()};let d=cu(c.size(),Kh(s,a.size(),c.size(),c.writes())),p=await du(i,s,d,c.read,{onProgress:(y,_)=>n.onProgress?.(y,_,"writing back"),signal:n.signal}),f=await zn(c),h=o.chunks.blocksKey?await fetch(await i.readUrl(o.chunks.blocksKey)).then(y=>y.ok?y.json():null).catch(()=>null):null,g=new Map((h?.blocks??[]).map(y=>[`${y[1]}:${y[2]}`,y])),b=(y,_)=>c.writes().some(v=>v.offset<y+_&&v.offset+v.length>y),{blocks:k}=await uu(c,f,c.size(),void 0,(y,_)=>b(y,_)?void 0:g.get(`${y}:${_}`)),w={v:1,block:Wh,size:c.size(),blocks:k};return o.chunks.blocksKey&&await i$(r,o.chunks.blocksKey,new TextEncoder().encode(JSON.stringify(w))),await Qt("v1-sessions",`/v1/sessions/${r}/files/${o.id}`,{method:"PATCH",body:{bytes_uploaded:c.size(),chunks:{...o.chunks,isoSize:c.size(),files:f.files.filter(y=>!y.name.startsWith(`${ao}/`)).map(y=>({name:y.name,size:y.totalSize}))}}}),await a$(r,c,f),{...u,uploaded:p.uploaded,copied:p.copied,image:c.size()}}finally{await c.close(),await dn(l)}}async function u$(e,t,n){if(e.kind==="peer"){let s=fr(e.ticket),i,a=new Promise(c=>{i=c}),l=await r$(e.ticket,re(t,s.iso?fe(s.files[0].name):"shared.iso"),{volume:s.label,keep:n,onEjected:()=>i()});return{mountpoint:l.mountpoint,stop:l.stop,status:l.status,ejected:a}}let r=await Qc(e,t),o=await xv(r);try{let s=await Sv(o.url);return{mountpoint:s.mountpoint,stop:async()=>{await s.detach(),await o.close(),await r.close()}}}catch(s){throw await o.close(),await r.close(),s}}async function d$(e,t,n,r,o){if(await Ve(xn(t)),e.kind==="peer")return(await n$(e.ticket,t,{onProgress:(i,a)=>r?.(i,a,"receiving"),signal:o})).bytes;let s=await Qc(e,n);try{return await $v(s,t,(i,a)=>r?.(i,a,"downloading"),o)}finally{await s.close()}}var p$=e=>"No tool matched this request's words outright. That is a word match, not a verdict: "+(e.length?`the nearest tools are
|
|
345
|
+
`+e.map(t=>`- ${t.id} \u2014 ${t.title}`).join(`
|
|
346
|
+
`)+`
|
|
347
|
+
Read what they do (and the rest of the tool list)`:"look through the tool list")+" and use one if it does the job. Only if none does: tell the user plainly and say so in finish (outcome failed or partly, why = no tool for it), then help another way if you can.";var m$={resolve:["resolve-drt","drt"],premiere:["premiere-prproj","prproj"],avid:["avid-avb","avb"],flame:["flame-fcpxml","fcpxml"]};function kD(e,t){let n=[];for(let[r,o]of Object.entries(t)){let s=e[r];for(;s&&(s instanceof m.ZodDefault||s instanceof m.ZodOptional||s instanceof m.ZodNullable);)s=s._def.innerType;s instanceof m.ZodEnum&&typeof o=="string"&&s.options.includes(o)&&n.push(`${r}=${o}`)}return n}var f$=["summary","flags","link"],_D=[{name:"account_login",title:"Sign in to conform.tools",description:"Sign in with the Google account you use on conform.tools. Opens the browser to the sign-in page and waits (up to 5 minutes) until it completes, then reports the plan. Needed once per machine; every other verb except timeline_routes and the account verbs requires a signed-in account with an active trial or subscription.",inputSchema:{},run:async()=>{let e="",t=await jh({onUrl:(n,r)=>{e=r?"":n,r||console.error(`open this URL to sign in: ${n}`)}});return Q(`signed in
|
|
348
|
+
${au(t)}${e?`
|
|
349
|
+
(sign-in URL: ${e})`:""}
|
|
350
|
+
${await Iu()}`,{account:t})}},{name:"account_status",title:"Account and plan",description:"The running conformtools version (and whether a newer one is on npm), who is signed in on this machine, and whether the account's trial or subscription is active (checked live against conform.tools, with a 72-hour offline grace).",inputSchema:{},run:async()=>{let[e,t]=await Promise.all([ls({force:!0}),Ch()]);return Q(`${await Ah()}
|
|
351
|
+
${au(e)}
|
|
352
|
+
${await Iu()}`,{account:e,version:ka,latest_version:t})}},{name:"account_logout",title:"Sign out",description:"Forget this machine's conform.tools sign-in.",inputSchema:{},run:async()=>(await Dh(),Q(`signed out (${li().env})`,{signed_in:!1}))},{name:"account_telemetry",title:"Telemetry and session capture on / off",description:"Turn conform.tools telemetry on or off, or show its state (action=status, the default). It is ON unless the user turns it off, and it has two parts. SESSION CAPTURE (the beta): each tool call's arguments as given and the tool's answer, with the request and the final reply; this is not scrubbed, so it includes file and folder paths, clip and show names and what a timeline contains (never media files); conform.tools uses it to fix its tools and to train and test models. OUTCOME TELEMETRY: per tool run, the tool name, ok or the error code, duration, package version, engine mode, counts (numbers only), the names of the arguments given and the call's place in the conversation (a random run id + number), and per rejected call the tool name and the names of the failing arguments. Off stops both. Only change it when the user asks; if they ask what is collected, tell them both parts plainly. Same as `conformtools telemetry on|off|status`.",inputSchema:{action:m.enum(["on","off","status"]).default("status")},run:async({action:e})=>((e==="on"||e==="off")&&await Ab(e==="on"),Q(await Eb(),{telemetry:await Ua()}))},{name:"conform_learn",title:"Load the conform.tools playbook for a task",description:`Call this FIRST, before any conform, timeline conversion, relink, verification, delivery or media prep task, and follow what it returns: the conform.tools playbook for the task (the order a conform artist works in, what to check, how to tell the user). task = conform (a turnover, timeline conversion, relink, online/offline conform, "is this conform right?") | autoconform (rebuild an edit from a reference render + source media) | deliver (consolidate, media manage, package or QC a turnover for the next facility) | deliverables (render and QC a finished program's deliverables: the usual set, naming, pre-render gate, audio routing, sign-off) | troubleshoot (a conformtools result looks wrong) | patch (fix a show already delivered: temps left in, replace with masters, insert timelines, patch renders and their QC) | prep (cut shots or trims out of a file, handles, raster, pixel aspect, anamorphic squeeze, letterbox, a copy for upload or another tool). hosts = the editing systems involved, which adds their notes. Once per task per conversation is enough. Needs a signed-in account (account_login).`,inputSchema:{task:m.enum(Eu).describe(Eu.join(" | ")),hosts:m.array(m.enum(Mu)).max(Mu.length).optional().describe("The editing systems involved, source and target")},run:async({task:e,hosts:t})=>{try{let n=await Cb(e,t??[]);return Q(n.text)}catch(n){return ee(new P("refused",`the playbook could not be loaded: ${n instanceof Error?n.message:String(n)}. Carry on with the tools; their descriptions still apply.`))}}},{name:"feedback",title:"Send conform.tools feedback: a problem, a missing capability, an idea or a lesson",description:`Feedback to the conform.tools team (one record with the website's box and the app's Feedback sheet). words="user" when the text is the USER's own words, because they asked you to send it ("tell them\u2026", "report this", "send feedback"): it reaches the team's Feedback list as theirs, so pass what they said, not your summary. Leave words out for your own note (a result they told you was wrong, a missing tool, a lesson): it is filed with the job it came from. topic=problem when the USER says a result was wrong or something is not working (a failed run is already recorded with the run itself; a run that finished with the wrong output is only known from them); topic=missing when they want something conform.tools cannot do yet (after find_verb found nothing that fits, say so and send it: what they wanted, in \`detail\` what they will do instead); topic=suggestion for an idea about the product; topic=playbook for a lesson or workflow rule when nothing broke ("never match archival by file name alone"). Also whenever the user asks to report, flag, tell the team or send feedback. Tell the user it was sent and give the feedback id. Never sends media, file contents or timeline files; file names at most, never full paths or values from the user's media.`,inputSchema:{summary:m.string().min(3).describe(`One line: the lesson or suggestion (max ${mu.summary} chars; longer is cut)`),detail:m.string().optional().describe(`Why, when it applies (max ${mu.what_happened} chars)`),topic:m.enum(["playbook","suggestion","problem","missing"]).optional().describe("playbook = how the work should be done (default); suggestion = an idea for the product; problem = the user says a result was wrong or something does not work; missing = something conform.tools cannot do yet"),words:m.enum(["user","claude"]).optional().describe("user = the text is the user's own words, sent because they asked; leave out (claude) for your own note"),source:m.enum(["mcp","app"]).optional().describe("Leave out (mcp). The desktop app's Feedback sheet says app"),context:m.record(m.union([m.string(),m.number(),m.boolean(),m.array(m.string())])).optional().describe("What helps the team: the host and its version, the tool, what kind of job (no names of the user's clips, shows or people, no paths)"),session_id:m.string().optional(),verb:m.string().optional().describe("The tool it is about, e.g. timeline_write")},run:async({summary:e,detail:t,topic:n,...r})=>{try{let o={...r,summary:n==="missing"?e:`[${n??"playbook"}] ${e}`,...n==="missing"?{task:e}:{},...t?{what_happened:t}:{}};return Pb(await Ib(await Mb(o,n==="problem"?"issue":n==="missing"?"gap":"note")),o)}catch(o){return ee(o)}}},{name:"find_verb",title:"Find the tool for a request",description:"Call this FIRST whenever no conformtools tool obviously fits what the user asked: it answers with the tools and artist recipes that do it, best first, or the nearest ones when none matches outright. That answer is how conform.tools learns what to build next, so call it before any workaround (ffmpeg, ffprobe, a script, another tool, manual steps in a host), and before telling the user conformtools cannot do something. asked = the user's message exactly as they wrote it (never reworded, shortened or with anything replaced: names and paths stay).",inputSchema:{asked:m.string().min(3).describe(`The user's message exactly as written: "can you check every clip in /Volumes/SHOW/DAY03 for variable frame rate"`)},run:async({asked:e})=>{let t=await h$(),n=rd(e,t);return n.length?Q(`These fit, best first (tool:<id> = an artist recipe: run it with tool_run id=<id>):
|
|
353
|
+
`+n.map(r=>`- ${r.id} \u2014 ${r.title} (${Math.round(r.score*100)}%)`).join(`
|
|
354
|
+
`)+`
|
|
355
|
+
If none of them does what was asked, say so to the user rather than forcing one.`,{hits:n.map(r=>r.id)}):Q(p$(od(e,t)),{hits:[]})}},{name:"begin",title:"Begin a user request",description:"Call this FIRST on every new user request, before any other tool. It starts the request and answers with what to know before acting: the conformtools tools and artist recipes that fit it (best first; when none matches outright it shows the nearest ones: use one if it does the job, and only if none does tell the user plainly and say so in finish, rather than forcing a tool or reaching for ffmpeg, Bash, a script or manual host steps), the open project's brief and the artist's profile. asked = the user's message exactly as they wrote it (never reworded, shortened or with anything replaced: names and paths stay). End the request with finish.",inputSchema:{asked:m.string().min(3).describe(`The user's message exactly as written: "ok now relink reel 3 to the camera originals"`)},run:async({asked:e})=>{cy();let t=await h$(),n=e.replace(/^\s*\[[^\]]*\]\s*/,""),r=rd(n,t),o=await xo().catch(()=>null),s=o?(await za(o.id,{local:!0}).catch(()=>"")).trim():"",i=await ng().catch(()=>""),a=[r.length?`Tools that fit, best first (tool:<id> = an artist recipe: tool_run id=<id>):
|
|
356
|
+
`+r.map(l=>`- ${l.id} \u2014 ${l.title} (${Math.round(l.score*100)}%)`).join(`
|
|
357
|
+
`)+`
|
|
358
|
+
If none of them does what was asked, say so to the user rather than forcing one.`:p$(od(n,t)),o?`Open project: ${o.name}. Work from this; never ask for what it says.${s?`
|
|
359
|
+
${s.length>6e3?`${s.slice(0,6e3)}
|
|
360
|
+
\u2026(project action=brief has the rest)`:s}`:""}`:"No project open: project action=list, then action=open id=\u2026 when this is a job (its brief, notes and facts come with it).",i,"Before replying, call finish with the reply and the outcome."].filter(Boolean);return Q(a.join(`
|
|
361
|
+
|
|
362
|
+
`),{hits:r.map(l=>l.id),project:o?.name??null})}},{name:"finish",title:"Finish a user request",description:"Call this LAST on every user request, with the reply you are about to give and how the request went. It checks the reply against what the request did (every path it names exists on this machine, every file the tools wrote is named, no {placeholder} is left in) and answers ok or what to fix: fix it, then reply. outcome: solved = the user got what they asked for; partly = blocked, refused or a workaround; failed = wrong or nothing (why, in a few words). When the user says an earlier result was wrong, that is failed, with why.",inputSchema:{answer:m.string().min(1).max(5e4).describe("The reply, as you are about to give it"),outcome:m.enum(ay).describe("solved | partly | failed"),why:m.string().max(200).optional().describe("For partly or failed: what was missing or wrong, in a few words")},run:async({answer:e})=>{let t=await py(e),n=uy();return Q(t.length?`fix, then reply:
|
|
363
|
+
${t.map(r=>`- ${r}`).join(`
|
|
364
|
+
`)}`:"ok \u2014 reply",{ok_to_send:!t.length,fixes:t.length,calls:n.calls,failed:n.failed,wrote:n.wrote.length})}},y$("script_run"),y$("script_read"),{name:"timeline_read",protectedStages:["canonicalize"],title:"Read a timeline file",description:"Read an editorial timeline file (Avid AAF/AVB bin, Premiere .prproj, Resolve .drt, Final Cut .fcpxml/.fcpxmld or a project's own CurrentVersion.fcpevent inside a library, FCP7 XML, OTIO, Flame archive) into a session on this machine. Nothing is uploaded. Returns a session_id to pass to the other timeline_* tools, plus a summary (rates, raster, tracks, clip counts, media link state, conform flags). Call this first for any request that mentions a cut, sequence, bin, timeline or conform.",inputSchema:{engine:m.enum(["local","hosted"]).optional().describe("Where the conversion runs: local = this machine, offline, nothing uploaded; hosted = conform.tools (the website's engine). Default: local when this build has it"),path:m.string().describe("Absolute path to the timeline file (or .fcpxmld bundle directory)"),format:m.enum(ib).optional().describe("Override detection. The file's own bytes decide the format (a bare Flame archive, a renamed export and an FCPXML saved as .xml all read without this); pass it only when the file is not recognised")},run:async({path:e,format:t})=>{try{let{session:n,format:r,sourcePath:o,notes:s}=await ds(e,t),i=await Kn(n,o??e,r);return Q(`session_id: ${i.id}
|
|
365
|
+
source: ${e} (${r})
|
|
366
|
+
${(s??[]).map(a=>`note: ${a}
|
|
367
|
+
`).join("")}${await Cr(n)}`,{session_id:i.id,format:r,...s?.length?{notes:s}:{}})}catch(n){return ee(n)}}},{name:"host_current",protectedStages:["canonicalize"],title:"What is open in Resolve / Premiere / Media Composer / Flame / Final Cut",description:`Find the project and timeline each editing host on this machine has open right now \u2014 no host API, no export dialog \u2014 and read it into a session as if its file had been given to timeline_read. Resolve (Studio): the timeline in the viewer, exported by Resolve itself as its own .drt (its project database is never read). Premiere: the project window's .prproj and the sequences open in its Timeline panel (last save). Media Composer: the open project's bins (newest first; the loaded sequence is not on disk). Flame: the running project/workspace's live workspace file (every sequence on the desktop). Final Cut: the project in the Timeline, decoded from its own store in the open library (CurrentVersion.fcpevent \u2192 FCPXML; effects, titles and the like come back as conform flags). via=export (or a timeline / out_path) asks the running host to export a timeline itself through its scripting door (read-only on the project) and reads that: Resolve any timeline of the open project by name as its own .drt; Baselight a scene (default the open one, or "host:job:scene") through FLAPI; Premiere, Media Composer, Flame through the conform.tools plugin (host_setup says how to install it). Use it when the open timeline is not readable from disk (a PostgreSQL project library, a timeline never saved) or to pick one by name; the reply carries project, timeline, path and session_id. Use when asked 'what do I have open', 'grab my current timeline', 'the sequence I'm working on', or to act on the open cut.`,inputSchema:{host:m.enum(Zt).optional().describe("One host; omit for all"),read:m.boolean().default(!0).describe("Also read the open timeline into a session (session_id in the reply)"),via:m.enum(["disk","export"]).default("disk").describe("disk: what the host has on disk, no host API; export: the running host exports the timeline itself (needs host)"),timeline:m.string().optional().describe("Timeline name to export (implies via=export); default the open one"),out_path:m.string().optional().describe("via=export: where to write the file; a temp file when omitted")},run:async({host:e,read:t,via:n,timeline:r,out_path:o})=>{if(n==="export"||r||o)return e?nn("host_export").run({host:e,timeline:r,out_path:o,read:t}):ee(new P("invalid_args","via=export needs host"));try{let i=await qy(e?[e]:void 0,void 0,t?async(c,u)=>{try{let{session:d}=await ds(c,u);return d.timelines.some(p=>p.tracks?.some(f=>f.items?.length))}catch{return!1}}:void 0),a=[],l=[];for(let c of i){let u=Uy(c),d={...c};if(l.push(d),t&&c.read)try{let{session:p,format:f,sourcePath:h,notes:g}=await ds(c.read.path,c.read.format);By(p,c);let b=await Kn(p,h??c.read.path,f);d.session_id=b.id,u+=`${(g??[]).map(k=>`
|
|
368
|
+
note: ${k}`).join("")}
|
|
369
|
+
session_id: ${b.id}
|
|
370
|
+
${(await Cr(p)).replace(/^/gm," ")}`}catch(p){u+=`
|
|
371
|
+
read failed: ${p instanceof Error?p.message:String(p)}`}a.push(u)}return Q(a.join(`
|
|
372
|
+
|
|
373
|
+
`),{hosts:l})}catch(s){return ee(s)}}},{name:"host_export",hidden:!0,protectedStages:["canonicalize"],title:"Export a timeline from the running host",description:`Ask the running host to export a timeline in its own format, through its scripting door (read-only on the project), and read it into a session. Resolve: any timeline of the open project by name (default: the one in the viewer) as Resolve's own .drt. Baselight: a scene (default: the one open in the app; or "host:job:scene") read shot by shot through FLAPI into an OTIO. Premiere, Media Composer, Flame: through the conform.tools plugin in the host (host_setup says how to install it), as OTIO (Premiere / Media Composer: the host's own export; Flame: the timeline as the plugin reads it). Use when host_current cannot read the open timeline from disk (a PostgreSQL project library, a timeline never saved), or to pick a timeline by name.`,inputSchema:{host:m.enum(Zt).describe("The host to export from"),timeline:m.string().optional().describe("Timeline name; the open one when omitted"),out_path:m.string().optional().describe("Where to write the file; a temp file when omitted"),read:m.boolean().default(!0).describe("Also read it into a session (session_id in the reply)")},run:async({host:e,timeline:t,out_path:n,read:r})=>{try{if(e==="premiere"&&!n&&r!==!1){let{premiereSession:l}=await import("./host-relink-MVHI3YQI.js"),c=an("premiere"),u=await l(c,t).catch(d=>{if(d.code==="panel_old")return null;throw d});if(u){let d=await Kn(u.session,u.path,/\.otio$/i.test(u.path)?"otio":"prproj"),p=await c.current(),f=u.session.timelines[0]?.name??t??p.timeline;return Q([`read ${p.project} / ${f} from ${u.from}`,...u.lossy?[`\u26A0 ${u.lossy}`]:[],`session_id: ${d.id}`,await Cr(u.session)].join(`
|
|
374
|
+
`),{path:u.path,format:/\.otio$/i.test(u.path)?"otio":"prproj",project:p.project,timeline:f,session_id:d.id,from:u.from})}}let o=n??re(await It("conform-export-"),`${(t??"current").replace(/[^\w.-]+/g,"_")}.${e==="resolve"?"drt":"otio"}`),s=await an(e).export({timeline:t,out_path:o}),i=[`exported ${s.project} / ${s.timeline} \u2192 ${s.path} (${s.format})`,...(s.notes??[]).map(l=>`\u26A0 ${l}`)].join(`
|
|
375
|
+
`),a={...s};if(r!==!1){let{session:l,format:c}=await ds(s.path,s.format);e==="resolve"&&await(await import("./host-relink-MVHI3YQI.js")).withOfflineReference(an("resolve"),l).catch(()=>0),e==="premiere"&&await(await import("./host-relink-MVHI3YQI.js")).withPremiereTimecodes(an("premiere"),l).catch(()=>0);let u=await Kn(l,s.path,c);i+=`
|
|
376
|
+
session_id: ${u.id}
|
|
377
|
+
${await Cr(l)}`,a.session_id=u.id}return Q(i,a)}catch(o){return ee(new P("refused",o instanceof Error?o.message:String(o)))}}},{name:"host_open",protectedStages:["write"],title:"Open a timeline file in the running host",description:`Import a timeline file into the running host as a NEW timeline (never overwrites one; a taken name gets a number). Resolve: into the open project's conform.tools media pool folder (into=current, the default), or into our scratch project (into=scratch: the user's project is saved first, then reopened). Baselight: a NEW scene in the open scene's job (into=current) or our job conform_tools (into=scratch), V1 built shot by shot from the file's media paths, saved; the scene in the app is never touched. folder (Resolve): the media pool folder to land it in, by path under Master, e.g. "000 - TIMELINES/20261006" (learn the project's layout with host_project first); a missing folder is refused unless create_folder=true. link_existing=true links the timeline to clips already in the media pool (no duplicate clips; Resolve importSourceClips off): the way to bring an insert/update timeline into a project that has the media. The user's timeline, folder and page are put back afterwards unless stay=true. Use after timeline_write to land a conversion in the host, or to bring a turnover in for checking. Premiere, Media Composer, Flame: through the host's conform.tools plugin, into the open project (Flame: the CONFORM.TOOLS reel group on the desktop, segments relinked to media on disk). session_id (+ timeline_id) opens a session's timeline directly \u2014 the push half of a Resolve tool: host_current via=export \u2192 timeline_edit add_handles / all_clips \u2192 host_open session_id timeline_id link_existing=true.`,inputSchema:{host:m.enum(Zt).describe("The host to open it in"),path:m.string().optional().describe("The timeline file (Resolve: .drt, .xml, .fcpxml, .aaf, .edl, .otio); or give session_id"),session_id:m.string().optional().describe("Open a timeline of this session instead of a file (written here first in the host's own format: .drt Resolve, .prproj Premiere, .avb Media Composer, .fcpxml Flame)"),timeline_id:m.string().optional().describe("With session_id: which timeline (e.g. the one timeline_edit just built); default the session's first"),name:m.string().optional().describe("Timeline name; the file name (or the session timeline's name) when omitted"),into:m.enum(["current","scratch"]).default("current").describe("current: the open project; scratch: our own project"),media_dirs:m.array(m.string()).optional().describe("Folders to link media from while importing"),stay:m.boolean().default(!1).describe("Leave the host showing the imported timeline"),folder:m.string().optional().describe('Resolve: media pool folder path to import into, e.g. "000 - TIMELINES/20261006" (default: conform.tools)'),create_folder:m.boolean().default(!1).describe("Create the folder (and its parents) when missing"),link_existing:m.boolean().default(!1).describe("Link to clips already in the media pool instead of importing new ones"),settings_from:m.string().optional().describe("Resolve: a timeline whose settings the new one takes (resolution, rate, color science and spaces, data levels, monitoring), verified; if a critical one does not take, the new timeline is deleted and the open refused")},run:async({host:e,path:t,session_id:n,timeline_id:r,name:o,into:s,media_dirs:i,stay:a,folder:l,create_folder:c,link_existing:u,settings_from:d})=>{try{if(n){let h=await ft(n),g=h.session.timelines.find(_=>_.id===r)??h.session.timelines.find(_=>_.kind!=="compound");if(!g)return ee(new P("not_found",`no timeline ${r??""} in session ${n}`));let b={...h.session,timelines:h.session.timelines.filter(_=>_.id===g.id||_.kind==="compound")},[k,w]=m$[e]??m$.resolve;t=(await Cu(b,k,re(await It("conform-open-"),`${g.name.replace(/[^\w.-]+/g,"_")}.${w}`),h.source_path)).path,o??=g.name}if(!t)return ee(new P("invalid_args","host_open needs path or session_id"));let p=await an(e).open({path:t,name:o,into:s,media_dirs:i,stay:a,folder:l,create_folder:c,link_existing:u,...d?{settings_from:d}:{}}),f=[`opened in ${e}: ${p.project} / ${p.timeline}${p.folder?` (media pool: ${p.folder})`:""}`,p.restored?"the user's timeline, folder and page were put back":"left showing the imported timeline",...u?["linked to clips already in the media pool (no new clips imported)"]:[],...p.settings?[`timeline settings from ${d}: ${p.settings}, verified`]:[],...p.notes];return Q(f.join(`
|
|
378
|
+
`),{...p})}catch(p){return ee(new P("refused",p instanceof Error?p.message:String(p)))}}},{name:"host_render",long:!0,title:"Render a timeline in the running host",description:`Render a timeline (or a frame range of it) with the host's own renderer and wait for the files. Only OUR job is queued and started; the user's render queue is never run, their Deliver settings are restored as soon as our job is queued, and their timeline and page come back when it finishes. Refuses while the host is already rendering. Resolve: preset = a render preset saved in Resolve (default: the project's current render settings); range = absolute timeline frames, inclusive; name = the output file name. Baselight: timeline = a scene (default: the one open in the app), preset = a deliverable defined in the scene (default: ProRes 422 HQ of the working space), queued on the local render queue as "conform.tools <name>". Premiere: preset = the path of a Media Encoder .epr. Flame (through its conform.tools hook): preset = one of Flame's export presets by name (required), range as Resolve's; Flame renders in the foreground and a running export cannot be cancelled from here. Picture only unless audio=true. audio_tracks (Resolve) = the Deliver page's audio output routing by timeline track, which its API cannot set: [1, 2] = A1 (5.1) on ch1-6 + A2 (stereo) on ch7-8 (an 8CH_5-1_STEREO deliverable), [2] = stereo only; set it whenever a name promises a channel layout. disable_tracks = video tracks to leave out of this render, by name (every track so named, e.g. ["Lower Thirds"] for a TEXTLESS version) or "V7": Resolve's API has no per-job track selection, so they are switched off on the Edit page (read back) for our job and switched back on when it ends. Resolve names the queued job itself ("Job N"); its API cannot. To QC the result, run qc_media on the rendered file. Long: pass background=true for a job id, then job action=status.`,inputSchema:{host:m.enum(Zt).describe("The host to render in"),timeline:m.string().optional().describe("Timeline name; the open one when omitted"),target_dir:m.string().optional().describe("Folder for the render; created if missing"),name:m.string().optional().describe("Output name without extension; the timeline name when omitted"),preset:m.string().optional().describe("A render preset saved in the host"),range:m.object({in:m.number().int(),out:m.number().int()}).optional().describe("Frame range, absolute timeline frames, inclusive"),audio:m.boolean().optional().describe("Render audio with the picture (default: off = picture only)"),disable_tracks:m.array(m.string()).optional().describe('Video tracks to leave out of this render, by name or "V7" (e.g. ["Lower Thirds"] for TEXTLESS)'),audio_tracks:m.array(m.number().int().positive()).optional().describe("Resolve: audio output n = timeline track audio_tracks[n], e.g. [1, 2] = 5.1 (A1) on ch1-6 + stereo (A2) on ch7-8; [2] = stereo only. Implies audio"),queue:m.boolean().default(!1).describe("Resolve: add the job to the render queue for the artist and stop there (nothing rendered)")},run:async({host:e,timeline:t,target_dir:n,name:r,preset:o,range:s,audio:i,disable_tracks:a,audio_tracks:l,queue:c,__progress:u,__signal:d})=>{let p=an(e);try{if(!n)return ee(new P("invalid_args","target_dir is required"));if(l?.length&&e!=="resolve")return ee(new P("unsupported","audio_tracks (output routing) is for DaVinci Resolve"));if(c&&e!=="resolve")return ee(new P("unsupported","queue (leave the job in the render queue) is for DaVinci Resolve"));let f=await p.renderStart({timeline:t,target_dir:n,name:r,preset:o,range:s,audio:(i??!1)||!!l?.length,...a?.length?{disable_tracks:a}:{},...l?.length?{audio_tracks:l}:{},...c?{queue:c}:{}});if(c)return Q(`queued in ${e}: ${r??t??"the timeline"} \u2192 ${n} (render queue job ${f.job_id}; nothing rendered \u2014 start it on the Deliver page)
|
|
379
|
+
the user's render settings, timeline and page were put back`,{host_render_job:f.job_id,queued:!0});if(f=await Wb(p,f,u,d),f.state!=="complete")return ee(new P(f.state==="cancelled"?"cancelled":"engine",`render ${f.state}${f.error?`: ${f.error}`:""}${f.notes?.length?`; ${f.notes.join("; ")}`:""}`));let h=f.outputs?.length?f.outputs:await Hb(n,r??t??"");return Q([`rendered in ${e} \u2192 ${h.join(", ")||n}${i||l?.length?"":" (picture only)"}`,...a?.length?[`without video tracks: ${a.join(", ")}`]:[],...l?.length?[`audio outputs: ${l.map((g,b)=>`${b+1} = timeline track ${g}`).join(", ")} \u2014 probe the file to confirm the channel layout`]:[],"the user's render settings, timeline and page were put back",`${e} render queue job ${f.job_id} (the host's own id, kept in its queue \u2014 not a conform.tools job id)`,...f.notes??[]].join(`
|
|
380
|
+
`),{host_render_job:f.job_id,outputs:h,...f.notes?{notes:f.notes}:{}})}catch(f){return ee(new P("refused",f instanceof Error?f.message:String(f)))}}},{name:"host_preset",title:"Read or author host render presets (incl. audio output routing)",description:"Resolve render presets. action=list: every preset (or names) with its container, codec, raster, audio codec and the Deliver page's audio OUTPUT routing (Timeline Track n / Bus n per output) \u2014 the routing the scripting API cannot read. action=author: save a NEW preset = base (a preset, or the Deliver page's current settings) with audio output n fed by timeline track audio_tracks[n] ([1, 2] = 5.1 on A1 \u2192 ch1-6 + stereo on A2 \u2192 ch7-8; [2] = stereo only). Never replaces a preset; names without dots. The user's Deliver settings and page are put back. Prove a new preset with a short test render (host_render range of ~11 frames) and media_probe the channels before the full render.",inputSchema:{host:m.enum(Zt).default("resolve").describe("The host"),action:m.enum(["list","author"]).default("list"),names:m.array(m.string()).optional().describe("list: only these presets"),name:m.string().optional().describe("author: the new preset's name (no dots), e.g. PR4444_8CH_5-1_STEREO"),base:m.string().optional().describe("author: the preset to start from; the Deliver page's current settings when omitted"),audio_tracks:m.array(m.number().int().positive()).optional().describe("author: timeline track per audio output, e.g. [1, 2]")},run:async({host:e,action:t,names:n,name:r,base:o,audio_tracks:s})=>{try{let i=an(e??"resolve");if(!i.presets||!i.presetAuthor)return ee(new P("unsupported",`${i.host}: host_preset is for DaVinci Resolve`));let a=c=>c.error?`${c.name}: ${c.error}`:`${c.name}: ${c.format??"?"} ${c.codec??"?"} ${c.width??"?"}x${c.height??"?"}; audio ${c.audio==="true"?`${c.audio_codec??"on"} \u2192 ${c.audio_outputs?.length?c.audio_outputs.map((u,d)=>`out ${d+1} = ${u}`).join(", "):"default routing"}`:"off"}`;if(t==="author"){if(!r||!s?.length)return ee(new P("invalid_args","author needs name and audio_tracks"));let c=await i.presetAuthor({name:r,...o?{base:o}:{},audio_tracks:s});return Q(`saved render preset "${c.preset}"${c.summary?`
|
|
381
|
+
${a({...c.summary,name:c.preset})}`:""}
|
|
382
|
+
prove it: host_render a ~11-frame range with this preset, then media_probe the channels`,c)}let l=await i.presets({...n?.length?{names:n}:{}});return Q([`${l.presets.length} render preset(s) in "${l.project}":`,...l.presets.map(a)].join(`
|
|
383
|
+
`),l)}catch(i){return ee(new P("refused",i instanceof Error?i.message:String(i)))}}},{name:"host_project",title:"Learn the open host project: media pool, render queue, tracks",description:"Read-only look at the project open in the running host, to learn its conventions before acting. Resolve: the media pool folder tree with clip counts (clips=true lists every clip with its file, start TC and usage); find = file paths or name fragments to look up project-wide ('is this file already in the project? where?'); the render queue with each job's name, timeline, output folder/file, status, mark in/out and the settings Resolve reports; and every track of a timeline (default: the open one) with its name and enabled/locked state. Use before host_open (which folder) and host_render (which tracks are Lower Thirds, which job made the deliverable).",inputSchema:{host:m.enum(Zt).default("resolve").describe("The host"),timeline:m.string().optional().describe("Timeline whose tracks to list; the open one when omitted"),clips:m.boolean().default(!1).describe("List every clip in every folder (large projects: long)"),find:m.array(m.string()).optional().describe("File paths or name fragments to look up in the media pool"),used:m.boolean().default(!1).describe("Resolve: also the ids of every media pool clip any timeline holds (`used`), read from the timelines themselves"),project:m.string().optional().describe("Resolve: read another project of the library instead (it is opened, then the open one again)"),export_dir:m.string().optional().describe("Resolve: also write every timeline of the project as .drt into this folder (`exported`)"),grades:m.array(m.object({key:m.union([m.string(),m.number()]),timeline:m.string(),track:m.number(),start:m.number()})).optional().describe("Resolve: these clips' grades as gallery-still .drx files into grades_dir (`grades`: key \u2192 path), for a copy into another project"),grades_dir:m.string().optional()},run:async({host:e,timeline:t,clips:n,find:r,used:o,project:s,export_dir:i,grades:a,grades_dir:l})=>{try{let c=an(e??"resolve");if(!c.project)return ee(new P("unsupported",`${c.host}: host_project is not available for this host yet`));let u=await c.project({timeline:t,clips:n,find:r,...o?{used:o}:{},...s?{project:s}:{},...i?{export_dir:i}:{},...a?.length?{grades:a,grades_dir:l}:{}}),d=0,p=0,f=[],h=(b,k)=>{k&&(d++,f.push(`${" ".repeat(k)}${b.path.split("/").pop()} (${b.clips} clip${b.clips===1?"":"s"})`)),p+=b.clips;for(let w of b.clip_list??[])f.push(`${" ".repeat(k+1)}- ${w.name} ${w.file}${w.start_tc?` TC ${w.start_tc}`:""}${w.usage?` used ${w.usage}x`:""}`);for(let w of b.folders)h(w,k+1)};h(u.pool,0);let g=[`${e??"resolve"} project "${u.project}": ${d} media pool folders, ${p} clips; ${u.jobs.length} render job(s)${u.timeline?`; timeline "${u.timeline}" has ${u.tracks.length} tracks`:""}`];g.push("media pool:",...f.length?f:[" (no folders)"]);for(let[b,k]of Object.entries(u.found??{}))g.push(k.length?`find "${b}": ${k.map(w=>`${w.folder||"Master"}/${w.name} (${w.file||"no file"}${w.usage?`, used ${w.usage}x`:""})`).join("; ")}`:`find "${b}": not in the project`);u.jobs.length&&g.push("render queue:");for(let b of u.jobs){let k=b.MarkIn!=null?` frames ${b.MarkIn}-${b.MarkOut}`:"";g.push(` ${b.RenderJobName??b.JobId} [${b.JobStatus||"?"}] "${b.TimelineName??""}" \u2192 ${_h(String(b.TargetDir??""),String(b.OutputFilename??""))}${k}${b.VideoCodec?` ${b.VideoFormat??""} ${b.VideoCodec}`:""}${b.PresetName?` preset ${b.PresetName}`:""}`)}return u.tracks?.length&&g.push(`tracks: ${Ju(u.tracks)}`),Q(g.join(`
|
|
384
|
+
`),u)}catch(c){return ee(new P("refused",c instanceof Error?c.message:String(c)))}}},{name:"host_items",title:"Live clip attributes in the host (color, flags, versions, groups)",description:"Resolve: per item of a timeline (default the open one) what its timeline file does not carry: clip color, flags, enabled, the loaded grade version, color group, node count, keywords, and its unique id. Items are addressed like timeline_query rows: kind + 1-based track + start (record frames from the timeline start), so the two join. Also the project's color groups and node-stack layer count. Read-only.",inputSchema:{host:m.enum(Zt).default("resolve").describe("The host (each says when it cannot do this yet)"),timeline:m.string().optional().describe("Timeline by name; the open one when omitted"),kind:m.enum(["video","audio"]).optional(),track:m.number().int().positive().optional(),selected:m.boolean().optional().describe("only the clips selected in the host's timeline right now: {selected: [{kind, track, start, id, name}]}"),follow:m.boolean().optional().describe("Resolve: only where the artist is (project, timeline, playhead) \u2014 cheap, for a window following Resolve"),blanking:m.boolean().optional().describe("Resolve: also the timeline's output blanking in pixels (Resolve 21.1 shows its Color page for a moment to answer)")},run:async({host:e,timeline:t,kind:n,track:r,selected:o,blanking:s,follow:i})=>{try{let a=an(e??"resolve");if(!a.items)return ee(new P("unsupported",`${a.host}: host_items is not available for this host yet`));if(i){let u=await a.items({timeline:t,follow:!0});return Q(`${u.project} / ${u.timeline} at ${u.playhead_tc}`,u)}if(o){let u=await a.items({timeline:t,selected:!0});return Q(`"${u.timeline}": ${u.selected.length} clip(s) selected`,u)}let l=await a.items({timeline:t,kind:n,track:r,...s?{blanking:s}:{}}),c=u=>l.items.filter(d=>d[u]&&(!Array.isArray(d[u])||d[u].length)).length;return Q(`"${l.timeline}": ${l.items.length} items; ${c("color")} with a clip color, ${c("flags")} flagged, ${l.items.filter(u=>!u.enabled).length} disabled; color groups: ${l.color_groups.join(", ")||"none"}`,l)}catch(a){return ee(new P("refused",a instanceof Error?a.message:String(a)))}}},{name:"host_apply",title:"Change clips in the open host timeline (color, flags, markers, grades, names)",description:"Resolve: carry out live edits on a timeline (default the open one), in order, each read back. Items are addressed {kind?, track, start} (a timeline_query row's track number and record start frame from the timeline start) or {id} (host_items). Ops: marker_add|marker_update|marker_delete {item?, frame, color?, name?, note?, duration?, data?, to_frame?} (no item = a timeline marker; frame from the timeline start, or from the clip's start for a clip marker); clip_color {item, color|''}; flags {item, add?:[color], clear?:color|'All'}; enabled {item, on}; name {item, name}; properties {item, set:{Pan, Tilt, ZoomX, ZoomY, RotationAngle, FlipX, CropLeft\u2026, Opacity, CompositeMode, RetimeProcess\u2026}}; metadata {item, set:{Keywords, Comments, Scene\u2026}} (the clip's media pool item); copy_grade {item, to:[item], from_timeline?} (verified by node count; from_timeline = the source item is in that timeline); copy_properties {item, to:[item], keys:[Pan, ZoomX, CropLeft, Opacity\u2026]} (the source's values as Resolve holds them); version {item, add|load|delete, type?:'local'|'remote'}; color_group {item, group|''}; cache {item, color?:bool, fusion?:'Auto'|'On'|'Off'}; fades {item, set}; output_blanking {item, set}; drx {item, path, graph?, mode?} (apply a .drx still); edit_keys {item, keys:[{t, transform, shape?}]} (timeline_align sizing_target edit, a move: Resolve cannot keyframe the Edit page from a script, so after every other op the moving clips are keyed on a copy, '<timeline> ALIGNED' \u2014 Resolve's own .drt of the timeline with only those clips' Transform keyed on Resolve's Edit-page law, every grade and setting as it was, linked to the same pool clips; the timeline itself is not changed); grade_sizing {item, target:'input'|'node', zoom, height?, rotation (degrees clockwise), pan, tilt (fractions of the timeline width / height, tilt up), flip_x?, flip_y?} (Color-page Input Sizing or node Sizing as timeline_align answers it, ADDED to the clip's grade as it stands on a new local version 'conform.tools aligned' (the colorist's version untouched; a grade that cannot be read is refused, never replaced); a clip on a remote version is moved onto its local one first; undo resets the grade and loads the remote version back); node_structure {item, node_structure: a .drx path} (that node tree onto the clip on a new local version 'conform.tools aligned', the colorist's own version untouched; undo goes back); copy_nodes {item, from:item, nodes:[label or number]} (only those nodes of the `from` clip's grade onto the clip: each node matched by label on both clips (a number = the source node of that number, by its label), the destination node's tools become the source's, every other node kept; on a new local version 'conform.tools nodes', checked node for node; undo goes back); lut {item, graph?, node, path}; playhead {tc} (move the playhead to a record timecode); pool_rename {clip:id, name}; pool_move {clips:[id], folder, create?}; pool_delete {clips:[id]}; pool_folder {folder:'A/B/C'} (make that media pool folder path, each missing level created); pool_import {paths:[file], folder:'A/B', at?:[frame]} (import files into that pool folder, made if missing; at = lay each on one new top video track at that frame from the timeline start; undo removes the track and what it added); track_delete {kind, index}; timeline_rename {timeline?, nth?, guid?, name} (nth = which of the sequences sharing that name, from 0; guid = exactly one: Premiere, where names repeat); timeline_duplicate {timeline?, name} (a copy under a name no timeline has, made the open one; answers its name); goto {timeline?, frame} (open that timeline with the playhead on frame, from its start). The reply has one result per op and an undo_id: host_apply {undo: undo_id} puts back everything that batch changed (pool_delete, copy_grade and drx cannot be undone). Changes the user's project: only when asked.",inputSchema:{host:m.enum(Zt).default("resolve").describe("The host (each says when it cannot do this yet)"),timeline:m.string().optional().describe("Timeline by name; the open one when omitted"),ops:m.array(m.object({op:m.string()}).passthrough()).optional().describe("The edits, in order (see description)"),undo:m.string().optional().describe("An undo_id from an earlier host_apply: put that batch back")},protectedStages:["canonicalize","write"],run:async({host:e,timeline:t,ops:n,undo:r})=>{try{let o=an(e??"resolve");if(!o.apply)return ee(new P("unsupported",`${o.host}: host_apply is not available for this host yet`));let s=re(tt(),"host-undo"),i=n;if(r){let p=JSON.parse(await ct(re(s,`${r.replace(/[^\w-]/g,"")}.json`)));i=p.ops,t=p.timeline}if(!i?.length)return ee(new P("usage","host_apply needs ops (or undo)"));let a=await o.apply({timeline:t,ops:i}),l;a.undo.length&&(l=`${Date.now().toString(36)}-${crypto.randomUUID().slice(0,6)}`,await Ve(s),await Ke(re(s,`${l}.json`),JSON.stringify({timeline:a.timeline,project:a.project,ops:a.undo})));let c=a.results.map((p,f)=>({...p,i:f})).filter(p=>!p.ok),d=[a.results.length>0&&a.results.every(p=>p.ok&&p.op==="timeline_discard")?`deleted ${a.timeline} from the project`:`${r?"undid":"applied"} ${a.applied}/${a.results.length} on "${a.timeline}" (${a.project})${l?`; undo_id: ${l}`:""}`];for(let p of c.slice(0,20))d.push(` #${p.i+1} ${p.op}: ${p.detail??(p.refused?`refused ${p.refused.join(", ")}`:"Resolve refused")}`);return c.length>20&&d.push(` \u2026and ${c.length-20} more`),Q(d.join(`
|
|
385
|
+
`),{...a,undo:void 0,undo_id:l})}catch(o){return ee(new P("refused",o instanceof Error?o.message:String(o)))}}},{name:"host_edit",title:"Edit the open Premiere sequence into a new one (resize, un-nest, frame rate, handles\u2026)",description:"Premiere: read the open sequence (the saved .prproj when it matches the live one \u2014 every effect, retime and nest \u2014 else Premiere's OTIO export with its timecodes), run timeline_edit operations on it, and import the result as a NEW sequence written by the conform.tools .prproj writer. The open sequence never changes. ops: [{kind, args}] in order, kinds as timeline_edit (timeline_id defaults to the sequence), plus unnest. Common jobs: resize without moving a pixel: {kind:'reformat', args:{resolution_w:3840, resolution_h:2160}} (HD \u2194 UHD: every clip keeps its framing; an aspect change needs fit:'fit'|'fill'|'stretch'); un-nest: {kind:'unnest'} (every nested sequence expanded into the cut with the nest's transform, opacity and speed composed onto its clips; multicam clips read as their active angle; adjustment layers kept); conform the rate: {kind:'timeline_rate', args:{fps_num, fps_den}}; a handles / all-clips / string-out version: add_handles {handles}, all_clips {}, stringout {}. name: the new sequence's name (default <sequence>_<KIND>). The reply lists what the writer could not carry.",inputSchema:{host:m.enum(["premiere"]).default("premiere"),timeline:m.string().optional().describe("Sequence by name; the active one when omitted"),ops:m.array(m.object({kind:m.string(),args:m.object({}).passthrough().optional()})).min(1),name:m.string().optional()},run:async({timeline:e,ops:t,name:n})=>{try{let{hostEdit:r}=await import("./host-relink-MVHI3YQI.js"),o=await r(an("premiere"),{timeline:e,ops:t,name:n});return Q(o.text,o.data)}catch(r){return ee(new P("refused",r instanceof Error?r.message:String(r)))}}},{name:"host_relink",title:"Conform into the open Premiere sequence (proxies \u2192 online, cut in returns)",description:"Premiere: link the open sequence's media with conform.tools' matcher (Conform Connect: reel, timecode containment, loose proxy names, picture when asked) instead of Premiere's Link Media, then hand the result to Premiere. The sequence is read from the saved .prproj when it matches the live one (every effect and retime), else Premiere's XML export. modes: replace = repoint every proxy project clip at its online file (every use follows; not in Premiere's undo, the reply says how to put it back); hires = attach the online file as full-res behind each proxy (Premiere's Toggle Proxies switches between them); proxy = the other way: the project is on the online media and each clip gets its proxy from the folder attached (matched by name + timecode, not by Premiere's Attach Proxies); cut_in = cut each matched return (VFX / color returns trimmed with handles, matched by reel + timecode) in over its clip on the track above (track, default the top + 1), video only, the clip's sizing carried, originals left underneath \u2014 one \u2318Z in Premiere; new_version = a NEW sequence written by the conform.tools .prproj writer from the relinked cut and imported (nothing in the open sequence changes). dry_run=true lists what would link to what. criteria / tolerances as timeline_relink (default: loose names for replace/hires, reel + timecode for cut_in). Changes the user's project: only when asked.",inputSchema:{host:m.enum(["premiere"]).default("premiere"),media_root:m.string().describe("The folder with the online media / returns"),mode:m.enum(["replace","hires","proxy","cut_in","new_version"]).default("new_version"),timeline:m.string().optional().describe("Sequence by name; the active one when omitted"),track:m.number().int().positive().optional().describe("cut_in: the video track to cut onto (default above the top track)"),name:m.string().optional().describe("new_version: the new sequence's name (default <sequence>_CONFORMED)"),dry_run:m.boolean().default(!1),criteria:m.object({}).passthrough().optional().describe("as timeline_relink criteria"),tolerances:m.object({}).passthrough().optional().describe("as timeline_relink tolerances")},run:async({media_root:e,mode:t,timeline:n,track:r,name:o,dry_run:s,criteria:i,tolerances:a})=>{try{let{hostRelink:l}=await import("./host-relink-MVHI3YQI.js"),c=await l(an("premiere"),{media_root:e,mode:t,timeline:n,track:r,name:o,dry_run:s,criteria:i,tolerances:a});return Q(c.text,c.data)}catch(l){return ee(new P("refused",l instanceof Error?l.message:String(l)))}}},{name:"host_setup",title:"Host readiness, and installing the host plugins",description:"What works with each editing host on this machine and what to do about what doesn't (Resolve: Studio, external scripting, an open project). action=install_probe installs ColorMatchProbe, the OFX plugin the app ships (Apple silicon Macs): it lets conform.tools read the Color page's selected clips and node (administrator password, then restart Resolve). action=install_panel installs the host's conform.tools plugin: Premiere's UXP panel with Adobe's own installer (the user then opens Window > UXP Plugins > conform.tools once); Flame's Python hook into this user's hook folder (then Rescan Python Hooks). Never with sudo. Only install when the user asks.",inputSchema:{host:m.enum(Zt).default("resolve").describe("The host"),action:m.enum(["status","install_panel","install_probe"]).default("status")},run:async({host:e,action:t})=>{try{let n=e??"resolve";if((t??"status")==="install_panel"){if(n==="flame"){let a=Af[n],l=await a.install();return Q([`conform.tools ${a.what} ${l.version} installed in ${l.dest}`,a.next].join(`
|
|
386
|
+
`),{...l})}if(n!=="premiere")return ee(new P("unsupported","install_panel installs the conform.tools plugin for Premiere Pro or Flame (Media Composer's panel: mcp/hosts/avid/panel)"));let i=await Jb();return Q([`conform.tools panel ${i.version} installed for Premiere Pro (Adobe's installer: ${i.output.split(`
|
|
387
|
+
`).pop()})`,"In Premiere: Window > UXP Plugins > conform.tools (restart Premiere first if it was running). It connects by itself from then on."].join(`
|
|
388
|
+
`),{...i})}if(t==="install_probe"){if(n!=="resolve")return ee(new P("unsupported","the probe is a DaVinci Resolve plugin"));let{installProbe:i}=await import("./probe-YOYK7HR5.js"),a=await i();return Q([`ColorMatchProbe installed at ${a.path} (with administrator approval)`,"Restart Resolve: it loads OFX plugins at launch."].join(`
|
|
389
|
+
`),{...a})}let r=await an(n).support(),o=[`${n}:`,...Object.entries(r).map(([i,a])=>` ${i}: ${a.ok?"ready":`no: ${a.reason}${a.setup?` (${a.setup})`:""}`}`)],s={host:n,support:r};if(n==="premiere"){let i=await Vb();o.push(` panel: ${i.installed?`installed${i.version?` (${i.version})`:""}`:`not installed (this release ships ${await Kb()}; host_setup host=premiere action=install_panel)`}`),s.panel={installed:i.installed,version:i.version}}if(n==="flame"){let i=Af[n],a=await i.installed();o.push(` ${i.what}: ${a.installed?`installed in ${a.dest}${a.version?` (${a.version})`:""}`:`not installed (this release ships ${await i.version()}; host_setup host=${n} action=install_panel)`}`),s.panel={installed:a.installed,version:a.version}}if(n==="resolve"){let{probeStatus:i}=await import("./probe-YOYK7HR5.js"),a=await i();o.push(` probe: ${a.next}`),s.probe=a}return Q(o.join(`
|
|
390
|
+
`),s)}catch(n){return ee(new P("refused",n instanceof Error?n.message:String(n)))}}},{name:"timeline_inspect",hidden:!0,title:"Inspect a session",description:"Look inside a read timeline. detail=summary (default) gives rates/tracks/counts; clips lists every item per track with record and source timecodes, media link state, speed, effects and conform flags; media lists every media reference with path, reel, timecode, raster, fps and whether it is linked; flags lists only the conform flags (things the reader could not carry 1:1); link is the Conform Connect view: which match criteria are usable for this timeline (populated on the references), what is unresolved and why, and the remembered media locations. Use clips to find item_id values for timeline_edit.",inputSchema:{session_id:m.string(),detail:m.enum(["summary","clips","media","flags","link"]).default("summary"),timeline_id:m.string().optional().describe("Limit clips listing to one timeline")},run:async({session_id:e,detail:t,timeline_id:n})=>{try{let r=await ft(e);switch(t){case"clips":return St(ab(r.session,n));case"media":return St(lb(r.session));case"flags":return St(cb(r.session));case"link":return St(await fb(r.session));default:return St(`${await Cr(r.session)}
|
|
391
|
+
history: ${r.history.length?r.history.join(" \u2192 "):"(unedited)"}`)}}catch(r){return ee(r)}}},{name:"timeline_query",title:"Query clips, media or markers (Edit Index)",description:`Search a read timeline the way the app's tables do \u2014 the Edit Index +, Unused Media and Marker Utility tools without a host app. table=clips: one row per clip with every IR field (record/source frames, reel, speed, transform, crop, opacity, media columns, link state), plus rec_in_tc / rec_out_tc (record timecode from the timeline's start TC and rate; out is exclusive), track_name (the lane's own name, if any) and track_enabled. table=media: one row per media reference with its usage count (how many clips use it) and link state \u2014 query "is:unused" lists media no cut uses. table=markers: every marker with record TC, color, name, note, duration and the clip under it \u2014 "is:red" lists red markers. query grammar: ${Fm} The reply shows at most limit rows (default 50); when more match it starts with TRUNCATED and truncated=true \u2014 never treat that list as complete. columns picks what to show (keys or the app's labels; the reply lists every available column). out_path writes the matched rows as CSV (a file, or a folder for a stamped name; markers use the Resolve suite's marker CSV). table=summary: rates, tracks, counts and the edit history; flags: only the conform flags (what the reader could not carry 1:1); link: which match criteria are usable for this timeline. Read-only: to change what it finds use timeline_edit with the item_ids in the rows.`,inputSchema:{session_id:m.string(),table:m.enum([...J_,...f$]).default("clips"),query:m.string().optional().describe(`Filter, e.g. 'is:offline', 'speed!=100 track:V1', 'track:in V5,V6', 'overlaps:01:00:10:00..01:00:12:00', 'is:unused', 'is:rate_mismatch', '"Frame rate":23.976', 'is:red note:vfx'. Omit for every row.`),timeline_id:m.string().optional().describe("Only this timeline (clips, markers); default every primary timeline"),columns:m.array(m.string()).optional().describe("Columns to return, by key or label; default the table's working set"),limit:m.number().int().default(50).describe("Rows in the reply, 1-5000 (0 or more = up to 5000; the CSV always has every match)"),out_path:m.string().optional().describe("Write the matched rows as CSV to this file or folder")},run:async({session_id:e,table:t,query:n,timeline_id:r,columns:o,limit:s,out_path:i})=>{let a=Y_(s);if(f$.includes(t))return nn("timeline_inspect").run({session_id:e,detail:t,timeline_id:r});try{let l=await ft(e),c=X_(l.session,{table:t,query:n,timeline_id:r,columns:o,csv:!!i}),u=l.session.timelines.find(h=>h.id===r)?.name??l.source_path.split(/[\\/]/).pop()??"session",d=i?await Q_(c,i,u):null,{csv:p,...f}=c;return Q(`${Z_(c,n??"",a)}${d?`
|
|
392
|
+
wrote ${d} (${c.matched} rows)`:""}`,{...f,rows:f.rows.slice(0,a),truncated:c.matched>a,csv_path:d})}catch(l){return ee(l)}}},{name:"timeline_edit",title:"Edit a session",description:`Apply one editing operation to the session in place (frame-accurate, on the IR, no host app needed). Operations and their args:
|
|
393
|
+
- slip {timeline_id,item_id,delta_frames}: move the source window, keep the record position
|
|
394
|
+
- trim {timeline_id,item_id,edge:'in'|'out',delta_frames,ripple?}: move one edge (+ lengthens the clip at out / shortens at in)
|
|
395
|
+
- delete {timeline_id,item_id or item_ids:[\u2026],ripple?}: one clip or many in one call (every black spacer at once); ripple closes the gaps
|
|
396
|
+
- move_clip {timeline_id,item_id,to_track_id?,to_frame?}
|
|
397
|
+
- transform {timeline_id,item_id,scale?,opacity?,position_x?,position_y?,rotation?,crop_*?}
|
|
398
|
+
- reformat {timeline_id?,resolution_w,resolution_h,fit?}: change the sequence raster
|
|
399
|
+
- stack_track {timeline_id,from,from_track?,name?}: another timeline's video track (with \`sources\`, another session's) laid onto this one as a new, switched-off top video track at the same record frames \u2014 a reference to align against (timeline_align reference_track)
|
|
400
|
+
- timeline_rate {timeline_id,fps_num,fps_den}
|
|
401
|
+
- add_markers {timeline_id?,markers:[{name?,note?,color?,time,duration?,item_id?}]}: time/duration in timeline frames (from the timeline start) or {value,rate}; duration defaults to 1 frame; the reply says why any marker was dropped
|
|
402
|
+
- stringout {extent?,handles?,name_prefix?}: build a string-out (every used source range, in order) with handles
|
|
403
|
+
- add_clip {timeline_id,path,source_start?,source_duration?,at_frame?,track_id?,fit?,without_audio?}: cut a media file in (probed here; its audio comes with it). source_start/source_duration in source frames (default the whole file); at_frame = timeline frame for the head, OVERWRITING what is there (default: append to the track); track_id default the last video track (an audio-only file goes to the last audio track)
|
|
404
|
+
- add_track {timeline_id,kind?:'Video'|'Audio'}: an empty track on top (video) or bottom (audio); reply carries its track_id
|
|
405
|
+
- add_handles {timeline_id?,handles,name?}: a NEW timeline, every video clip end to end with \xB1handles frames per side clamped to the media (negative trims each end); stills skipped and listed; named {TL}_{N}FR_HANDLES / {TL}_TRIM_{N}FR
|
|
406
|
+
- all_clips {timeline_ids?,handles?,name?,include_disabled?,include_image_sequences?(true),include_stills?,include_offline?(true),include_references?,reference_pattern?('_REF|_REFERENCE| REF'),mark_duplicates?(true),reduce_duplicates?,per_resolution?,stack?,order?:'timeline'|'source_tc'}: a NEW timeline of every piece of footage used across the timelines, overlapping uses of one clip merged; stack=V1 one uncut piece per shot with takes above; duplicates = the same shot under two clips (marked; reduce rebuilds from the copy holding every frame)
|
|
407
|
+
- delete_track {timeline_id,track_id}: the track and everything on it
|
|
408
|
+
- relink, new_timeline, node_sizing, finish_op (advanced)
|
|
409
|
+
args.sources [session_id\u2026]: also run over those sessions' timelines (one host_current via=export per Resolve timeline \u2192 all_clips over several); their ids become '<session_id>/<id>'; only the timelines the op builds are added here, the sources stay untouched.
|
|
410
|
+
Get item_id / timeline_id from timeline_query. track_id / to_track_id take the track's id or its label as timeline_read prints it (V2, A1). A target that is not there fails and lists every timeline's lanes. Frame deltas are in timeline frames.`,inputSchema:{session_id:m.string(),kind:m.enum(ub),args:m.object({}).passthrough().describe("Arguments for the operation, see description")},run:async({session_id:e,kind:t,args:n})=>{try{let r=await ft(e);t==="add_clip"&&(n=await CD(r.session,n));let o=Array.isArray(n.sources)?n.sources.map(String).filter(i=>i!==e):[],s=o.length?db(r.session,await Promise.all(o.map(async i=>({id:i,session:(await ft(i)).session}))),t,n):Ba(r.session,t,n);return await Yt(r,`${t} ${JSON.stringify(n)}`),Q(`${s.summary}${s.meta?`
|
|
411
|
+
${JSON.stringify(s.meta,null,1).slice(0,4e3)}`:""}`,{summary:s.summary,meta:s.meta??null})}catch(r){return ee(r)}}},{name:"timeline_author",title:"Author a timeline from media",description:"Build a NEW timeline from media files and a shot list, on this machine, with the app's own editing operations (no host app). Each shot: path, source_in (first source frame, 0 = the file's first frame), duration (timeline frames), and optionally at (timeline frame; default append), track (1-based video track; created as needed), scale (percent), position_x/position_y (frame pixels from centre), rotation (degrees clockwise), flip_h/flip_v (mirror), scale_end/position_x_end/position_y_end/rotation_end (animate linearly to these by the shot's last frame), speed (percent of real time; a 29.97 clip played frame for frame in a 23.976 timeline is 80). Returns a session_id for timeline_write / timeline_query. Use to make a test cut whose answer is known exactly (write it, render it in the host, then auto conform the render against the media).",inputSchema:{name:m.string().describe("Timeline name"),fps_num:m.number().int().positive().describe("Timeline rate numerator, e.g. 24000"),fps_den:m.number().int().positive().describe("Timeline rate denominator, e.g. 1001"),width:m.number().int().positive(),height:m.number().int().positive(),start_tc:m.string().optional().describe("Timeline start timecode, e.g. \"00:59:52:00\" (';' before the frames = drop frame); default 00:00:00:00. Shot `at` stays frames from the timeline start"),shots:m.array(m.object({path:m.string(),source_in:m.number().int().nonnegative(),duration:m.number().int().positive(),at:m.number().int().nonnegative().optional(),track:m.number().int().positive().optional(),scale:m.number().positive().optional(),position_x:m.number().optional(),position_y:m.number().optional(),rotation:m.number().optional(),flip_h:m.boolean().optional(),flip_v:m.boolean().optional(),scale_end:m.number().positive().optional(),position_x_end:m.number().optional(),position_y_end:m.number().optional(),rotation_end:m.number().optional(),speed:m.number().positive().optional()})).min(1)},run:async e=>{try{let{session:t,summary:n}=await ma(e),r=await Kn(t,re(tt(),"authored",`${e.name}.authored`),"authored");return Q(`session_id: ${r.id}
|
|
412
|
+
${n.join(`
|
|
413
|
+
`)}
|
|
414
|
+
${await Cr(t)}`,{session_id:r.id})}catch(t){return ee(t)}}},{name:"timeline_generate",repoOnly:!0,title:"Generate a test cut from a bucket",description:"Make a NEW timeline from a bucket of media: a seeded random edit with a chosen mix of hard cases, laid in by timeline_author, so its answer is known exactly. Same media + seed + mix = the same cut. Every shot is tagged with the classes it tests: "+pa.join(", ")+". mix: a preset ("+Object.keys(Js).join(", ")+"; default hard) or weights per class. Returns a session_id for timeline_write and the shot list with record ranges and classes. Use to test auto conform, compare or any matcher: generate, write, render in the host (optionally grade it), auto conform the render, score per class.",inputSchema:{media:m.array(m.string()).min(1).describe("Media files or folders (walked; folders named *proxy*/*proxies* or cache skipped)"),seed:m.number().int().describe("Random seed"),shots:m.number().int().positive().max(500).optional().describe("V1 shots (default 24)"),audio:m.boolean().optional().describe("Lay sync sound in under normal-speed shots whose clips have it (needed for frankenbite)"),look:m.boolean().optional().describe("Look at each planned shot and re-plan around flat picture \u2014 empty backdrops, grey cards (default true)"),mix:m.union([m.enum(Object.keys(Js)),m.record(m.enum(pa),m.number().nonnegative())]).optional(),name:m.string().optional(),fps_num:m.number().int().positive().optional().describe("Default 24000"),fps_den:m.number().int().positive().optional().describe("Default 1001"),width:m.number().int().positive().optional().describe("Default 1920"),height:m.number().int().positive().optional().describe("Default 1080")},run:async e=>{try{let t=await CT(e),n=e.name??`generated ${e.seed}`,r=await Kn(t.session,re(tt(),"authored",`${n}.authored`),"authored"),o=new Map;for(let i of t.shots)for(let a of i.classes)o.set(a,(o.get(a)??0)+1);let s=[`session_id: ${r.id}`,`${t.shots.length} shots from ${t.pool.used} clips: ${[...o].map(([i,a])=>`${a} ${i}`).join(", ")}`,...t.pool.skipped.length?[`skipped ${t.pool.skipped.length}: ${t.pool.skipped.slice(0,5).join("; ")}`]:[],await Cr(t.session)];return Q(s.join(`
|
|
415
|
+
`),{session_id:r.id,shots:t.shots,titles:t.titles,skipped:t.pool.skipped})}catch(t){return ee(t)}}},{name:"timeline_relink",title:"Link / relink media (Conform Connect)",description:`The app's Conform Connect link wizard, as one call, on the same matcher and coverage law. Finds the media for the session's unbound references under a folder on this machine and repoints them.
|
|
416
|
+
gather: 'walk' (default) scans the folder recursively (name-first pre-filter, cap 2000) and matches by the criteria; 'path' is strict link \u2014 each reference must exist at its recorded relative path under the folder, no scan.
|
|
417
|
+
criteria (all optional; default = file_name on, tight): file_name + file_name_mode tight|loose (loose strips _Sxxx, _vN and proxy words like proxy/prx/offline/h264/prores and accepts \u22650.6 similarity), reel_name, total_duration, resolution, bit_depth, file_format, codec, media_umid, extensions, picture (the analysis engine compares the reference's own file with each candidate at the same TC; needs the reference readable). Enabled criteria are strict AND. Timecode containment (the file must hold the cut) and fps are ALWAYS enforced. For renamed media use reel_name=true, file_name=false. For proxy\u2192OCF use file_name_mode loose and leave resolution/codec off.
|
|
418
|
+
tolerances: timecode_tolerance_frames (1), duration_tolerance_seconds (0.1), min_name_similarity (0.6), fps_tolerance (0.005).
|
|
419
|
+
scope: ref_ids limits to a zone; lane video|audio|both limits by track usage; reset=true re-points already-linked refs in scope (they are unbound first).
|
|
420
|
+
dry_run=true proposes without changing anything: per reference matched/ambiguous/unmatched, the chosen file, confidence, reasons, refusals with the coverage reason, and alternatives; compare=true adds the per-criterion project-vs-media table. accept=[{ref_id,candidate_id}] commits only those rows (ids from a dry run) \u2014 the manual pick. Without accept, every matched row is applied. media_root omitted \u2192 the remembered locations are tried; remember=true saves this folder. Ends with the link summary and what is still unresolved, with the reason.`,inputSchema:{session_id:m.string(),media_root:m.string().optional().describe("Folder to link from; omit to use remembered locations"),gather:m.enum(["walk","path"]).default("walk"),criteria:m.object({file_name:m.boolean().optional(),file_name_mode:m.enum(["tight","loose"]).optional(),reel_name:m.boolean().optional(),total_duration:m.boolean().optional(),resolution:m.boolean().optional(),bit_depth:m.boolean().optional(),file_format:m.boolean().optional(),codec:m.boolean().optional(),media_umid:m.boolean().optional(),extensions:m.array(m.string()).optional().describe("Only consider these extensions, e.g. ['mxf','mov']"),picture:m.boolean().optional().describe("Also match by picture where the reference's own file is readable (proxy \u2192 OCF): each candidate must show the same frames at the same TC; picks the one right file among ambiguous candidates, refuses a name match that shows another picture or a TC slip")}).optional(),tolerances:m.object({timecode_tolerance_frames:m.number().optional(),duration_tolerance_seconds:m.number().optional(),min_name_similarity:m.number().optional(),fps_tolerance:m.number().optional(),aspect_tolerance:m.number().optional()}).optional(),ref_ids:m.array(m.string()).optional().describe("Only these references (a zone)"),lane:m.enum(["video","audio","both"]).default("both"),reset:m.boolean().default(!1).describe("Re-point refs in scope even if already linked"),dry_run:m.boolean().default(!1).describe("Propose only; change nothing"),compare:m.boolean().default(!1).describe("With dry_run: show the per-criterion comparison for each matched row"),accept:m.array(m.object({ref_id:m.string(),candidate_id:m.string()})).optional().describe("Commit only these rows (from a dry run)"),cap:m.number().int().min(1).max(2e4).default(2e3),remember:m.boolean().default(!1)},run:async e=>{try{let t=await ft(e.session_id),n=await Zb(t.session,e);return n.changed&&(t.session=n.session,await Yt(t,n.note)),St(n.text)}catch(t){return ee(t)}}},{name:"timeline_write",protectedStages:["write"],title:"Write a timeline for a host",description:"Write the session for a host, on this machine. Prefer a DESTINATION (the host the user is going to): resolve, premiere, avid, flame, finalcut, baselight, protools \u2014 it writes the host's native file AND its fallback (e.g. resolve = .drt + XML for Resolve; avid = .avb + AAF) into one folder named for the host, with a README saying which to open first. Single formats still work as targets: resolve-drt (DaVinci Resolve timeline, preferred for Resolve), premiere-prproj, avid-avb (Media Composer bin), avid-aaf, flame-archive, baselight-blscene, finalcut-fcpxmld, resolve-xmeml, flame-fcpxml. Short aliases drt/prproj/avb/aaf/xmeml/fcpxml work (OTIO is read, not written). Returns the written path and the capability issues: what this target host cannot carry from the source (nests flattened, effects dropped, etc.) \u2014 always relay those to the user. A conversion on conform.tools keeps the original timeline file with it, as on the website, so the result is checked (never media; off with account_telemetry).",inputSchema:{engine:m.enum(["local","hosted"]).optional().describe("Where the conversion runs: local = this machine, offline, nothing uploaded; hosted = conform.tools (the website's engine). Default: local when this build has it"),session_id:m.string(),target:m.string().describe("A destination (resolve, premiere, avid, flame, finalcut, baselight, protools) or a single target format, e.g. resolve-drt, or an alias like drt"),out_path:m.string().optional().describe("Output file path, or a directory (file name is derived; a destination writes a host-named folder inside it). Defaults next to the source file."),timeline_id:m.string().optional().describe("Write only this timeline (e.g. the one timeline_edit add_handles / all_clips just built); default the session's timelines as read")},run:async({session_id:e,target:t,out_path:n,timeline_id:r})=>{try{let o=await ft(e);if(r&&!o.session.timelines.some(c=>c.id===r))return ee(new P("not_found",`no timeline ${r} in session ${e} (${o.session.timelines.map(c=>`${c.id} "${c.name}"`).join(", ")})`));let s=r?{...o.session,timelines:[...o.session.timelines.filter(c=>c.id===r),...o.session.timelines.filter(c=>c.id!==r&&c.kind==="compound")]}:o.session;if(Su(t)){let c=await pb(s,t,n,o.source_path);await Yt(o,`write ${t} \u2192 ${c.folder}`);let u=c.files.map(d=>`${d.path} (${d.bytes} bytes, ${d.target})`+(d.issues.length?`
|
|
421
|
+
issues (${d.issues.length}):
|
|
422
|
+
${d.issues.map(p=>` - [${p.severity??"info"}] ${p.code?`${p.code}: `:""}${p.message}`).join(`
|
|
423
|
+
`)}`:`
|
|
424
|
+
no capability issues`));return St(`wrote ${c.folder}/ \u2014 README.txt says which to open first
|
|
425
|
+
${u.join(`
|
|
426
|
+
`)}${c.pending?`
|
|
427
|
+
${c.pending} is not included yet (writer pending its host's import law)`:""}`)}let i=await Cu(s,t,n,o.source_path);await Yt(o,`write ${t} \u2192 ${i.path}`);let a=i.issues.length?`
|
|
428
|
+
issues (${i.issues.length}):
|
|
429
|
+
${i.issues.map(c=>`- [${c.severity??"info"}] ${c.code?`${c.code}: `:""}${c.message}`).join(`
|
|
430
|
+
`)}`:`
|
|
431
|
+
no capability issues`,l=await gi("conform-artist",["write"]);return Q(`wrote ${i.path} (${i.bytes} bytes)${a}${l?`
|
|
432
|
+
|
|
433
|
+
Reading this write (conform.tools playbook):
|
|
434
|
+
${l}`:""}`,i.serverSession?{server_session:i.serverSession}:void 0)}catch(o){return ee(o)}}},{name:"timeline_routes",title:"Supported formats and operations",description:"List what can be read, what can be written (first-class vs beta), aliases, and the editing operations. Use when asked 'can you convert X to Y' or what the tool supports.",inputSchema:{},run:()=>St(mb())},{name:"timeline_sessions",title:"List sessions",description:"List sessions read earlier (id, source file, format, when, edit history). Sessions persist across restarts.",inputSchema:{},run:async()=>{let e=await Zh();return St(e.length?e.map(t=>`${t.id} ${t.source_path} (${t.source_format}) updated ${t.updated_at}${t.history.length?` \u2014 ${t.history.length} edits`:""}`).join(`
|
|
435
|
+
`):"(no sessions)")}},{name:"session_export",title:"Export Session IR",description:"Write the session's IR JSON (the engine's canonical timeline representation) to a file, for tooling, diffing or archiving.",inputSchema:{session_id:m.string(),out_path:m.string()},run:async({session_id:e,out_path:t})=>{try{let n=await ft(e);return await Ke(t,JSON.stringify(n.session,null,1)),St(`wrote ${t}`)}catch(n){return ee(n)}}},{name:"media_probe",title:"Probe a media file",description:"Read a media file's facts on this machine (never uploads): container, codec, raster, frame rate, start timecode, frame count, duration, audio, reel. Supports mov/mp4/m4v (ProRes, DNx, H.264/HEVC\u2026), braw, crm, mxf (ARRI/Sony/DNx), wav, RED .R3D (spanned clips: any part or the .RDC folder), stills (exr/dpx/tiff/jpg/png/dng/cr3: raster; an EXR's own framesPerSecond + timeCode from its header; a numbered frame's whole sequence from its folder \u2014 first/last, length, gaps, start TC). Use before media_trim to know the file's start timecode and length. A WAV has no frame rate: pass fps (the project's) for its BWF start TC and length in frames; without it both 23.976 and 24 are shown.",inputSchema:{path:m.string(),fps:m.number().positive().optional().describe("audio-only files: the video rate to count the BWF timecode and length at (23.976, 24, 25, 29.97\u2026)")},run:async({path:e,fps:t})=>{try{if(eb(e)){let r=await nb(e);return Q(rb(r),{...r})}let n=await st(e);return Q(H1(n,t),{...n})}catch(n){return ee(n)}}},{name:"timeline_diff",protectedStages:["canonicalize"],title:"Source diff of two cuts (online vs editorial)",description:"Compare WHERE THE PICTURE COMES FROM in two cuts aligned by record TC: A = the online/colour timeline, B = the newest editorial turnover (each a session_id or a timeline file). Per record frame it takes the topmost enabled video clip (by_track=true: each video track by name, V1 vs V1\u2026) and reports the record ranges whose source differs: only_in_a / only_in_b (missing or extra clips), different_file (another file or reel \u2014 temp vs master; a different TC base is called out), same_name_different_clip (same file name but a different start TC or length: dated batch folders reuse names, never trust the name alone), source_tc (same file, slipped N frames). Starts with the count per kind; every range lists both sides' file, source TC, track and item id. csv_path / edl_path write every range (the EDL carries B's sources: what to drop into A); session=true makes a new session of B's clips under those ranges only (an insert timeline for timeline_write). Read-only on both cuts.",inputSchema:{a_session_id:m.string().optional().describe("A (online/colour) as a session"),a:m.string().optional().describe("A as a timeline file, instead of a_session_id"),b_session_id:m.string().optional().describe("B (editorial turnover) as a session"),b:m.string().optional().describe("B as a timeline file, instead of b_session_id"),a_timeline_id:m.string().optional(),b_timeline_id:m.string().optional(),by_track:m.boolean().default(!1).describe("Compare each video track by name instead of the topmost picture"),limit:m.number().int().min(1).max(5e3).default(100).describe("Ranges in the reply (files always have all)"),csv_path:m.string().optional(),edl_path:m.string().optional(),session:m.boolean().default(!1).describe("Also create a session of B's differing clips (insert timeline)")},run:async({a_session_id:e,a:t,b_session_id:n,b:r,a_timeline_id:o,b_timeline_id:s,by_track:i,limit:a=100,csv_path:l,edl_path:c,session:u})=>{try{let d=async(w,y,_)=>{if(w){let v=await ft(w);return{session:v.session,name:`session ${w} (${fe(v.source_path)})`}}if(y)return{session:(await ds(y)).session,name:fe(y)};throw new P("invalid_args",`give ${_}_session_id or ${_} (a timeline file)`)},p=await d(e,t,"a"),f=await d(n,r,"b"),h=Dv(p.session,f.session,{a_timeline_id:o,b_timeline_id:s,by_track:i}),g=[];l&&(await Ke(l,qv(h.ranges)),g.push(`CSV: ${l} (${h.ranges.length} ranges)`)),c&&(await Ke(c,Uv(h,`${h.tb.name} SOURCE DIFF`)),g.push(`EDL: ${c} (B sources)`));let b;if(u&&h.ranges.length){let w=await Kn(Gv(f.session,h),re(tt(),"authored",`${h.tb.name} source diff.authored`),"diff");b=w.id,g.push(`session_id: ${w.id} (B's clips under the differing ranges; timeline_write it)`)}let k=Object.fromEntries(Zm.map(w=>[w,h.ranges.filter(y=>y.kind===w).length]));return Q([Bv(h,p.name,f.name,a),...g].join(`
|
|
436
|
+
`),{counts:k,total:h.ranges.length,fps:h.fps,ranges:h.ranges.slice(0,a),truncated:h.ranges.length>a,session_id:b,csv_path:l,edl_path:c})}catch(d){return ee(d)}}},{name:"media_aspect",title:"Active picture and OAR of a movie",description:"Find a movie's active picture (letterbox / pillarbox / windowbox) and the original aspect ratio it implies, snapped to the standard ratios (1.33, 1.78, 1.85, 1.90, 2.00, 2.39 \u2026), with the OAR raster (full width, even height). 16 frames across the clip; a bar counts only when \u226580% of them carry it, so fades and black leaders don't invent one. Use on the screener / editorial REF to decide OAR deliverables vs a 16x9 container, and on a render to confirm it.",inputSchema:{path:m.string(),samples:m.number().int().min(4).max(64).optional().describe("Frames sampled (default 16)")},run:async({path:e,samples:t})=>{try{let n=await _x(e,t);return Q(vx(n),{...n})}catch(n){return ee(n)}}},{name:"media_find",title:"Find media by name or ID on a volume",description:"Search a folder or volume (read-only walk) for media whose name holds a name or ID fragment, and probe each match so temp and master can be told apart: codec, raster, rate, start\u2013end TC, frames, duration. Matching ignores case, spaces/underscores/dots and doubled extensions (`X.mov.mov`, `X.mov_001.mov`); when the whole fragment is not found, a file that holds every digit-bearing token of it matches as an id match (a misspelt word around the ID). Files with the same name in different folders are called out: dated batch folders reuse names for DIFFERENT clips, so match by TC + duration, never by name alone. Bounded by max_depth, max_entries and time_limit_s; when a bound stops it the reply starts with TRUNCATED.",inputSchema:{path:m.string().describe("Folder or volume to search"),query:m.string().min(2).describe("Name or ID fragment, e.g. 'XD32995' or 'XD32995_0158_0221_MultiClip.mov'"),max_depth:m.number().int().min(0).max(30).default(10),max_entries:m.number().int().min(1).max(2e6).default(2e5).describe("Directory entries to visit before stopping"),time_limit_s:m.number().min(1).max(600).default(60),probe:m.boolean().default(!0).describe("Probe each match (codec, raster, rate, TC, length)"),limit:m.number().int().min(1).max(5e3).default(100)},run:async({path:e,query:t,max_depth:n,max_entries:r,time_limit_s:o,probe:s,limit:i})=>{try{let a=await z1(e,t,{max_depth:n??10,max_entries:r??2e5,time_limit_s:o??60,probe:s??!0});return i??=100,Q(W1(a,e,t,i),{scanned:a.scanned,truncated:a.truncated,total:a.hits.length,hits:a.hits.slice(0,i).map(l=>({path:l.path,match:l.match,size:l.size,facts:l.facts?Pa(l.facts):null,source_timecode:l.facts?.source_timecode??null,frames:l.facts?.available_range?.duration?.value??l.facts?.declared_duration?.value??null,error:l.error}))})}catch(a){return ee(a)}}},{name:"media_coverage",title:"Does a file cover these TC ranges (and how much handle)?",description:"Check that a media file holds the source ranges a cut needs, and how much handle it has: per range covered, or NOT covered and short by N frames at head/tail, plus the head/tail handle in frames. ranges: [{in, out, label?}] as absolute source timecode (the file's own TC, e.g. 23:59:12:10; out exclusive, as an EDL reads; TC wraps at midnight) or file-local frame numbers. Or session_id + item_ids: the clips' used source ranges (from their own media's TC), checked against path, or against each clip's own file when path is omitted. A master with a different TC base than the temp the cut was made on will show NOT covered: that is the answer (the client's clip-TC list is then the mapping). handles: also flag ranges with less than this many frames each side.",inputSchema:{path:m.string().optional().describe("The media file to check (required with ranges)"),ranges:m.array(m.object({in:m.union([m.string(),m.number().int()]),out:m.union([m.string(),m.number().int()]),label:m.string().optional()})).optional(),session_id:m.string().optional(),item_ids:m.array(m.string()).optional().describe("Clip item ids (timeline_query / timeline_query)"),handles:m.number().int().min(0).default(0).describe("Required handle per side, frames")},run:async({path:e,ranges:t,session_id:n,item_ids:r,handles:o})=>{try{let s=new Map,i=[];if(t?.length){if(!e)throw new P("invalid_args","path is required with ranges");s.set(e,[...t])}if(n){if(!r?.length)throw new P("invalid_args","item_ids is required with session_id");let p=(await ft(n)).session,f=new Map((p.media_references??[]).map(g=>[g.id,g])),h=new Map(p.timelines.flatMap(g=>g.tracks.flatMap(b=>b.items)).map(g=>[g.id,g]));for(let g of r){let b=h.get(g);if(!b?.source_range){i.push(`${g}: no such clip with a source range`);continue}let k=b.media_reference_id?f.get(b.media_reference_id):void 0,w=(k?.local_path??k?.target_url??"").replace(/^file:\/\//,""),y=e??w;if(!y){i.push(`${g}: the clip has no media path; pass path`);continue}let _=b.source_range.start.rate||k?.source_fps||24,v=k?.source_fps||_,T=b.source_range.start.value*v/_,$=b.source_range.duration.value*v/_,x=k?.source_timecode?At(k.source_timecode,v):null,R=Math.round(v)*86400,C=!!k?.source_timecode?.includes(";"),B=L=>x==null?Math.round(L):He(Math.round(x+L)%R,v,C);(s.get(y)??s.set(y,[]).get(y)).push({label:`${g} ${b.name??""}`.trim(),in:B(T),out:B(T+$)})}}if(!s.size)throw new P("invalid_args",i.length?i.join("; "):"give path + ranges, or session_id + item_ids");let a=[],l=[],c=0,u=0;for(let[p,f]of s){let h=await K1(p,f,o);l.push({path:p,facts:Pa(h.facts),rows:h.rows}),a.push(`${p}
|
|
437
|
+
${Pa(h.facts)}`,...h.rows.map(g=>` - ${g.label}: ${g.in_tc}\u2013${g.out_tc} (${g.frames} fr) ${g.note}`)),c+=h.rows.filter(g=>!g.covered).length,u+=h.rows.length}let d=c?`${c} of ${u} range${u===1?"":"s"} NOT covered`:`all ${u} range${u===1?"":"s"} covered`;return Q([d,...a,...i.map(p=>`skipped ${p}`)].join(`
|
|
438
|
+
`),{covered:u-c,not_covered:c,files:l,skipped:i})}catch(s){return ee(s)}}},{name:"media_sort",title:"File a folder of deliverables by a recipe",description:`0.9.5's Output Sorter: every file of \`folder\` filed into folders by a recipe \u2014 ordered rules (first match wins: a whole keyword, contains, starts / ends with, an extension, a regex with {1}\u2026{9}, any), a project name read from the file name ({PROJECT}), destination templates ({PROJECT} {RULE} {KEYWORD} {EXT} {YYYY} {MM} {DD} \u2026). Nothing is ever overwritten (a taken name is skipped, or kept under a free name), a destination never leaves its root, apply re-plans from disk, every run is undoable (undo=<undo_id>, or media_move undo=\u2026). recipe: a built-in (${wu.map(e=>e.id).join(", ")}), or a recipe object / a .json file of one. mode plan shows where every file goes; apply files them (all, or \`only\`: source paths).`,inputSchema:{folder:m.string().describe("The folder of files to sort"),recipe:m.union([m.string(),m.record(m.unknown())]).default("mixes-splits").describe("A built-in recipe id, a recipe object, or a path to a recipe .json"),mode:m.enum(["plan","apply"]).default("plan"),recursive:m.boolean().optional().describe("Into subfolders too"),destination_root:m.string().optional().describe("File into this folder instead of inside `folder`"),operation:m.enum(["move","copy"]).optional().describe("Override the recipe's (copy keeps the originals)"),only:m.array(m.string()).optional().describe("apply: just these source paths")},run:async({folder:e,recipe:t,mode:n,recursive:r,destination_root:o,operation:s,only:i})=>{try{let a=typeof t=="string"?wu.find(p=>p.id===t)?.recipe??JSON.parse(await ct(mt(t))):t,l={directories:[mt(e)],recursive:!!r,include_hidden:!1,destination_root:o?mt(o):"",recipe:{...a,...s?{operation:s}:{}},only:i??[]};if(n==="plan"){let p=await qt({op:"sort_plan",request:l});if(p.ok===!1)return ee(new P("invalid_args",String(p.why)));let f=p.counts;return Q(`${p.scanned} file(s): ${Object.entries(f).map(([h,g])=>`${g} ${h}`).join(", ")}${p.warnings.length?`
|
|
439
|
+
${p.warnings.join(`
|
|
440
|
+
`)}`:""}`,{...p})}let c=await qt({op:"sort_apply",request:l});if(c.ok===!1)return ee(new P("refused",String(c.why)));let u=c.moved,d=u.length?`files-${Date.now().toString(36)}`:void 0;return d&&(await Ve(re(tt(),"move-undo")),await Ke(re(tt(),"move-undo",`${d}.json`),JSON.stringify({sort:!0,moved:u,created_dirs:c.created_dirs}))),Q([`filed ${u.length} file(s)${Number(c.skipped)?`, ${c.skipped} left where they were`:""}`,...c.errors.map(p=>`not filed: ${p}`),...d?[`undo_id: ${d} (media_move undo=\u2026 puts them back)`]:[]].join(`
|
|
441
|
+
`),{...c,...d?{undo_id:d}:{},ok:!c.errors.length})}catch(a){return ee(a)}}},{name:"media_odd_images",title:"Make odd-sized stills even",description:"0.9.5's Odd Image Size Fixer: every still in `folder` (or `files`) whose width or height is odd \u2014 most codecs and some hosts refuse it, Resolve draws a black line \u2014 rewritten in its own format at even dimensions (the last row / column cropped; with max, scaled to fit first), ICC profile and EXIF kept. The original is copied first to 'zORIGINAL IMAGES' beside it (the first original is never overwritten). mode plan lists what would change; apply rewrites; undo=<undo_id> (or media_move undo=\u2026) puts every original back. PNG, JPEG, TIFF, WebP, GIF, BMP.",inputSchema:{folder:m.string().optional().describe("A folder of stills"),files:m.array(m.string()).optional().describe("\u2026or these files"),max:m.number().int().positive().optional().describe("Also scale anything larger to fit this many pixels"),mode:m.enum(["plan","apply"]).default("plan")},run:async({folder:e,files:t,max:n,mode:r})=>{try{let o=(t??[]).map(u=>mt(u));if(e){let u=mt(e);for await(let d of Ct(u))d.isFile&&!d.name.startsWith(".")&&o.push(re(u,d.name))}if(o=[...new Set(o)].sort(),!o.length)return ee(new P("invalid_args","media_odd_images needs a folder or files"));let i=(await qt({op:"odd_fix",files:o,...n?{max:n}:{},dry_run:r==="plan"})).files,a=i.filter(u=>u.status==="fixed"),l=i.filter(u=>u.status==="error"),c;return r==="apply"&&a.length&&(c=`files-${Date.now().toString(36)}`,await Ve(re(tt(),"move-undo")),await Ke(re(tt(),"move-undo",`${c}.json`),JSON.stringify({odd:!0,fixed:a.map(u=>[u.path,u.backup])}))),Q([`${r==="plan"?"would make":"made"} ${a.length} of ${o.length} still(s) even${a.length?`: ${a.slice(0,8).map(u=>`${fe(u.path)} ${u.original}\u2192${u.new}`).join(", ")}${a.length>8?" \u2026":""}`:""}`,...l.map(u=>`not done: ${fe(u.path)} \u2014 ${u.why}`),...c?[`undo_id: ${c} (media_move undo=\u2026 puts the originals back)`]:[]].join(`
|
|
442
|
+
`),{files:i,...c?{undo_id:c}:{},ok:!l.length})}catch(o){return ee(o)}}},{name:"media_patch_sequence",title:"Patch frames into an image sequence",description:`0.9.5's Image Sequence Patcher: the folders beside the sequence's folder with "patch" in their name hold fixed frames; each replaces the sequence's frame of the same name. The original goes to <sequence>_originalframes (numbered when that frame is backed up already), the patch is COPIED in (a failed copy puts the original straight back), the used patch folders are filed under zAPPLIED_PATCHES. mode plan lists every patch frame and whether the sequence has it; apply patches (all, or \`only\`: "folder/file" keys); undo=<undo_id> (or media_move undo=\u2026) puts everything back.`,inputSchema:{sequence:m.string().describe("The image sequence's folder (or a frame in it)"),folders:m.array(m.string()).optional().describe(`The patch folders (names beside the sequence's folder); default every one with "patch" in its name`),mode:m.enum(["plan","apply"]).default("plan"),only:m.array(m.string()).optional().describe('apply: just these "folder/file" keys')},run:async({sequence:e,folders:t,mode:n,only:r})=>{try{let o=mt(e);await Bt(o).then(a=>a.isDirectory,()=>!1)||(o=o.replace(/[\\/][^\\/]+$/,""));let s=t?.length?t:await Xb(o);if(!s.length&&n==="plan")return Q(`no patch folder beside ${fe(o)} (a folder next to it with "patch" in its name)`,{sequence:o,folders:[],rows:[]});if(!s.length)return ee(new P("not_found",`no patch folder beside ${fe(o)} (a folder next to it with "patch" in its name)`));if(n==="plan"){let a=await Qb(o,s);return Q(`${a.length} patch frame(s) in ${s.join(", ")}; ${a.filter(l=>!l.replaces).length} not in the sequence`,{sequence:o,folders:s,rows:a})}let i=await Yb(o,s,r?.length?new Set(r):void 0);return Q([`patched ${i.patched} frame(s) into ${fe(o)}; originals in ${fe(o)}_originalframes, patch folders filed under zAPPLIED_PATCHES`,...i.errors.map(a=>`not patched: ${a}`),...i.undo_id?[`undo_id: ${i.undo_id} (media_move undo=\u2026 puts it all back)`]:[]].join(`
|
|
443
|
+
`),{...i,ok:!i.errors.length})}catch(o){return ee(o)}}},{name:"media_move",title:"Move media files into a folder (and back)",description:"Move files into a folder on disk (Unused Media's 'move the files'): the destination is proved writable first; a missing file is skipped and named; a name already taken gets ' (1)'; across volumes it copies, checks the size and deletes. Every move is recorded: undo=<undo_id> puts each file back (never over a file that has appeared at the old path). Media pool clips are not relinked: move only media no timeline uses.",inputSchema:{paths:m.array(m.string()).optional().describe("The files to move"),destination:m.string().optional().describe("The folder they go into"),undo:m.string().optional().describe("Put back the files a move recorded (its undo_id)"),renames:m.array(m.object({from:m.string(),to:m.string()})).optional().describe("Rename files in place instead (Image Sequence Renamer): collision-safe (frames may shift onto each other's numbers), refused before anything moves when a target is a file outside the batch; undoable")},run:async({paths:e,destination:t,undo:n,renames:r,__progress:o})=>{try{if(r?.length){let i=await td(r.map(a=>({from:mt(a.from),to:mt(a.to)})));return Q([`renamed ${i.moved.length} file(s)`,...i.skipped.length?[`${i.skipped.length} missing, skipped`]:[],...i.failed.map(a=>`failed: ${fe(a.path)} \u2014 ${a.error}`),...i.undo_id?[`undo_id: ${i.undo_id} (media_move undo=\u2026 puts the names back)`]:[]].join(`
|
|
444
|
+
`),{...i})}if(n){let i=await e0(n);return Q(`put back ${i.restored} file(s)${i.failed.length?`; ${i.failed.length} not: ${i.failed.map(a=>`${fe(a.path)} (${a.error})`).join("; ")}`:""}`,{...i,ok:!i.failed.length})}if(!e?.length||!t)return ee(new P("invalid_args","media_move needs paths and destination (or undo)"));let s=await Zy(e,mt(t),o);return Q([`moved ${s.moved.length} file(s) to ${t}`,...s.skipped.length?[`${s.skipped.length} offline / missing, skipped: ${s.skipped.map(i=>fe(i)).join(", ")}`]:[],...s.failed.map(i=>`failed: ${fe(i.path)} \u2014 ${i.error}`),...s.undo_id?[`undo_id: ${s.undo_id} (media_move undo=\u2026 puts them back)`]:[]].join(`
|
|
445
|
+
`),{...s})}catch(s){return ee(s)}}},{name:"media_trim",title:"Trim a media file",description:"Cut a shorter file out of a source WITHOUT re-encoding (byte-exact essence copy, index rebuilt; source timecode is preserved so the trim relinks in any host). in/out are frame indexes (0 = first frame) or timecodes relative to the file's start TC; out is the LAST frame included unless out_exclusive=true. handles adds frames on both sides (clamped to the file). Supports mov/mp4/m4v (ProRes, DNx, H.264/HEVC \u2014 long-GOP snaps to keyframes), braw, crm, mxf, wav, and RED .R3D (spanned .RDC clips: pass any part or the folder; output is a new .RDC). Returns the new path(s) and the frames written.",inputSchema:{path:m.string(),in:m.union([m.string(),m.number().int()]).describe("First frame: frame index or timecode like 01:00:10:00"),out:m.union([m.string(),m.number().int()]).describe("Last frame (inclusive) or timecode; set out_exclusive for an edit-style out point"),out_exclusive:m.boolean().optional(),handles:m.number().int().min(0).optional().describe("Extra frames on each side"),out_path:m.string().optional().describe("Output file or directory; default is next to the source as <name>_trim_<in>-<out>.<ext>")},run:async e=>{try{let t=await Ia(e),n=t.facts.streams?.find(r=>r.kind==="video");return St(`${t.outputs.map(r=>`wrote ${r.path} (${(r.bytes/1e6).toFixed(1)} MB${r.part?`, part ${r.part}`:""})`).join(`
|
|
446
|
+
`)}
|
|
447
|
+
frames ${t.first_frame}\u2013${t.last_frame} (${t.frames} frames)${t.asked?` \u2014 snapped to keyframes (asked ${t.asked.first_frame}\u2013${t.asked.last_frame})`:""}
|
|
448
|
+
source: ${n?.codec??"?"} ${n?.width??"?"}x${n?.height??"?"} @ ${t.fps} fps, start TC ${t.facts.source_timecode??"none"}`)}catch(t){return ee(t)}}},{name:"media_patch",long:!0,title:"Patch frames into a master",description:"Cut a fixed range of frames into a finished master BY TIMECODE, WITHOUT re-encoding (the Resolve 'bypass re-encode' fix, for ProRes and DNxHD/HR .mov). patch = a render of the fixed range in the master's exact spec with record TC: codec/profile, raster, rate, alpha/depth and color tags are checked first, the patch lands at (patch start TC \u2212 master start TC) and needs a TC track at the master's TC rate and DF/NDF; a mismatch, a patch without TC or a range outside the master is refused and nothing is written. in/out on the master (frames or timecodes, like media_trim; out inclusive) only cross-check that placement or pick part of the patch: an in= that disagrees with the TC is refused. Patch frames may be bigger or smaller than the ones they replace. mode new (default): a new file beside the master (<name>_patched), rewritten contiguously in the master's interleave order; the master untouched. mode section: a new file of just the patched range with the master's TC and audio. mode in_place: ONLY when the user asks to modify the master itself \u2014 the patch frames are appended and the index rewritten (the file grows by the patch, the replaced frames stay as dead bytes, the patched span loses interleave locality), the old index kept so mode=undo restores the file byte for byte. mode check: the spec + TC check, nothing written. mode plan (H.264/HEVC, BEFORE rendering a patch; needs in/out, no patch): the whole-GOP span of the master to render (keyframe at/before in \u2192 frame before the next keyframe after out; an open GOP after it included), its TCs, the GOP length and B-frames. Every write is verified (frame count, the master's TC track unchanged, frames at the patch's TC byte-identical to the patch and decoding to its pixels, the frames either side the master's, audio and untouched frames identical) and rolled back if it fails. in_place proves audio/TC untouched from the index by default (every sample at its original offset and size, the write append-only), so a feature master patches in about a minute; verify=full re-reads and hashes them (minutes a pass over a share). patches=[\u2026] puts several into one master in one call (all checked first; overlap refused). Long: background=true for a job id with progress. H.264/HEVC (long-GOP): a patch that replaces whole closed GOPs encoded like the master's (span from a master keyframe to the frame before the next, identical avcC/hvcC, keyframes and B-frame offsets) cuts in with no re-encode; anything else is refused, naming the GOP span to render.",inputSchema:{path:m.string().describe("The master .mov"),patch:m.string().optional().describe("The render of the fixed range (not needed for mode=undo)"),mode:m.enum(["new","section","in_place","check","undo","plan"]).optional().describe("Default new; in_place only when asked to modify the master itself; plan before rendering a long-GOP patch"),in:m.union([m.string(),m.number().int()]).optional().describe("Cross-check: the master frame (index or timecode) to start at; must agree with the patch's TC"),out:m.union([m.string(),m.number().int()]).optional().describe("Last master frame to replace (inclusive); default: to the end of the patch"),patch_in:m.number().int().min(0).optional().describe("First patch frame to use (default: the one at in= by TC, else 0)"),out_path:m.string().optional().describe("Output file or folder for mode new/section; never overwritten"),patches:m.array(m.string()).optional().describe("in_place/check: several patch renders into this master in one call, each placed by its own TC (instead of patch)"),verify:m.enum(["index","full"]).optional().describe("in_place: index (default) proves audio/TC untouched from the index; full re-reads and hashes them")},run:async({__progress:e,__signal:t,...n})=>{try{let r=await of(n,e);return Q(r.text,r.data)}catch(r){return ee(r)}}},{name:"media_retag",title:"Retag a file's color (no re-encode)",description:"Change what a ProRes .mov SAYS its color is (primaries / transfer / matrix), WITHOUT converting a pixel: the video colr atom (nclc/nclx) and every ProRes frame header are rewritten in place (same size, nothing moves) and read back. Use it for 'the same file tagged Rec.709' or to fix a mis-tagged render. Names: rec709, p3d65, dci-p3, rec2020 (primaries); rec709/g24, g26, pq, hlg (transfer); rec709, rec2020 (matrix); or ITU-T H.273 codes. out_path (file or folder) = a retagged copy, never overwriting (name it with the artist's naming: the color/gamma fields change); in_place=true only when the user asks to change the file itself. The file's hash changes, so a checksum manifest that went out with it is stale. Refused: H.264/HEVC (the tags live in the SPS, a re-encode) and files without a colr atom.",inputSchema:{path:m.string().describe("The ProRes .mov to retag"),primaries:m.union([m.string(),m.number().int().min(0).max(255)]).describe("rec709 | p3d65 | dci-p3 | rec2020 | H.273 code"),transfer:m.union([m.string(),m.number().int().min(0).max(255)]).describe("rec709 (=g24) | g26 | pq | hlg | H.273 code"),matrix:m.union([m.string(),m.number().int().min(0).max(255)]).describe("rec709 | rec2020 | H.273 code"),out_path:m.string().optional().describe("A retagged copy (file or folder); never overwritten"),in_place:m.boolean().optional().describe("Retag this file itself (only when the user asks)")},run:async e=>{try{let t=await Xv(e);return Q(t.text,t.data)}catch(t){return ee(t)}}},{name:"media_dcp",long:!0,title:"Make a DCP from a master",description:`Build a SMPTE OV DCP folder from a finished ProRes master and its mix WAV, natively on this machine (the same DCI J2K encoder, MXF writers and validator as conform.tools/dcp); to change frames of a finished DCP use media_dcp_patch. The master is fitted into the DCI container keeping its aspect (flat 1.85 up to 1.9:1, scope above; container= to force; 16:9 lands pillarboxed in flat, a 2.39 OAR master fills scope), rest black. color = what the master IS (rec709 = BT.1886 2.4, srgb, p3d65): ask if the master's tags or the artist's profile don't say. The rate is the master's own (24/25/30/48/50/60 in 2K, 24/25/30 in 4K). A 23.976/29.97 master needs reclock=true: frame-for-frame at 24/30, sound sped up 0.1% with no pitch correction (Resolve's method; the mix is the master-rate mix). Ask before reclocking. The WAV (48/96 kHz integer PCM, any channel count, 5.1 = 6 ch in SMPTE order) must end with the picture: a mix longer or a frame+ shorter is refused (run render_gate first). Prove a new master with from/count (~48 frames) first.
|
|
449
|
+
encrypt=true: SMPTE 429-6 AES-128 + HMAC, CPL/PKL signed with the facility identity (~/.conform-mcp/dcp/signer.pem, created on first use with issuer as the organisation). The content key is written ONLY to <out_dir>/<title>_KEYS/keys.json: tell the user it is the only copy, never ship it inside the DCP. Then media_dcp_kdm per venue.
|
|
450
|
+
title = ContentTitleText and folder name, DCNC form (naming / artist's profile; a new version gets a new date/version). Lands in out_dir/<title> (default beside the master), never overwritten, then validated (DCI raster, J2K rate caps, hashes, CPL/PKL/ASSETMAP, signatures) with PASS/FAIL. Refused up front if the volume lacks room for the worst case (250 Mb/s + sound). Speed \u2248 40+ fps 2K, \u2248 15 fps 4K encoded on an M-series Mac: a feature runs a long time, so background=true.`,inputSchema:{path:m.string().describe("The ProRes master .mov"),wav:m.string().describe("The program's mix WAV (5.1 = 6 channels L R C LFE Ls Rs)"),title:m.string().describe("ContentTitleText / folder name, DCNC form e.g. FILM_FTR-1_F_EN-XX_51_2K_20261009_TBD_SMPTE_OV"),color:m.enum(Ao(ja)).describe("The master's color encoding"),out_dir:m.string().optional().describe("Folder the DCP folder is created in (default: beside the master)"),container:m.enum(Ao(Hg)).optional().describe("DCI container; default from the master's aspect"),resolution:m.enum(Ao(zg)).optional().describe("Default 2k"),kind:m.string().optional().describe(`CPL ContentKind: ${Ao(Wg).join(", ")}\u2026 (default feature)`),issuer:m.string().optional().describe("Issuer, and the organisation of a newly created signing identity"),encrypt:m.boolean().optional().describe("Encrypt + sign the package (fresh content key, written to keys.json beside it)"),reclock:m.boolean().optional().describe("23.976 \u2192 24 (29.97 \u2192 30): picture frame-for-frame, sound +0.1% varispeed"),from:m.number().int().min(0).optional().describe("First master frame (test builds)"),count:m.number().int().min(1).optional().describe("Frames to build (test builds); default to the end")},run:async({__progress:e,__signal:t,...n})=>{try{let r=await Qv(n,e,t);return Q(af(r),r)}catch(r){return ee(r)}}},{name:"media_dcp_patch",long:!0,title:"Patch frames into a DCP",description:"Overwrite frames of a finished SMPTE DCP with a fix (a VFX shot, a title, a bad frame, a sound pop) without rebuilding the package. The fix (path) is: a ProRes .mov render of just the fixed range (encoded here with the media_dcp DCI J2K encoder, fitted into the DCP's own container at its rate; color = what the render IS), .j2c codestreams (one file, or a folder of them, sorted by name), a picture track .mxf (another DCP's), a .wav (same channels and rate as the DCP's sound) or a sound track .mxf. at = the first composition frame it replaces: a frame number or HH:MM:SS:FF counted from the composition's first frame; reel=N makes at relative to reel N; a .mov with a TC track can be placed by its own TC with start_tc= (the DCP's first frame, e.g. 01:00:00:00). Length never changes (overwrite, not insert), so sound, subtitles and reel lengths stay where they were. Before anything is written every patch frame is checked against the reel it lands in (raster, components, 2K/4K profile; a different COD is a warning), against the DCI 250 Mb/s per-frame cap, and for range/overlap/channel layout; a refusal writes nothing. Only the reels a patch touches are re-wrapped (new track files with new asset UUIDs: changed bytes never keep the old id); untouched reels are carried as the same files (hard-linked on the same volume: instant for a feature) or, mode=vf, referenced from the OV (the VF carries only the re-wrapped reels: send it to venues and labs that hold the OV; it plays nowhere else). mode=ov (default) is a self-contained new OV. mode=check: placement, which reels re-wrap and every check, nothing written (a .mov fix: one frame is encoded to check it). The output is proven before it is reported: patch frames, the 2 frames either side of every seam and each reel's head/tail byte-identical to their source, every other edit unit by length, then the validator; verify=full also recomputes every hash. Lands in out_dir/<title> (default: beside the DCP; title default = the source's DCNC name with OV/VF set), never overwritten. Name a new version in the DCNC title (FTR-2) when the client tracks versions. Encrypted DCPs and Interop packages are refused. ENCRYPTED: an encrypted source needs keys (its keys.json from media_dcp encrypt=true); encrypt=true writes the result encrypted with a fresh key (+ signed, keys.json beside it). Without path it only re-packages: encrypt=true encrypts an OV, keys alone makes a decrypted copy. An encrypted patch is one fix (path + at as a frame number) into a new OV; wav= replaces the whole mix there.",inputSchema:{dcp:m.string().describe("The DCP folder (the one with ASSETMAP.xml)"),path:m.string().optional().describe("The fix: .mov (ProRes), .j2c or a folder of .j2c, .mxf, .wav"),at:m.union([m.number().int().min(0),m.string()]).optional().describe("First composition frame replaced: frame number or HH:MM:SS:FF from the composition start"),reel:m.number().int().min(1).optional().describe("Make at relative to this reel (1-based)"),color:m.enum(Ao(ja)).optional().describe("A .mov fix: its color encoding (required for .mov)"),from:m.number().int().min(0).optional().describe("First frame of the fix to use (default 0)"),count:m.number().int().min(1).optional().describe("Frames of the fix to use (default: all of it)"),patches:m.array(m.object({path:m.string(),at:m.union([m.number().int().min(0),m.string()]).optional(),reel:m.number().int().min(1).optional(),color:m.enum(Ao(ja)).optional(),from:m.number().int().min(0).optional(),count:m.number().int().min(1).optional()})).optional().describe("Several fixes in one pass (instead of path/at); overlap refused"),mode:m.enum(["ov","vf","check"]).optional().describe("ov (default): a new self-contained OV; vf: only what changed, referencing the OV; check: nothing written"),package:m.enum(["ov","vf"]).optional().describe("mode=check: check as this package type"),title:m.string().optional().describe("ContentTitleText / folder name (default: the source's, OV/VF set)"),out_dir:m.string().optional().describe("Folder the new package is created in (default: beside the DCP)"),cpl:m.string().optional().describe("Which CPL, when the package has several (file name, title or uuid)"),start_tc:m.union([m.number().int().min(0),m.string()]).optional().describe("The composition's first frame as TC, to place a .mov fix by its own timecode"),issuer:m.string().optional(),keys:m.string().optional().describe("keys.json of an encrypted source DCP"),encrypt:m.boolean().optional().describe("Encrypt + sign the new package (fresh content key)"),wav:m.string().optional().describe("Encrypted patch only: a new mix WAV replacing the whole sound"),verify:m.enum(["quick","full"]).optional().describe("full: also recompute every asset hash (reads the whole package)")},run:async({__progress:e,__signal:t,...n})=>{try{let r=n;if(r.keys||r.encrypt){let s=await eT(r,e,t);return Q(af(s),s)}let o=await tT(r,e,t);return Q(nT(o),o)}catch(r){return ee(r)}}},{name:"media_dcp_kdm",title:"Make a KDM for a DCP",description:"Write a KDM (SMPTE 430-1) that lets ONE projector/media block play an encrypted DCP made by media_dcp, for a window. keys = that DCP's keys.json; recipient = the venue's server/projector certificate .pem (they send it; a chain file is fine, the device leaf is picked). from/to are UTC dates (YYYY-MM-DD; to is inclusive to 23:59:59) or full YYYY-MM-DDThh:mm:ss: confirm the screening dates with the user, and allow for the venue's time zone. Signed with the same facility identity as the DCP, self-verified. Written beside keys.json as <title>_KDM_<recipient>_<from>_<to>.xml, never overwritten. The KDM is safe to email; keys.json is not.",inputSchema:{keys:m.string().describe("The encrypted DCP's keys.json"),recipient:m.string().describe("The projector/server certificate (.pem) from the venue"),from:m.string().optional().describe("First day it plays, UTC (default now)"),to:m.string().describe("Last day it plays, UTC"),out_dir:m.string().optional().describe("Default: beside keys.json")},run:async e=>{try{let t=await Yv(e);return Q(Zv(t),t)}catch(t){return ee(t)}}},{name:"gfx_make",long:!0,title:"Make a graphics package",description:`Design a graphic ONCE and get it for every deliverable: lower thirds, locators (location IDs), legal lines and end crawls, rendered on this machine as ProRes 4444 + alpha (the matte Resolve, Premiere, Avid and FCP read) for every aspect ratio and position. The reformat is automatic and art-directed, not a stretch: type is sized on the short edge so it is physically the same in every format, each graphic stays pinned to its anchor inside action-safe (9:16 also keeps clear of the platform caption band and right rail), and text re-wraps to each format's width with the plate growing to fit. Formats default to all of ${Lu.join(", ")} (or name a raster like 1280x720); resolution uhd doubles every raster. Positions: a lower third fans to bottom-left/bottom/bottom-right by default, a locator to top-left/top-right; any of ${Nu.join(", ")} or all \u2014 each enters from its own side. End crawls are full frame. Content: one graphic (name+title \xB7 location+sub \xB7 text \xB7 credits) or many (items=[{\u2026}] or csv_path, one package per item). End crawl credits use the paste dialect: '# Section', 'Role | Name', '> wrapped paragraph', '@image logo.png' or '@image sag.png | dga.png 18' (a row of logos, images_dir), blank = gap; or credits_path (.txt) / csv_path (a credits sheet: section, role, name columns). Look: a preset (${ju.join(", ")}), an object of {family, accent, primary, secondary, plate (${ty.join("|")}), style (${ny.join("|")}), stagger, ease, radiusLu, padLu, uppercase, tracking}, or look_path (a .look.json from conform.tools/gfx or an earlier package) \u2014 the same look keeps every type on-brand. Fonts: family = a shipped face (${ry.join(", ")}), any installed family by name (gfx_fonts lists them), or a font file/folder; fonts= adds files (e.g. the bold) under their own family names. An unknown family is refused, never substituted. Every run writes <base>/preview.png (every format \xD7 position at the hold, true relative sizes) and <base>/still.png (the design full size): run preview_only=true first, LOOK at them, adjust, then render. Output: out_dir/<base>/<position>/<format>_<w>x<h>.mov, manifest.json and look.json (reuse with look_path). background_color=#rrggbb makes opaque ProRes 422 HQ instead (named _on_rrggbb). lottie=true also writes <base>.lottie (editable in Resolve/web; outlines for shipped and supplied fonts). options passes generator settings (lower third: center, nameLu, titleLu, maxWidthLu\u2026 \xB7 legal: sizeLu, minLu, sizeHpct, scrim, align \xB7 crawl: lineLu, colGapLu, gutterFrac). Held frames are encoded once, so a 21-file lower-third package takes seconds.`,inputSchema:{type:m.enum(Object.keys(ey)),name:m.string().optional().describe("lower_third: the name line"),title:m.string().optional().describe("lower_third: the title line"),location:m.string().optional().describe("locator: the location line"),sub:m.string().optional().describe("locator: the second line (time, date, INT./EXT.)"),text:m.string().optional().describe("legal: the disclaimer paragraph"),credits:m.string().optional().describe("end_crawl: credits in the paste dialect"),items:m.array(m.record(m.string())).optional().describe("Many graphics of this type, e.g. [{name, title}, \u2026]; one package each"),csv_path:m.string().optional().describe("A CSV of items (name,title \xB7 location,sub \xB7 text) or, for end_crawl, a credits sheet"),credits_path:m.string().optional().describe("end_crawl: a .txt (paste dialect) or .csv credits file"),images_dir:m.string().optional().describe("end_crawl: folder the @image names are in (default: the credits file's folder)"),look:m.union([m.string(),m.record(m.unknown())]).optional().describe(`A preset (${ju.join(", ")}) or look fields`),look_path:m.string().optional().describe("A .look.json (conform.tools/gfx, or an earlier package's look.json)"),family:m.string().optional().describe("Typeface: shipped id, installed family name, or a font file/folder"),fonts:m.array(m.string()).optional().describe("Font files or folders to make available (each under its own family name)"),formats:m.array(m.string()).optional().describe(`Default all: ${Lu.join(", ")}; or a raster like 1280x720`),positions:m.array(m.string()).optional().describe(`Anchors (${Nu.join(", ")}) or ["all"]; default per type`),resolution:m.enum(["hd","uhd"]).optional().describe("hd (16:9 = 1920\xD71080, default) or uhd (\xD72)"),fps:m.number().positive().optional().describe("Default 23.976"),duration:m.number().positive().max(600).optional().describe("Seconds (default: lower third 6, locator 5, legal 6, crawl 12)"),start_tc:m.string().optional().describe("Start timecode (default 00:00:00:00)"),background_color:m.string().optional().describe("#rrggbb: opaque ProRes 422 HQ on this color instead of 4444 + alpha"),options:m.record(m.unknown()).optional().describe("Generator settings beyond the look"),lottie:m.boolean().optional().describe("Also write an editable .lottie per graphic"),preview_only:m.boolean().optional().describe("Only the preview sheet + still; render nothing"),out_dir:m.string().optional().describe("Package folder (default <MCP home>/gfx/<type>_<time>)")},run:async({__progress:e,__signal:t,...n})=>{try{let r=await sy(n,e,t);return Q(iy(r),r)}catch(r){return ee(r)}}},{name:"gfx_fonts",title:"List typefaces for graphics",description:"The typefaces gfx_make can set: the shipped faces (by id; OFL, embeddable in a .lottie) and every family installed on this machine with its weights. query filters by name. A face not listed can still be used by passing its font file or folder to gfx_make.",inputSchema:{query:m.string().optional().describe("Part of a family name, e.g. 'helv'")},run:async({query:e})=>{try{let t=await oy(e),n=[`shipped: ${t.shipped.map(r=>`${r.id} (${r.label}, ${r.weights.join("/")})`).join(" \xB7 ")}`,`installed${e?` matching '${e}'`:""} (${t.installed.length}): ${t.installed.slice(0,200).map(r=>`${r.family}${r.weights.length>1?` [${r.weights.join("/")}]`:""}`).join(" \xB7 ")}${t.installed.length>200?" \u2026(query= to narrow)":""}`].join(`
|
|
451
|
+
`);return Q(n,t)}catch(t){return ee(t)}}},{name:"media_fix",long:!0,repoOnly:!0,title:"Fix frames: duplicates, cadence, retime",description:"Remake the frames a picture got wrong, as new media (ProRes 422 HQ at the source's timecode, so it relinks like the original). One plan, one executor: the analysis engine decides each output frame \u2014 a source frame as it is, or a frame BETWEEN two (RIFE v4.22.lite) \u2014 and the result is checked. Kinds: duplicates \u2014 the frames QC (qc_media) calls repeated: a double frame, a hang, slow motion by repeating frames; each repeat becomes the motion between the frames around it, the frame count kept (include_freezes: also a freeze continuing from motion \u2014 off by default, a freeze may be the edit's). cadence \u2014 an AI render (e.g. Seedance video_edit) against the plate it was made from: held frames cut, skipped plate frames put back, the output at the plate's count and rate; a render the AI RE-PACED is reported and not repaired unless force=true (filling it would cut real frames). retime \u2014 a constant speed (percent, 100 = real time) or a ramp ([frame, percent] keys) from src_in for `frames` output frames: optical-flow slow motion and speed changes better than a host's frame blend; or with session_id, every retimed clip of the timeline (its own speed or speed ramp, handles each side) rendered at the timeline's rate and record TC and the item relinked to it at 100 %. plan_only reports the plan without writing. The plan, the check, the decode and the encode are the engine and media-core; the between frames are RIFE on MLX (media-gen, Apple Silicon, its weights in models/rife/ of the MCP home); a plan with none (holds cut only) needs neither.",inputSchema:{kind:m.enum(["duplicates","cadence","retime"]),path:m.string().optional().describe("The clip to fix (cadence: the AI render); omit for a timeline retime"),session_id:m.string().optional().describe("retime: every retimed clip of this session's timeline (or item_ids) rendered with optical flow and relinked, played 1:1"),item_ids:m.array(m.string()).optional().describe("retime with session_id: only these items"),handles:m.number().int().min(0).max(240).optional().describe("retime with session_id: frames rendered each side of the used range (default 12)"),out_dir:m.string().optional().describe("retime with session_id: where the renders go (default <MCP home>/renders/<session id>)"),out_path:m.string().optional().describe("Output .mov; default <path>_<kind>.mov beside it"),plan_only:m.boolean().optional(),include_freezes:m.boolean().optional().describe("duplicates: also remake freezes continuing from motion"),plate:m.string().optional().describe("cadence: the source plate the AI was given"),plate_start:m.number().int().min(0).optional().describe("cadence: first plate frame the AI was given (default 0)"),plate_frames:m.number().int().min(2).optional().describe("cadence: plate frames the AI was given (default: to the end)"),mask:m.array(m.number()).length(4).optional().describe("cadence: x0,y0,x1,y1 fractions, an area the AI changed on purpose, left out of the alignment"),force:m.boolean().optional().describe("cadence: repair even when a re-pace is detected"),src_in:m.number().min(0).optional().describe("retime: source in-point (frame, default 0)"),frames:m.number().int().min(1).optional().describe("retime: output frames (default: the source's count)"),speed:m.number().positive().optional().describe("retime: constant speed in percent (50 = half speed)"),ramp:m.array(m.array(m.number()).length(2)).optional().describe("retime: speed ramp keys [output frame, percent]")},run:async e=>{try{if(e.session_id){if(e.kind!=="retime")throw new Error("session_id is for kind=retime (a timeline's retimed clips)");let n=await ft(e.session_id),r=await Wv(n.session,{session_id:e.session_id,item_ids:e.item_ids,handles:e.handles,out_dir:e.out_dir,plan_only:e.plan_only});r.changed&&(n.session=r.session,await Yt(n,`media_fix retime: ${r.items.filter(s=>s.wrote).length} clip(s) rendered with optical flow and relinked`));let o=[`${r.items.filter(s=>s.wrote).length} of ${r.items.length} retimed clip(s) ${e.plan_only?"planned":"rendered with optical flow and relinked (played 1:1)"}`,...r.items.map(s=>` ${s.name} (${s.speed}): ${s.skipped??`${s.frames} frames, ${s.between} remade${s.wrote?` \u2192 ${s.wrote}`:""}`}`)].join(`
|
|
452
|
+
`);return Q(o,{session_id:e.session_id,items:r.items})}if(!e.path)throw new Error("path is required (or session_id with kind=retime)");let t=await zv(e);return Q(Vv(t),{...t})}catch(t){return ee(t)}}},{name:"media_consolidate",long:!0,title:"Consolidate media for a timeline",description:"Timeline-driven trim: for every source file the cut uses, write a byte-exact trim of just the used frames plus handles into out_dir (no re-encode; ProRes/DNx/H.264 mov, mxf, wav, RED .R3D). This is the conform 'consolidate' / 'media manage' step. By default only linked references are trimmed (run timeline_relink first so paths are verified); set only_linked=false to trim whatever paths exist on disk. With relink=true (default) the session is repointed at the trims, so a following timeline_write links to the consolidated media. Reports each output and everything skipped, with the reason.",inputSchema:{session_id:m.string(),out_dir:m.string().describe("Folder for the trimmed media"),handles:m.number().int().min(0).default(24).describe("Frames of handle on each side of every used range"),relink:m.boolean().default(!0).describe("Repoint the session at the trims"),only_linked:m.boolean().default(!0)},run:async({session_id:e,out_dir:t,handles:n,relink:r,only_linked:o})=>{try{let s=await ft(e),i=await hb(s.session,t,n,{relink:r,only_linked:o});return await Yt(s,`consolidate \u2192 ${t} (${i.outputs.length} files, ${n} handles)`),St(i.text)}catch(s){return ee(s)}}},{name:"color_prep",long:!0,title:"Prep a conform for color: the colorist's node tree, input CSTs and a first balance",description:"The color prep step of a conform, onto the session's timeline (timeline_read the prproj/drt/xml first). Every shot gets the colorist's OWN node tree, the input Color Space Transform for what it was shot in, and a first balance in their balance node; timeline_write target=resolve-drt then writes it as a separate .drt (their project is never touched). TREE: tree = a gallery still or PowerGrade (.drx) of their tree, exported from Resolve's gallery. The first time, call with tree only: it lists the nodes and you ASK the user which is the balance node and which the input CST (never pick from labels), AND how they build their grade \u2014 where their look lives (look_levels: clip / group_pre / group_post / adjustment_clips / timeline / output; colorists differ: groups or not, timeline grade, adjustment clips) and where their LUTs/DCTLs live (lut_dirs) \u2014 then call again with balance_node + cst_node + look_levels (+ lut_dirs); all of it is remembered in the artist profile, so later preps need no tree. CSTs: read per clip from the camera's own metadata (Sony X-OCN/XAVC, ARRI, RED; MOV color tags): camera log \u2192 its space into the tree's working space; Rec.709 video \u2192 Rec.709 with inverse OOTF; graphics, stills and alpha \u2192 no tree, no grade. A clip that cannot be identified, or is identified only by container tags (camera files often tag log as Rec.709), is returned as a QUESTION and nothing is written: ask the user, then pass answers=[{match, as}]. "+(Ln()?"BALANCE = Autobalance, part of Autocolor (default on; the Autocolor pack runs on this machine, download=true the first time after asking): step 1 = each shot balanced on its own; step 2 = p2, the shots side by side in edit order (2x2 grids of 4 neighbours) so cuts match; step 3 = faces: each person's skin COLOUR matched across the shots of one setup (who is who and which shots share a setup are found automatically; brightness stays as lit). One balance node per shot (primaries only, Lum Mix 100). The result says how many people were matched. balance=false = tree and CSTs only. ":"BALANCE: Autobalance is not in this release yet; the tree and the CSTs are written without it, and there is no download to ask for. ")+"Long: background=true for a job id.",inputSchema:{session_id:m.string().describe("The conform's session (timeline_read of their timeline)"),timeline:m.string().optional().describe("Timeline id or name (default: the first)"),tree:m.string().optional().describe("Path to a .drx (gallery still / PowerGrade) of the colorist's node tree; omit to use the remembered one"),balance_node:m.number().int().optional().describe("With tree: the node id the USER says is their balance node"),cst_node:m.number().int().optional().describe("With tree: the node id the USER says is their input Color Space Transform"),look_levels:m.array(m.enum(zc)).optional().describe("With tree: where the USER says their look lives (any combination)"),lut_dirs:m.array(m.string()).optional().describe("With tree: the folders the USER keeps their LUTs and DCTLs in"),working:m.string().optional().describe("With tree, instead of cst_node when the USER says their input CST is not in this tree (group pre-clip / color management): the space the tree works in, <SPACE>_COLORSPACE/<CURVE>_GAMMA"),answers:m.array(m.object({match:m.string(),as:m.string()})).optional().describe(`The user's answers to the color questions: match = part of the file/folder/clip name; as = "rec709" | "graphic" | "<SPACE>_COLORSPACE/<CURVE>_GAMMA"`),balance:m.boolean().optional().describe("Balance the shots (default true); false = tree and CSTs only"),download:m.boolean().optional().describe(Ln()?"Allow the one-time Autocolor pack download (ask the user first)":"Not in this release (Autobalance is not released yet)")},run:async({session_id:e,timeline:t,tree:n,balance_node:r,cst_node:o,look_levels:s,lut_dirs:i,working:a,answers:l,balance:c,download:u,__progress:d})=>{try{let p=await ft(e),f;if(n){let b=await RS(n,r,o,s,i,a);if(b.ask)return Q(b.ask,{needs:"node choice"});f=b.tree}else f=await CS();if(!f)return Q("I need the colorist's node tree once: export a still of it from Resolve's gallery (right-click the still > Export, .drx) or a PowerGrade, and give me the path (tree=\u2026).",{needs:"tree"});let h=await SS(p.source_path),g=await ES(p.session,{timeline:t,tree:f,answers:l,balance:c,download:u,project:h,progress:b=>d?.(0,0,b)});if(!g.ops.length)return Q(g.text,g.data);for(let b of g.ops)Ba(p.session,"finish_op",b);return await Yt(p,`color_prep: ${f.name}, ${g.ops.length} clips`),Q(g.text,{...g.data,session_id:e})}catch(p){return ee(p)}}},{name:"color_lut",title:"Write a 3D LUT of Resolve's Color Space Transform (.cube)",description:"A dailies / viewing LUT from one colour space to another as a .cube, exact to Resolve's own Color Space Transform (the one model the engine uses for every CST): S-Log3 S-Gamut3.Cine to Rec.709, LogC4 to Rec.709, V-Log to Rec.709 gamma 2.4\u2026 from / to take a name (slog3-sgamut3cine, slog3, logc4, logc3, red-log3g10, canon-log3, canon-log2, vlog, bmd-film-gen5, dwg-intermediate, dlog, flog2, nlog, apple-log, acescct, rec709, rec709-gamma24, rec2020, p3d65, srgb, cineon\u2026) or Resolve's tokens (SGAMUT3CINE_COLORSPACE/SONY_SLOG3_GAMMA). The transform only: no look, no tone mapping, no camera metadata. Never overwrites.",inputSchema:{from:m.string().describe("The source space: a name (slog3-sgamut3cine, logc4, red-log3g10, vlog\u2026) or SPACE_COLORSPACE/CURVE_GAMMA"),to:m.string().default("rec709-gamma24").describe("The target space (default rec709-gamma24: Rec.709 at gamma 2.4, Resolve's CST default; rec709 = Rec.709 curve, srgb, p3d65\u2026)"),size:m.number().int().optional().describe("Points per axis: 17, 33 (default) or 65"),out_path:m.string().describe("The .cube to write (never overwritten)"),title:m.string().max(80).optional().describe("The LUT's TITLE line (default: from \u2192 to)")},run:async({from:e,to:t,size:n,out_path:r,title:o})=>{try{let s=n??33;if(!Qf.includes(s))throw new P("invalid_args",`size must be one of ${Qf.join(", ")}`);let i=Xf(e),a=Xf(t??"rec709-gamma24"),l=await PS(i,a,s),c=`${i.space}/${i.gamma} \u2192 ${a.space}/${a.gamma}`.replace(/_(COLORSPACE|GAMMA)/g,""),u=await IS(r,FS(l,s,o??c));return Q(`wrote ${u} (${s}\xD7${s}\xD7${s}, ${c}; Resolve's Color Space Transform, no look)`,{path:u,size:s,from:i,to:a})}catch(s){return ee(s)}}},{name:"color_match",title:"Match a shot's color to a reference image",description:"Conform Connect's auto color, headless: solve the grade that moves a SOURCE frame onto a REFERENCE image (a generated still, a client frame grab, a graded still \u2014 png/jpg/tiff/exr/dpx decoded by our own engine, or a frame of another clip). The same histogram + covariance match and fold fit the Lab runs; the result is Resolve corrector nodes (tone 1, match matrix, tone 2 bypassed) as finish entries. Default method hm-mkl-hm works against ANY reference; hm-mvgd-hm is the Lab's default and needs a pixel-aligned pair (the same frame recolored, e.g. an AI color transfer output). With session_id + item the grade is installed on that clip, so timeline_write resolve-drt then carries it as live nodes on Resolve's color page. "+(Ln()?'reference "ai" balances the frame with the local model (color from the model, exposure mostly held, as on conform.tools) and fits it from the pixel pairs (method pixel); the first use needs download: true. ':'reference "ai" (the local AI balance) is not in this release yet. ')+"With session_id + item, a Color Space Transform on the clip's color page (read from the .drt) runs first \u2014 our own CST, exact to Resolve's \u2014 so the balance and the fit happen after it, and the written .drt keeps that CST node in front of the new nodes. Camera-native raw sources are refused (they decode as log); match on a proxy or a rendered frame.",inputSchema:{source:m.string().describe("Media file (ProRes/DNx/MXF) or a still to grade"),frame:m.union([m.number().int(),m.string()]).optional().describe("Frame index or timecode of the source frame (default: the middle of the file)"),reference:m.string().describe(Ln()?'The look to match: a still image, a media file (+reference_frame), or "auto" \u2014 Autobalance, a first-pass balance made on THIS machine (Apple Silicon, 16 GB+; nothing is uploaded)':"The look to match: a still image or a media file (+reference_frame)"),reference_frame:m.union([m.number().int(),m.string()]).optional(),method:m.enum(bS).optional().describe('default hm-mkl-hm; for reference "auto" the default is primaries: ONE corrector node of gain/lift per channel, one gamma, contrast and saturation, skin protected on faces'),mixer:m.boolean().optional().describe("method primaries: also use the RGB Mixer (default false: a plain balance of gain/lift/gamma/contrast/saturation)"),skin_protect:m.number().min(1).max(20).optional().describe("method primaries: skin protection strength, default 3 (1 = off). Only inside detected faces, scaled by how much of the frame they fill; it moves color only and keeps the balance's contrast"),transfer:m.enum(["srgb","g24"]).optional().describe("Override the source's encoding (default: g24 for video, srgb for stills)"),session_id:m.string().optional().describe("Install the grade on a clip of this session"),item:m.string().optional().describe("The clip to grade: item id or unique clip name (with session_id)"),download:m.boolean().optional().describe(Ln()?'reference "auto" only: allow the one-time model download (~4.3 GB into ~/.conform-mcp/models). Ask the user first.':"Not in this release (Autobalance is not released yet)")},run:async({source:e,frame:t,reference:n,reference_frame:r,method:o,transfer:s,session_id:i,item:a,download:l,mixer:c,skin_protect:u})=>{try{let d=i?await ft(i):null;if(d&&!a)throw new P("invalid_args","item is required with session_id");let p=d&&a?_S(d.session,a):null;if(d&&!p)throw new P("not_found",`no clip '${a}' in session ${i} (timeline_query lists ids and names)`);let f=p?kS(d.session,p.itemId):void 0,h=await yS({source:e,frame:t,reference:n,reference_frame:r,method:o,transfer:s,item_id:a,download:l,cst:f,mixer:c,skinBoost:u}),g={method:h.method,transfer:h.transfer,residual:h.residual,luma_stops:h.lumaStops,source:h.source,reference:h.reference,entries:h.entries,...h.cst?{cst:h.cst}:{}},b="";if(d&&p){let k=wS(h,p.timelineId,p.itemId);for(let w of k)Ba(d.session,"finish_op",w);await Yt(d,`color_match ${fe(n)} \u2192 ${p.name||p.itemId} (${h.method})`),g.session_id=i,g.item_id=p.itemId,b=`
|
|
453
|
+
installed on ${p.name||p.itemId} in session ${i}: timeline_write target=resolve-drt writes it as corrector nodes`}return Q(vS(h)+b,g)}catch(d){return ee(d)}}},{name:"p2p_send",title:"Send files or a package peer to peer (Iroh)",description:"Serve a file, or a folder such as a media_deliver package, straight from this machine to one recipient over Iroh (encrypted QUIC, direct or relayed): no upload, no bucket. Returns a ticket for the recipient to pass to p2p_receive, and a job_id: the files are served until job action=cancel. The recipient only ever pulls the bytes it asks for (seek+response), so nothing is pushed.",inputSchema:{path:m.string().describe("A file, or a folder to send with its layout (e.g. a media_deliver folder package)"),proxies:m.boolean().default(!0).describe("Beside each video the recipient's mount shows <clip>_proxy.mov (ProRes 422 Proxy, up to 1280x720), encoded here only for the frames they play")},run:async({path:e,proxies:t})=>{try{let n=await t$(e);if(!n.length)return ee(new P("not_found",`nothing to send in ${e}`));let r=await mh(n,{proxies:t}),o=yi("p2p_send",async(i,a)=>(await new Promise(l=>{a.addEventListener("abort",()=>l()),r.closed.then(l)}),r.stop(),St("stopped serving"))),s=fr(r.ticket).files.length;return Q(`serving ${s} file(s) as ${o.id} \u2014 job action=cancel job_id=${o.id} to stop
|
|
454
|
+
ticket (give this to the recipient): ${r.ticket}`,{ticket:r.ticket,job_id:o.id,files:s})}catch(n){return ee(n)}}},{name:"account_bucket",title:"Your bucket: where client sends and deliveries land",description:"Connect your own S3-compatible bucket (AWS S3, Cloudflare R2, Backblaze B2, Wasabi, MinIO) to your conform.tools account. Projects then default to it: what clients send through a project_link, and media_deliver destination=bucket, land there. action=show \xB7 set (endpoint https://\u2026, bucket, access_key_id, region?, secret_access_key \u2014 or leave it out and set CONFORM_BUCKET_SECRET in the MCP's environment so the secret never passes through the chat) \xB7 forget. set tests the bucket first (write, ranged server-side copy, read back, delete) and saves only if every step works. The secret is kept server-side (Vault), never shown again.",inputSchema:{action:m.enum(["show","set","forget"]).default("show"),endpoint:m.string().optional().describe("set: e.g. https://<account>.r2.cloudflarestorage.com, https://s3.us-west-2.amazonaws.com"),bucket:m.string().optional(),region:m.string().optional().describe("set: default auto"),access_key_id:m.string().optional(),secret_access_key:m.string().optional().describe("set: or CONFORM_BUCKET_SECRET in the environment")},run:async({action:e,endpoint:t,bucket:n,region:r,access_key_id:o,secret_access_key:s})=>{try{let i=c=>c?`your bucket: ${c.bucket} at ${c.endpoint} (key ${c.access_key_id}${c.verified_at?`, checked ${c.verified_at.slice(0,10)}`:""})`:"no bucket connected \u2014 account_bucket action=set endpoint=\u2026 bucket=\u2026 access_key_id=\u2026";if(e==="show"){let{storage:c}=await Qt("v1-me","/v1/me/storage");return Q(i(c),{storage:c})}if(e==="forget")return await Qt("v1-me","/v1/me/storage",{method:"DELETE"}),St("bucket forgotten; new projects use conform.tools storage");let a=s??zt("CONFORM_BUCKET_SECRET");if(!t||!n||!o||!a)return ee(new P("invalid_args","set needs endpoint, bucket, access_key_id and secret_access_key (or CONFORM_BUCKET_SECRET)"));let{storage:l}=await Qt("v1-me","/v1/me/storage",{method:"PUT",body:{endpoint:t,bucket:n,region:r,access_key_id:o,secret_access_key:a}});return Q(`${i(l)} \u2014 tested and saved; new projects send into it`,{storage:l})}catch(i){return ee(i)}}},{name:"project",title:"Projects: the job you are working on, its shared context, and what clients send into it",description:`A project is one job ("PRIMROSE \xB7 Ep 104") on conform.tools, shared by everyone in the org: its context (the standing notes \u2014 client, deliverables, naming, handles, specs, decisions \u2014 that everyone, and Claude over the MCP, works from), its sessions, and what clients send through its links (project_link), in conform.tools storage or the org's own bucket (storage='org'), trimmed to their cut + the project's handles. Starting work on a job: action=open first (project_id from list) \u2014 its brief comes back (the facility's notes, the project's notes, and what the work has shown: every cut version read and what changed, where the media lives, deliveries, QC), and every session you make from then on joins the project. When you learn something about the job, save it in its section: action=context section="Turnover specs" text=\u2026 (sections: Client & deliverables, Turnover specs, Naming, Decisions, Open questions). action=open (project_id) \xB7 brief (project_id?: the brief again, synced) \xB7 context (project_id? default the open one; section? one section; text? saves it (or the whole notes) over the version read, else reads) \xB7 facility (text? the org's notes for every project: client/vendor specs, house rules) \xB7 attach (project_id?, session_id: one of the org's conform.tools sessions, e.g. an older send, joins it) \xB7 create (name, client_name?, handles?, storage?) \xB7 list \xB7 incoming (every client app sharing LIVE right now, on any project \u2014 mount one with delivery_fetch) \xB7 show (project_id: its links, every send newest first, and any client app sharing LIVE peer to peer) \xB7 archive (project_id: its links stop working).`,inputSchema:{action:m.enum(["open","brief","context","facility","attach","create","list","incoming","show","archive"]),project_id:m.string().optional().describe("default for context/attach: the open project"),text:m.string().max(2e5).optional().describe("context: the notes (or with section, that section's body) to save; facility: the facility notes to save; omit to read"),section:m.string().max(120).optional().describe(`context: one section of the notes, read or saved alone (${Nb.join(" / ")}, or any other heading)`),session_id:m.string().optional().describe("attach: a conform.tools session id"),name:m.string().optional().describe("create: the job's name"),client_name:m.string().optional(),handles:m.number().int().min(0).max(240).optional().describe("create: trim handles in frames for what clients send (default 24)"),storage:m.enum(["conform","org"]).optional().describe("create: the org's own bucket (default when account_bucket has one) or conform.tools storage")},run:async({action:e,project_id:t,name:n,client_name:r,handles:o,storage:s,text:i,session_id:a,section:l})=>{try{let c=(f,h={})=>Qt("v1-projects",f,h),u=f=>[f.updated_by?`saved by ${f.updated_by} ${String(f.updated_at).slice(0,16).replace("T"," ")}`:"",f.pending?"saved on this machine only; it goes up when conform.tools is reachable":f.offline?"offline: this machine's copy":""].filter(Boolean).join(" \xB7 ");if(e==="open"){if(!t)return ee(new P("invalid_args","open needs project_id (project action=list)"));let{project:f}=await c(`/v1/projects/${t}`);await Qh({id:f.id,name:f.name});let h=await va(f.id);return Q([`open: ${f.name}${f.client_name?` \xB7 ${f.client_name}`:""} \u2014 ${f.handles}-frame handles; sessions you make now join it`,await za(f.id),"Work from this brief: do not ask for what it already says. Save what you learn with project action=context section=\u2026 text=\u2026"].join(`
|
|
455
|
+
|
|
456
|
+
`),{project:f,context:h})}if(e==="brief"){let f=await xo(),h=t??f?.id;return h?Q(await za(h),{project_id:h}):ee(new P("invalid_args","brief needs project_id, or a project opened with project action=open"))}if(e==="facility"){let f=i===void 0?await Bb():await qb(i);return Q(i===void 0?f.text.trim()?`${f.text.trim()}
|
|
457
|
+
|
|
458
|
+
(facility notes of ${f.name}${f.updated_by?`, saved by ${f.updated_by}`:""}${f.offline?"; offline: this machine's copy":""})`:"no facility notes yet: client and vendor specs, house rules that hold for every project. Save with project action=facility text=\u2026":`saved the facility notes (${f.text.length} characters)`,{org:f})}if(e==="context"||e==="attach"){let f=t??(await xo())?.id;if(!f)return ee(new P("invalid_args",`${e} needs project_id, or a project opened with project action=open`));if(e==="attach")return a?(await c(`/v1/projects/${f}/sessions`,{method:"PUT",body:{session_id:a}}),St(`session ${a} joined project ${f}`)):ee(new P("invalid_args","attach needs session_id"));if(l){if(i===void 0){let b=jb((await va(f)).text,l);return Q(b||`no "${l}" section yet`,{section:l,text:b})}let g=await Db(f,l,i);return Q(`saved "${l}" in the project's notes${g.pending?": on this machine only, it goes up when conform.tools is reachable":""}`,{context:g})}let h=i===void 0?await va(f):await Xh(f,i);return Q(i===void 0?h.text.trim()?`${h.text.trim()}
|
|
459
|
+
|
|
460
|
+
(${u(h)||"shared with the project"})`:"no context yet for this project":`saved the project's context (${h.text.length} characters)${h.pending?": on this machine only, it goes up when conform.tools is reachable":""}`,{context:h})}let d=f=>`${(Number(f||0)/1e6).toFixed(1)} MB`;if(e==="create"){if(!n)return ee(new P("invalid_args","create needs name"));let f=s??((await Qt("v1-me","/v1/me/storage").catch(()=>({storage:null}))).storage?"org":"conform"),{project:h}=await c("/v1/projects",{body:{name:n,client_name:r,handles:o,storage:f}});return Q(`project ${h.name} (${h.id}) \u2014 ${h.handles}-frame handles, ${h.storage==="org"?"your bucket":"conform.tools storage"}
|
|
461
|
+
next: project_link project_id=${h.id} for a link to send your client`,{project:h})}if(e==="list"){let[{projects:f},h]=await Promise.all([c("/v1/projects"),xo()]);return Q(f.length?f.map(g=>`- ${g.name}${g.client_name?` (${g.client_name})`:""} \xB7 ${g.id}${g.id===h?.id?" \xB7 OPEN":""}${g.live?.length?` \xB7 LIVE: ${g.live.length} sharing now (project action=incoming)`:""}`).join(`
|
|
462
|
+
`):"no projects yet \u2014 project action=create name=\u2026",{projects:f,open:h})}if(e==="incoming"){let{projects:f}=await c("/v1/projects"),h=f.flatMap(g=>(g.live??[]).map(b=>({project:g.name,project_id:g.id,...b})));return Q(h.length?h.map(g=>`- ${g.project}${g.label?` \xB7 ${g.label}`:""} \xB7 sharing since ${String(g.seen_at).slice(11,16)} \u2192 delivery_fetch from=${g.ticket} as=mount (or as=trims / as=iso)`).join(`
|
|
463
|
+
`):'nobody is sharing right now \u2014 a client presses "Let <you> connect" in their Send app (project_link makes one)',{live:h})}if(!t)return ee(new P("invalid_args",`${e} needs project_id`));if(e==="archive")return await c(`/v1/projects/${t}`,{method:"PATCH",body:{archived:!0}}),St(`archived ${t}; its links no longer work`);let p=await c(`/v1/projects/${t}`);return Q([`${p.project.name}${p.project.client_name?` \xB7 ${p.project.client_name}`:""} \u2014 ${p.project.handles}-frame handles, ${p.project.storage==="org"?"your bucket":"conform.tools storage"}`,`links (${p.links.length}):`,...p.links.flatMap(f=>[` - ${f.label??"(no label)"} ${f.url} ${f.alive?`\xB7 expires ${f.expires_at?.slice(0,10)??"never"}`:"\xB7 OFF"}${f.last_used_at?` \xB7 last used ${f.last_used_at.slice(0,16)}`:""}`,...f.peer?[` LIVE: their app is sharing its cut from their machine \u2192 delivery_fetch from=${f.peer.ticket} as=mount (or as=trims / as=iso)`]:[]]),`sends (${p.sessions.length}):`,...p.sessions.map(f=>` - ${f.created_at.slice(0,16)} ${f.label??""} ${f.sender_email??""} ${f.status} ${d(f.total_bytes)} \u2192 delivery_fetch from=bucket:${f.id}`)].join(`
|
|
464
|
+
`),p)}catch(c){return ee(c)}}},{name:"project_link",title:"A link for your client to send footage into a project",description:`Make a link for one client and one project. Send it to them: it downloads a small app named for you and the project ("Send to Stefan"); they double-click it, drop their Premiere/Avid/Resolve/Final Cut project on it, and it finds their media by the project's own paths, trims to the cut + handles and sends it into the project \u2014 no account, no folders to point at. Or, instead of Send, they press "Let <you> connect": the app serves the same trimmed cut from their machine peer to peer (nothing uploaded) and project action=show gives the ticket to mount it (delivery_fetch from=<ticket> as=mount \u2014 opening a clip fetches only what is read). action=create (project_id, label? e.g. 'Jen at Northlight', recipient_email?, expires_in_days? default 30, null = never) \xB7 revoke (project_id, link_id). Sends show up in project action=show.`,inputSchema:{action:m.enum(["create","revoke"]).default("create"),project_id:m.string(),link_id:m.string().optional(),label:m.string().optional(),recipient_email:m.string().optional(),expires_in_days:m.number().int().min(1).max(365).nullable().optional()},run:async({action:e,project_id:t,link_id:n,label:r,recipient_email:o,expires_in_days:s})=>{try{if(e==="revoke")return n?(await Qt("v1-projects",`/v1/projects/${t}/links/${n}`,{method:"DELETE"}),St(`link ${n} turned off`)):ee(new P("invalid_args","revoke needs link_id"));let{link:i}=await Qt("v1-projects",`/v1/projects/${t}/links`,{body:{label:r,recipient_email:o,expires_in_days:s}});return Q(`send this to your client: ${i.url}
|
|
465
|
+
(expires ${i.expires_at?.slice(0,10)??"never"}; project_link action=revoke link_id=${i.id} turns it off)`,{link:i})}catch(i){return ee(i)}}},{name:"team",title:"Team: the org's seats and who is in it",description:"The org you belong to on conform.tools: everyone in it shares its projects (and their context) and rides on the owner's plan. action=list (members, seats used of the plan's cap, pending invites) \xB7 invite (email: they get an email to join; owner only, within the seat cap) \xB7 revoke (invite_id: a pending invite) \xB7 remove (profile_id: a member leaves the org; owner only).",inputSchema:{action:m.enum(["list","invite","revoke","remove"]),email:m.string().optional().describe("invite: who to invite"),invite_id:m.string().optional().describe("revoke: from action=list"),profile_id:m.string().optional().describe("remove: the member, from action=list")},run:async({action:e,email:t,invite_id:n,profile_id:r})=>{try{let o=(l,c={})=>Qt("v1-orgs",l,c);if(e==="invite")return t?(await o("/v1/orgs/me/invites",{body:{email:t}}),St(`invited ${t}: they get an email to join your team`)):ee(new P("invalid_args","invite needs email"));if(e==="revoke")return n?(await o(`/v1/orgs/me/invites/${n}`,{method:"DELETE"}),St(`invite ${n} revoked`)):ee(new P("invalid_args","revoke needs invite_id (team action=list)"));if(e==="remove")return r?(await o(`/v1/orgs/me/members/${r}`,{method:"DELETE"}),St(`removed ${r} from the team`)):ee(new P("invalid_args","remove needs profile_id (team action=list)"));let s=await o("/v1/orgs/me"),i=s.seatCap>=999?"unlimited":String(s.seatCap),a=s.members.map(l=>({profile_id:l.profile?.id,name:l.profile?.full_name??null,email:l.profile?.email??null,role:l.role}));return Q([`${s.org?.name??"your team"} \u2014 ${s.seatsUsed} of ${i} seats${s.isOwner?" (you own it)":""}`,...a.map(l=>`- ${l.name??l.email} <${l.email}> ${l.role} \xB7 ${l.profile_id}`),...(s.pendingInvites??[]).map(l=>`- invited ${l.email} (until ${String(l.expires_at).slice(0,10)}) \xB7 invite ${l.id}`)].join(`
|
|
466
|
+
`),{org:s.org,is_owner:s.isOwner,seat_cap:s.seatCap,seats_used:s.seatsUsed,members:a,invites:s.pendingInvites??[]})}catch(o){return ee(o)}}},{name:"delivery_fetch",long:!0,title:"Open a delivery: list it, fetch the .iso, cut trims from it, or mount it live",description:`A delivery is one .iso (media_deliver writes it). This reads one WHEREVER it is \u2014 from=a .iso path on this machine, a bucket delivery (bucket:<session id>, from media_deliver destination=bucket), or a peer's p2p_send ticket \u2014 the same way:
|
|
467
|
+
as=list: what it holds (files, sizes, how much of each is real bytes). as=iso: the whole image to out_path. as=trims: a folder at out_path in the delivery's own layout, each clip cut to the edit's frames + handles from the recipe the .iso carries; only reads the bytes the trims need (only=['A001C003'] or ['01_PROJECT_FILES'] keeps matching paths). as=mount (macOS): mount it now; from a bucket or a peer, opening a clip fetches only what is read; returns a job_id that keeps it mounted until job action=cancel or the user ejects it. Unmounting a peer's mount leaves a .iso of what was read (out_path, default ~/Downloads/<name>.iso): every file at its full size, only the bytes that came over recorded, so it takes the disk of what was read and mounts again offline. From a peer it says the path: direct (tens of MB/s on a good line) or through a relay when the two networks can't reach each other (a few MB/s: fine to browse and check shots, slow to play back hi-res); job action=status shows it live.
|
|
468
|
+
A peer's machine must stay on and serving. Long: background=true for a job id.`,inputSchema:{from:m.string().describe("A .iso path, bucket:<session id> (or the bare id), or a p2p_send ticket"),as:m.enum(["list","iso","trims","mount"]).default("list"),out_path:m.string().optional().describe("as=iso: the .iso to write; as=trims: the folder to write into; as=mount (a peer's): where unmounting keeps what was read (default ~/Downloads/<name>.iso)"),only:m.array(m.string()).optional().describe("as=trims: keep only paths containing one of these"),background:m.boolean().default(!1).describe("Return a job id immediately; follow it with job action=status, cancel with job action=cancel")},run:async({from:e,as:t,out_path:n,only:r,__progress:o,__signal:s})=>{let i=await It("conform-fetch-");try{let a=gh(e);if(t==="mount"){let c;if(a.kind==="peer"){let f=fr(a.ticket),h=f.iso?fe(f.files[0].name).replace(/\.iso$/i,""):hh(f.label??"CONFORM_P2P");c=n?mt(n):mt(`~/Downloads/${h}.iso`)}let u=await u$(a,i,c),d=yi("delivery_fetch",async(f,h)=>{let g=u.status&&setInterval(()=>{let k=u.status();f(k.fetched,k.total,`${k.files} files \xB7 ${dh(k.path)} \xB7 ${(k.rate/1e6).toFixed(1)} MB/s${k.error?` \xB7 ${k.error}`:""}`)},2e3);await new Promise(k=>{h.addEventListener("abort",()=>k()),u.ejected?.then(k)}),g&&clearInterval(g);let b=await u.stop().finally(()=>dn(i));return b?Q(`unmounted ${u.mountpoint}
|
|
469
|
+
kept ${b.path}: ${b.files} files, ${(b.kept/1e6).toFixed(1)} MB that came over (image ${(b.image/1e6).toFixed(1)} MB)`,{kept:b}):St(`unmounted ${u.mountpoint}`)});u.status&&await new Promise(f=>setTimeout(f,3e3));let p=u.status?.();return Q(`mounted at ${u.mountpoint}${a.kind==="file"?"":" \u2014 clips fetch as they are read; files the sender adds while sharing appear in it"}`+(p?`
|
|
470
|
+
path: ${dh(p.path)} (job action=status job_id=${d.id} shows it live, with MB/s)`:"")+`
|
|
471
|
+
job_cancel ${d.id} (or eject it) to unmount${c?`; what was read is kept at ${c}`:""}`,{mountpoint:u.mountpoint,job_id:d.id,...p?{path:p.path}:{}})}if(t==="iso"){if(!n)return ee(new P("invalid_args","as=iso needs out_path (the .iso to write)"));if(a.kind==="file")return ee(new P("invalid_args","that .iso is already on this machine"));let c=await d$(a,n,i,o,s);return Q(`fetched ${(c/1e6).toFixed(1)} MB \u2192 ${n}`,{path:n,bytes:c})}if(t==="list"&&a.kind==="peer"&&!fr(a.ticket).iso){let c=fr(a.ticket),u=d=>`${(d/1e6).toFixed(1)} MB`;return Q([`${c.label??"shared files"}: ${c.files.length} file(s), ${u(c.files.reduce((d,p)=>d+p.size,0))} \u2014 mount it, or as=iso to receive it whole`,...c.files.map(d=>`- ${d.name} ${u(d.size)}`)].join(`
|
|
472
|
+
`),{files:c.files,name:c.label??"shared files"})}let l=await Qc(a,i);try{if(t==="list"){let u=await zm(l),d=p=>`${(p/1e6).toFixed(1)} MB`;return Q([`${l.name}: ${u.files.length} file(s), ${d(u.image)} image${u.recipes?`, ${u.recipes} edit(s) in it (trims available)`:" (no recipe: trims come out as stored)"}`,...u.files.map(p=>`- ${p.name} ${d(p.size)}${p.recorded<p.size?` (${d(p.recorded)} real \u2014 the cut's frames)`:""}`)].join(`
|
|
473
|
+
`),{...u,name:l.name})}if(!n)return ee(new P("invalid_args","as=trims needs out_path (the folder to write into)"));let c=await Wm(l,n,{only:r,onProgress:o,signal:s});return Q([`wrote ${c.files} file(s), ${(c.bytes/1e6).toFixed(1)} MB of trims \u2192 ${n}`,...c.untrimmed.length?["not trimmed (written as stored):",...c.untrimmed.map(u=>` - ${u}`)]:[]].join(`
|
|
474
|
+
`),c)}finally{await l.close()}}catch(a){return ee(a)}finally{t!=="mount"&&await dn(i)}}},{name:"media_deliver",protectedStages:["write"],long:!0,title:"Deliver a package: folder, .iso, into your bucket, or peer to peer",description:`The app's i2o delivery, on this machine: the conform package a colorist or VFX house receives. Layout: 01_PROJECT_FILES/source (the original timeline), 01_PROJECT_FILES/converted (the requested host timelines, media paths rewritten to the package), 02_MEDIA (every used source trimmed byte-exact to the used frames + handles; RED clips as .RDC bundles), 03_REFERENCES.
|
|
475
|
+
destination=folder writes that tree into out_path. destination=iso writes ONE sparse UDF image (mountable on macOS/Windows/Linux; only the cut's frames are real bytes) at out_path, with its recipe inside so trims can be cut from any copy of it later (delivery_fetch as=trims).
|
|
476
|
+
destination=bucket puts that .iso into the org's OWN bucket (bring-your-own bucket, set up on conform.tools) as a delivery the web inbox lists: blocks an earlier delivery in that bucket already holds are copied there server-side instead of uploaded. Returns bucket:<id> for delivery_fetch / add_to; recipients=[emails] are notified.
|
|
477
|
+
destination=p2p serves that .iso from this machine to one recipient over Iroh (no upload, no bucket): returns a ticket for their delivery_fetch (mount it live, cut trims, or take the .iso) and a job_id that serves until job action=cancel.
|
|
478
|
+
add_to=<a .iso path or bucket:<id>> adds this delivery INTO an earlier one instead (any destination=iso|bucket): only what it lacks goes in \u2014 a clip's new frames, new clips into their folder, a changed timeline beside the old one as name_v2 \u2014 so a re-cut costs only its new frames; in a bucket only those bytes are uploaded.
|
|
479
|
+
Only linked references ship (run timeline_relink first). A clip that cannot be trimmed is reported and NEVER shipped whole. timeline_formats picks which host timelines ride along, e.g. ['resolve-drt','avid-avb'] (default resolve-drt).`,inputSchema:{session_id:m.string(),destination:m.enum(["folder","iso","bucket","p2p"]),out_path:m.string().optional().describe("folder: where to write; iso: the .iso path; bucket/p2p: optional \u2014 also keep the .iso here"),add_to:m.string().optional().describe("An earlier delivery to add this one into: a .iso path or bucket:<session id>"),recipients:m.array(m.string()).optional().describe("destination=bucket: emails to notify"),label:m.string().optional().describe("destination=bucket: the delivery's name in the inbox (default: the volume name)"),volume_name:m.string().optional().describe("Package / volume name; default from the source file"),handles:m.number().int().min(0).default(24),preserve_structure:m.boolean().default(!1).describe("Mirror the sources' parent folders under 02_MEDIA"),timeline_formats:m.array(m.string()).default(["resolve-drt"]),only_linked:m.boolean().default(!0)},run:async({session_id:e,destination:t,out_path:n,add_to:r,recipients:o,label:s,volume_name:i,handles:a,preserve_structure:l,timeline_formats:c,only_linked:u,__progress:d,__signal:p})=>{try{let f=await ft(e),h={volume_name:i,handles:a,preserve_structure:l,timeline_formats:c,only_linked:u},g=w=>`${(w/1e6).toFixed(1)} MB`;if(t==="folder"){if(r)return ee(new P("invalid_args","add_to adds into a .iso: use destination=iso or bucket"));if(!n)return ee(new P("invalid_args","out_path is required"));let w=await Ev(f.session,f.source_path,{...h,out_path:n});await Yt(f,`deliver folder \u2192 ${n}`);let y=await gi("delivery-qc",w.keys);return St(`${w.text}${y?`
|
|
480
|
+
|
|
481
|
+
Reading this delivery (conform.tools playbook):
|
|
482
|
+
${y}`:""}`)}let b=await It("conform-deliver-"),k=!1;try{let w=n&&!r?n:re(b,`${i??fe(f.source_path,Hn(f.source_path))}.iso`);d?.(0,0,"building the .iso");let y=await Mv(f.session,f.source_path,{...h,out_path:w}),_=y.text.split(`
|
|
483
|
+
`).filter($=>!$.startsWith("wrote ")&&!$.startsWith("- ")).join(`
|
|
484
|
+
`);if(r){let $=gh(r),x=await c$($,y.path,{onProgress:d,signal:p});return await Yt(f,`deliver add_to \u2192 ${r}`),Q(`added into ${r}: ${g(x.bytes)} in ${x.filled} range(s)${x.added.length?`
|
|
485
|
+
new: ${x.added.filter(R=>!R.startsWith(".conform/")).join(", ")}`:""}${x.versioned.filter(R=>!R.startsWith(".conform/")).length?`
|
|
486
|
+
changed, added beside the old: ${x.versioned.filter(R=>!R.startsWith(".conform/")).join(", ")}`:""}${x.bytes===0?`
|
|
487
|
+
(nothing new \u2014 this delivery was already in it)`:""}`+`${x.uploaded!==void 0?`
|
|
488
|
+
bucket: uploaded ${g(x.uploaded)}, copied ${g(x.copied??0)} server-side; the delivery is now ${g(x.image)}`:""}
|
|
489
|
+
|
|
490
|
+
${_}`.trimEnd(),x)}if(t==="iso"){await Yt(f,`deliver iso \u2192 ${y.path}`);let $=await gi("delivery-qc",y.keys);return St(`${y.text}${$?`
|
|
491
|
+
|
|
492
|
+
Reading this delivery (conform.tools playbook):
|
|
493
|
+
${$}`:""}`)}if(t==="bucket"){let $=await l$(y.path,{label:s,recipients:o,onProgress:d,signal:p});return await Yt(f,`deliver bucket \u2192 ${$.session_id}`),Q([`delivered to your bucket as bucket:${$.session_id} (${g($.image)} image): uploaded ${g($.uploaded)}${$.copied?`, ${g($.copied)} already in ${$.reused_from} earlier deliver${$.reused_from===1?"y":"ies"} \u2014 copied there server-side, not uploaded`:""}`,`it is in the conform.tools inbox; delivery_fetch from=bucket:${$.session_id} lists it, cuts trims or mounts it${o?.length?`; ${o.join(", ")} notified`:""}`,...n?[`kept a copy at ${y.path}`]:[],"",_].join(`
|
|
494
|
+
`).trimEnd(),$)}let v=await mh([y.path]);k=!n;let T=yi("media_deliver",async($,x)=>(await new Promise(R=>{x.addEventListener("abort",()=>R()),v.closed.then(R)}),v.stop(),k&&await dn(b),St("stopped serving")));return await Yt(f,`deliver p2p (${T.id})`),Q(`serving ${fe(y.path)} (${g(y.bytes)}) peer to peer as ${T.id} \u2014 job action=cancel job_id=${T.id} to stop
|
|
495
|
+
ticket for the recipient's delivery_fetch (as=mount to watch it now, as=trims, or as=iso): ${v.ticket}
|
|
496
|
+
|
|
497
|
+
${_}`.trimEnd(),{ticket:v.ticket,job_id:T.id})}finally{k||await dn(b)}}catch(f){return ee(f)}}},{name:"timeline_judge",hidden:!0,repoOnly:!0,title:"Judge a written timeline against its source",description:"Law-backed check of a written timeline file against the source it came from: the same timing, sizing, link and content judges that run on every production conversion, using each host's decoded rules. Pass the source file and the written file (e.g. the AAF you read and the .drt you wrote). Returns a verdict (clean / issues), the reasons, per-tier tallies and the clips with issues. Judged formats: prproj, drt, xmeml, aaf, avb, flame. Use after timeline_write when the user asks whether the conversion is right, or before delivering.",inputSchema:{source_path:m.string().describe("The original timeline file"),output_path:m.string().describe("The written timeline file to judge")},run:async({source_path:e,output_path:t})=>{try{return St(await gb(e,t))}catch(n){return ee(n)}}},{name:"timeline_autoconform",long:!0,protectedStages:["canonicalize"],title:"Auto conform a reference to source media",description:`Rebuild a cut from a reference render, in the analysis engine (one native process): every frame of the reference and the pool as a small luma grid at each codec's cheapest tier, one alignment of the whole reference against the pool (grade-proof take codes name the clip, motion names the frame), each shot matched whole in its own framing (punch-ins, flops, retimes, ramps), every placement pinned by one sharp frame check, the production sound for what the picture can't settle, each shot's sizing measured (keyframed moves too), and a new timeline session at the reference's raster and rate with markers on every issue (gap, unresolved, ambiguous, xml). reference: the cut's render (ProRes, H.264, HEVC, or a camera original). pool: folders and/or files of source media (mov/mp4/r3d/mxf/braw/ari/crm; spanned RED = one clip). hints_session_id: an editor's timeline of the same cut \u2014 CHECKED, never believed: each claim is pinned from its own take and in-point, only what the claims that hold leave unexplained is searched (nearest takes first), and every claim not kept as written is reported ("the timeline has A at 120, the picture matches B at 133"). With a good timeline nothing is searched at all. trust=true (with hints_session_id): the Aligner \u2014 the timeline's takes and in-points stand as written and only the sizing is measured (Baselight-style: the clips have the right TC, match the framing, keyframed moves included). Returns a session_id for timeline_write plus the coverage stats and the issue list. H.264/HEVC decode with the OS's own decoder (macOS today).`,inputSchema:{reference:m.string().describe("Path to the reference render of the cut (ProRes, H.264, HEVC, or a camera original)"),pool:m.array(m.string()).min(1).describe("Folders and/or media files to search"),hints_session_id:m.string().optional().describe("Session id of the editor's timeline for this cut, if you have one"),trust:m.boolean().optional().describe("With hints_session_id: keep the timeline's takes and in-points as written and measure only the sizing (the Aligner)"),reference_audio:m.string().optional().describe("The reference's sound from another file (a .wav beside a picture-only render)"),display_transform:m.boolean().optional().describe("Decode camera originals display-referred (Log \u2192 Rec.709/2.4 through the Color Space Transform) to match a GRADED reference. Experimental; X-OCN today"),sizing:m.boolean().optional().describe("Measure each placed shot's scale/position/rotation/mirror (default on; shots it cannot measure are left at 100 % and flagged)"),name:m.string().optional().describe("Timeline name"),background:m.boolean().default(!1).describe("Return a job id immediately; follow it with job action=status, cancel with job action=cancel")},run:async({reference:e,pool:t,hints_session_id:n,trust:r,reference_audio:o,display_transform:s,sizing:i,name:a,__progress:l,__signal:c})=>{try{if(r&&!n)throw new P("invalid_args","trust keeps a timeline's in-points: give hints_session_id");let u=n?(await ft(n)).session:void 0,d=await _c({reference:e,pool:t,hints:u,trust:r,reference_audio:o,display_transform:s,sizing:i,name:a,onProgress:l,signal:c}),p=await Kn(d.session,e,"autoconform");await Ta(p.id,kc,d.rebuild);let f=await gi("auto-conform",fT(d)),h=Vs(d.rebuild).length;return Q(`session_id: ${p.id}
|
|
498
|
+
${hT(d)}
|
|
499
|
+
${await Cr(d.session)}`+(h?`
|
|
500
|
+
|
|
501
|
+
${h} shot(s) the engine was unsure of: timeline_autoconform_review session_id=${p.id} shows each with a contact sheet to accept or reject.`:"")+(f?`
|
|
502
|
+
|
|
503
|
+
Reading this result (conform.tools playbook):
|
|
504
|
+
${f}`:""),{session_id:p.id,unsure:h})}catch(u){return ee(u)}}},{name:"media_cuts",long:!0,title:"Find the cuts in a movie (shot / scene detection)",description:"Every shot boundary of a movie, from the analysis engine's one cut detector (a cut is a spike in the frame-to-frame change against the frames around it; going to or from black is a cut, black to black is not; a jump within one take counts when it stands far over the change around it), plus its black runs. Returns the shots with source timecode and a session_id of the movie cut at every shot (one clip per shot, the movie as its source) for timeline_write to any host \u2014 the cut-up an editor imports to re-edit or conform a flat render. Measured against authored cuts with an exact answer key (bench/cuts-bench.ts). Reads the grid index the conform builds, so a file already conformed is instant.",inputSchema:{path:m.string().describe("The movie (a render, a reference, a camera original)"),name:m.string().optional().describe("Name of the cut-up timeline (default: <file> cuts)"),background:m.boolean().default(!1).describe("Return a job id immediately; follow it with job action=status")},run:async({path:e,name:t,__progress:n})=>{try{let r=await xT(e,t,n),o=await Kn(r.session,e,"cuts");return Q(`session_id: ${o.id}
|
|
505
|
+
${r.text}`,{session_id:o.id,...r.data})}catch(r){return ee(r)}}},{name:"media_sync",long:!0,title:"Sync dailies: each picture file's sound found in the sound recorder's files",description:"Dailies sound sync in the analysis engine: every picture file's scratch track is found in the production sound recorder's WAVs (spectral landmarks, then the waveform lined up to the sample \u2014 it survives a different microphone, level and room). The sound decides and the timecode confirms: where camera and recorder both carry timecode (BWF time reference), how far they disagree is reported in frames (a jam to fix); a file with no scratch sound, or too quiet to match, is placed by timecode alone and says so. Returns, per picture file, the recorder file, the sync (recorder seconds / samples / timecode at the picture's first frame) and how it was found, plus a session_id of the dailies: every picture file whole on V1 in timecode order with its recorder file laid under it at the sync, one audio track per channel \u2014 for timeline_write to any host. Pinned by an authored test with an exact answer (rust/analysis-core/tests/sync_planted.rs).",inputSchema:{picture:m.array(m.string()).min(1).describe("Picture files or folders (camera originals, proxies), searched recursively"),sound:m.array(m.string()).min(1).describe("The sound recorder's WAVs or folders of them, searched recursively"),name:m.string().optional().describe("Name of the dailies timeline"),background:m.boolean().default(!1).describe("Return a job id immediately; follow it with job action=status")},run:async({picture:e,sound:t,name:n,__progress:r})=>{try{let o=await $T({picture:e,sound:t,name:n},r),s=await Kn(o.session,t[0],"sync");return Q(`session_id: ${s.id}
|
|
506
|
+
${o.text}`,{session_id:s.id,...o.data})}catch(o){return ee(o)}}},{name:"qc_media",long:!0,title:"QC of a movie: frames, edges, pixels, sound",description:"QC of one file, picture and sound, in the analysis engine: every frame for doubled frames inside motion, freezes, black flashes and black segments mid-program, and flash frames (one frame far from both neighbours that match each other; 4+ in 2 s is a strobe, reported to check); every frame's edges at full resolution for blanking (a flat-black line on any edge, 1 px counts) and black corners; and stuck / hot / dead pixels across 24 frames spread over the file (a pixel that holds one value while the picture around it moves). Sound, every audio track: integrated loudness (BS.1770) and true peak, clipping (runs at full scale), dropouts (digital silence cut into sound), a silent channel beside live ones, DC offset, a stereo pair out of phase. Verdict PASS / CHECK / FAIL with each finding at source timecode. Heads and tails (leaders, holds) are reported as information, not failures. edges_every N reads every Nth frame's edges instead of all (faster on long programs).",inputSchema:{path:m.string().describe("The file to QC (a deliverable render, a master)"),edges_every:m.number().int().min(1).max(240).optional().describe("Check the edges of every Nth frame (default 1: all)"),background:m.boolean().default(!1).describe("Return a job id immediately; follow it with job action=status")},run:async({path:e,edges_every:t,__progress:n})=>{try{let r=await ST(e,{edges_every:t},n);return Q(r.text,r.data)}catch(r){return ee(r)}}},{name:"timeline_autoconform_review",title:"Review the shots auto conform was unsure of",description:"After timeline_autoconform: the shots the engine could not confirm, each with an A/B contact sheet (top row = the reference, bottom = the guessed source clip, five frames across the shot) returned as images. gap_guess = left as a gap, with the engine's best guess; doubtful = placed, but the in-point or the take is in doubt. Look at each sheet and settle only what you are sure of: accept=[ref_start] places a gap's guess, reject=[ref_start] turns a doubtful placement into a gap. Same set, different moment or a near-identical take of the same setup: leave it and name it to the artist. Rebuilds the session from the engine's own result (no re-run); then timeline_write. offset/limit page through the sheets (4 per call).",inputSchema:{session_id:m.string().describe("The session timeline_autoconform returned"),accept:m.array(m.number().int()).optional().describe("ref_start of each gap_guess to place"),reject:m.array(m.number().int()).optional().describe("ref_start of each doubtful shot to turn into a gap"),offset:m.number().int().min(0).optional().describe("First review shot to show (default 0)"),limit:m.number().int().min(0).max(12).optional().describe("Contact sheets per call (default 4; 0 = list only)")},run:async e=>{try{let t=await pT(e),{images:n,...r}=t;return{...Q(mT(t),{...r,session_id:e.session_id}),images:n}}catch(t){return ee(t)}}},{name:"qc_compare",long:!0,title:"Compare two versions of a cut and rebuild the new one from the old",description:"Reference Compare: rebuild a new render of a cut (B) from the old one (A) and say what changed: frames inserted, removed, moved, replaced, held, reversed or retimed. It is an auto conform of B with A as the only source (the analysis engine), so it is perceptual (survives a regrade or a re-render), takes any codec and resolution either side, and places every frame of B on A's own frame with its timing: a freeze, a reverse, a retime at its speed, a ramp as its curve. Builds the reconform: A-source events + holes of new material tiling B (motion effects as CMX3600 M2); events the engine wants an eye on are flagged CHECK. Writes a CMX3600 EDL and/or CSV when given paths, and returns a session of B rebuilt from A's media (session_id, for timeline_write). Use for a re-cut after color ('what changed in v3?'), checking a deliverable against the approved version, or reconforming changes into a graded timeline. Long: background=true for a job id.",inputSchema:{a:m.string().describe("Path to the OLD version (whose media and grade exist)"),b:m.string().describe("Path to the NEW version, to rebuild from A"),edl_path:m.string().optional().describe("Write the reconform as a CMX3600 EDL here"),csv_path:m.string().optional().describe("Write the reconform events as CSV here")},run:async({a:e,b:t,edl_path:n,csv_path:r,__progress:o,__signal:s})=>{try{let i=await ET({a:e,b:t,onProgress:o,signal:s});n&&await Ke(n,i.edl),r&&await Ke(r,i.csv);let a=await Kn(i.session,t,"reconform"),l=[`session_id: ${a.id} (B rebuilt from A; timeline_write it to any host)`,...n?[`EDL: ${n}`]:[],...r?[`CSV: ${r}`]:[],MT(i,{a:e,b:t})].join(`
|
|
507
|
+
`);return Q(l,{session_id:a.id,summary:i.summary,stats:i.stats,events:i.events.map(c=>({index:c.index,kind:c.kind,record:[c.recordInTc,c.recordOutTc],...c.aInTc?{a:[c.aInTc,c.aOutTc]}:{},...c.motion?{speed:c.motion.ramp?"ramp":c.motion.percent}:{}})),check:i.check.map(c=>({index:c.index,record:[c.recordInTc,c.recordOutTc],note:c.unreproducible.note}))})}catch(i){return ee(i)}}},{name:"render_gate",title:"Check a timeline before a deliverable render",description:"Run BEFORE every deliverable render. From the read timeline and the mix WAVs (placed by their BWF timecode): the program start (the mix's 2-pop + 2 s, else program_start, else the artist profile's, else the picture's first frame), picture end vs the mix's last sound (any difference, even 1 frame, is an EDIT ERROR: fix or ask, never cut at picture), picture/mix starting late, the last program frame (picture, not a gap), gaps inside the program, video layers ending just short of the end, and the deliverable name's audio promise (8CH_5-1_STEREO = 6ch + 2ch) vs the mix files. Returns READY/STOP and the Mark In/Out to render with (Out inclusive). Then render (host_render, audio_tracks for the output routing) and qc_deliverable the file.",inputSchema:{session_id:m.string().describe("The timeline (timeline_read / host_current)"),mix:m.array(m.string()).optional().describe("The mix WAV(s); the first sets the program length"),program_start:m.string().optional().describe("Program start TC when the mix has no 2-pop (default: the artist profile's program_start)"),name:m.string().optional().describe("The deliverable file name about to be rendered"),timeline_id:m.string().optional()},run:async({session_id:e,...t})=>{try{let n=await mx((await ft(e)).session,t);return Q(fx(n),{...n})}catch(n){return ee(n)}}},{name:"timeline_sound",long:!0,title:"Check the cut's sound against the cut",description:"The sound of a read timeline measured where it sits: every audio clip's file is read once by the analysis engine (envelope, onsets, silences, tempo, beats, loudness per clip span) and mapped to record timecode. Checks: hits (strong music/SFX onsets vs picture cuts and title starts: on a hit, a near miss by N frames, strong hits no cut uses), seams (music joins: level jump, off the beat, tempo change), gaps (dead air under picture, holes in the music bed, long pauses in dialogue), edges (a clip starting/ending inside sound with no fade; dialogue cut mid-word; speech on the cut), sync (a clip's sound vs its own picture at the same record frame: a source offset = out of sync; every J/L cut's lead and trail), titles (each title vs the nearest word and whether speech runs under its start/end), levels (integrated loudness per clip at its gain; outliers vs the role's median), keys (gain keyframes inside speech). Roles come from track/clip names (VO, DX, MX, SFX\u2026) or `roles`. Findings carry record TC and become host_apply marker_add ops (data \"ConformTools:sound\"). Use after a cut is read (timeline_read / host_current) to find where music hits and cuts disagree, where a seam is off the beat, where sound is cut on the frame, before notes go to the editor. Long: background=true for a job id.",inputSchema:{session_id:m.string().describe("The timeline (timeline_read / host_current)"),checks:m.array(m.enum($f)).optional().describe("Which checks (default all)"),roles:m.record(m.string(),m.enum(Sf)).optional().describe("Track label or clip name \u2192 dialogue | music | sfx | other, overriding the names"),hit_tolerance:m.number().int().min(1).max(24).optional().describe("A cut this many frames or fewer from a hit is a near miss (default 4)"),dead_air:m.number().positive().optional().describe("Dead air this long or longer is reported, seconds (default 0.5)"),level_spread:m.number().positive().optional().describe("A clip this many LU or more from its role's median is reported (default 6)"),markers:m.boolean().optional().describe("Emit marker_add ops for the findings (default true)"),timeline_id:m.string().optional()},run:async({session_id:e,__progress:t,__signal:n,...r})=>{try{let o=await yx((await ft(e)).session,r);return Q(wx(o),{...o})}catch(o){return ee(o)}}},{name:"qc_deliverable",long:!0,title:"Sign off a deliverable render",description:"QC a rendered deliverable before it goes out, PASS/FAIL per check: codec/raster/rate/bit depth/chroma (when given), start TC (mark_in, start_tc or the artist profile's program_start; else reported only) and frame count (mark_in..mark_out inclusive, or frames), the file name against the facility naming profile and against the file itself (codec, raster, color tags, audio channels), black at the head/tail with its length (WARN; end_on_picture=true makes tail black FAIL), audio per output track (channels, integrated loudness, true peak; AAC included) and against the mix WAVs (each track must match one mix within 0.5 LU: +6 LU = summed twice, an unmatched mix = missing bus), and picture vs the approved REF (frame-exact at the render's start TC; burn-ins and a regrade do not count as differences). Use after every deliverable render. Long: background=true for a job id.",inputSchema:{path:m.string().describe("The rendered deliverable"),mark_in:m.union([m.string(),m.number().int()]).optional().describe("Timeline Mark In (TC or frame): the expected start TC"),mark_out:m.union([m.string(),m.number().int()]).optional().describe("Timeline Mark Out, INCLUSIVE: with mark_in, the expected frame count"),start_tc:m.string().optional().describe("Expected start TC when there is no mark_in (default: the artist profile's program_start)"),frames:m.number().int().positive().optional().describe("Expected frame count"),codec:m.string().optional().describe("e.g. 'ProRes 4444', 'ProRes 422 HQ', 'H.264'"),width:m.number().int().positive().optional(),height:m.number().int().positive().optional(),fps:m.number().positive().optional(),bit_depth:m.number().int().optional(),chroma:m.string().optional().describe("e.g. 4:4:4"),channels:m.number().int().min(0).optional().describe("Total audio channels expected"),loudness_lufs:m.number().optional().describe("Target integrated loudness per track (e.g. -24)"),loudness_tolerance:m.number().positive().optional().describe("\xB1 LU (default 1)"),true_peak:m.number().optional().describe("True-peak ceiling, dBTP (e.g. -2)"),mix:m.array(m.string()).optional().describe("The mix WAVs / stems the audio outputs must carry"),ref:m.string().optional().describe("The approved reference movie"),ref_in:m.union([m.string(),m.number().int()]).optional().describe("The REF's TC/frame for the render's first frame (default the render's start TC)"),name:m.boolean().optional().describe("Check the name against the naming profile (default true)"),end_on_picture:m.boolean().optional().describe("The program ends on its end card: any black at the tail FAILS (default: WARN with its length)")},run:async({__progress:e,__signal:t,...n})=>{try{let r=await ux(n);return Q(dx(r),{...r})}catch(r){return ee(r)}}},{name:"patch_plan",title:"Plan patch renders for changed shots",description:"Work out the patches to re-render for changed shots on a read timeline (a session from host_current / timeline_read), before anything is queued. Each patch runs from the head of the WHOLE clip before the change to the tail of the WHOLE clip after it, cut on existing edits of the picture as it plays (the topmost enabled video layer), never inside a lower third/title (graphics tracks, by name) or a transition; contiguous changes share one patch. Says the neighbouring clips, whether TEXTLESS is needed (a graphics track has content in range \u2192 TEXTED + TEXTLESS, with the tracks to leave out of TEXTLESS), picture only, file TC = record TC of the head. Returns host_render-ready ranges (absolute frames, inclusive) plus record TC. Give master (a delivered file's name) to get each patch's file name, render job name and folder from the naming profile. Read-only.",inputSchema:{session_id:m.string(),changes:m.array(m.union([m.string(),m.object({in:m.union([m.string(),m.number()]),out:m.union([m.string(),m.number()])})])).min(1).describe("The changed shots: clip item_ids (timeline_query), or record ranges {in, out} as record TC or absolute timeline frames, out inclusive"),timeline_id:m.string().optional().describe("The timeline (default the session's first with video)"),master:m.string().optional().describe("A delivered master's file name (or path) to name the patches from (naming profile)"),first_patch:m.number().int().min(1).default(1).describe("Number of the first patch (PATCH01)")},run:async({session_id:e,changes:t,timeline_id:n,master:r,first_patch:o})=>{try{let s=await ft(e),i=Cx(s.session,t,{timeline_id:n,first_patch:o}),a=Ax(i);if(r){let l=await Co(),c=new Date,u=i.patches.map(p=>p.versions.map(f=>({text:f,...yu(l,r,{nn:p.nn,text:f,when:c})})));a+=`
|
|
508
|
+
`+u.flat().map(p=>`name ${p.file}${p.job?` job ${p.job}`:""} \u2192 ${p.folder}`).join(`
|
|
509
|
+
`);let d=[...new Set(u.flat().flatMap(p=>p.warnings))];return d.length&&(a+=`
|
|
510
|
+
`+d.map(p=>`warning: ${p}`).join(`
|
|
511
|
+
`)),Q(a,{...i,names:u})}return Q(a,{...i})}catch(s){return ee(s)}}},{name:"media_frame",title:"Grab frames from a media file",description:"Decode a frame of a media file to a PNG on this machine (our own decoders: ProRes, DNx, H.264/HEVC, MXF, camera originals, stills \u2014 exr/dpx/tiff/jpg/png/dng/cr3, scaled with width=; never uploads). frame is a frame index (0 = first) or an ABSOLUTE source timecode (the file's start TC is honoured); default the middle frame. around=N makes a contact sheet of the frames \xB1N (every step-th), each labelled with its TC \u2014 check a shot change, not one middle frame. b = a second file: A/B rows of the same frames (b_frame defaults to the same absolute TC; give it when the TC bases differ) with a perceptual difference score per column (survives a regrade, burn-in/watermark, rescale). Prove a frame offset with media_align. session_id + item_id / record grabs the source frame under a timeline position (returns the source file, frame and TC it resolved to). Writes out_path (.png) or a temp file; returns the path \u2014 open it to look.",inputSchema:{path:m.string().optional().describe("The media file; or session_id + item_id / record for the source frame under a timeline position"),session_id:m.string().optional().describe("Through a session: the source file and frame under item_id (record moves inside it) or under record (the topmost enabled video clip); the clip must be linked (timeline_relink first)"),item_id:m.string().optional(),record:m.union([m.string(),m.number().int()]).optional().describe("With session_id: record TC like 01:00:10:00, or frames from the timeline head"),timeline:m.string().optional().describe("With session_id: timeline id or name (default the primary)"),frame:m.union([m.string(),m.number().int()]).optional().describe("Frame index or absolute source TC like 01:00:10:00; default the middle frame"),around:m.number().int().min(0).max(48).optional().describe("Contact sheet: \xB1N frames around frame"),step:m.number().int().min(1).optional().describe("Contact sheet: every Nth frame (default 1)"),b:m.string().optional().describe("A second file for A/B (e.g. the master against the temp)"),b_frame:m.union([m.string(),m.number().int()]).optional().describe("B's frame or TC for A's frame; default the same absolute TC"),width:m.number().int().min(16).max(8192).optional().describe("Output width per frame (default full size; 480 per tile on a sheet)"),out_path:m.string().optional().describe("PNG to write; default a temp file")},run:async({session_id:e,item_id:t,record:n,timeline:r,...o})=>{if(e)return nn("timeline_frame").run({session_id:e,item_id:t,record:n,timeline:r,...o});if(!o.path)return ee(new P("invalid_args","media_frame needs path, or session_id with item_id / record"));try{let s=await Eo(o);return Q(Ru(s),{...s})}catch(s){return ee(s)}}},{name:"timeline_frame",hidden:!0,title:"Grab the source frame under a timeline position",description:"media_frame through a session: the source file and frame under an item (item_id; record moves inside it) or under a record TC (the topmost enabled video clip there), decoded to a PNG; around=N for a contact sheet. Returns the file, source frame and TC it resolved to. The clip must be linked (timeline_relink first).",inputSchema:{session_id:m.string(),item_id:m.string().optional(),record:m.union([m.string(),m.number().int()]).optional().describe("Record TC like 01:00:10:00, or frames from the timeline head"),timeline:m.string().optional().describe("Timeline id or name (default the primary)"),around:m.number().int().min(0).max(48).optional(),step:m.number().int().min(1).optional(),width:m.number().int().min(16).max(8192).optional(),out_path:m.string().optional()},run:async({session_id:e,item_id:t,record:n,timeline:r,...o})=>{try{let s=await ft(e),i=sb(s.session,{item_id:t,record:n,timeline:r}),a=await Eo({...o,path:i.path,frame:i.frame});return Q(`record ${i.record_tc} (${i.track}, item ${i.item}) = ${fe(i.path)} frame ${i.frame} (${a.frames[a.frames.length>>1]?.tc??"?"})
|
|
512
|
+
${Ru(a)}`,{...a,source:i})}catch(s){return ee(s)}}},{name:"timeline_align",long:!0,title:"Match each clip's framing to a reference track",description:"The Aligner: for every clip on the target video tracks that sits over a clip of the REFERENCE track (an offline, a client render, the graded master), the reference's picture and the clip's raw source frame at the same record frame are fitted in the analysis engine (the sizing auto conform uses), and the clip's WHOLE transform comes back \u2014 scale, position, rotation, flips \u2014 in IR units and as Resolve edit-page properties (Pan, Tilt, ZoomX, ZoomY, RotationAngle, FlipX, FlipY in its scripting API's units). Verdict per clip: aligned / animated (samples \u2265 2 and the framing moves: the clip is then measured on EVERY frame, each frame's answer in `keys`, and written as the fewest keyframes on Resolve's own ease (Dissolve Type) that stay within 1 px at rest and half a frame of timing while it moves \u2014 `grade_keys`, for sizing_target input / node one keyframed Colour-page op (`grade_keys` on Resolve's Dissolve-Type ease); for edit an `edit_keys` op (`edit_keys` on Resolve's Edit-page Bezier law), keyed on a copy of the timeline, '<timeline> ALIGNED', as Resolve's API cannot keyframe the Edit page) / no_match (another shot or moment; confidence = the fit's agreement 0\u20131, trusted from 0.4) / refused (not linked, no reference under it, the reference clip itself resized). Returns host_apply ops: `properties` for every aligned clip and a marker per clip (data \"ConformTools:align\"); apply them with host_apply on the live timeline (host_current via=export it first, timeline_relink so the media is linked). apply_session writes the aligned transforms into the session (timeline_write / host_open builds a <TL>_ALIGNED). Resolve units assume the timeline's input scaling 'fit' (Scale entire image to fit); pass input_scaling for fill / crop / stretch. sizing_target says where the framing goes in Resolve: edit (default) = the Edit page transform (`properties` ops); input = the Color page's clip Input Sizing, node = the Sizing of node 1 (`grade_sizing` ops, written as a grade .drx). input / node leave the clip's own edit transform (the client XML's) untouched and carry only the correction on top of it, so the cut goes back to Premiere without the aligner's resizes; input ADDS the sizing to the clip's grade as it stands (every node and version kept) on a new local version 'conform.tools aligned', leaving the colorist's own version untouched (undo goes back to it); node writes Sizing into the chosen node of that same kept grade (a node that already has Sizing of its own is refused); a clip on a REMOTE grade version (shared by every use of that source clip, in every timeline) is first moved onto its local version, so the other uses never change. Node sizing has no flip and cannot show picture outside the clip's own fitted raster.",inputSchema:{session_id:m.string(),reference_track:m.union([m.number().int().positive(),m.literal("offline")]).optional().describe(`Required: the reference's video track, 1-based (V1 = 1), or "offline" = the timeline's linked offline reference clip. Never guessed: ask the artist which it is`),tracks:m.array(m.number().int().positive()).optional().describe("Video tracks to align (default: every other video track)"),timeline_id:m.string().optional().describe("Timeline id or name (default the primary)"),samples:m.union([m.number().int().min(1).max(600),m.literal("all"),m.literal("half"),m.literal("ends")]).optional().describe('Frames measured per clip to SEE a move: "ends" = the first and last frames and the quarters between (a move shows as them disagreeing, even one that returns to where it started), "half" = every half second and the last frame (the default), a count spread over it, or "all" = every frame (up to 600 per clip; the static answer is the median of the trusted frames). A clip they show moving is measured on every frame anyway'),step:m.number().int().min(1).optional().describe("Measure every step-th frame instead (12 = every half second at 24 fps)"),scope:m.enum(["all","playhead","selected"]).optional().describe("Which clips: all (default), the clip under `at`, or the `picks`"),at:m.number().int().optional().describe("scope playhead: the record frame (from the timeline start)"),picks:m.array(m.string()).optional().describe('scope selected: "track:start" of each clip (video track, record start in frames from the timeline start)'),input_scaling:m.enum(Au).optional().describe("Resolve's input scaling for the clips (default fit)"),apply_session:m.boolean().optional().describe("Write the aligned transforms into the session"),markers:m.boolean().optional().describe("Include marker ops (default true)"),sizing_target:m.enum(bb).optional().describe("Where the framing goes in Resolve: edit (Edit page transform, default), input (Color page Input Sizing) or node (node 1 Sizing)"),node:m.union([m.number().int().positive(),m.string(),m.object({layer:m.number().int().positive(),node:m.union([m.number().int().positive(),m.string()])})]).optional().describe("node: which node gets the Sizing \u2014 its number as Resolve shows it, or its label (default 1), or {layer, node}. The clip's grade goes onto a new local version 'conform.tools aligned', every node kept, the colorist's version untouched"),layer:m.number().int().positive().optional().describe("node: which node stack `node` is in (1 = the first; default 1)"),background:m.boolean().default(!1).describe("Return a job id immediately; follow it with job action=status")},run:async({session_id:e,__progress:t,__signal:n,...r})=>{try{let o=await ft(e),s;if(o.source_format==="drt"&&o.source_path&&await Ye(o.source_path)){s=new Map;let a=Ub(await Ut(o.source_path));for(let[l,c]of a)if(c.active){let u=Gb(c.active);u.length&&s.set(l,u)}}let i=await yb(o.session,{...r,inputs:s},t,n);return r.apply_session&&i.applied&&await Yt(o,`timeline_align: ${i.applied} transform(s) from V${i.reference_track}`),Q(wb(i),{...i,session_id:e})}catch(o){return ee(o)}}},{name:"qc_decide",title:"Decide a QC finding",description:"Record what the artist decided about one Master QC finding (0.9.5 dispositions): fixed, intent (artistic intent), best_available, wont_fix, not_issue \u2014 or open to undecide. Kept per project + timeline and per finding `key` (each Finishing QC row carries it: check|start|end|clip), across re-runs: a decided finding stays listed and stops counting against the verdict.",inputSchema:{project:m.string().describe("The host project (a Finishing QC row's scope.project)"),timeline:m.string().describe("The timeline (the row's scope.timeline)"),key:m.string().describe("The finding's key (the row's key)"),status:m.enum(sl.map(([e])=>e)),note:m.string().optional().describe("Why, in the artist's words")},run:async({project:e,timeline:t,key:n,status:r,note:o})=>(await OS(e,t,n,r,o),Q(`${n}: ${r==="open"?"open again":LS({status:r,note:o,at:""})}`,{key:n,status:r}))},{name:"qc_blanking",long:!0,title:"Find clips whose sizing shows black",description:"The Blanking Detector on a session: every clip's placement (its IR transform at each frame: scale, position, rotation, anchor, crop, over the source's fit) checked for black inside the delivery frame \u2014 the whole raster, or with `aspect` the centred delivered ratio (16:9, 1.85, 2.00, 2.20, 2.35, 2.39, 2.76, 4:3, 1:1, 9:16, none, or a number), so the deliverable's own bars are never a finding. pixels=true also decodes `samples` source frames per clip in the analysis engine and measures the source's own black edges (QC's edge rule): a letterbox baked into a source and revealed by a pull-out is caught too. Each frame is judged on the topmost enabled clip; findings are ranges (strictness strict 1 px / 1 frame \u2014 default, standard 2 px / 2 frames, relaxed 6 px / 4 frames) with depth per edge, zones, and the least zoom that fills the frame (about the clip's anchor, position kept). Returns host_apply ops: a ZoomX/ZoomY `properties` fix per clip (a keyframed clip gets markers only) and a marker per range (data \"ConformTools:blanking\").",inputSchema:{session_id:m.string(),timeline_id:m.string().optional().describe("Timeline id or name (default the primary)"),aspect:m.union([m.enum(Object.keys(kb)),m.number().positive(),m.string()]).optional().describe("Delivered aspect when bars are part of the deliverable (default none: the whole raster)"),strictness:m.enum(Object.keys(Vg)).optional(),tolerance_px:m.number().int().min(0).optional().describe("the strictness's black-edge tolerance in px (overrides its number)"),min_frames:m.number().int().min(1).optional().describe("frames a reveal must last to count"),gap_frames:m.number().int().min(0).optional().describe("frames between reveals that still make one range"),black_threshold:m.number().int().min(0).max(255).optional().describe("8-bit level at or under which a pixel is black"),pixels:m.boolean().optional().describe("Also measure the sources' own black edges on decoded frames (needs linked media)"),samples:m.number().int().min(1).max(12).optional().describe("pixels: source frames measured per clip (default 3)"),input_scaling:m.enum(Au).optional().describe("Resolve's input scaling, for the zoom fix's units (default fit)"),markers:m.boolean().optional().describe("Include marker ops (default true)"),background:m.boolean().default(!1).describe("Return a job id immediately; follow it with job action=status")},run:async({session_id:e,__progress:t,__signal:n,...r})=>{try{let o=await ft(e),s=await Tb(o.session,r,t,n);return Q(xb(s),{...s,session_id:e})}catch(o){return ee(o)}}},{name:"patch_verify",long:!0,title:"Verify a rendered patch against the delivered master",description:"Check a rendered patch against the master it patches: spec (codec, ProRes profile, pixel format, bit depth, raster, frame rate, color tags), frame count, start TC = the record TC, picture only, then the picture frame by frame against the master at the same TC (every frame; per-frame mismatches with their TC and difference, plus the patch's shot changes). After a splice (media_patch), the seam decode proof: full-raster decoded frames \xB12 s around each seam, exact: inside the span = the patch, outside = original (a backup or the unpatched master) when given, and every frame decodes. Use after every patch render, before it goes to the client. Read-only. Long: background=true for a job id.",inputSchema:{patch:m.string().describe("The rendered patch file"),master:m.string().describe("The delivered master file it patches"),expected_tc:m.string().optional().describe("The record TC the patch must start at (patch_plan start_tc)"),expected_frames:m.number().int().min(1).optional().describe("The frame count it must have (patch_plan frames)"),tolerance:m.number().min(0).max(255).default(10).describe("Largest luma difference (0-255, on a 64-wide thumbnail) still counted as the same picture"),original:m.string().optional().describe("After a splice: the backup / unpatched master, so the seam proof checks the neighbouring frames are untouched")},run:async({patch:e,master:t,expected_tc:n,expected_frames:r,tolerance:o,original:s,__progress:i})=>{try{let a=await Ex({patch:e,master:t,expected_tc:n,expected_frames:r,tolerance:o,original:s},i);return Q(Mx(a,{patch:e,master:t}),{...a})}catch(a){return ee(a)}}},{name:"artist_profile",title:"How this artist works: learn, read and remember",description:"conform.tools works the way THIS artist/facility works, never one built-in way. Their profile holds naming templates, the usual deliverable set, folders/bins, conventions (program_start TC, end_on_picture, theatrical_tag) and workflow rules in their words, each with where it came from. action=get (default) shows it; read it before naming, rendering or delivering. learn reads a folder of their DELIVERED files (read only): matches each name element to what the file really is (codec, raster+rate, color, audio, dates) and saves the naming template, the usual deliverable set and the codec folders (project= keeps them as that project's spellings; save=false previews). remember saves a preference: rule='\u2026' (topic e.g. deliverables/naming/render/patch) and/or conventions={program_start:'01:00:00:00', \u2026}. Save only what is THIS artist's choice; when they correct you, ask: 'your preference, or should every artist work this way?'; the second is a product issue (report kind=issue), not a profile rule. forget removes a rule (number or text). set replaces the whole profile JSON.",inputSchema:{action:m.enum(["get","learn","remember","forget","set"]).default("get"),path:m.string().optional().describe("learn: a folder of delivered files (or one file)"),project:m.string().optional().describe("learn: save as this project's spellings over the artist's"),facility:m.string().optional().describe("learn: the artist's or facility's name"),save:m.boolean().default(!0).describe("learn: false = preview only"),rule:m.string().optional().describe("remember: the preference in the artist's words; forget: text or number"),topic:m.string().optional().describe("remember: naming, deliverables, render, patch, conform\u2026"),source:m.string().optional().describe("remember: where it came from (default 'told')"),conventions:m.object({program_start:m.string().optional(),end_on_picture:m.boolean().optional(),theatrical_tag:m.string().optional(),no_audio_tag:m.string().optional()}).optional(),profile:m.record(m.string(),m.unknown()).optional().describe("set: the whole profile JSON")},run:async({action:e,path:t,project:n,facility:r,save:o,rule:s,topic:i,source:a,conventions:l,profile:c})=>{try{let u=await mi();switch(e??"get"){case"learn":{if(!t)return ee(new P("invalid_args","learn needs path (a folder of delivered files)"));let d=await Y1(t,{project:n,facility:r,save:o}),p=[`${d.source}${d.saved?` \u2192 saved ${d.saved}`:" (preview, not saved)"}`,...Object.entries(d.learned.templates??{}).map(([f,h])=>` ${f}: ${h}`),...(d.learned.deliverables??[]).map(f=>` usual: ${f.label} (${f.CODEC} ${f.AUDIOCONFIG} .${f.ext}${f.texts.length?`, ${f.texts.join("/")}`:""})`),...Object.entries(d.learned.codec_folders??{}).map(([f,h])=>` folder: ${f}\u2026 \u2192 ${h}`),...d.misfits.length?[` ${d.misfits.length} name(s) follow another pattern: ${d.misfits.slice(0,5).join(", ")}`]:[],...d.name_issues.map(f=>` check ${f.file}: ${f.issues.join("; ")}`),"Ask the artist what files cannot show: is this the usual set, the program start TC, any optional kinds (artist_profile action=remember)."];return Q(p.join(`
|
|
513
|
+
`),{...d})}case"remember":{if(!s&&!l)return ee(new P("invalid_args","remember needs rule or conventions"));s&&(u=Z1(u,{rule:s,topic:i,source:a??"told"})),l&&(u=tg(u,l,a??"told"));let d=await hi(u);return Q(`remembered \u2192 ${d}
|
|
514
|
+
${fi(u)}`,{profile:u,path:d})}case"forget":{if(!s)return ee(new P("invalid_args","forget needs rule (its number or text)"));u=eg(u,/^\d+$/.test(s)?Number(s):s);let d=await hi(u);return Q(`forgotten \u2192 ${d}
|
|
515
|
+
${fi(u)}`,{profile:u,path:d})}case"set":{let d=await hi(c);return Q(`saved \u2192 ${d}`,{path:d})}default:return Q(fi(u),{profile:u})}}catch(u){return ee(u)}}},{name:"naming",title:"The artist's naming: build and check names",description:"The artist's own naming convention (from their artist_profile) for everything conform.tools names: deliverables, patches, timelines, documents, render jobs, folders. There is no built-in convention: with no profile, learn it first (artist_profile action=learn) or ask. Names are copied EXACTLY from the convention (separators, order, spellings). action=get shows the profile; set saves one ({facility, templates: {kind: '[TITLE]_[TEXT]_\u2026'}, values?, codec_folders?}); build makes a name of a kind from values; patch derives a patch's file name, render job name and folder FROM a delivered master's file name (the artist's patch template, their no-audio tag when picture-only, today's date/time, every other element the master's); check validates a name against the template (separators, order), against the file's probe facts (path: codec, raster, rate, color tags, audio channels, the H264_25mbps bitrate) and against the master it patches; legacy operator initials after the date are noted, not required. deliverables expands the artist's usual deliverable set for a program (values: TITLE, COLORSPACE, GAMMA, FORMAT at the OAR) into file names: TEXTLESS only with textless=true (text over picture), optional kinds (UHD H.264) with include_optional. project applies that project's own spellings (profile.projects[PROJECT]: templates/values/deliverables) over the facility's structure.",inputSchema:{action:m.enum(["get","set","build","patch","check","deliverables"]).default("get"),project:m.string().optional().describe("Use this project's spellings (profile.projects[project]) over the facility's"),textless:m.boolean().optional().describe("deliverables: the program has text over picture, so a TEXTLESS version is made"),include_optional:m.boolean().optional().describe("deliverables: include the optional kinds (e.g. UHD H.264)"),profile:m.record(m.string(),m.unknown()).optional().describe("set: the profile JSON"),kind:m.string().optional().describe("build/check: the template kind (deliverable, patch, timeline, replace_list, tracklayout, qc, render_job, deliverables_folder)"),values:m.record(m.string(),m.string()).optional().describe("build: the elements, e.g. {TITLE: 'TRIMBLE', SOURCE: 'TRIMBLE_LP COLOR', PURPOSE: 'ARCHIVAL', SCOPE: 'REPLACE_XD32995'}; YYYYMMDD/HHMM default to now"),name:m.string().optional().describe("check: the name to check"),path:m.string().optional().describe("check: the file the name is for (probed)"),master:m.string().optional().describe("patch/check: the delivered master's file name"),nn:m.number().int().min(1).default(1).describe("patch: the patch number"),text:m.enum(["TEXTED","TEXTLESS"]).optional().describe("patch: the version (default the master's)"),picture_only:m.boolean().default(!0).describe("patch: AUDIOCONFIG = the artist's no-audio tag")},run:async({action:e,profile:t,kind:n,values:r,name:o,path:s,master:i,nn:a,text:l,picture_only:c,project:u,textless:d,include_optional:p})=>{try{let f=await Co(u);switch(e??"get"){case"set":{let h=await hi(t);return Q(`saved the ${t?.facility??""} naming profile \u2192 ${h}`,{path:h})}case"build":{if(!n)return ee(new P("invalid_args","build needs kind"));let h=X1(f,n,{...Q1(),...r});return Q(h,{name:h,kind:n})}case"patch":{if(!i)return ee(new P("invalid_args","patch needs master (a delivered file's name)"));let h=yu(f,i,{nn:a??1,text:l,picture_only:c});return Q([h.file,h.job?`render job: ${h.job}`:"",`folder: ${h.folder}`,...h.warnings.map(g=>`warning: ${g}`)].filter(Boolean).join(`
|
|
516
|
+
`),{...h})}case"check":{if(!o)return ee(new P("invalid_args","check needs name"));let h=Fa(f,o,{kind:n,master:i,probe:s?await st(s):void 0}),g=h.issues.filter(b=>b.level==="error");return Q([`${g.length?"WRONG":"ok"}: ${o} (${f.facility} ${h.kind})`,...h.issues.map(b=>` ${b.level}: ${b.element}: ${b.message}`)].join(`
|
|
517
|
+
`),{...h,ok_name:!g.length})}case"deliverables":{let h=V1(f,r??{},{textless:!!d,include_optional:p});return Q([`${f.facility}${u?` / ${u}`:""} usual deliverables:`,...h.map(g=>` ${g.name} (${g.label}, ${g.text}, ${g.raster}${g.container?" 16x9 container":""}, ${g.audio})`),...d?[]:[" (no TEXTLESS: pass textless=true when the program has text over picture)"]].join(`
|
|
518
|
+
`),{deliverables:h})}default:return Q(Object.keys(f.templates).length?`${f.facility} naming profile
|
|
519
|
+
${JSON.stringify(f,null,2)}`:fi(f),{profile:f})}}catch(f){return ee(f)}}},{name:"media_align",long:!0,title:"Frame offset between a temp and its master",description:"Prove (or find) where a range of file A (the temp / graded reference) sits in file B (the master), frame-exact. Give a_in/a_out (frame or absolute TC in A; default all of A) and b_in, the frame/TC in B the client maps a_in to; without b_in all of B is searched. Checks \xB1search frames (default 12), anchored on shot changes present in both; perceptual (a regrade, a burned-in TC/watermark, a rescale do not move it). Reports overall and per shot: exact / offset N frames (+ = later in B) with a confidence / unverifiable (static picture: the offsets that fit equally) / no match, plus flash-frame risk (a B shot change inside or within 3 frames of the range). Use before replacing a temp with a master on another TC base, and when the client's mapping disagrees with the graded temp.",inputSchema:{a:m.string().describe("The temp / graded reference"),a_in:m.union([m.string(),m.number().int()]).optional(),a_out:m.union([m.string(),m.number().int()]).optional().describe("Last frame included"),b:m.string().describe("The master"),b_in:m.union([m.string(),m.number().int()]).optional().describe("The client's in-point in B for a_in; omit to search"),search:m.number().int().min(1).max(250).optional().describe("\xB1frames checked (default 12)")},run:async({__progress:e,__signal:t,...n})=>{try{let r=await Da({...n,signal:t});return Q(ob(r),{...r})}catch(r){return ee(r)}}},{name:"tool",title:"Tools: the artist's own and the ones that ship, as recipes",description:`Every tool in the conform.tools app is a recipe: typed inputs + nodes wired by reference, each node a block \u2014 a conform.tools verb (verb.<name>), a Resolve call (resolve.pull, resolve.apply, resolve.<edit>), or logic (rows.filter, review, ops.collect, plan.*). Every tool the app ships (${ps.filter(e=>!e.hidden).map(e=>e.name).join(", ")}) and every verb as a one-node tool is an editable default: saving a recipe under a default's id replaces it for this artist, delete puts the default back. Host blocks (host.read, host.apply, host.open, host.render, edit.<op>) take host = resolve | premiere | avid | flame | fcp and work on whichever host's adapter or panel can do it (tool action=blocks says which). action=list (every tool) \xB7 show (id: its recipe) \xB7 blocks (every block with its params, to build with) \xB7 save (spec: a recipe \u2014 {id, name, group?, about?, host?, preview?, inputs:[{id, label, type: text|number|bool|choice|color|marker_color|file|files|folder|rename_steps|track|tracks|timeline|timelines|render_preset|source, choices?:[[value,label]], default?, optional?, when?:{input, is:[\u2026]}}], nodes:[{id, use, args, when?, label?}], view?}; view = the tool's screen when it opens in the app, a split tree {split:'row'|'col', panes:[\u2026], size?} whose leaves are {pane: knobs|viewer|rows|result|compare|graphics|running, show?: '$source'|'$review'|'$result'|'$<node>' (or two for compare), size?: 0\u20131}; leave it out and the app lays the screen out from the steps) \xB7 delete (id: one of the artist's own, or an edited default: back to the default) \xB7 export (ids or id, path: save the recipes out to a .json recipe file to share) \xB7 import (path: a recipe .json file; each tool checked and saved) \xB7 layout (the artist's hidden tools and \u2605 favourites) \xB7 arrange (layout: {hidden?:[ids], favourites?:[tool ids or block uses] | null}: merged in) \xB7 hide / show_tool (id) \xB7 workspace (project_id: the job's tabs \u2014 {open:[tool ids in tabs], source: {host} | {session_id, name?} | {path} | null (the timeline the tools work on)}) \xB7 workspace_save (project_id, workspace: the whole thing; open a tool in a tab for the artist). References in args: "$in.x" an input, "$node" or "$node.a.b" an earlier node's output, "$a|$b" the first that is set; when: "$in.source=file". A review node pauses a run on its rows for the artist's OK. When the artist describes a tool they want, read tool action=blocks, write the recipe, save it, and tell them it is in Tools; run it with tool_run.`,inputSchema:{action:m.enum(["list","show","blocks","save","delete","layout","arrange","hide","show_tool","export","import","workspace","workspace_save"]).default("list"),project_id:m.string().optional().describe("workspace: the project"),workspace:m.record(m.unknown()).optional().describe("workspace_save: {open:[tool ids], source}"),id:m.string().optional(),ids:m.array(m.string()).optional().describe("export: several tools into one file"),path:m.string().optional().describe("export: the .json recipe file to write \xB7 import: the file to read"),spec:m.record(m.unknown()).optional().describe("save: the recipe"),layout:m.record(m.unknown()).optional().describe("arrange: the parts of the layout to change")},run:async({action:e,id:t,ids:n,path:r,spec:o,layout:s,project_id:i,workspace:a})=>{try{if(e==="workspace"||e==="workspace_save"){let c=i||"local",u=e==="workspace_save"?await bs(c,a??{}):await ol(c),d=u?.source?"host"in u.source?`${u.source.host} (live)`:"session_id"in u.source?`timeline ${u.source.name??u.source.session_id}`:u.source.path:"none chosen";return Q(u?`open: ${u.open.join(", ")||"nothing"} \xB7 timeline: ${d}`:"nothing open",{workspace:u})}if(e==="export"){if(!r)return ee(new P("invalid_args","export needs path"));let c=await Oy(n?.length?n:t?[t]:[],r);return Q(`saved ${c.tools.length} tool(s) to ${c.path}`,c)}if(e==="import"){if(!r)return ee(new P("invalid_args","import needs path"));let c=await Ly(r,ed);for(let u of c)(await wr(u.id)).shipped||await nl(u.id);return Q(`imported ${c.map(u=>`'${u.name}' (${u.id})`).join(", ")} \u2014 in Tools`,{tools:c})}if(e==="layout"){let c=await gs();return Q(JSON.stringify(c,null,2),{layout:c})}if(e==="arrange"){let c=await tl(s??{});return Q("layout saved",{layout:c})}if(e==="hide"||e==="show_tool"){if(!t)return ee(new P("invalid_args",`${e} needs id`));let c=await gs(),u=e==="hide"?[...new Set([...c.hidden,t])]:c.hidden.filter(f=>f!==t),d=c.favourites&&e==="hide"?c.favourites.filter(f=>f!==t):c.favourites,p=await tl({hidden:u,favourites:d});return e==="show_tool"&&await nl(t),Q(`${t} ${e==="hide"?"hidden":"shown"}`,{layout:p})}if(e==="blocks"){let c=Qy();return Q(c.map(u=>`- ${u.use}${u.effect?" (changes things)":""}: ${u.about}`).join(`
|
|
520
|
+
`),{blocks:c})}if(e==="save"){let c=await Wu(o,ed);return(await wr(c.id)).shipped||await nl(c.id),Q(`saved tool '${c.name}' (${c.id}) \u2014 it is in Tools; tool_run id=${c.id}`,{tool:c})}if(e==="delete"){if(!t)return ee(new P("invalid_args","delete needs id"));let c=(await Io()).find(u=>u.id===t);return await My(t)?St(c?.shipped?`${t} is back to the default`:`deleted ${t}`):ee(new P("not_found",`${t} is not one of your tools, nor an edited default (a default as it ships can be hidden: action=hide)`))}if(e==="show"){if(!t)return ee(new P("invalid_args","show needs id"));let c=await wr(t);return Q(JSON.stringify(c,null,2),{tool:c})}let l=await Io();return Q(l.map(c=>`- ${c.id}: ${c.name} [${c.group}]${c.template?" (default)":c.shipped?" (default, edited)":" (yours)"}${c.hidden?" (hidden)":""} \u2014 ${c.about.split(". ")[0]}`).join(`
|
|
521
|
+
`),{tools:l})}catch(l){return ee(l)}finally{["save","delete","import","arrange","hide","show_tool"].includes(e)&&rg().catch(()=>{})}}},{name:"tool_run",long:!0,title:"Run a tool, and the job's runs: what is waiting for an OK, apply, undo",description:"Run a tool (tool action=list) with its inputs: {id, inputs} \u2014 on top of the settings the artist left in its tab in this job (app action=state shows them), so 'run it' runs what they see. When it reaches a review it stops and answers state=review with the rows and a run_id: show the artist the rows, then action=apply (run_id, and keep:[row ids] or drop:[row ids or 1-based row numbers]; neither = every row). Every run is shared with the app: a run you start shows in that tool's tab in the artist's window, and a review the artist has open in a tab is yours to read (action=list), apply or drop. action=list (project_id?, id?: the job's runs, newest first \u2014 waiting reviews with their rows, results, what can be undone) \xB7 csv (path, run_id? | id? | table: the rows it shows, a review's or the result's table, as a .csv) \xB7 apply (run_id?, keep? | drop?: no run_id = the job's latest review, that tool's with id) \xB7 drop (leave a review without applying) \xB7 undo (run_id?: put back what a run changed; none = the job's latest run that can be undone). preview=true runs only up to the first review or the first node that changes anything (nothing changes). Answers state=done with the result (and undo_id when the host can put it back), and sessions: each step that made a timeline \u2192 its session_id. until = a node id: run only what that node needs and answer its output (the tool editor's Run on a node). A `source` input takes a timeline already read (a host.read answer, or {session_id}); left out, the tool reads its host's open timeline. project_id: the job (default: the open one).",inputSchema:{action:m.enum(["run","list","apply","drop","undo","csv"]).default("run"),id:m.string().optional().describe("run: the tool \xB7 list / apply / undo: only that tool's runs"),spec:m.record(m.unknown()).optional().describe("a recipe to run without saving it (the builder's Try it)"),inputs:m.record(m.unknown()).default({}),preview:m.boolean().default(!1),run_id:m.string().optional().describe("apply / drop / undo: the run (its id, or its review's run_id)"),keep:m.array(m.string()).optional().describe("apply: exactly these review rows"),drop:m.array(m.union([m.string(),m.number().int()])).optional().describe("apply: every row but these (row ids, or 1-based row numbers)"),until:m.string().optional().describe("a node id: run only what it needs, answer its output"),path:m.string().optional().describe("csv: the .csv file to write"),table:m.object({rows:m.array(m.object({id:m.string(),cells:m.record(m.unknown())})),columns:m.array(m.array(m.string()).length(2))}).optional().describe("csv: these rows instead of a run's (the window's own preview, which is not a recorded run)"),session_id:m.string().optional().describe("csv to a .html path: the session the rows' clips are in; each row (id = its item) gets its clip's picture"),project_id:m.string().optional().describe("the job (default: the job open in the app / the current project)"),by:m.string().optional().describe("who is asking (the app window says 'app'; default 'assistant')")},protectedStages:["canonicalize","write"],run:async({action:e,id:t,spec:n,inputs:r,preview:o,run_id:s,keep:i,drop:a,until:l,path:c,table:u,session_id:d,project_id:p,by:f,__signal:h,__progress:g})=>{try{let b=p||(await xo())?.id||"local",k={signal:h,progress:g,tool:wr,until:l};if(e==="list"){let $=Go(b,t);return Q($.length?$.slice(0,20).map(x=>Cm(x)).join(`
|
|
522
|
+
`):"no runs in this job yet",{runs:$})}if(e==="csv"){if(!c)return ee(new P("invalid_args","csv needs a path"));let $=u?{name:t??"rows",state:{state:"done",ok:!0,text:"",table:u}}:s?oa(s):Go(b,t)[0];if(!$)return ee(new P("not_found","no run to save (run the tool first)"));let x=R_($);if(x===null)return ee(new P("not_found",`${$.name}: this run has no rows to save`));if(/\.html?$/i.test(c)){let C=new Map,B=u?.rows??[];for(let[L,Z]of B.entries()){if(!d||h?.aborted)break;g?.(L,B.length,"pictures");let O=(await nn("timeline_frame").run({session_id:d,item_id:Z.id,width:160}).catch(()=>null))?.structuredContent?.out_path;O&&await Ye(O)&&C.set(Z.id,`data:image/png;base64,${To(await Ut(O))}`)}return await Ke(mt(c),$_($,C)),Q(`${$.name}: ${B.length} row(s), ${C.size} with a picture, saved to ${c}`,{path:c})}let R=/\.json$/i.test(c)&&u?JSON.stringify(u.rows.map(C=>C.cells),null,2):null;return await Ke(mt(c),R??x),Q(`${$.name}: ${x.split(`
|
|
523
|
+
`).length-1} row(s) saved to ${c}`,{path:c})}if(e==="drop"){let $=x_(b,{id:s,tool:t});return Q(`left ${$.name}'s review; nothing applied`,{run:$})}if(e==="undo"){let $=await S_(b,{id:s,tool:t},async(x,R)=>{let C=[],B=!0;for(let L of x.split("+").reverse()){let Z=L.startsWith("files-")?await Po("media_move",{undo:L}):await Po("host_apply",{undo:L,...R&&!x.includes("+")?{timeline:R}:{}});B&&=!Z.isError,C.push(Z.content.map(X=>X.text).join(`
|
|
524
|
+
`))}return{ok:B,text:C.join(`
|
|
525
|
+
`)}});return Q(`${$.name}: ${$.undone}`,{run:$})}let w={project:b,by:f||"assistant"},y,_;if(e==="apply"||s)({run:y,state:_}=await T_(b,{id:s,tool:t,name:t?await wr(t).then($=>$.name,()=>{}):void 0,keep:i,drop:a,by:w.by,inputs:r},k));else{let $=n?Ti.parse(n):await wr(String(t??""));w.by==="app"&&await Nh($.id);let x=await ol(b);if(!n&&x?.settings[$.id]&&w.by!=="app"){let R={...x.settings[$.id],...r};r=Object.fromEntries(Object.entries(R).filter(([C,B])=>{let L=$.inputs.find(Z=>Z.id===C);return B!==""&&B!=null&&!(Array.isArray(B)&&!B.length)&&(!L?.when||L.when.is.includes(String(R[L.when.input]??"")))}))}$.inputs.some(R=>R.type==="source")&&r.source===void 0&&x?.source&&"session_id"in x.source&&(r={...r,source:{session_id:x.source.session_id}}),{run:y,state:_}=await v_($,r,w,{...k,preview:o})}let v=_.state==="review"?`${_.label}: ${_.rows.length} row(s) waiting for the artist's OK (in the ${y?.name??"tool"} tab too) \u2014 tool_run action=apply run_id=${_.run_id} [keep | drop]`:_.state==="ready"?`ready to run: next is ${_.label}, which changes things`:_.text,T={..._,...y?{run:{id:y.id,tool:y.tool,status:y.status}}:{}};return _.state==="done"&&!_.ok?ee(new P("engine",v)):Q(v,T)}catch(b){return ee(b)}}},{name:"app",title:"The app window: open a tool for the artist (settings filled in), its timeline, Home",description:"Drive the conform.tools app the artist has open, the way they would by hand. Everything here is saved with the job (its workspace), so it holds when the window opens later; a window that is open follows at once. action=state (project_id?: the job's open tabs, its timeline, each tool's settings, runs waiting for an OK) \xB7 open (tool, settings?, source?: open that tool's tab with these settings filled in \u2014 what the artist asked for, ready to Run; the rest stay at their defaults; source = its timeline) \xB7 close (tool) \xB7 timeline (source: {host: resolve|premiere|avid|flame|fcp} live | {session_id, name?} a timeline in the job | {path} a file; with tool: that tool's own timeline (each tab picks its own), without: the job's, which a tool takes until it has its own and when it works in that app) \xB7 home (back to Home). Every tool is listed in the window's sidebar. To run a tool, review and apply: tool_run (its runs show in the tool's tab). SEE AND USE THE WINDOW ITSELF (testing, or doing what the artist would): ui (what the window shows right now, as data: the view and tool, every control by its label with its value / on / disabled, each field's value, the tables shown (columns + rows), the result card, errors, and layout problems: text cut off, a box scrolling sideways, anything past the edge) \xB7 press (target: a control's label, exact or the start of it; nth when several share it: presses it like a click, answers what the window shows after) \xB7 set (target: a field's label; value: types it in like the artist, answers the field after) \xB7 console (target?: a regex: the window's last logs, warnings and errors) \xB7 shot (a picture of the window as it looks now; macOS). Needs the window open.",inputSchema:{action:m.enum(["state","open","close","timeline","home","ui","press","set","console","shot","ui_answer","reveal"]).default("state"),path:m.string().optional().describe("reveal: a file or folder to show in Finder / Explorer"),target:m.string().optional().describe("press / set: the control's or field's label as the window shows it; console: only lines matching this regex"),value:m.unknown().optional().describe("set: what to put in the field"),nth:m.number().int().positive().optional().describe("press / set: the nth control with that label (default 1)"),req_id:m.string().optional().describe("ui_answer: the window's own reply (not for callers)"),answer:m.record(m.unknown()).optional().describe("ui_answer: the window's own reply (not for callers)"),project_id:m.string().optional().describe("the job (default: local, the one the window works in)"),tool:m.string().optional().describe("open / close: the tool id (tool action=list)"),settings:m.record(m.unknown()).optional().describe("open: the tool's inputs to fill in, by input id"),source:m.record(m.unknown()).optional().describe("timeline / open: {host} | {session_id, name?} | {path}")},run:async({action:e,project_id:t,tool:n,settings:r,source:o,target:s,value:i,nth:a,req_id:l,answer:c,path:u})=>{try{if(e==="reveal"){if(!u)return ee(new P("invalid_args","reveal needs a path"));let g=mt(u),b=Xt(),k=b==="darwin"?await sn("open",["-R",g]):b==="win32"?await sn("explorer.exe",[`/select,${g}`]):await sn("xdg-open",[g.replace(/[\\/][^\\/]*$/,"")||g]);return k.success||b==="win32"?Q(`shown: ${g}`):ee(new P("not_found",k.stderr.trim()||`could not show ${g}`))}let d=t||"local";if(e==="ui_answer")return Ry(String(l??""),c??{}),Q("thanks");if(e==="shot")return await AD();if(e==="ui"||e==="press"||e==="set"||e==="console"){if(!hs())throw new P("not_found","the app window is not open: open conform.tools first");if(e!=="ui"&&!s)throw new P("invalid_args",`${e} needs target (a label the window shows: app action=ui lists them)`);let g=await $y(d,{op:e,...s?{target:s}:{},...i!==void 0?{value:i}:{},...a?{nth:a}:{}}),b=String(g.text??"");return g.ok===!1?ee(new P("not_found",b||`nothing called "${s}" on screen`,g)):Q(b,g)}let p=async()=>await ol(d)??rl.parse({}),f=g=>{if(!n)throw new P("invalid_args",`${g} needs tool`);return n},h=()=>hs()?"":" (the app window is not open: it shows when it opens)";if(e==="state"){let g=await p(),b=Go(d).filter(_=>_.status==="review"),k=g.source?"host"in g.source?`${g.source.host} (live)`:"session_id"in g.source?`timeline ${g.source.name??g.source.session_id}`:g.source.path:"none chosen",w=hs()?Sy():null,y=w?` \xB7 the artist is looking at ${w.project!==d?`job ${w.project}, `:""}${w.view==="tool"&&w.tool?`the ${w.tool} tab`:"Home"}`:"";return Q([`job ${d} \xB7 tabs: ${g.open.join(", ")||"none"} \xB7 timeline: ${k}${hs()?y:" \xB7 the window is not open"}`,...Object.entries(g.sources).map(([_,v])=>`${_} timeline: ${JSON.stringify(v)}`),...Object.entries(g.settings).filter(([_])=>g.open.includes(_)).map(([_,v])=>`${_} settings: ${JSON.stringify(v).slice(0,400)}`),...b.map(_=>Cm(_,10))].join(`
|
|
526
|
+
`),{workspace:g,waiting:b,window_open:hs()>0,front:w})}if(e==="open"){let g=await wr(f("open")),b=await Io(),k=_=>/\$in\.(\w+)=([\w-]+)$/.exec((_??"").trim()),w=b.find(_=>!_.hidden&&_.id!==g.id&&_.nodes.some(v=>v.use===`tool.${g.id}`&&k(v.when)));if(w){let[,_,v]=k(w.nodes.find(T=>T.use===`tool.${g.id}`).when);r={[_]:v,...Object.fromEntries(Object.entries(r??{}).map(([T,$])=>[T==="source"?T:`${v}_${T}`,$]))},g=w}let y=await p();if(r){let _=new Set(g.inputs.map(T=>T.id)),v=Object.keys(r).filter(T=>!_.has(T));if(v.length)throw new P("invalid_args",`${g.name} has no setting ${v.join(", ")} (it has ${[..._].join(", ")})`)}return await bs(d,{...y,open:[g.id],settings:r?{...y.settings,[g.id]:{...Ey(g),...r}}:y.settings,sources:o?{...y.sources,[g.id]:o}:y.sources}),Wr({type:"open",project:d,tool:g.id}),Q(`opened ${g.name}${r?` with ${Object.entries(r).map(([_,v])=>`${_}=${JSON.stringify(v)}`).join(", ")}`:""}${h()}`,{tool:g.id})}if(e==="close"){let g=await p();return await bs(d,{...g,open:g.open.filter(b=>b!==f("close"))}),Q(`closed ${n}`)}if(e==="timeline"){if(!o)throw new P("invalid_args","timeline needs source");let g=await p();if(n){let k=await wr(n),w=await bs(d,{...g,sources:{...g.sources,[k.id]:o}});return Q(`${k.name}'s timeline is ${JSON.stringify(w.sources[k.id])}${h()}`,{tool:k.id,source:w.sources[k.id]})}let b=await bs(d,{...g,source:o});return Q(`the job's timeline is ${JSON.stringify(b.source)}${h()}`,{source:b.source})}return e==="home"?(Wr({type:"home",project:d}),Q(`Home${h()}`)):ee(new P("invalid_args",`unknown action ${e}`))}catch(d){return ee(d)}}},{name:"job_status",hidden:!0,title:"Status of a background job",description:"Status, phase and progress of a job started with background=true (auto conform, deliver, consolidate), and its result once finished.",inputSchema:{job_id:m.string()},run:async({job_id:e})=>{let t=await fy(e);if(!t)return ee(new P("not_found",`no job ${e}`));let n=qu(t);return t.status==="done"&&t.result?Q(`${n}
|
|
527
|
+
|
|
528
|
+
${t.result.content.map(r=>r.text).join(`
|
|
529
|
+
`)}`,{job:t,result:t.result.structuredContent??null}):Q(n,{job:t})}},{name:"job_cancel",hidden:!0,title:"Cancel a background job",description:"Cancel a running background job. Partial outputs already written stay on disk and are named in the job's result.",inputSchema:{job_id:m.string()},run:async({job_id:e})=>Bu(e)?Q(`cancelling ${e}`,{job_id:e}):ee(new P("not_found",`no running job ${e}`))},{name:"job_list",hidden:!0,title:"List jobs",description:"Recent background jobs (running and finished) with status and progress.",inputSchema:{},run:async()=>{let e=await hy();return Q(e.length?e.map(qu).join(`
|
|
530
|
+
`):"(no jobs)",{jobs:e})}},{name:"job",title:"Background jobs: status, cancel, list",description:"Jobs started with background=true (auto conform, deliver, consolidate, peer-to-peer serving). action=status (job_id): status, phase, progress and, once finished, its result \xB7 cancel (job_id): stop it; partial outputs already written stay on disk and are named in its result \xB7 list: recent jobs, running and finished.",inputSchema:{action:m.enum(["status","cancel","list"]).default("status"),job_id:m.string().optional()},run:async({action:e,job_id:t})=>e==="list"?nn("job_list").run({}):t?nn(e==="cancel"?"job_cancel":"job_status").run({job_id:t}):ee(new P("invalid_args",`action=${e} needs job_id`))}],vD=new Set(["account_login","account_status","account_logout","account_telemetry","timeline_routes","feedback","find_verb","begin","finish"]),TD=/^(account_|feedback$|report|job|conform_learn$|find_verb$|begin$|finish$|script_(run|read)$)/;async function h$(){let e=await Io().catch(()=>[]);return[...ys.filter(t=>!TD.test(t.name)).map(t=>({id:t.name,title:t.title,text:[t.description,...Object.values(t.inputSchema).map(n=>n.description??"")].join(" ")})),...e.filter(t=>t.group!=="API"&&!t.part).map(t=>({id:`tool:${t.id}`,title:t.name,text:t.about,aka:t.aka}))]}var ya={timeline_query:"out_path"};function xD(e,t){if(e!=="timeline_write"||typeof t.target!="string")return[];let n=t.target.trim().toLowerCase();if(Su(n))return[`target=${n}`];try{return[`target=${qa(n)}`]}catch{return[]}}function g$(e,t){return e!=="tool_run"&&e!=="tool"?[]:typeof t.id!="string"?[]:[`tool=${ps.some(n=>n.id===t.id)&&/^[a-z0-9_.-]{1,40}$/.test(t.id)?t.id:"custom"}`]}function b$(e,t){if(e==="tool_run"&&(t.action==null||t.action==="run")){let r=((typeof t.id=="string"?ps.find(o=>o.id===t.id):void 0)?.nodes??[]).map(o=>String(o.use??"")).filter(o=>/^[a-z_]+\.[a-z0-9_]+$/.test(o)).map(o=>o.startsWith("verb.")?`await ct.${o.slice(5)}()`:`${o}()`);return r.length?r.join("; "):null}return e!=="script_run"&&e!=="script_read"||typeof t.code!="string"?null:t.code.slice(0,8e3)}function y$(e){let t=e==="script_read",n=(o,s)=>ks.has(o)||o in ya&&s[ya[o]]==null,r=(o,s={})=>!!nn(o)&&!w$.test(o)&&(!t||n(o,s));return{name:e,title:t?"Run a script of conformtools calls that only read":"Run a script of conformtools calls",description:(t?"script_run for jobs that only read (probe every clip, inspect a cut, QC each file): its scripts can call only tools that change nothing, so clients run it without asking first. Same arguments and answer as script_run. ":"The way to do a job with the fewest tokens: one TypeScript script instead of a call per step (read a cut, probe or relink every clip, QC each one, report only the failures). The in-between answers stay inside the script, never in your context; only what it returns comes back, in one round trip and one approval. Only reading? script_read is the same and runs without asking in more clients. ")+"Every conformtools tool is `await ct.<tool>(args)` with the tool's own arguments; it resolves to the tool's answer ({ok, text, ...its fields}) and throws an Error (e.code, e.verb) when the tool fails. The code is the body of an async function: await, loops, Promise.all, try/catch; `return` the answer, console.log lines come back too. Return only what the user needs: a few fields, or `r.text` (the tool's own short summary) when you do not know its fields; never whole answers. Sandboxed: no files, network or processes except through ct.*. types = tool names answers with their TypeScript declarations (arguments, and the answer's fields once a script here has seen them) and runs nothing: ask it first when unsure of a tool's fields.",inputSchema:{code:m.string().max(1e5).optional().describe('The script: the body of an async function, e.g. `const r = await ct.timeline_read({ path: "~/cut.aaf" }); return r.summary;`'),path:m.string().optional().describe("A saved script (.ts) to run instead of code"),save_as:m.string().regex(/^[\w.-]{1,64}$/).optional().describe("Also keep the script in the current project's scripts/ folder under this name; run it again later with path"),types:m.array(m.string()).max(20).optional().describe("Tool names whose ct.* TypeScript declarations to answer with; nothing runs")},long:!0,run:async({code:o,path:s,save_as:i,types:a,__signal:l,__progress:c})=>{if(a?.length){let y=a.filter(v=>!r(v));if(y.length)return ee(new P("not_found",`no tool ${y.join(", ")} for scripts`));let _=await k$();return Q(b_(a.map(v=>nn(v)),Object.fromEntries(Object.entries(_).map(([v,T])=>[v,ea(T)]))))}if(!o?.trim()&&!s?.trim())return ee(new P("invalid_args","no script given: pass code (the body of an async function, e.g. `return (await ct.timeline_read({ path })).text`) or path (a saved .ts script)"));if(o?.trim()&&s?.trim())return ee(new P("invalid_args","give code (the script) or path (a saved .ts script), not both"));let u=o?.trim()?o:await ct(s);if(i){let y=re(tt(),"projects",(await xo())?.id??"local","scripts");await Ve(y),await Ke(re(y,i.endsWith(".ts")?i:`${i}.ts`),u)}let d=await k$(),p=[],f=async(y,_)=>{if(!r(y,_))throw new P("not_found",t&&nn(y)&&!w$.test(y)?y in ya?`${y} with ${ya[y]} writes a file: leave ${ya[y]} out in script_read, or use script_run`:`${y} changes things: script_read calls only tools that read; use script_run`:`no tool ${y} for scripts`);let v=OD(y,_),T=v.ok?await Po(y,v.data,{signal:l}):v.result,$=T.structuredContent??{},x=T.content.map(L=>L.text).join(`
|
|
531
|
+
`);if(T.isError)throw new P($.code??"engine",String($.message??x));let R={ok:!0,...$,text:x},C=d[y],B=Zi(C??"null",nc(R));return JSON.stringify(B)!==JSON.stringify(C)&&(d[y]=B,p.includes(y)||p.push(y)),R},h;try{h=await p_(u,f,{signal:l,onCall:(y,_)=>c?.(y,0,`ct.${_}`)})}catch(y){return ee(y)}let g=h.value===void 0?"":typeof h.value=="string"?h.value:JSON.stringify(h.value,null,1),b=new Map;for(let y of h.calls)b.set(y,(b.get(y)??0)+1);let k=[...b].map(([y,_])=>`${y}${_>1?` \xD7${_}`:""}`).join(", "),w=[g.length>yh?`${g.slice(0,yh)}
|
|
532
|
+
\u2026 (${g.length-yh} more characters cut: return less, or a summary)`:g||"(the script returned nothing)",...h.logs.length?["console:",...h.logs]:[],`${h.calls.length} call${h.calls.length===1?"":"s"}${k?`: ${k}`:""}${i?` \xB7 saved as scripts/${i}`:""}`,...p.length?["answer fields (beside ok and text), for the next script:",...p.map(y=>`ct.${y} \u2192 ${ea(d[y])}`)]:[]];return p.length&&await Ke(T$(),JSON.stringify(d)).catch(()=>{}),Q(w.join(`
|
|
533
|
+
`),{calls:h.calls.length})}}}var w$=/^(account_(login|logout|telemetry)|script_(run|read)|begin|finish)$/,T$=()=>re(tt(),"script-shapes.json"),k$=async()=>{try{return JSON.parse(await ct(T$()))}catch{return{}}},yh=2e4,ks=new Set(["account_status","conform_learn","find_verb","begin","finish","timeline_read","host_project","timeline_inspect","timeline_routes","timeline_sessions","host_items","media_probe","media_find","media_coverage","timeline_judge","timeline_autoconform","job_status","job_list","patch_plan","patch_verify","media_align","media_cuts","qc_media","media_sync","qc_blanking","gfx_fonts","script_read"]),SD=new Set(["account_login","account_logout","account_telemetry","feedback","job","timeline_query","host_current","host_open","host_setup","timeline_edit","timeline_autoconform_review","timeline_author","timeline_generate","timeline_relink","project","project_link","color_match","color_prep","color_lut","job_cancel","naming","artist_profile","media_frame","timeline_frame","timeline_align","tool","app"]);function CK(e){return{readOnlyHint:ks.has(e),destructiveHint:!ks.has(e)&&!SD.has(e)}}var $D={asked:m.string().optional().describe("First call after each user message only: the user's message exactly as they wrote it (never reworded, shortened or with anything replaced: names and paths stay); start with [solved], [partly] or [failed: why] for the request before (solved = the user got what they asked for; blocked, refused or a workaround is partly or failed)")},RD={background:m.boolean().default(!1).describe("Return a job id immediately; follow it with job action=status, cancel with job action=cancel")},x$=e=>({...$D,...e.long?RD:{},...e.inputSchema}),_$=new Set(["timeline_id","path","media_reference_id","media_reference","source_start","source_duration","at_frame","track_id","fit","without_audio"]);async function CD(e,t){let n=Object.keys(t).filter(u=>!_$.has(u));if(n.length)throw new P("refused",`add_clip does not take ${n.join(", ")}; it takes ${[..._$].filter(u=>u!=="media_reference").join(", ")} (path = a file to probe; media_reference_id = a reference already in the session, from timeline_query table=media)`);if(typeof t.path!="string"||!t.path){if(t.media_reference_id)return t;throw new P("refused","add_clip needs path (the media file to cut in)")}let{path:r,...o}=t,s=await st(mt(r)),i=e.media_references??[],a=i.find(u=>u.target_url===s.target_url);if(a)return{...o,media_reference_id:a.id};let l=s.id,c=2;for(;i.some(u=>u.id===l);)l=`${s.id} (${c++})`;return{...o,media_reference_id:l,media_reference:{...s,id:l}}}async function AD(){if(Xt()!=="darwin")throw new P("unsupported","shot is macOS only for now");let t=(await sn("osascript",["-l","JavaScript","-e","ObjC.import('CoreGraphics');function run(a){const w=ObjC.castRefToObject($.CGWindowListCopyWindowInfo(17,0)).js.find((d)=>d.js.kCGWindowOwnerPID.js===+a[0]&&d.js.kCGWindowLayer.js===0);return w?String(w.js.kCGWindowNumber.js):''}",String(xh())])).stdout.trim();if(!t)throw new P("not_found","no app window on screen (this engine is not the app's, or its window is closed or minimised)");let n=await It("ct-shot-"),r=re(n,"window.png");try{let o=await sn("screencapture",["-x","-o",`-l${t}`,r]);if(!o.success||!await Ye(r))throw new P("refused",`screencapture could not take the window: allow Screen Recording for conform.tools (System Settings \u203A Privacy & Security). ${o.stderr.trim()}`);return await sn("sips",["-Z","1600",r]),{...Q(`the window as it looks now (window ${t})`),images:[{data:To(await Ut(r)),mimeType:"image/png"}]}}finally{await dn(n)}}async function Po(e,t,n={}){let r=nn(e);if(!r)return ee(new P("not_found",`unknown verb '${e}'`));let o=e==="script_run"||e==="script_read"||e==="tool_run"&&!n.client&&(t.action==null||t.action==="run"),s=Lb(t.asked,o);if(!("asked"in r.inputSchema)){let{asked:d,...p}=t;t=p}if(e==="finish"&&s&&typeof t.outcome=="string"&&Object.assign(s,{previous:t.outcome,previous_why:typeof t.why=="string"?t.why:null}),!vD.has(e))try{await Lh()}catch(d){let p=ee(d);return Ga(e,p,0,Object.keys(t),{request:s,client:n.client}),p}let i=MD(t),a=await ED(i);if(a)return ee(new P("refused_overwrite",`refused: ${a.arg} is ${a.path}, the file this call reads from. conform.tools never writes over a source: write beside it under a new name (cut_v2.xml, or a folder), and the user replaces the original if they want to.`));let l=t.engine==="local"||t.engine==="hosted"?t.engine:void 0,c=()=>a1.run({verb:e,declared:r.protectedStages??[]},()=>FD(r,e,i,n,s)),u=l?await l1.run(l,c):await c();return r.long&&i.background||(dy(i,u,ks.has(e)),pu(e,i,u),Fu(e,i,u,S$)),PD(e,u)}var v$=["out_path","output_path","csv_path","edl_path"];async function ED(e){let t=s=>s.replace(/[\\/]+$/,""),n=v$.filter(s=>typeof e[s]=="string"&&e[s]);if(!n.length)return null;let r=new Set([...$$].filter(s=>!v$.includes(s)).flatMap(s=>[e[s]].flat()).filter(s=>typeof s=="string"&&!!s).map(t));if(typeof e.session_id=="string"){let s=(await ft(e.session_id).catch(()=>null))?.source_path;s&&r.add(t(s))}let o=n.find(s=>r.has(t(e[s])));return o?{arg:o,path:e[o]}:null}var S$=async(e,t)=>(await nn("timeline_diff").run({a:e,b:t})).content.map(n=>n.text).join(`
|
|
534
|
+
`),$$=new Set(["path","paths","out_path","out_dir","media_root","reference","pool","source_path","output_path","plate","render","target_dir","media_dirs","a","b","edl_path","csv_path","patch","master","credits_path","images_dir","look_path","fonts","destination_root","export_dir","grades_dir"]);function MD(e){let t={...e};for(let n of $$){let r=t[n];n==="reference"&&(r==="auto"||r==="ai")||(typeof r=="string"&&r?t[n]=mt(r):Array.isArray(r)&&(t[n]=r.map(o=>typeof o=="string"&&o?mt(o):o)))}return t}var ID={timeline_read:"conform",host_current:"conform",timeline_relink:"conform",timeline_write:"conform",timeline_autoconform:"autoconform",media_consolidate:"deliver",media_deliver:"deliver"};function PD(e,t){let n=ID[e];return!n||t.isError||Rb()?t:{...t,content:[...t.content,{type:"text",text:`Next: call conform_learn task=${n} (with the hosts involved) before going further, and follow the playbook it returns.`}]}}async function FD(e,t,n,r,o){let s=performance.now(),i=async(l,c)=>{let u=Math.round(performance.now()-s),d=l.content.map(f=>f.text).join(`
|
|
535
|
+
`),p=typeof n.session_id=="string"?n.session_id:d.match(/session_id: (\w+)/)?.[1];return await r1({ts:new Date().toISOString(),verb:t,ms:u,ok:!l.isError,code:l.isError?String(l.structuredContent?.code??"engine"):void 0,msg:l.isError?d.slice(0,500):void 0,...c.withArgs?{args:n1(n)}:{},job:c.job,session:p,note:c.note}),u},a=async(l,c)=>{let u=await i(l,{job:c,withArgs:!0}),d=(t==="find_verb"||t==="begin")&&Array.isArray(l.structuredContent?.hits)?l.structuredContent.hits:void 0;return!(e.long&&n.background)&&!r.poll&&r0(t,n,l,u,r.client),e.long&&n.background||Ga(t,l,u,[...Object.keys(n),...kD(e.inputSchema,n),...g$(t,n),...xD(t,n)],{request:o,hits:d,client:r.client,poll:r.poll,script:b$(t,n)}),l};if(e.long){let{background:l,...c}=n,u=t==="tool_run"&&typeof c.id=="string"?(await wr(c.id).catch(()=>null))?.name??c.id:e.title,d=yi(t,async(p,f)=>await e.run({...c,__signal:f,__progress:l||!r.progress?p:(h,g,b)=>{p(h,g,b),r.progress(h,g,b)}}),u);return l||r.signal?.addEventListener("abort",()=>Bu(d.id),{once:!0}),l?(Du(d.id)?.then(async p=>{pu(t,c,p),Fu(t,c,p,S$),Ga(t,p,await i(p,{job:d.id,note:"job finished"}),[...Object.keys(c),...g$(t,c)],{request:o,client:r.client,script:b$(t,c)})}),a(Q(`started ${d.id} (${t}) \u2014 poll job action=status`,{job_id:d.id}),d.id)):a(await Du(d.id),d.id)}try{return await a(await e.run(n))}catch(l){return a(ee(l))}}function OD(e,t){let n=nn(e);if(!n)return{ok:!1,result:ee(new P("not_found",`unknown verb '${e}'`))};let r=m.object(x$(n)).safeParse(t??{});if(r.success)return{ok:!0,data:r.data};Pu(e,Ha(r.error.issues));let o=r.error.issues.map(s=>`${s.path.join(".")||"(args)"}: ${s.message}`).join("; ");return{ok:!1,result:ee(new P("invalid_args",o,{fields:Ha(r.error.issues)}))}}function AK(e,t){let n=nn(e)?.inputSchema.session_id;return(t??{}).session_id===void 0&&n&&!n.isOptional()?Yh():void 0}function EK(e,t){let n=nn(e);if(!n)return;let r=m.object(x$(n)).safeParse(t??{});r.success||Pu(e,Ha(r.error.issues))}var R$=_D.filter(e=>!e.repoOnly||xa),ys=R$.filter(e=>!e.hidden);function nn(e){return ys.find(t=>t.name===e)??R$.find(t=>t.name===e)}export{sR as a,XD as b,QD as c,YD as d,jD as e,fy as f,Bu as g,hy as h,CK as i,x$ as j,Po as k,OD as l,AK as m,EK as n,ys as o,nn as p};
|