conformtools 0.6.11 → 0.6.13
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 +15 -1
- package/dist/{account-IUWNSDG5.js → account-F54SG45Q.js} +1 -1
- package/dist/agent-hook-setup-RTQT5JEN.js +3 -0
- package/dist/{analysis-engine-M7W32RRC.js → analysis-engine-UWIK7AYB.js} +1 -1
- package/dist/{bridge-SV7PCLQY.js → bridge-PWYOJ7E7.js} +1 -1
- package/dist/browser/timeline_core_bg.wasm +0 -0
- package/dist/{chunk-2WBGXD27.js → chunk-4BTTR6U3.js} +2 -2
- package/dist/{chunk-NSQP6CTA.js → chunk-4VFDGL4E.js} +1 -1
- package/dist/{chunk-THVX57I3.js → chunk-6WLSIH2N.js} +1 -1
- package/dist/{chunk-DGXZB7MO.js → chunk-7W5AFZYX.js} +1 -1
- package/dist/chunk-B54TEGMG.js +5 -0
- package/dist/chunk-BTS3DFPD.js +7 -0
- package/dist/chunk-BYMCZJBQ.js +3 -0
- package/dist/{chunk-64X5DLH5.js → chunk-EP4L2BWV.js} +1 -1
- package/dist/chunk-ERUN634Q.js +6 -0
- package/dist/{chunk-6HZP2OJA.js → chunk-G3HBKJ5L.js} +1 -1
- package/dist/{chunk-IK6RKNS5.js → chunk-H4BU5WA6.js} +1 -1
- package/dist/{chunk-XIAG7ACN.js → chunk-I2Y2P5NH.js} +2 -2
- package/dist/{chunk-2CY2OOOJ.js → chunk-J43UCJ6G.js} +1 -1
- package/dist/chunk-L3HRAIDR.js +8 -0
- package/dist/chunk-LKQTE6T5.js +158 -0
- package/dist/chunk-LRGA6QJQ.js +514 -0
- package/dist/{chunk-JXTRQ3UG.js → chunk-LZRCXSUJ.js} +1 -1
- package/dist/chunk-NZLL44HU.js +3 -0
- package/dist/chunk-OD445COC.js +7 -0
- package/dist/chunk-XI6XF7FQ.js +3 -0
- package/dist/{chunk-6VP6G7CY.js → chunk-Y455Y6V4.js} +4 -4
- package/dist/{claude-setup-REU4AOKX.js → claude-setup-NGZ5NDYH.js} +1 -1
- package/dist/cli.js +9 -9
- package/dist/engine-6ACEWA4S.js +5 -0
- package/dist/framing-P5RGN5V3.js +3 -0
- package/dist/gfx-worker.js +1 -1
- package/dist/{h264-B2TLLEMI.js → h264-JI62TU4W.js} +1 -1
- package/dist/{h264-mxf-3GED5PBT.js → h264-mxf-J2QPZO4U.js} +1 -1
- package/dist/hook.js +3 -0
- package/dist/host-relink-76CFY32O.js +10 -0
- package/dist/hosted-L26AGRIY.js +3 -0
- package/dist/hosts-TBHEPV6A.js +3 -0
- package/dist/http.js +3 -3
- package/dist/{inspect-RJFJQSHZ.js → inspect-U656APGR.js} +2 -2
- package/dist/{isobmff-C5A2EFKH.js → isobmff-UISATYUR.js} +1 -1
- package/dist/{mc-video-ARKIHPA7.js → mc-video-LSTKUKNL.js} +1 -1
- package/dist/mcp.js +8 -7
- package/dist/{media-22VAJIVT.js → media-XBNKYKB7.js} +1 -1
- package/dist/mxf-ZL57VJ3C.js +3 -0
- package/dist/{ops-BCTGDBXT.js → ops-ZQEQXW2N.js} +1 -1
- package/dist/probe-ZDX6XNRF.js +3 -0
- package/dist/{r3d-FX7V4BIE.js → r3d-R4TLYJVE.js} +1 -1
- package/dist/resolve-bridge.py +31 -2
- package/dist/{sequence-patch-CN4VC5W3.js → sequence-patch-C2QRIT5V.js} +1 -1
- package/dist/store-JNWELX35.js +3 -0
- package/dist/timeline-JONFBIA3.js +3 -0
- package/package.json +5 -5
- package/dist/chunk-2QT5MMBP.js +0 -499
- package/dist/chunk-5YWO2LBG.js +0 -3
- package/dist/chunk-6NLB5TZ2.js +0 -7
- package/dist/chunk-G3SZDPDS.js +0 -3
- package/dist/chunk-RKIRHMON.js +0 -5
- package/dist/chunk-ROPKSAFP.js +0 -6
- package/dist/chunk-S6KP52OG.js +0 -8
- package/dist/chunk-VE423Z2L.js +0 -132
- package/dist/chunk-XF3YMBI7.js +0 -3
- package/dist/engine-274GQLUB.js +0 -5
- package/dist/framing-ZTMYZR2S.js +0 -3
- package/dist/host-relink-FHNXXMHW.js +0 -10
- package/dist/hosted-BWAYLJXR.js +0 -3
- package/dist/hosts-Y6HGDRLM.js +0 -3
- package/dist/mxf-CQSI6H5T.js +0 -3
- package/dist/probe-72QZKMCC.js +0 -3
- package/dist/store-H676BOKI.js +0 -3
- package/dist/timeline-5TGA5HBY.js +0 -3
- /package/dist/{still-WUCFH2WX.js → still-4UR35GZH.js} +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
-
import{a as L}from"./chunk-
|
|
3
|
+
import{a as L}from"./chunk-H4BU5WA6.js";import{A as R,C as W,D as I,aa as P,m as _,r as C,x as N,z as O}from"./chunk-XI6XF7FQ.js";import X from"node:http";import{connect as Y}from"node:net";import{createHash as M,randomBytes as U}from"node:crypto";import{Buffer as d}from"node:buffer";var j="258EAFA5-E914-47DA-95CA-C5AB0DC85B11";function A(a,e,c=!1){let n=e.length,r=c?128:0,s=n<126?d.from([128|a,r|n]):n<65536?d.from([128|a,r|126,n>>8,n&255]):(()=>{let o=d.alloc(10);return o[0]=128|a,o[1]=r|127,o.writeBigUInt64BE(BigInt(n),2),o})();if(!c)return d.concat([s,d.from(e)]);let t=U(4),i=d.from(e);for(let o=0;o<i.length;o++)i[o]^=t[o&3];return d.concat([s,t,i])}function D(a,e,c,n=!1){let r=d.alloc(0),s=[],t=0,i=!1,o=[],p=[],u=()=>{i||(i=!0,p.forEach(l=>l()))},f=(l=1e3,g="")=>{if(i)return;let h=d.from(g),m=d.alloc(2+h.length);m.writeUInt16BE(l,0),h.copy(m,2);try{a.write(A(8,m,n))}catch{}a.end(),u()};return a.on("data",l=>{for(r=d.concat([r,l]);r.length>=2;){let g=(r[0]&128)!==0,h=r[0]&15,m=(r[1]&128)!==0,v=r[1]&127,w=2;if(v===126){if(r.length<4)return;v=r.readUInt16BE(2),w=4}else if(v===127){if(r.length<10)return;let b=r.readBigUInt64BE(2);if(b>BigInt(c))return f(1009,"too big");v=Number(b),w=10}if(m===n)return f(1002,n?"server frames must not be masked":"client frames must be masked");if(v>c||t+v>c)return f(1009,"message too big");let T=m?4:0;if(r.length<w+T+v)return;let S=d.from(r.subarray(w+T,w+T+v));if(m){let b=r.subarray(w,w+4);for(let x=0;x<S.length;x++)S[x]^=b[x&3]}if(r=r.subarray(w+T+v),h===8)return f(1e3);if(h===9){a.write(A(10,S,n));continue}if(h!==10){if(h===1||h===0){if(s.push(S),t+=S.length,g){let b=d.concat(s).toString("utf8");s=[],t=0,o.forEach(x=>x(b))}continue}return f(1003,"text frames only")}}}),a.on("close",u),a.on("error",u),{origin:e,send:l=>{i||a.write(A(1,d.from(l,"utf8"),n))},close:f,onMessage:l=>{o.push(l)},onClose:l=>{p.push(l)}}}function J(a,e){let c=new Set,n=X.createServer((r,s)=>{let t=n.address();a.onHttp?.(r,s,typeof t=="object"&&t?t.port:a.port)||(s.writeHead(426,{"content-type":"text/plain"}),s.end("websocket only"))});return n.on("upgrade",(r,s)=>{let t=r.headers["sec-websocket-key"];if(r.url?.split("?")[0]!==a.path||typeof t!="string"||String(r.headers.upgrade).toLowerCase()!=="websocket"){s.end(`HTTP/1.1 400 Bad Request\r
|
|
4
4
|
\r
|
|
5
5
|
`);return}let i=M("sha1").update(t+j).digest("base64");s.write(`HTTP/1.1 101 Switching Protocols\r
|
|
6
6
|
Upgrade: websocket\r
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
-
import{c as u,d as y,f as w,g as h}from"./chunk-LVGGCRDW.js";import{a as f,d as p}from"./chunk-
|
|
3
|
+
import{c as u,d as y,f as w,g as h}from"./chunk-LVGGCRDW.js";import{a as f,d as p}from"./chunk-OD445COC.js";import{a}from"./chunk-PHAMF4JF.js";import{b as g}from"./chunk-XI6XF7FQ.js";u(!0);var b={aaf:"aaf",avb:"avb",prproj:"prproj",drt:"resolve-drt",otio:"otio",capcut:"capcut",flame:"flame-archive",fcpxml:"resolve-fcpxml",xmeml:"fcp-xml",blscene:"baselight-blscene"},R=Object.keys(b),v=new Set([502,503,504,529,546]),d=(e,o)=>`${f().supabaseUrl}/functions/v1/${e}${o}`;async function m(){let e=await p();if(!e&&g("CONFORM_ANONYMOUS_READ")==="1")return f().anonKey;if(!e)throw new a("not_signed_in","reading and writing timelines runs on conform.tools \u2014 sign in first (account_login)");return e}async function S(e,o){let t;for(let n=0;n<3;n++){try{let i=await fetch(e,o);if(!v.has(i.status)||n===2)return i;t=new Error(`status ${i.status}`)}catch(i){if(t=i,n===2)break}await new Promise(i=>setTimeout(i,1500*(n+1)))}throw new a("offline",`conform.tools is unreachable (${t instanceof Error?t.message:String(t)}) \u2014 reading and writing timelines need the network`)}async function _(e,o){let n=(await e.json().catch(()=>({})))?.error?.message??`${o} failed (${e.status})`;throw e.status===401?new a("not_signed_in",`${n} \u2014 sign in again (account_login)`):e.status===402||e.status===403?new a("not_entitled",n):new a(e.status>=500?"engine":"refused",n)}async function P(e,o){let t=b[e];if(!t)throw new a("unsupported",`'${e}' timelines are not read by conform.tools yet`);let{fmt:n,extract:i}=await y(o,t),c=JSON.stringify({format:n,source_filename:o.name,persist:!1})+`
|
|
4
4
|
`+(typeof i=="string"?i:JSON.stringify(i)),s=await S(d("v1-timeline-canonicalize","/v1/timeline-canonicalize"),{method:"POST",headers:{"content-type":"application/x-ct-canonicalize-v1",authorization:`Bearer ${await m()}`,apikey:f().anonKey},body:c});s.ok||await _(s,"read");let l=await s.json();return JSON.stringify(l.session)}async function N(e,o){let t=await S(d("v1-write","/v1/write"),{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${await m()}`,apikey:f().anonKey,"x-engine-accept-delivery":"cdn"},body:JSON.stringify({target_format:e,session:o})});t.ok||await _(t,"write");let n=h(t.headers.get(w))??[];if(t.headers.get("x-engine-delivery")==="cdn"){let r=await t.json(),c=await fetch(r.download_url);if(!c.ok)throw new a("engine",`download failed (${c.status})`);let s=new Uint8Array(await c.arrayBuffer());if(s.byteLength!==r.size)throw new a("engine",`download incomplete: ${s.byteLength} of ${r.size} bytes`);return{body:s,contentType:r.content_type,filenameSuggestion:r.filename,issues:n,serverSession:r.session_id??void 0}}let i=t.headers.get("content-disposition")?.match(/filename="([^"]+)"/)?.[1];return{body:new Uint8Array(await t.arrayBuffer()),contentType:t.headers.get("content-type")??"application/octet-stream",filenameSuggestion:i??`timeline.${e}`,issues:n,serverSession:t.headers.get("x-session-id")??void 0}}async function j(e,o,t){try{let n={"content-type":"application/json",authorization:`Bearer ${await m()}`,apikey:f().anonKey},i=k=>d("v1-sessions",`/v1/sessions/${encodeURIComponent(e)}/original${k}`),r=await fetch(i(""),{method:"POST",headers:n,body:JSON.stringify({filename:o,content_type:"application/octet-stream"})});if(!r.ok)return!1;let{key:c,upload:s}=await r.json();return(await fetch(s.url,{method:s.method??"PUT",headers:s.headers??{"content-type":"application/octet-stream"},body:t})).ok?(await fetch(i("/complete"),{method:"POST",headers:n,body:JSON.stringify({key:c})})).ok:!1}catch{return!1}}export{R as a,P as b,N as c,j as d};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
-
import{d as _}from"./chunk-
|
|
3
|
+
import{d as _}from"./chunk-LZRCXSUJ.js";function l(f){let m=[...f].sort((s,t)=>s.first_frame-t.first_frame),e=[];for(let s of m){let t=e[e.length-1];t&&s.first_frame<=t.last_frame+1?t.last_frame=Math.max(t.last_frame,s.last_frame):e.push({...s})}return e}async function g(f,m,e){let s=l(f),t=l(f.map(r=>({first_frame:Math.max(0,r.first_frame-m),last_frame:r.last_frame+m}))),n=[];for(let r of t)try{n.push(await e(r.first_frame,r.last_frame+1))}catch(o){let i=_(o)?.file_frames,u=s.filter(a=>a.last_frame>=r.first_frame&&a.first_frame<=r.last_frame);if(i==null||r.last_frame+1<=i||u.some(a=>a.first_frame<0||a.last_frame+1>i))throw o;n.push(await e(r.first_frame,i))}return n}export{l as a,g as b};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
+
import{Jb as S,Kb as L,Lb as A,Mb as E,Nb as P,Ob as T,Pb as M,Qb as D,Rb as N,Sb as z,Tb as I,wb as R}from"./chunk-LKQTE6T5.js";import{a as w}from"./chunk-PHAMF4JF.js";import{Z as l,s as j}from"./chunk-XI6XF7FQ.js";async function K(r,t){let d=t.media_root?[t.media_root]:await N();if(!d.length)throw new w("invalid_args","no media_root given and no remembered locations \u2014 pass the folder to link from");for(let e of d)try{if(!(await j(e)).isDirectory)throw 0}catch{throw new w("invalid_args",`media_root is not a folder on this machine: ${e}`)}let i=L(r,{ref_ids:t.ref_ids,lane:t.lane,reset:t.reset});if(!i.length)return{session:r,changed:!1,note:"",text:"nothing in scope: every reference in scope is already linked (use reset=true to re-point) or the ids/lane matched nothing"};if(t.reset)for(let e of i)e.binding_state="unbound",delete e.coverage_reason;let h=[],b=!1,m=[];for(let e of d)if(t.gather==="path")for(let n of i){let c=n.local_path??n.target_url??"",o=c?await E(e,c):null;o?h.push(o):m.push(`${n.id} ${l(c)}: not at its recorded path under ${e}`)}else{let n=await A(e,i,t.cap);h.push(...n.paths),b||=n.capped}let{refs:_,failed:u}=await P([...new Set(h)]);t.remember&&t.media_root&&await z(t.media_root);let k=new Set(i.map(e=>e.id)),p=R(r,_,k);if(p.splits.length){r=p.session;let e=new Set([...k,...p.splits.flatMap(n=>n.into)]);i=(r.media_references??[]).filter(n=>e.has(n.id));for(let n of p.splits){let c=o=>l(i.find(B=>B.id===o)?.target_url??o);m.push(`split ${n.ref_id} across ${n.into.length} section file(s): ${n.into.map(c).join(", ")}`)}}let a=S(t.criteria),s=T(r,i,_,a,t.tolerances),O=t.criteria?.picture?await M(r,s):[],y=[`scope: ${i.length} reference(s)${t.lane!=="both"?` (${t.lane} lane)`:""}${t.ref_ids?` (zone of ${t.ref_ids.length})`:""}; gather=${t.gather} under ${d.join(", ")}: ${_.length} candidate clip(s)${b?` (CAPPED at ${t.cap} \u2014 narrow the folder)`:""}`,`criteria: ${[...Object.entries(a).filter(([,e])=>e===!0).map(([e])=>e),...t.criteria?.picture?["picture"]:[]].join(", ")}${a.fileName?` (${a.fileNameMode})`:""}${a.fileExtensions?`; ext ${a.fileExtensions}`:""}; timecode containment + fps always on`,...u.length?[`could not probe ${u.length}: ${u.slice(0,5).join("; ")}`]:[],...m.slice(0,20),...O.slice(0,40)];if(t.dry_run)return{session:r,changed:!1,note:"",text:[...y,I(r,s,{compare:t.compare}),"(dry run \u2014 nothing changed; pass accept=[{ref_id,candidate_id}] to commit chosen rows, or run again without dry_run to apply every matched row)"].join(`
|
|
4
|
+
`)};let f,g=[];if(t.accept?.length){f=[];for(let e of t.accept){let n=s.rows.find(o=>o.ref_id===e.ref_id);n&&(n.candidate?.id===e.candidate_id||n.alternatives.some(o=>o.id===e.candidate_id))?f.push(e):g.push(`${e.ref_id} \u2192 ${e.candidate_id}: not a proposed match or alternative for that reference`)}}else f=s.rows.filter(e=>e.status==="matched"&&e.candidate).map(e=>({ref_id:e.ref_id,candidate_id:e.candidate.id}));let $=D(r,s,f),v=$.session.media_references??[],x=v.filter(e=>i.some(n=>n.id===e.id)&&e.binding_state==="linked").length,U=$.applied,C=v.filter(e=>i.some(n=>n.id===e.id)&&e.binding_state!=="linked").map(e=>` - ${e.id} ${l(e.target_url??"")}: ${e.coverage_reason??(s.rows.find(n=>n.ref_id===e.id)?.status==="ambiguous"?"ambiguous \u2014 pick one with accept":"no file matched")}`),q=[...y,`Linked ${x} of ${i.length}${g.length?`; ${g.length} pick(s) vetoed`:""}`,...U.map(e=>`- ${e.ref_id}: ${l(e.before.path??"?")} \u2192 ${e.after.path}${e.warning?` \u26A0 ${e.warning}`:""}`),...g.map(e=>` \u2717 ${e}`),...C.length?["unresolved:",...C]:[]].join(`
|
|
5
|
+
`);return{session:$.session,changed:!0,note:`relink ${t.gather} ${d[0]} (${x}/${i.length})`,text:q}}export{K as a};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
+
import{A as w,E as y,a as h,aa as c,m as x,n as k,t as u,x as C,z as A}from"./chunk-XI6XF7FQ.js";var O=new Set(["ffmpeg","ffprobe","ffplay","sox","soxi","mediainfo","exiftool","mkvmerge","mkvextract","mp4box","bmxtranswrap","raw2rgb","redline","art-cmd","oiiotool","iconvert","idiff","asdcp-wrap","asdcp-unwrap","asdcp-info","opendcp","dcp_inspect","handbrakecli","gst-launch-1.0","mencoder","mplayer","sips","afconvert","avconvert","qtfaststart","mediaconch","bwfmetaedit","x264","x265","aomenc","svtav1encapp","otiotool","otioconvert","otioview","cineform","ale2csv"]),I=["mov","mp4","m4v","mxf","mkv","avi","webm","mts","m2ts","mpg","mpeg","r3d","braw","ari","arx","crm","dng","dpx","exr","wav","aif","aiff","bwf","flac","mp3","aac","m4a","caf"],N=["aaf","avb","edl","drt","otio","fcpxml","fcpxmld","prproj","ptx","ale","xml","csv"],U=new Set(["xml","csv","png","jpg","jpeg","tif","tiff"]),L=new Set([...I,...N,...U]);var m="conformtools-hook",d=o=>o&&typeof o=="object"&&!Array.isArray(o)?o:{},g=o=>!!o&&typeof o=="object"&&typeof o.command=="string"&&o.command.includes(m);function $(o,e,t={}){let n=d(o.hooks),r=Array.isArray(n.PostToolUse)?[...n.PostToolUse]:[],s={type:"command",command:e,timeout:10,...t.async?{async:!0}:{}};for(let i=0;i<r.length;i++){let a=d(r[i]),l=Array.isArray(a.hooks)?a.hooks:[],f=l.findIndex(g);if(f<0)continue;if(JSON.stringify(l[f])===JSON.stringify(s)&&a.matcher==="Bash")return{settings:o,result:"kept"};let b=[...l];return b[f]=s,r[i]={...a,matcher:"Bash",hooks:b},{settings:{...o,hooks:{...n,PostToolUse:r}},result:"updated"}}return{settings:{...o,hooks:{...n,PostToolUse:[...r,{matcher:"Bash",hooks:[s]}]}},result:"installed"}}function S(o){let e=d(o.hooks);if(!Array.isArray(e.PostToolUse))return{settings:o,removed:!1};let t=!1,n=e.PostToolUse.map(i=>{let a=d(i);if(!Array.isArray(a.hooks))return i;let l=a.hooks.filter(f=>!g(f));return l.length!==a.hooks.length&&(t=!0),l.length?{...a,hooks:l}:null}).filter(i=>i!==null);if(!t)return{settings:o,removed:!1};let r={...e};n.length?r.PostToolUse=n:delete r.PostToolUse;let s={...o};return Object.keys(r).length?s.hooks=r:delete s.hooks,{settings:s,removed:!0}}function T(o,e,t){let n=d(o.hooks),r=Array.isArray(n.afterShellExecution)?[...n.afterShellExecution]:[],s={command:e,timeout:10,matcher:t},i=r.findIndex(g);return i>=0&&JSON.stringify(r[i])===JSON.stringify(s)?{settings:o,result:"kept"}:(i>=0?r[i]=s:r.push(s),{settings:{version:1,...o,hooks:{...n,afterShellExecution:r}},result:i>=0?"updated":"installed"})}function P(o){let e=d(o.hooks);if(!Array.isArray(e.afterShellExecution))return{settings:o,removed:!1};let t=e.afterShellExecution.filter(s=>!g(s));if(t.length===e.afterShellExecution.length)return{settings:o,removed:!1};let n={...e};t.length?n.afterShellExecution=t:delete n.afterShellExecution;let r={...o};return Object.keys(n).length?r.hooks=n:delete r.hooks,{settings:r,removed:!0}}function E(){return`\\b(${[...O].map(e=>e.replace(/[.+-]/g,"\\$&")).join("|")})\\b|\\.(${[...L].join("|")})\\b`}function F(o){let e=(o??"").toLowerCase();return e?e.includes("claude-code")||e.includes("claude code")?"claude":e.includes("codex")?"codex":e.includes("cursor")?"cursor":null:null}var J=["claude","codex","cursor"],p=()=>({claude:c(k(),".claude","settings.json"),codex:c(k(),".codex","hooks.json"),cursor:c(k(),".cursor","hooks.json")});async function M(){let o=new URL(import.meta.url),e=h(new URL("./hook.js",o));if(await u(e)){await w(x());let n=c(x(),`${m}.js`);return await y(e,n),`node "${n}"`}let t=h(new URL("../adapters/hook.ts",o));return await u(t)?`deno run --allow-read --allow-write --allow-env --no-check --unstable-sloppy-imports "${t}" ${m}`:null}async function v(o){if(!await u(o))return{};let e=await C(o);try{return e.trim()?JSON.parse(e):{}}catch{return"invalid"}}async function j(o,e){let t;return await u(o)?(t=`${o}.conformtools-backup`,await y(o,t)):await w(c(o,"..")),await A(o,JSON.stringify(e,null,2)+`
|
|
4
|
+
`),t}async function B(o,e={}){let t=e.file??p()[o];try{let n=e.command??await M();if(!n)return{client:o,file:t,result:"skipped",detail:"no hook script beside this build"};let r=await v(t);if(r==="invalid")return{client:o,file:t,result:"failed",detail:`${t} is not valid JSON; nothing was changed`};let s=o==="cursor"?T(r,n,E()):$(r,n,{async:o==="codex"});if(s.result==="kept")return{client:o,file:t,result:"kept"};let i=await j(t,s.settings);return{client:o,file:t,result:s.result,backup:i}}catch(n){return{client:o,file:t,result:"failed",detail:n instanceof Error?n.message:String(n)}}}async function z(o,e={}){let t=e.file??p()[o],n=await v(t);if(n==="invalid")return{client:o,file:t,removed:!1};let r=o==="cursor"?P(n):S(n);if(!r.removed)return{client:o,file:t,removed:!1};let s=await j(t,r.settings);return{client:o,file:t,removed:!0,backup:s}}async function R(){let o=p(),e=[];for(let t of J)await u(c(o[t],".."))&&e.push(t);return e}var Z=async()=>Promise.all((await R()).map(o=>B(o))),G=async()=>Promise.all((await R()).map(o=>z(o)));async function D(o,e=p()[o]){let t=await v(e);return t!=="invalid"&&JSON.stringify(t).includes(m)}var H={claude:"Claude Code",codex:"Codex",cursor:"Cursor"},_="which other programs the agent ran on media or timeline files (program names and file extensions only; never a command, a path, a name, a prompt or an output)";function q(o){return o.length?o.map(e=>{let t=H[e.client],n={installed:`${t}: agent hook installed in ${e.file}${e.backup?` (backup: ${e.backup})`:""}`,updated:`${t}: agent hook refreshed in ${e.file}`,kept:`${t}: agent hook already in ${e.file}`,skipped:`${t}: agent hook not installed (${e.detail})`,failed:`${t}: agent hook not installed: ${e.detail}`}[e.result];return e.client==="codex"&&(e.result==="installed"||e.result==="updated")?`${n}; Codex asks you to trust it once (/hooks)`:n}).concat(`It records ${_}. conformtools hooks off removes it; conformtools telemetry off removes it with the rest.`).join(`
|
|
5
|
+
`):"Agent hook: no Claude Code, Codex or Cursor folder on this machine; nothing to install."}function Q(o){let e=o.filter(t=>t.removed);return e.length?e.map(t=>`${H[t.client]}: agent hook removed from ${t.file}`).join(`
|
|
6
|
+
`):"Agent hook: not installed anywhere on this machine."}async function V(){let o=await R();return o.length?[...await Promise.all(o.map(async t=>`${H[t]}: agent hook ${await D(t)?"on":"off"} (${p()[t]})`)),`It records ${_}. conformtools hooks on|off.`].join(`
|
|
7
|
+
`):"Agent hook: no Claude Code, Codex or Cursor folder on this machine."}export{F as a,J as b,p as c,M as d,B as e,z as f,R as g,Z as h,G as i,D as j,_ as k,q as l,Q as m,V as n};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
+
import{Wc as d}from"./chunk-LKQTE6T5.js";import{A as p,D as m,aa as f,m as c,x as u,z as l}from"./chunk-XI6XF7FQ.js";import o from"node:process";import{readFileSync as g,rmSync as h}from"node:fs";import{createConnection as w}from"node:net";var x=new Set(["tool_run","app","tool"]),s=()=>f(c(),"engine.json");async function I(e,r){await p(c()),await l(s(),JSON.stringify({port:e,token:r||void 0,pid:o.pid})),await m(s(),384);for(let t of["SIGINT","SIGTERM"])o.on(t,()=>o.exit(0));o.on("exit",()=>{try{JSON.parse(g(s(),"utf8")).pid===o.pid&&h(s())}catch{}})}function S(e,r=1500){return new Promise(t=>{let n=w({host:"127.0.0.1",port:e}),i=y=>{clearTimeout(a),n.destroy(),t(y)},a=setTimeout(()=>i(!1),r);n.once("connect",()=>i(!0)).once("error",()=>i(!1))})}async function O(e,r){if(!x.has(e))return null;let t;try{t=JSON.parse(await u(s()))}catch{return null}if(t.pid===o.pid||!await S(t.port))return null;let n;try{n=await fetch(`http://127.0.0.1:${t.port}/verbs/${e}`,{method:"POST",body:JSON.stringify(r),headers:{"content-type":"application/json","x-conform-client":d()??"mcp",...t.token?{authorization:`Bearer ${t.token}`}:{}}})}catch{return null}if(n.status===401||n.status===404)return null;let{text:i,...a}=await n.json();return{content:[{type:"text",text:i??""}],structuredContent:a,isError:!n.ok}}export{I as a,O as b};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
-
import{a as E}from"./chunk-PHAMF4JF.js";import{
|
|
3
|
+
import{a as E}from"./chunk-PHAMF4JF.js";import{R as x,b as y,f as g,g as f,j as w,k as h,r as p,u as b}from"./chunk-XI6XF7FQ.js";async function k(){let e=f()==="win32"?"conformtools-analyze.exe":"conformtools-analyze",r=[y("CONFORM_ANALYZE"),w(e),p(new URL(`./${e}`,import.meta.url)),p(new URL(`../../rust/target/release/${e}`,import.meta.url))].filter(Boolean);for(let n of r)if(await b(n))return n;return null}var R=e=>e.code==="not_entitled"?new E("not_entitled",String(e.why)):void 0;async function A(e){let r=await P(),n=await r.ask({op:"job",reference:e.reference,clips:e.clips,lite:e.lite??!0,display:!!e.display});if(!n.ok)throw r.close(),R(n)??new Error(`analysis engine: ${n.why}`);return r}async function N(e,r,n){let i=await P(),t=()=>i.close();n?.addEventListener("abort",t);let s;try{s=await i.ask(e,r)}finally{n?.removeEventListener("abort",t),i.close()}if(n?.aborted)throw new Error("cancelled");if(!s.ok)throw R(s)??new Error(s.why??`the analysis engine could not run ${e.op}`);return s}async function P(){let e=await k();if(!e)throw new Error(h("the analysis engine (conformtools-analyze)"));let r="",n=null,i=[],t=x(e,["serve"],o=>{r+=new TextDecoder().decode(o);let a;for(;(a=r.indexOf(`
|
|
4
4
|
`))>=0;){let c=r.slice(0,a);r=r.slice(a+1);let l=JSON.parse(c);if(l.progress){n?.progress?.(l.progress[0],l.progress[1],l.phase??"");continue}let d=n;n=null,d?.done(l)}},o=>{console.error(o.trimEnd()),i=[...i,...o.split(`
|
|
5
5
|
`).filter(a=>a.trim())].slice(-3)}),s=null;t.exited.then(o=>{s={ok:!1,why:`the analysis engine exited${o==null?"":` (code ${o})`}${i.length?`: ${i.join(" | ").slice(0,400)}`:""}`},n?.done(s)});let m=Promise.resolve();return{ask:(o,a)=>{let c=m.then(async()=>{t.hold(!0);try{if(s)return s;let l=new Promise(v=>{n={done:v,progress:a}}),u=await t.write(new TextEncoder().encode(JSON.stringify(o)+`
|
|
6
6
|
`)).then(()=>!0,()=>!1)?await l:await Promise.race([l,t.exited.then(()=>s??{ok:!1,why:"the analysis engine exited"})]);return u.miss&&(console.error(`[mirror] MISS \u2014 ${u.miss} is not in the mirror. Replay never reads the source drive; record this case again with the drive mounted (CONFORM_MIRROR_MODE=record).`),g(75)),u}finally{t.hold(!1)}});return m=c.catch(()=>{}),c},close:()=>t.close()}}export{k as a,A as b,N as c,P as d};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
+
import{Ub as D,Vb as F,Wb as N}from"./chunk-LKQTE6T5.js";import{i as j}from"./chunk-4VFDGL4E.js";import{$ as k,A as M,E as C,G as R,H as T,K as q,L,O as w,Z as b,aa as _,ca as I,g as y,m as O,r as S,s as A,t as x,u as P,x as H,z as E}from"./chunk-XI6XF7FQ.js";var B=16e3,h=class extends Error{constructor(t,i){super(i);this.code=t}},$=class d{constructor(e,t=j,i=B){this.spec=e;this.bridge=t;this.waitMs=i;this.renders=new Map;this.host=e.host,e.items&&(this.items=n=>this.modelItems(n??{}))}async peer(){let e=await(await this.bridge()).waitFor(this.host,this.waitMs);if(!e)throw new h("not_connected",`${this.host}: the conform.tools plugin in ${this.spec.label} is not connected. ${this.spec.setup}`);return e}async needs(e){let t=await this.peer();if(!t.capabilities.includes(e))throw new h("panel_old",`${this.host}: the conform.tools plugin open in ${this.spec.label} ${t.version||""} has no ${e} (an older plugin); update it (${this.spec.setup})`);return t}async ask(e,t={},i){return await this.peer(),await(await this.bridge()).request(this.host,e,t,i)}static{this.announced=(e,t)=>e.optional_verbs.includes(t)}async support(){let e={ok:!1,reason:"the renderplugin is a DaVinci Resolve plugin"},t;try{t=await(await this.bridge()).waitFor(this.host,Math.min(3e3,this.waitMs))}catch(s){let a={ok:!1,reason:s instanceof Error?s.message:String(s)};return{export:a,open:a,render:a,markers:a,renderplugin:e}}if(!t){let s={ok:!1,reason:`the conform.tools plugin in ${this.spec.label} is not connected`,setup:this.spec.setup};return{export:s,open:s,render:s,markers:s,renderplugin:e}}let i=(s,a)=>s?{ok:!0}:{ok:!1,reason:`this plugin version has no ${a}`},n=t.capabilities;return{export:i(n.includes("timeline_read")||n.includes("timeline_write"),"timeline_read"),open:i(d.announced(t,"timeline_write.import_file"),"timeline_write.import_file"),render:i(n.includes("render"),"render"),markers:i(n.includes("markers"),"markers"),renderplugin:e}}async current(){let e=await this.ask("session.current_project");if(!e)return{project:"",timelines:[],timeline:""};let t=await this.ask("session.timeline_count",{project:e}),i=[];for(let s=1;s<=t;s++){let a=await this.ask("session.timeline_by_index",{project:e,index:s});a&&i.push(await this.ask("session.name",{handle:a}))}let n=await this.ask("session.current_timeline",{project:e});return{project:await this.ask("session.name",{handle:e}),timelines:i,timeline:n?await this.ask("session.name",{handle:n}):""}}async project(e={}){let t=await this.current();return{project:t.project,timeline:e.timeline??t.timeline,timelines:t.timelines,tracks:[],jobs:[],found:{},pool:{path:"",clips:0,folders:[]}}}async sequence(e){let t=await this.ask("session.current_project");if(!t)throw new h("no_project",`${this.host}: no project is open`);if(!e){let s=await this.ask("session.current_timeline",{project:t});if(!s)throw new h("no_timeline",`${this.host}: no timeline is active`);return{project:t,seq:s,name:await this.ask("session.name",{handle:s})}}let i=await this.ask("session.timeline_count",{project:t}),n=[];for(let s=1;s<=i;s++){let a=await this.ask("session.timeline_by_index",{project:t,index:s});if(!a)continue;let p=await this.ask("session.name",{handle:a});if(p===e)return{project:t,seq:a,name:p};n.push(p)}throw new h("not_found",`${this.host}: no timeline named "${e}" (have: ${n.join(", ")})`)}async model(e){let{project:t,seq:i}=await this.sequence(e);return await this.ask("timeline_read.model",{timeline:i,project:t},12e4)}async export(e){if(!e.out_path)throw new h("usage",`${this.host}: export needs out_path`);let t=await this.peer(),{project:i,seq:n,name:s}=await this.sequence(e.timeline),a=await this.ask("session.name",{handle:i}),p=r=>d.announced(t,r),m=e.out_path,c,l=[];if(p("timeline_write.export_otio")||p("timeline_write.export_xml")){let r=p("timeline_write.export_otio"),o=await this.ask(r?"timeline_write.export_otio":"timeline_write.export_xml",{project:i,timeline:n,path:e.out_path},12e4);if(c=o.format??(r?"otio":"xmeml"),o.ok===!1)throw new h("export_failed",`${this.host}: ${this.spec.label} did not write ${e.out_path}${o.errors?.length?` (${o.errors.join("; ")})`:""}`);o.path&&o.path!==e.out_path&&(m=await this.adopt(o.path,e.out_path)),l=o.warnings??[]}else if(p("timeline_read.export_file")){let r=await this.ask("timeline_read.export_file",{timeline:n,fmt:"otio",path:e.out_path},12e4);if(!r)throw new h("export_failed",`${this.host}: ${this.spec.label} exported no OTIO`);c="otio",r!==e.out_path&&(m=await this.adopt(r,e.out_path))}else{await this.needs("timeline_read");let r=await this.ask("timeline_read.model",{timeline:n,project:i},12e4),o=J(r);await E(e.out_path,JSON.stringify(o.otio)),c="otio",l=o.notes}if(!D.includes(c))throw new h("export_failed",`${this.host}: ${this.spec.label} exported ${c}, which the engine does not read (${m})`);if(!await P(m)||(await A(m)).size===0)throw new h("export_failed",`${this.host}: ${this.spec.label} did not write ${m}`);return{path:m,format:c,project:a,timeline:s,...l.length?{notes:l}:{}}}async adopt(e,t){let i=k(e)&&k(e)!==k(t)?t.slice(0,t.length-k(t).length)+k(e):t;if(await C(e,i),!F(i))throw new h("export_failed",`${this.host}: ${this.spec.label} exported ${b(e)}, which the engine does not read`);return i}async open(e){if(e.into==="scratch")throw new h("unsupported",`${this.host}: opening into a scratch project is not supported; the import lands in the open project`);let t=await this.peer();if(!d.announced(t,"timeline_write.import_file"))throw new h("unsupported",`${this.host}: this conform.tools plugin cannot import timelines (${this.spec.setup})`);let i=await this.ask("session.current_project");if(!i)throw new h("no_project",`${this.host}: no project is open`);let n=await this.ask("timeline_write.import_file",{project:i,path:e.path,sequences:null},3e5);if(!n.ok)throw new h("import_failed",`${this.host}: ${this.spec.label} did not import ${e.path}${n.issues?.length?` (${n.issues.join("; ")})`:""}`);let s=[...n.issues??[]];return n.imported.length>1&&s.push(`imported ${n.imported.length} timelines: ${n.imported.map(a=>a.name).join(", ")}`),e.name&&s.push(`${this.spec.label} names imported timelines after the file's own; name was not applied`),e.media_dirs?.length&&s.push(`${this.spec.label} links media from the paths in the file; media_dirs was not used (relink with timeline_relink before writing)`),{project:await this.ask("session.name",{handle:i}),timeline:n.imported[0]?.name??b(e.path),notes:s,restored:!e.stay,...n.bin?{folder:n.bin}:{}}}async modelItems(e){let t=await this.model(e.timeline),i=[...e.kind==="audio"?[]:t.items.map(n=>({kind:"video",track:n.track,start:n.start-t.start_frame,end:n.end-t.start_frame,id:n.handle?.$h??n.clip_id??"",name:n.name??"",color:n.color??"",flags:n.flags??[],enabled:n.enabled??!0,file:n.file_path})),...e.kind==="video"?[]:(t.audio_items??[]).map(n=>({kind:"audio",track:n.track,start:n.start-t.start_frame,end:n.end-t.start_frame,id:"",name:n.name??"",file:n.file_path??""}))].filter(n=>e.track===void 0||n.track===e.track);return{project:(await this.current()).project,timeline:t.timeline,start_frame:t.start_frame,fps:t.fps,items:i,color_groups:[],layers:1}}async apply(e){let t=e.ops.length>0&&e.ops.every(l=>l.op==="timeline_rename"&&(l.timeline||l.guid)),{project:i,seq:n,name:s}=await this.sequence(t?void 0:e.timeline),a=[],p=[],m=l=>l.op.startsWith("marker_")&&!l.item;for(let l=0;l<e.ops.length;){let r=l;for(;r<e.ops.length&&m(e.ops[r])===m(e.ops[l]);)r++;let o=e.ops.slice(l,r),u=m(o[0])?await this.markerOps(n,o):await this.clipOps(n,o,e.timeline);a.push(...u.results),p.unshift(...u.undo),l=r}let c=a.filter(l=>l.ok).length;return{project:await this.ask("session.name",{handle:i}),timeline:s,results:a,undo:p,applied:c,failed:a.length-c}}async clipOps(e,t,i){let n=await this.peer();if(n.capabilities.includes("edit"))return await this.ask("edit.apply",{timeline:e,ops:t},6e4+t.length*500);let s=(l,r)=>({op:l.op,ok:!1,detail:r});if(!n.capabilities.includes("item_meta"))return{results:t.map(l=>s(l,`${this.host}: clip edits are not reachable over this plugin`)),undo:[]};let a=await this.model(i),p=l=>l?"id"in l?{$h:l.id}:(l.kind??"video")!=="video"?null:a.items.find(r=>r.track===l.track&&r.start-a.start_frame===l.start)?.handle??null:null,m=[],c=[];for(let l of t){let r=p(l.item);try{if(!r)m.push(s(l,`no video item at ${JSON.stringify(l.item??null)}`));else if(l.op==="clip_color"){let o=await this.ask("item_meta.color",{handle:r}),u=l.color?await this.ask("item_meta.set_color",{handle:r,color:l.color}):await this.ask("item_meta.clear_color",{handle:r});m.push({op:l.op,ok:u}),u&&c.unshift({op:"clip_color",item:l.item,color:o})}else if(l.op==="enabled"&&d.announced(n,"item_meta.set_enabled")){let o=a.items.find(f=>f.handle?.$h===r.$h)?.enabled??!0,u=await this.ask("item_meta.set_enabled",{item:r,enabled:!!l.on});m.push({op:l.op,ok:u}),u&&c.unshift({op:"enabled",item:l.item,on:o})}else m.push(s(l,`${this.host}: '${l.op}' is not reachable over this plugin`))}catch(o){m.push(s(l,o instanceof Error?o.message:String(o)))}}return{results:m,undo:c}}async markerOps(e,t){let i=await this.peer(),n=r=>d.announced(i,r),s=new Map((await this.ask("markers.list",{target:e})).map(r=>[r.frame,r])),a=[],p=[],m=async r=>{let o=await this.ask("markers.add",{target:e,frame:r.frame,color:r.color??"",name:r.name??"",note:r.note??"",duration:r.duration??1,custom_data:r.custom_data??""});return o&&s.set(r.frame,{color:"",name:"",note:"",duration:1,...r}),o},c=async r=>{let o=await this.ask("markers.delete_at",{target:e,frame:r});return o&&s.delete(r),o},l=r=>({op:"marker_add",frame:r.frame,color:r.color,name:r.name,note:r.note,duration:r.duration,...r.custom_data?{data:r.custom_data}:{}});for(let r of t){let o=Number(r.frame);try{if(r.op==="marker_add"){let u=s.get(o);u&&await c(o);let f=await m({frame:o,color:r.color,name:r.name,note:r.note,duration:Number(r.duration??1),custom_data:r.data});a.push({op:r.op,ok:f}),f&&p.unshift(...u?[l(u)]:[],{op:"marker_delete",frame:o})}else if(r.op==="marker_update"){let u=s.get(o);if(!u){a.push({op:r.op,ok:!1,detail:`no marker at frame ${o}`});continue}let f=r.to_frame!==void 0?Number(r.to_frame):o,v={...u,frame:f,...r.color!==void 0?{color:String(r.color)}:{},...r.name!==void 0?{name:String(r.name)}:{},...r.note!==void 0?{note:String(r.note)}:{}},g=!0;n("markers.set_color")&&n("markers.set_text")&&n("markers.move")?(r.color!==void 0&&(g=await this.ask("markers.set_color",{target:e,frame:o,color:r.color})&&g),(r.name!==void 0||r.note!==void 0)&&(g=await this.ask("markers.set_text",{target:e,frame:o,name:r.name,note:r.note})&&g),f!==o&&(g=await this.ask("markers.move",{target:e,frame:o,to_frame:f})&&g),s.delete(o),s.set(f,v)):g=await c(o)&&await m(v),a.push({op:r.op,ok:g}),p.unshift({op:"marker_update",frame:f,color:u.color,name:u.name,note:u.note,...f!==o?{to_frame:o}:{}})}else if(r.op==="marker_delete"){let u=s.get(o),f=!!u&&await c(o);a.push({op:r.op,ok:f,...u?{}:{detail:`no marker at frame ${o}`}}),f&&u&&p.unshift(l(u))}else a.push({op:r.op,ok:!1,detail:`${this.host}: '${r.op}' is not reachable over this plugin`})}catch(u){a.push({op:r.op,ok:!1,detail:u instanceof Error?u.message:String(u)})}}return{results:a,undo:p}}async renderStart(e){if(await this.needs("render"),e.renderplugin)throw new h("unsupported","the renderplugin is a DaVinci Resolve plugin");if(e.disable_tracks?.length||e.audio_tracks?.length)throw new h("unsupported",`${this.host}: disable_tracks / audio_tracks are DaVinci Resolve's; pick a preset that renders what you need`);if(!e.preset)throw new h("usage",`${this.host}: preset is required: one of ${this.spec.label}'s export presets by name`);let{seq:t,name:i}=await this.sequence(e.timeline),n=e.name??i,s={purpose:"deliver",format:"preset",preset:e.preset,target_dir:e.target_dir,name:n,...e.range?{range:[e.range.in,e.range.out]}:{}},a=await this.ask("render.submit",{timeline:t,job:s});if(!a?.id)throw new h("render_refused",`${this.host}: ${a?.error??`${this.spec.label} refused the render`}`);if(!await this.ask("render.start",{job_ids:[a.id]}))throw new h("render_refused",`${this.host}: ${this.spec.label} did not start job ${a.id}`);return this.renders.set(a.id,{dir:e.target_dir,name:n}),{job_id:a.id,state:"queued",percent:0}}async renderStatus(e){let t=await this.ask("render.status",{job_id:e});if(!t)return{job_id:e,state:"failed",percent:0,error:`${this.host}: no render job ${e}`};let i={done:"complete",rendering:"rendering",queued:"queued",failed:"failed",cancelled:"cancelled"}[t.state]??"rendering",n={job_id:e,state:i,percent:Math.round(t.progress??(i==="complete"?100:0)),...t.error?{error:t.error}:{}};if(i==="complete"||i==="failed"||i==="cancelled"){let s=this.renders.get(e);i==="complete"&&s&&(n.outputs=await W(s.dir,s.name)),await this.ask("render.remove",{job_id:e}).catch(()=>!1),this.renders.delete(e)}return n}async renderCancel(e){return await this.ask("render.cancel",{job_id:e})?{job_id:e,state:"cancelled",percent:0}:{...await this.renderStatus(e),error:`${this.spec.label}'s running export cannot be cancelled from here; stop it in ${this.spec.label}`}}};async function W(d,e){let t=[];try{for await(let i of L(d))i.isFile&&i.name.startsWith(`${e}.`)&&t.push(_(d,i.name))}catch{}return t.sort()}function J(d){let e=(c,l)=>({OTIO_SCHEMA:"RationalTime.1",value:c,rate:l}),t=(c,l,r,o=r)=>({OTIO_SCHEMA:"TimeRange.1",start_time:e(c,r),duration:e(l,o)}),i=d.fps,n=d.tracks?.length?d.tracks:[...new Set(d.items.map(c=>c.track))].sort((c,l)=>c-l).map(c=>({index:c,enabled:!0,name:"",items:d.items.filter(l=>l.track===c)})),s=c=>(c.reversed?-1:1)*(c.speed||1)/(c.fps_factor||1),a=new Map;for(let c of d.items)if(c.file_path&&c.start_tc!=null&&c.src_abs_in!=null){let l=c.src_abs_in-c.start_tc+Math.ceil((c.end-c.start)*Math.abs(s(c))*(c.fps_factor||1));a.set(c.file_path,Math.max(a.get(c.file_path)??0,l))}let p=n.map(c=>{let l=d.start_frame,r=[];for(let o of[...c.items].sort((u,f)=>u.start-f.start)){if(o.start<l)continue;o.start>l&&r.push({OTIO_SCHEMA:"Gap.1",name:"",source_range:t(0,o.start-l,i)});let u=o.src_fps||i,f=o.start_tc!=null&&a.has(o.file_path)?o.start_tc:null,v=f!=null?o.src_abs_in:o.src_in??o.src_abs_in??0,g=s(o);r.push({OTIO_SCHEMA:"Clip.2",name:o.name??b(o.file_path||""),enabled:o.enabled!==!1,source_range:t(v,o.end-o.start,u,i),media_references:{DEFAULT_MEDIA:{OTIO_SCHEMA:"ExternalReference.1",name:b(o.file_path||""),target_url:o.file_path?`file://${o.file_path}`:"",...f!=null?{available_range:t(f,a.get(o.file_path),u)}:{},metadata:{}}},active_media_reference_key:"DEFAULT_MEDIA",effects:Math.abs(g-1)>1e-6?[{OTIO_SCHEMA:"LinearTimeWarp.1",name:"",effect_name:"LinearTimeWarp",time_scalar:g}]:[],markers:[],metadata:o.reel?{cmx_3600:{reel:o.reel}}:{}}),l=o.end}return{OTIO_SCHEMA:"Track.1",name:c.name||`V${c.index}`,kind:"Video",enabled:c.enabled!==!1,children:r,effects:[],markers:[],metadata:{}}}),m=[];return d.audio_items?.length&&m.push(`${d.audio_items.length} audio clip(s) not carried: the host's plugin reports no audio source times`),d.transitions?.length&&m.push(`${d.transitions.length} transition(s) not carried (cuts in their place)`),{otio:{OTIO_SCHEMA:"Timeline.1",name:d.timeline,global_start_time:e(d.start_frame,i),metadata:{},tracks:{OTIO_SCHEMA:"Stack.1",name:"tracks",children:p,effects:[],markers:[],metadata:{}}},notes:m}}var X=16e3;var G="Install the conform.tools panel (host_setup host=premiere action=install_panel), then in Premiere open Window > UXP Plugins > conform.tools. It connects by itself from then on.";var U=class extends ${constructor(t=j,i=X){super({host:"premiere",label:"Premiere Pro",setup:G},t,i);this.items=async(t={})=>{await this.needs("edit");let{seq:i}=await this.sequence(t.timeline),n=await this.ask("edit.items",{timeline:i,kind:t.kind,track:t.track},12e4),s=n.project_path?await K(n.project_path,n.timeline).catch(p=>({error:p instanceof Error?p.message:String(p)})):{error:"the project has never been saved"},a=0;if(!("error"in s))for(let p of n.items){let m=s.get(`${p.kind}:${p.track}:${p.start}:${Number(p.end)-Number(p.start)}`);m?Object.assign(p,m,{saved:!0}):(p.saved=!1,a++)}return{...n,color_groups:[],layers:1,..."error"in s?{saved_note:`saved project not read: ${s.error}`}:{unsaved_items:a}}};this.premiereRenders=new Map}async current(){let t=await this.ask("session.describe");return{project:t.project,timelines:t.timelines,timeline:t.current}}async liveMarkers(t){if(!$.announced(await this.peer(),"edit.markers"))return null;let{seq:i}=await this.sequence(t);return await this.ask("edit.markers",{timeline:i},12e4)}async model(t){return await super.model(t)}async projectClips(){return await this.needs("edit"),await this.ask("edit.project_clips",{},12e4)}async relinkClips(t){return await this.needs("edit"),await this.ask("edit.relink_clips",{items:t},6e4+t.length*2e3)}async cutIn(t,i){await this.needs("edit");let{seq:n}=await this.sequence(t);return await this.ask("edit.cut_in",{timeline:n,cuts:i},12e4+i.length*3e3)}async renderStart(t){if(t.range)throw new h("unsupported","premiere: a frame range is not supported yet; set in/out on the sequence in Premiere");if(!t.preset||!/\.epr$/i.test(t.preset))throw new h("usage","premiere: preset must be the path of a Media Encoder preset (.epr)");let{seq:i,name:n}=await this.sequence(t.timeline);await M(t.target_dir);let s=_(t.target_dir,`${t.name??n}.mov`),a=await this.ask("render.export_sequence",{timeline:i,output_path:s,preset_path:t.preset,queue:!1},6e4);if(!a.ok)throw new h("render_refused","premiere: Premiere refused the export");let p=a.job||`ppro-${Date.now()}`;return this.premiereRenders.set(p,s),{job_id:p,state:"rendering",percent:0}}async renderStatus(t){let i=await this.ask("render.progress"),n=i[t]??i.last,s=this.premiereRenders.get(t);return n?.event==="error"||n?.event==="onEncodeError"?{job_id:t,state:"failed",percent:0,error:String(n.data??"encode error")}:n?.event==="complete"||n?.event==="onEncodeComplete"||s&&await x(s)&&!n?{job_id:t,state:"complete",percent:100,...s?{outputs:[s]}:{}}:{job_id:t,state:"rendering",percent:typeof n?.data=="number"?Math.round(Number(n.data)*100):0}}async renderCancel(t){return{job_id:t,state:"cancelled",percent:0,error:"Premiere's export cannot be cancelled from here; cancel it in Premiere / Media Encoder"}}};async function K(d,e){let{session:t}=await N(d,"prproj"),i=t.timelines.find(s=>s.name===e),n=new Map;if(!i)throw new Error(`the saved project has no sequence "${e}" (saved before it was made?)`);for(let s of i.tracks)if(!(s.kind!=="Video"&&s.kind!=="Audio"))for(let a of s.items){if(a.kind==="gap"||a.kind==="transition")continue;let p=a;n.set(`${s.kind==="Video"?"video":"audio"}:${s.track_index}:${a.timeline_range.start.value}:${a.timeline_range.duration.value}`,{saved_id:a.id,...p.speed_factor!=null&&p.speed_factor!==1?{retime:p.speed_factor}:{},...p.speed_ramped?{ramped:!0}:{},...p.speed_reverse?{reversed:!0}:{},...a.kind==="nested"?{nested:!0}:{},...p.is_multicam?{multicam:!0}:{},...p.effects?.some(m=>/stabiliz/i.test(m.kind??""))?{stabilized:!0}:{},...p.effects?.length?{saved_effects:p.effects.map(m=>m.name??m.kind??"")}:{}})}return n}function z(d=y()){return d==="darwin"?"/Library/Application Support/Adobe/Adobe Desktop Common/RemoteComponents/UPI/UnifiedPluginInstallerAgent/UnifiedPluginInstallerAgent.app/Contents/MacOS/UnifiedPluginInstallerAgent":d==="win32"?"C:\\Program Files\\Common Files\\Adobe\\Adobe Desktop Common\\RemoteComponents\\UPI\\UnifiedPluginInstallerAgent\\UnifiedPluginInstallerAgent.exe":null}async function V(){for(let d of["./uxp-plugin/","./premiere-uxp/"]){let e=S(new URL(d,import.meta.url));if(await P(_(e,"manifest.json")))return e}throw new Error("premiere: the conform.tools panel is missing from this install")}async function Q(){return JSON.parse(await H(_(await V(),"manifest.json"))).version}async function oe(d=y()){let e=z(d);if(!e||!await x(e))return{installed:!1,listing:"Creative Cloud's plugin installer is not on this machine"};let t=await w(e,d==="win32"?["/list","all"]:["--list","all"],{timeoutMs:6e4}),i=t.stdout.split(`
|
|
4
|
+
`).find(n=>/CONFORM\.TOOLS|conformtools/i.test(n));return{installed:!!i&&/enabled|installed/i.test(i),version:i?.match(/(\d+\.\d+\.\d+)\s*$/)?.[1],listing:t.stdout.trim()}}async function ae(d=y()){let e=z(d);if(!e||!await x(e))throw new Error("premiere: Creative Cloud's plugin installer (UnifiedPluginInstallerAgent) is not on this machine; install Creative Cloud");let t=await V(),i=await Q(),n=await q("conform-ccx-");for(let l of["manifest.json","index.html","index.js","lib","icons"])await T(_(t,l),_(n,l));let s=_(O(),"premiere");await M(s);let a=I(_(s,`conformtools-premiere-${i}.ccx`));await R(a);let p=d==="darwin"?await w("sh",["-c",`cd '${n.replace(/'/g,"'\\''")}' && zip -r -q -X '${a.replace(/'/g,"'\\''")}' manifest.json index.html index.js lib icons`]):await w("powershell",["-NoProfile","-Command",`Compress-Archive -Path '${n}\\*' -DestinationPath '${a.replace(/\.ccx$/,".zip")}' -Force; Move-Item -Force '${a.replace(/\.ccx$/,".zip")}' '${a}'`]);if(await R(n),!p.success)throw new Error(`premiere: could not package the panel: ${p.stderr.trim()}`);await w(e,d==="win32"?["/remove","conform.tools"]:["--remove","conform.tools"],{timeoutMs:12e4});let m=await w(e,d==="win32"?["/install",a]:["--install",a],{timeoutMs:18e4}),c=`${m.stdout}
|
|
5
|
+
${m.stderr}`.trim();if(!m.success||!/Installation Successful/i.test(c))throw new Error(`premiere: Adobe's installer refused the panel: ${c.split(`
|
|
6
|
+
`).pop()}`);return{version:i,ccx:a,output:c}}export{$ as a,U as b,K as c,Q as d,oe as e,ae as f};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
-
import{c as r,d as t}from"./chunk-6V4OEOOX.js";import{i as n}from"./chunk-
|
|
3
|
+
import{c as r,d as t}from"./chunk-6V4OEOOX.js";import{i as n}from"./chunk-LZRCXSUJ.js";async function d(e){if(!r(e.name))return null;try{return await n(t(e),{verb:"inspect"})}catch(i){return console.warn(`[probeMedia] ${e.name} probe failed:`,i),null}}export{d as a};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
-
import{b as s}from"./chunk-
|
|
3
|
+
import{b as s}from"./chunk-XI6XF7FQ.js";var l="0.6.13";function a(t,i){let n=t.split("-")[0].split(".").map(Number),o=i.split("-")[0].split(".").map(Number);for(let e=0;e<Math.max(n.length,o.length);e++){let r=(n[e]||0)-(o[e]||0);if(r)return r>0}return!1}var u=null;function p(){return s("CONFORM_UPDATE_CHECK")==="off"?Promise.resolve(null):u??=fetch("https://registry.npmjs.org/conformtools/latest",{signal:AbortSignal.timeout(2e3)}).then(t=>t.ok?t.json():null).then(t=>typeof t?.version=="string"?t.version:null).catch(()=>null)}var c="run npx -y conformtools@latest setup claude (or setup codex) once: it registers the server so every new session runs the newest version (npx --prefer-online), then restart the MCP client; if an old global install is shadowing it: npm rm -g conformtools";async function f(){let t=await p();return`conformtools ${l}`+(t&&a(t,l)?` \u2014 update available: ${t} \u2192 ${c}`:"")}export{l as a,a as b,p as c,c as d,f as e};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
-
import{a as ut}from"./chunk-2CY2OOOJ.js";import{a as fe,b as mt}from"./chunk-ROPKSAFP.js";import{rc as lt,wb as ct}from"./chunk-VE423Z2L.js";import{a as pt}from"./chunk-NSQP6CTA.js";import{M as at,S as Y}from"./chunk-C2ESM27Z.js";import{b as Pe,d as it}from"./chunk-NU3X7P4N.js";import{$ as F,A as Q,D as tt,F as pe,J as G,K as rt,N as me,T as nt,U as ot,Y as st,Z as de,b as I,g as V,h as Qe,n as Te,q as Ye,r as Xe,t as ae,u as ce,w as le,x as Ze,y as et,z as ue}from"./chunk-G3SZDPDS.js";function dt(r,e){let t=async()=>{throw new Error(`${r}: ${e}`)},n={ok:!1,reason:e};return{host:r,wired:!1,support:async()=>({export:n,open:n,render:n,markers:n,renderplugin:n}),export:t,open:t,renderStart:t,renderStatus:t,renderCancel:t}}var Vt=ArrayBuffer,O=Uint8Array,ge=Uint16Array,Gt=Int16Array;var he=Int32Array,Ee=function(r,e,t){if(O.prototype.slice)return O.prototype.slice.call(r,e,t);(e==null||e<0)&&(e=0),(t==null||t>r.length)&&(t=r.length);var n=new O(t-e);return n.set(r.subarray(e,t)),n},Z=function(r,e,t,n){if(O.prototype.fill)return O.prototype.fill.call(r,e,t,n);for((t==null||t<0)&&(t=0),(n==null||n>r.length)&&(n=r.length);t<n;++t)r[t]=e;return r},qt=function(r,e,t,n){if(O.prototype.copyWithin)return O.prototype.copyWithin.call(r,e,t,n);for((t==null||t<0)&&(t=0),(n==null||n>r.length)&&(n=r.length);t<n;)r[e++]=r[t++]};var zt=["invalid zstd data","window size too large (>2046MB)","invalid block type","FSE accuracy too high","match distance too far back","unexpected EOF"],$=function(r,e,t){var n=new Error(e||zt[r]);if(n.code=r,Error.captureStackTrace&&Error.captureStackTrace(n,$),!t)throw n;return n},ft=function(r,e,t){for(var n=0,o=0;n<t;++n)o|=r[e++]<<(n<<3);return o},Jt=function(r,e){return(r[e]|r[e+1]<<8|r[e+2]<<16|r[e+3]<<24)>>>0},Wt=function(r,e){var t=r[0]|r[1]<<8|r[2]<<16;if(t==3126568&&r[3]==253){var n=r[4],o=n>>5&1,s=n>>2&1,i=n&3,m=n>>6;n&8&&$(0);var a=6-o,c=i==3?4:i,u=ft(r,a,c);a+=c;var d=m?1<<m:o,f=ft(r,a,d)+(m==1&&256),h=f;if(!o){var l=1<<10+(r[5]>>3);h=l+(l>>3)*(r[5]&7)}h>2145386496&&$(1);var p=new O((e==1?f||h:e?0:h)+12);return p[0]=1,p[4]=4,p[8]=8,{b:a+d,y:0,l:0,d:u,w:e&&e!=1?e:p.subarray(12),e:h,o:new he(p.buffer,0,3),u:f,c:s,m:Math.min(131072,h)}}else if((t>>4|r[3]<<20)==25481893)return Jt(r,4)+8;$(0)},H=function(r){for(var e=0;1<<e<=r;++e);return e-1},ee=function(r,e,t){var n=(e<<3)+4,o=(r[e]&15)+5;o>t&&$(3);for(var s=1<<o,i=s,m=-1,a=-1,c=-1,u=s,d=new Vt(512+(s<<2)),f=new Gt(d,0,256),h=new ge(d,0,256),l=new ge(d,512,s),p=512+(s<<1),g=new O(d,p,s),S=new O(d,p+s);m<255&&i>0;){var _=H(i+1),v=n>>3,A=(1<<_+1)-1,x=(r[v]|r[v+1]<<8|r[v+2]<<16)>>(n&7)&A,b=(1<<_)-1,w=A-i-1,T=x&b;if(T<w?(n+=_,x=T):(n+=_+1,x>b&&(x-=w)),f[++m]=--x,x==-1?(i+=x,g[--u]=m):i-=x,!x)do{var P=n>>3;a=(r[P]|r[P+1]<<8)>>(n&7)&3,n+=2,m+=a}while(a==3)}(m>255||i)&&$(0);for(var E=0,N=(s>>1)+(s>>3)+3,C=s-1,M=0;M<=m;++M){var y=f[M];if(y<1){h[M]=-y;continue}for(c=0;c<y;++c){g[E]=M;do E=E+N&C;while(E>=u)}}for(E&&$(0),c=0;c<s;++c){var k=h[g[c]]++,L=S[c]=o-H(k);l[c]=(k<<L)-s}return[n+7>>3,{b:o,s:g,n:S,t:l}]},Kt=function(r,e){var t=0,n=-1,o=new O(292),s=r[e],i=o.subarray(0,256),m=o.subarray(256,268),a=new ge(o.buffer,268);if(s<128){var c=ee(r,e+1,6),u=c[0],d=c[1];e+=s;var f=u<<3,h=r[e];h||$(0);for(var l=0,p=0,g=d.b,S=g,_=(++e<<3)-8+H(h);_-=g,!(_<f);){var v=_>>3;if(l+=(r[v]|r[v+1]<<8)>>(_&7)&(1<<g)-1,i[++n]=d.s[l],_-=S,_<f)break;v=_>>3,p+=(r[v]|r[v+1]<<8)>>(_&7)&(1<<S)-1,i[++n]=d.s[p],g=d.n[l],l=d.t[l],S=d.n[p],p=d.t[p]}++n>255&&$(0)}else{for(n=s-127;t<n;t+=2){var A=r[++e];i[t]=A>>4,i[t+1]=A&15}++e}var x=0;for(t=0;t<n;++t){var b=i[t];b>11&&$(0),x+=b&&1<<b-1}var w=H(x)+1,T=1<<w,P=T-x;for(P&P-1&&$(0),i[n++]=H(P)+1,t=0;t<n;++t){var b=i[t];++m[i[t]=b&&w+1-b]}var E=new O(T<<1),N=E.subarray(0,T),C=E.subarray(T);for(a[w]=0,t=w;t>0;--t){var M=a[t];Z(C,t,M,a[t-1]=M+m[t]*(1<<w-t))}for(a[0]!=T&&$(0),t=0;t<n;++t){var y=i[t];if(y){var k=a[y];Z(N,t,k,a[y]=k+(1<<w-y))}}return[e,{n:C,b:w,s:N}]},Qt=ee(new O([81,16,99,140,49,198,24,99,12,33,196,24,99,102,102,134,70,146,4]),0,6)[1],Yt=ee(new O([33,20,196,24,99,140,33,132,16,66,8,33,132,16,66,8,33,68,68,68,68,68,68,68,68,36,9]),0,6)[1],Xt=ee(new O([32,132,16,66,102,70,68,68,68,68,36,73,2]),0,5)[1],gt=function(r,e){for(var t=r.length,n=new he(t),o=0;o<t;++o)n[o]=e,e+=1<<r[o];return n},Oe=new O(new he([0,0,0,0,16843009,50528770,134678020,202050057,269422093]).buffer,0,36),Zt=gt(Oe,0),Me=new O(new he([0,0,0,0,0,0,0,0,16843009,50528770,117769220,185207048,252579084,16]).buffer,0,53),er=gt(Me,3),X=function(r,e,t){var n=r.length,o=e.length,s=r[n-1],i=(1<<t.b)-1,m=-t.b;s||$(0);for(var a=0,c=t.b,u=(n<<3)-8+H(s)-c,d=-1;u>m&&d<o;){var f=u>>3,h=(r[f]|r[f+1]<<8|r[f+2]<<16)>>(u&7);a=(a<<c|h)&i,e[++d]=t.s[a],u-=c=t.n[a]}(u!=m||d+1!=o)&&$(0)},tr=function(r,e,t){var n=6,o=e.length,s=o+3>>2,i=s<<1,m=s+i;X(r.subarray(n,n+=r[0]|r[1]<<8),e.subarray(0,s),t),X(r.subarray(n,n+=r[2]|r[3]<<8),e.subarray(s,i),t),X(r.subarray(n,n+=r[4]|r[5]<<8),e.subarray(i,m),t),X(r.subarray(n),e.subarray(m),t)},rr=function(r,e,t){var n,o=e.b,s=r[o],i=s>>1&3;e.l=s&1;var m=s>>3|r[o+1]<<5|r[o+2]<<13,a=(o+=3)+m;if(i==1)return o>=r.length?void 0:(e.b=o+1,t?(Z(t,r[o],e.y,e.y+=m),t):Z(new O(m),r[o]));if(!(a>r.length)){if(i==0)return e.b=a,t?(t.set(r.subarray(o,a),e.y),e.y+=m,t):Ee(r,o,a);if(i==2){var c=r[o],u=c&3,d=c>>2&3,f=c>>4,h=0,l=0;u<2?d&1?f|=r[++o]<<4|(d&2&&r[++o]<<12):f=c>>3:(l=d,d<2?(f|=(r[++o]&63)<<4,h=r[o]>>6|r[++o]<<2):d==2?(f|=r[++o]<<4|(r[++o]&3)<<12,h=r[o]>>2|r[++o]<<6):(f|=r[++o]<<4|(r[++o]&63)<<12,h=r[o]>>6|r[++o]<<2|r[++o]<<10)),++o;var p=t?t.subarray(e.y,e.y+e.m):new O(e.m),g=p.length-f;if(u==0)p.set(r.subarray(o,o+=f),g);else if(u==1)Z(p,r[o++],g);else{var S=e.h;if(u==2){var _=Kt(r,o);h+=o-(o=_[0]),e.h=S=_[1]}else S||$(0);(l?tr:X)(r.subarray(o,o+=h),p.subarray(g),S)}var v=r[o++];if(v){v==255?v=(r[o++]|r[o++]<<8)+32512:v>127&&(v=v-128<<8|r[o++]);var A=r[o++];A&3&&$(0);for(var x=[Yt,Xt,Qt],b=2;b>-1;--b){var w=A>>(b<<1)+2&3;if(w==1){var T=new O([0,0,r[o++]]);x[b]={s:T.subarray(2,3),n:T.subarray(0,1),t:new ge(T.buffer,0,1),b:0}}else w==2?(n=ee(r,o,9-(b&1)),o=n[0],x[b]=n[1]):w==3&&(e.t||$(0),x[b]=e.t[b])}var P=e.t=x,E=P[0],N=P[1],C=P[2],M=r[a-1];M||$(0);var y=(a<<3)-8+H(M)-C.b,k=y>>3,L=0,re=(r[k]|r[k+1]<<8)>>(y&7)&(1<<C.b)-1;k=(y-=N.b)>>3;var ne=(r[k]|r[k+1]<<8)>>(y&7)&(1<<N.b)-1;k=(y-=E.b)>>3;var oe=(r[k]|r[k+1]<<8)>>(y&7)&(1<<E.b)-1;for(++v;--v;){var Ae=C.s[re],qe=C.n[re],Re=E.s[oe],ze=E.n[oe],Je=N.s[ne],We=N.n[ne];k=(y-=Je)>>3;var Ke=1<<Je,U=Ke+((r[k]|r[k+1]<<8|r[k+2]<<16|r[k+3]<<24)>>>(y&7)&Ke-1);k=(y-=Me[Re])>>3;var J=er[Re]+((r[k]|r[k+1]<<8|r[k+2]<<16)>>(y&7)&(1<<Me[Re])-1);k=(y-=Oe[Ae])>>3;var se=Zt[Ae]+((r[k]|r[k+1]<<8|r[k+2]<<16)>>(y&7)&(1<<Oe[Ae])-1);if(k=(y-=qe)>>3,re=C.t[re]+((r[k]|r[k+1]<<8)>>(y&7)&(1<<qe)-1),k=(y-=ze)>>3,oe=E.t[oe]+((r[k]|r[k+1]<<8)>>(y&7)&(1<<ze)-1),k=(y-=We)>>3,ne=N.t[ne]+((r[k]|r[k+1]<<8)>>(y&7)&(1<<We)-1),U>3)e.o[2]=e.o[1],e.o[1]=e.o[0],e.o[0]=U-=3;else{var ie=U-(se!=0);ie?(U=ie==3?e.o[0]-1:e.o[ie],ie>1&&(e.o[2]=e.o[1]),e.o[1]=e.o[0],e.o[0]=U):U=e.o[0]}for(var b=0;b<se;++b)p[L+b]=p[g+b];L+=se,g+=se;var W=L-U;if(W<0){var K=-W,Bt=e.e+W;K>J&&(K=J);for(var b=0;b<K;++b)p[L+b]=e.w[Bt+b];L+=K,J-=K,W=0}for(var b=0;b<J;++b)p[L+b]=p[W+b];L+=J}if(L!=g)for(;g<p.length;)p[L++]=p[g++];else L=p.length;t?e.y+=L:p=Ee(p,0,L)}else if(t){if(e.y+=f,g)for(var b=0;b<f;++b)p[b]=p[g+b]}else g&&(p=Ee(p,g));return e.b=a,p}$(2)}},nr=function(r,e){if(r.length==1)return r[0];for(var t=new O(e),n=0,o=0;n<r.length;++n){var s=r[n];t.set(s,o),o+=s.length}return t};function we(r,e){for(var t=[],n=+!e,o=0,s=0;r.length;){var i=Wt(r,n||e);if(typeof i=="object"){for(n?(e=null,i.w.length==i.u&&(t.push(e=i.w),s+=i.u)):(t.push(e),i.e=0);!i.l;){var m=rr(r,i,e);m||$(5),e?i.e=i.y:(t.push(m),s+=m.length,qt(i.w,0,m.length),i.w.set(m,i.w.length-m.length))}o=i.b+i.c*4}else o=i;r=r.subarray(o)}return nr(t,s)}function D(r){let e=[],t=0,n=()=>{let s=0,i=1;for(;;){let m=r[t++];if(s+=(m&127)*i,i*=128,!(m&128))return s}},o=s=>Array.from(s,i=>i.toString(16).padStart(2,"0")).join("");for(;t<r.length;){let s=t,i=n(),m=Math.floor(i/8),a=i&7,c;if(a===0){let u=t;n(),c=r.slice(u,t)}else if(a===2){let u=n();c=r.slice(t,t+u),t+=u}else if(a===5)c=r.slice(t,t+4),t+=4;else if(a===1)c=r.slice(t,t+8),t+=8;else throw new Error(`wire type ${a}`);e.push([m,a,o(r.slice(s,t)),c])}return e}var or=r=>Array.from(r,e=>e.toString(16).padStart(2,"0")).join(""),yt=r=>Uint8Array.from(r.match(/../g)??[],e=>parseInt(e,16));function ye(r){let e=r.trim().toLowerCase();if(e.startsWith("80"))return e;if(e.startsWith("81"))return"80"+or(we(yt(e.slice(2))));throw new Error(`grade body: unknown encoding 0x${e.slice(0,2)}`)}function ht(r){let e={};for(let t of r.matchAll(/<ListMgt::LmVersion DbId="[^"]+">([\s\S]*?)<\/ListMgt::LmVersion>/g)){let n=/<Name>([^<]*)<\/Name>/.exec(t[1])?.[1],o=/<Body>([0-9a-fA-F]+)<\/Body>/.exec(t[1])?.[1];n&&o&&(e[n]=ye(o))}return e}function wt(r){let e=new Map;for(let t of r.matchAll(/<ListMgt::LmVersion DbId="([^"]+)">([\s\S]*?)<\/ListMgt::LmVersion>/g)){let n=/<Body>([0-9a-fA-F]+)<\/Body>/.exec(t[2])?.[1];n&&e.set(t[1],ye(n))}return e}function _t(r){let e=Y(r),t=c=>new TextDecoder().decode(e[c]),n=Object.keys(e).find(c=>c.startsWith("SeqContainer/")&&c.endsWith(".xml"));if(!n)throw new Error("grade bodies: no SeqContainer in the .drt");let o=new Map,s=new Map,i=Object.keys(e).filter(c=>c.startsWith("MediaPool/")&&c.endsWith(".xml"));for(let c of i)for(let u of t(c).matchAll(/<Sm2MpVideoClip DbId="([^"]+)">([\s\S]*?)<\/Sm2MpVideoClip>/g)){let d=/<pLmVerTable>([\s\S]*?)<\/pLmVerTable>/.exec(u[2]);d&&(o.set(u[1],ht(d[1])),s.set(u[1],wt(d[1])))}let m=new Map,a=0;for(let c of t(n).matchAll(/<Sm2TiTrack DbId="[^"]+">([\s\S]*?)<\/Sm2TiTrack>/g))if(/<Type>([^<]*)<\/Type>/.exec(c[1])?.[1]==="0"){a++;for(let u of c[1].matchAll(/<Sm2TiVideoClip DbId="[^"]+">([\s\S]*?)<\/Sm2TiVideoClip>/g)){let d=u[1],f=/<Start>(-?\d+)<\/Start>/.exec(d)?.[1],h=/<Name>([^<]*)<\/Name>/.exec(d)?.[1]??"";if(f===void 0)continue;let l=/<pLmVerTable>([\s\S]*?)<\/pLmVerTable>/.exec(d),p=/<MediaRef>([^<]+)<\/MediaRef>/.exec(d)?.[1],g=l&&/<pActive>([^<]+)<\/pActive>/.exec(l[1])?.[1],S=g?wt(l[1]).get(g)??(p?s.get(p)?.get(g):void 0):void 0;m.set(`${a}:${f}`,{name:h,local:l?ht(l[1]):{},remote:p&&o.get(p)||{},...S?{active:S}:{}})}}return m}function on(r){let e=a=>D(a),t=a=>{let c=0,u=1;for(let d of a)if(c+=(d&127)*u,u*=128,!(d&128))break;return c},n=e(yt(r.slice(2))).find(a=>a[0]===3&&a[1]===2&&e(a[3]).some(c=>c[0]===8&&t(c[3])===84)),s=(n?e(n[3]).filter(a=>a[0]===9).flatMap(a=>e(a[3])):[]).find(a=>a[0]===1&&a[1]===2&&e(a[3]).some(c=>c[0]===1&&c[1]===0&&t(c[3])===10));return s?e(s[3]).filter(a=>a[0]===6&&a[1]===2).map(a=>{let c=e(a[3]),u=t(c.find(h=>h[0]===1&&h[1]===0)?.[3]??new Uint8Array([0]))/2,d=c.find(h=>h[0]===2&&h[1]===2)?.[3]??new Uint8Array,f={t:u,zoom:1,height:1,rotation:0,pan:0,tilt:0,flip_x:!1,flip_y:!1};for(let h of e(d)){if(h[0]===5&&h[1]===2){let A=e(h[3]);f.ease_in=t(A.find(x=>x[0]===1)?.[3]??new Uint8Array([1])),f.ease_out=t(A.find(x=>x[0]===2)?.[3]??new Uint8Array([1]));continue}if(h[0]!==3||h[1]!==2)continue;let l=e(h[3]),p=t(l.find(A=>A[0]===1)?.[3]??new Uint8Array),g=l.find(A=>A[0]===2)?.[3],S=g&&e(g).find(A=>A[0]===1&&A[1]===5),_=g&&e(g).find(A=>A[0]===2&&A[1]===0),v=S?new DataView(S[3].buffer,S[3].byteOffset,4).getFloat32(0,!0):_?t(_[3]):void 0;v!==void 0&&(p===271581186?f.height=v:p===271581187?f.zoom=v:p===271581188?f.rotation=v:p===271581189?f.pan=v:p===271581190?f.tilt=v:p===271581191?f.flip_y=!!v:p===271581192&&(f.flip_x=!!v))}return f}).sort((a,c)=>a.t-c.t):[]}var sr=r=>Array.from(r,e=>e.toString(16).padStart(2,"0")).join(""),B=r=>Uint8Array.from(r.match(/../g)??[],e=>parseInt(e,16)),bt=r=>{let e=[];do e.push(r&127|(r>127?128:0)),r=Math.floor(r/128);while(r);return e};function St(r){let e=B(r.trim());if(e.length<9)throw new Error("EffectFiltersBA: too short");if(e[8]===128)return e.slice(9);if(e[8]===129)return we(e.slice(9));throw new Error(`EffectFiltersBA: unknown encoding 0x${e[8].toString(16)}`)}function ir(r){let e=new Uint8Array(9);return new DataView(e.buffer).setUint32(0,2),new DataView(e.buffer).setUint32(4,r.length+1),e[8]=128,sr(new Uint8Array([...e,...r]))}var $e=r=>{let e=D(r).find(t=>t[0]===1&&t[1]===0);return e?ar(e[3]):-1};function ar(r){let e=0,t=1;for(let n of r)if(e+=(n&127)*t,t*=128,!(n&128))break;return e}var Ne=(r,e)=>new Uint8Array([...bt(r<<3|2),...bt(e.length),...e]);function cr(r,e){let t=new DataView(r.buffer,r.byteOffset,r.byteLength),n=-t.getInt32(0)/16;if(!Number.isInteger(n)||n<2||r.length!==4+n*16||r[10]!==12)return r;let o=Array.from({length:n},(a,c)=>({frame:t.getUint32(4+c*16,!0),value:t.getFloat64(4+c*16+8,!0)})),s=o.map(a=>e(a.frame));if(!s.slice(0,-1).some(Boolean))return r;let i=new Uint8Array(4+n*64),m=new DataView(i.buffer);return m.setInt32(0,-(n*64)),o.forEach((a,c)=>{let u=4+c*64;m.setUint32(u,a.frame,!0),i[u+6]=13,m.setFloat64(u+8,a.value,!0);let d=c>0?s[c-1]:void 0,f=c<n-1?s[c]:void 0;d&&m.setFloat64(u+16,-(d.in/10)*(a.frame-o[c-1].frame),!0),f&&m.setFloat64(u+32,f.out/10*(o[c+1].frame-a.frame),!0)}),i}function lr(r,e){let t=[];for(let n of D(r))if(n[0]===9&&n[1]===2&&n[3].length){let o=D(n[3]).map(s=>s[0]===10&&s[1]===2?[...Ne(10,cr(s[3],e))]:[...B(s[2])]).flat();t.push(...Ne(9,new Uint8Array(o)))}else t.push(...B(n[2]));return new Uint8Array(t)}function ur(r){let e=[];for(let t of D(r)){if(t[0]!==9||t[1]!==2||!t[3].length)continue;let n=D(t[3]).find(i=>i[0]===10&&i[1]===2)?.[3];if(!n||n.length<4)continue;let o=new DataView(n.buffer,n.byteOffset,n.byteLength),s=-o.getInt32(0)/16;Number.isInteger(s)&&s>e.length&&n.length===4+s*16&&Array.from({length:s},(i,m)=>n[4+m*16+6]).every(i=>i===12)&&(e=Array.from({length:s},(i,m)=>o.getUint32(4+m*16,!0)))}return e}function pr(r,e){let t=D(e).find(s=>s[0]===1&&s[1]===2&&$e(s[3])===4);if(!t)throw new Error("the written clip carries no Transform group");let n=[],o=!1;for(let s of r?D(r):[]){if(s[0]===1&&s[1]===2&&$e(s[3])===4){o||(n.push(...B(t[2])),o=!0);continue}n.push(...B(s[2]))}return o||n.push(...B(t[2])),new Uint8Array(n)}function vt(r){let e=[],t=0;for(let n of r.matchAll(/<Sm2TiTrack DbId="[^"]+">([\s\S]*?)<\/Sm2TiTrack>/g)){if(/<Type>([^<]*)<\/Type>/.exec(n[1])?.[1]!=="0")continue;t++;let o=n.index+n[0].indexOf(n[1]);for(let s of n[1].matchAll(/<Sm2TiVideoClip DbId="[^"]+">([\s\S]*?)<\/Sm2TiVideoClip>/g)){let i=/<Start>(-?\d+)<\/Start>/.exec(s[1])?.[1];i!==void 0&&e.push({track:t,start:Number(i),at:o+s.index,end:o+s.index+s[0].length,body:s[0]})}}return e}var kt=r=>Object.keys(r).find(e=>e.startsWith("SeqContainer/")&&e.endsWith(".xml"));function xt(r,e,t,n){let o=Y(r),s=Y(e),i=kt(o),m=kt(s);if(!i||!m)throw new Error("no SeqContainer in the .drt");let a=new TextDecoder().decode(o[i]),c=vt(a),u=vt(new TextDecoder().decode(s[m])),d=[],f=[],h=[];for(let p of t){let g=`V${p.item.track}@${p.item.start}`,S=c.find(y=>y.track===p.item.track&&y.start===p.item.start+n),_=S?c.filter(y=>y.track===S.track).indexOf(S):-1,v=_>=0?u.filter(y=>y.track===p.item.track)[_]:void 0,A=v&&/<EffectFiltersBA>([0-9a-fA-F]+)<\/EffectFiltersBA>/.exec(v.body)?.[1];if(!S||!A){f.push(g);continue}let x=/<EffectFiltersBA>([0-9a-fA-F]*)<\/EffectFiltersBA>/.exec(S.body),b=D(St(A)),w=b.find(y=>y[0]===1&&y[1]===2&&$e(y[3])===4),T=w?ur(w[3]):[];if(T.length!==p.keys.length){f.push(`${g} (the engine wrote ${T.length} keys for ${p.keys.length})`);continue}let P=new Map(T.map((y,k)=>[y,p.keys[k].shape])),E=new Uint8Array(b.flatMap(y=>y===w?[...Ne(1,lr(y[3],k=>P.get(k)))]:[...B(y[2])])),N=pr(x?.[1]?St(x[1]):null,E),C=`<EffectFiltersBA>${ir(N)}</EffectFiltersBA>`,M=x?S.body.replace(x[0],C):S.body.replace(/(<\/Sm2TiVideoClip>)$/,`${C}$1`);h.push({at:S.at,end:S.end,body:M}),d.push(g)}for(let p of h.sort((g,S)=>S.at-g.at))a=a.slice(0,p.at)+p.body+a.slice(p.end);let l={...o,[i]:new TextEncoder().encode(a)};return{drt:at(l),keyed:d,missing:f}}function At(r,e,t){let n=r.source_range,o=r.timeline_range,s=n?.start.rate||t,i=n?.start.value??0,m=n?.duration&&o?.duration&&o.duration.value?n.duration.value/n.duration.rate/(o.duration.value/o.duration.rate)*s/t:s/t,a=[],c=0;for(let f of e){let h={value:i+f.t*m,rate:s},l=(p,g)=>a.push({id:`${r.id}-align-${c++}`,parameter_path:p,time:h,value:g,interp:"linear"});l("scale",f.transform.scale_x),e.some(p=>Math.abs(p.transform.scale_y-p.transform.scale_x)>.001)&&l("scale.y",f.transform.scale_y),l("position.x",f.transform.position_x),l("position.y",f.transform.position_y),l("rotation",f.transform.rotation)}let u=e[0].transform,d=(r.keyframes??[]).filter(f=>!/^(scale|position|rotation)/.test(String(f.parameter_path)));Object.assign(r,{scale:u.scale_x,position_x:u.position_x,position_y:u.position_y,rotation:u.rotation,keyframes:[...d,...a]}),Math.abs(u.scale_y-u.scale_x)>.001&&Object.assign(r,{scale_x:u.scale_x,scale_y:u.scale_y}),u.flip_h?r.flip_horizontal=!0:delete r.flip_horizontal,u.flip_v?r.flip_vertical=!0:delete r.flip_vertical}function Tt(r=V()){if(r==="win32"){let e=I("PROGRAMDATA")??"C:\\ProgramData",t=I("PROGRAMFILES")??"C:\\Program Files";return{api:`${e}\\Blackmagic Design\\DaVinci Resolve\\Support\\Developer\\Scripting`,lib:`${t}\\Blackmagic Design\\DaVinci Resolve\\fusionscript.dll`}}return r==="linux"?{api:"/opt/resolve/Developer/Scripting",lib:"/opt/resolve/libs/Fusion/fusionscript.so"}:{api:"/Library/Application Support/Blackmagic Design/DaVinci Resolve/Developer/Scripting",lib:"/Applications/DaVinci Resolve/DaVinci Resolve.app/Contents/Libraries/Fusion/fusionscript.so"}}async function mr(r){let e=I("RESOLVE_SCRIPT_LIB");if(e)return e;if(r==="darwin"){let n=(await me("ps",["-axo","comm="])).stdout.split(`
|
|
3
|
+
import{a as fe,b as mt}from"./chunk-ERUN634Q.js";import{a as ut}from"./chunk-J43UCJ6G.js";import{Q as at,Wb as lt}from"./chunk-LKQTE6T5.js";import{a as pt}from"./chunk-4VFDGL4E.js";import{M as it,S as Y}from"./chunk-C2ESM27Z.js";import{b as Pe,d as ct}from"./chunk-NU3X7P4N.js";import{A as Q,E as tt,G as pe,K as G,L as rt,O as me,U as nt,V as ot,Z as st,_ as de,aa as F,b as I,g as V,h as Qe,n as Te,q as Ye,r as Xe,t as ae,u as ce,w as le,x as Ze,y as et,z as ue}from"./chunk-XI6XF7FQ.js";function dt(r,e){let t=async()=>{throw new Error(`${r}: ${e}`)},n={ok:!1,reason:e};return{host:r,wired:!1,support:async()=>({export:n,open:n,render:n,markers:n,renderplugin:n}),export:t,open:t,renderStart:t,renderStatus:t,renderCancel:t}}var Vt=ArrayBuffer,O=Uint8Array,ge=Uint16Array,Gt=Int16Array;var he=Int32Array,Ee=function(r,e,t){if(O.prototype.slice)return O.prototype.slice.call(r,e,t);(e==null||e<0)&&(e=0),(t==null||t>r.length)&&(t=r.length);var n=new O(t-e);return n.set(r.subarray(e,t)),n},Z=function(r,e,t,n){if(O.prototype.fill)return O.prototype.fill.call(r,e,t,n);for((t==null||t<0)&&(t=0),(n==null||n>r.length)&&(n=r.length);t<n;++t)r[t]=e;return r},qt=function(r,e,t,n){if(O.prototype.copyWithin)return O.prototype.copyWithin.call(r,e,t,n);for((t==null||t<0)&&(t=0),(n==null||n>r.length)&&(n=r.length);t<n;)r[e++]=r[t++]};var zt=["invalid zstd data","window size too large (>2046MB)","invalid block type","FSE accuracy too high","match distance too far back","unexpected EOF"],$=function(r,e,t){var n=new Error(e||zt[r]);if(n.code=r,Error.captureStackTrace&&Error.captureStackTrace(n,$),!t)throw n;return n},ft=function(r,e,t){for(var n=0,o=0;n<t;++n)o|=r[e++]<<(n<<3);return o},Jt=function(r,e){return(r[e]|r[e+1]<<8|r[e+2]<<16|r[e+3]<<24)>>>0},Wt=function(r,e){var t=r[0]|r[1]<<8|r[2]<<16;if(t==3126568&&r[3]==253){var n=r[4],o=n>>5&1,s=n>>2&1,i=n&3,m=n>>6;n&8&&$(0);var a=6-o,c=i==3?4:i,u=ft(r,a,c);a+=c;var d=m?1<<m:o,f=ft(r,a,d)+(m==1&&256),h=f;if(!o){var l=1<<10+(r[5]>>3);h=l+(l>>3)*(r[5]&7)}h>2145386496&&$(1);var p=new O((e==1?f||h:e?0:h)+12);return p[0]=1,p[4]=4,p[8]=8,{b:a+d,y:0,l:0,d:u,w:e&&e!=1?e:p.subarray(12),e:h,o:new he(p.buffer,0,3),u:f,c:s,m:Math.min(131072,h)}}else if((t>>4|r[3]<<20)==25481893)return Jt(r,4)+8;$(0)},H=function(r){for(var e=0;1<<e<=r;++e);return e-1},ee=function(r,e,t){var n=(e<<3)+4,o=(r[e]&15)+5;o>t&&$(3);for(var s=1<<o,i=s,m=-1,a=-1,c=-1,u=s,d=new Vt(512+(s<<2)),f=new Gt(d,0,256),h=new ge(d,0,256),l=new ge(d,512,s),p=512+(s<<1),g=new O(d,p,s),S=new O(d,p+s);m<255&&i>0;){var _=H(i+1),v=n>>3,A=(1<<_+1)-1,x=(r[v]|r[v+1]<<8|r[v+2]<<16)>>(n&7)&A,b=(1<<_)-1,w=A-i-1,T=x&b;if(T<w?(n+=_,x=T):(n+=_+1,x>b&&(x-=w)),f[++m]=--x,x==-1?(i+=x,g[--u]=m):i-=x,!x)do{var P=n>>3;a=(r[P]|r[P+1]<<8)>>(n&7)&3,n+=2,m+=a}while(a==3)}(m>255||i)&&$(0);for(var E=0,N=(s>>1)+(s>>3)+3,C=s-1,M=0;M<=m;++M){var y=f[M];if(y<1){h[M]=-y;continue}for(c=0;c<y;++c){g[E]=M;do E=E+N&C;while(E>=u)}}for(E&&$(0),c=0;c<s;++c){var k=h[g[c]]++,L=S[c]=o-H(k);l[c]=(k<<L)-s}return[n+7>>3,{b:o,s:g,n:S,t:l}]},Kt=function(r,e){var t=0,n=-1,o=new O(292),s=r[e],i=o.subarray(0,256),m=o.subarray(256,268),a=new ge(o.buffer,268);if(s<128){var c=ee(r,e+1,6),u=c[0],d=c[1];e+=s;var f=u<<3,h=r[e];h||$(0);for(var l=0,p=0,g=d.b,S=g,_=(++e<<3)-8+H(h);_-=g,!(_<f);){var v=_>>3;if(l+=(r[v]|r[v+1]<<8)>>(_&7)&(1<<g)-1,i[++n]=d.s[l],_-=S,_<f)break;v=_>>3,p+=(r[v]|r[v+1]<<8)>>(_&7)&(1<<S)-1,i[++n]=d.s[p],g=d.n[l],l=d.t[l],S=d.n[p],p=d.t[p]}++n>255&&$(0)}else{for(n=s-127;t<n;t+=2){var A=r[++e];i[t]=A>>4,i[t+1]=A&15}++e}var x=0;for(t=0;t<n;++t){var b=i[t];b>11&&$(0),x+=b&&1<<b-1}var w=H(x)+1,T=1<<w,P=T-x;for(P&P-1&&$(0),i[n++]=H(P)+1,t=0;t<n;++t){var b=i[t];++m[i[t]=b&&w+1-b]}var E=new O(T<<1),N=E.subarray(0,T),C=E.subarray(T);for(a[w]=0,t=w;t>0;--t){var M=a[t];Z(C,t,M,a[t-1]=M+m[t]*(1<<w-t))}for(a[0]!=T&&$(0),t=0;t<n;++t){var y=i[t];if(y){var k=a[y];Z(N,t,k,a[y]=k+(1<<w-y))}}return[e,{n:C,b:w,s:N}]},Qt=ee(new O([81,16,99,140,49,198,24,99,12,33,196,24,99,102,102,134,70,146,4]),0,6)[1],Yt=ee(new O([33,20,196,24,99,140,33,132,16,66,8,33,132,16,66,8,33,68,68,68,68,68,68,68,68,36,9]),0,6)[1],Xt=ee(new O([32,132,16,66,102,70,68,68,68,68,36,73,2]),0,5)[1],gt=function(r,e){for(var t=r.length,n=new he(t),o=0;o<t;++o)n[o]=e,e+=1<<r[o];return n},Oe=new O(new he([0,0,0,0,16843009,50528770,134678020,202050057,269422093]).buffer,0,36),Zt=gt(Oe,0),Me=new O(new he([0,0,0,0,0,0,0,0,16843009,50528770,117769220,185207048,252579084,16]).buffer,0,53),er=gt(Me,3),X=function(r,e,t){var n=r.length,o=e.length,s=r[n-1],i=(1<<t.b)-1,m=-t.b;s||$(0);for(var a=0,c=t.b,u=(n<<3)-8+H(s)-c,d=-1;u>m&&d<o;){var f=u>>3,h=(r[f]|r[f+1]<<8|r[f+2]<<16)>>(u&7);a=(a<<c|h)&i,e[++d]=t.s[a],u-=c=t.n[a]}(u!=m||d+1!=o)&&$(0)},tr=function(r,e,t){var n=6,o=e.length,s=o+3>>2,i=s<<1,m=s+i;X(r.subarray(n,n+=r[0]|r[1]<<8),e.subarray(0,s),t),X(r.subarray(n,n+=r[2]|r[3]<<8),e.subarray(s,i),t),X(r.subarray(n,n+=r[4]|r[5]<<8),e.subarray(i,m),t),X(r.subarray(n),e.subarray(m),t)},rr=function(r,e,t){var n,o=e.b,s=r[o],i=s>>1&3;e.l=s&1;var m=s>>3|r[o+1]<<5|r[o+2]<<13,a=(o+=3)+m;if(i==1)return o>=r.length?void 0:(e.b=o+1,t?(Z(t,r[o],e.y,e.y+=m),t):Z(new O(m),r[o]));if(!(a>r.length)){if(i==0)return e.b=a,t?(t.set(r.subarray(o,a),e.y),e.y+=m,t):Ee(r,o,a);if(i==2){var c=r[o],u=c&3,d=c>>2&3,f=c>>4,h=0,l=0;u<2?d&1?f|=r[++o]<<4|(d&2&&r[++o]<<12):f=c>>3:(l=d,d<2?(f|=(r[++o]&63)<<4,h=r[o]>>6|r[++o]<<2):d==2?(f|=r[++o]<<4|(r[++o]&3)<<12,h=r[o]>>2|r[++o]<<6):(f|=r[++o]<<4|(r[++o]&63)<<12,h=r[o]>>6|r[++o]<<2|r[++o]<<10)),++o;var p=t?t.subarray(e.y,e.y+e.m):new O(e.m),g=p.length-f;if(u==0)p.set(r.subarray(o,o+=f),g);else if(u==1)Z(p,r[o++],g);else{var S=e.h;if(u==2){var _=Kt(r,o);h+=o-(o=_[0]),e.h=S=_[1]}else S||$(0);(l?tr:X)(r.subarray(o,o+=h),p.subarray(g),S)}var v=r[o++];if(v){v==255?v=(r[o++]|r[o++]<<8)+32512:v>127&&(v=v-128<<8|r[o++]);var A=r[o++];A&3&&$(0);for(var x=[Yt,Xt,Qt],b=2;b>-1;--b){var w=A>>(b<<1)+2&3;if(w==1){var T=new O([0,0,r[o++]]);x[b]={s:T.subarray(2,3),n:T.subarray(0,1),t:new ge(T.buffer,0,1),b:0}}else w==2?(n=ee(r,o,9-(b&1)),o=n[0],x[b]=n[1]):w==3&&(e.t||$(0),x[b]=e.t[b])}var P=e.t=x,E=P[0],N=P[1],C=P[2],M=r[a-1];M||$(0);var y=(a<<3)-8+H(M)-C.b,k=y>>3,L=0,re=(r[k]|r[k+1]<<8)>>(y&7)&(1<<C.b)-1;k=(y-=N.b)>>3;var ne=(r[k]|r[k+1]<<8)>>(y&7)&(1<<N.b)-1;k=(y-=E.b)>>3;var oe=(r[k]|r[k+1]<<8)>>(y&7)&(1<<E.b)-1;for(++v;--v;){var Ae=C.s[re],qe=C.n[re],Re=E.s[oe],ze=E.n[oe],Je=N.s[ne],We=N.n[ne];k=(y-=Je)>>3;var Ke=1<<Je,U=Ke+((r[k]|r[k+1]<<8|r[k+2]<<16|r[k+3]<<24)>>>(y&7)&Ke-1);k=(y-=Me[Re])>>3;var J=er[Re]+((r[k]|r[k+1]<<8|r[k+2]<<16)>>(y&7)&(1<<Me[Re])-1);k=(y-=Oe[Ae])>>3;var se=Zt[Ae]+((r[k]|r[k+1]<<8|r[k+2]<<16)>>(y&7)&(1<<Oe[Ae])-1);if(k=(y-=qe)>>3,re=C.t[re]+((r[k]|r[k+1]<<8)>>(y&7)&(1<<qe)-1),k=(y-=ze)>>3,oe=E.t[oe]+((r[k]|r[k+1]<<8)>>(y&7)&(1<<ze)-1),k=(y-=We)>>3,ne=N.t[ne]+((r[k]|r[k+1]<<8)>>(y&7)&(1<<We)-1),U>3)e.o[2]=e.o[1],e.o[1]=e.o[0],e.o[0]=U-=3;else{var ie=U-(se!=0);ie?(U=ie==3?e.o[0]-1:e.o[ie],ie>1&&(e.o[2]=e.o[1]),e.o[1]=e.o[0],e.o[0]=U):U=e.o[0]}for(var b=0;b<se;++b)p[L+b]=p[g+b];L+=se,g+=se;var W=L-U;if(W<0){var K=-W,Bt=e.e+W;K>J&&(K=J);for(var b=0;b<K;++b)p[L+b]=e.w[Bt+b];L+=K,J-=K,W=0}for(var b=0;b<J;++b)p[L+b]=p[W+b];L+=J}if(L!=g)for(;g<p.length;)p[L++]=p[g++];else L=p.length;t?e.y+=L:p=Ee(p,0,L)}else if(t){if(e.y+=f,g)for(var b=0;b<f;++b)p[b]=p[g+b]}else g&&(p=Ee(p,g));return e.b=a,p}$(2)}},nr=function(r,e){if(r.length==1)return r[0];for(var t=new O(e),n=0,o=0;n<r.length;++n){var s=r[n];t.set(s,o),o+=s.length}return t};function we(r,e){for(var t=[],n=+!e,o=0,s=0;r.length;){var i=Wt(r,n||e);if(typeof i=="object"){for(n?(e=null,i.w.length==i.u&&(t.push(e=i.w),s+=i.u)):(t.push(e),i.e=0);!i.l;){var m=rr(r,i,e);m||$(5),e?i.e=i.y:(t.push(m),s+=m.length,qt(i.w,0,m.length),i.w.set(m,i.w.length-m.length))}o=i.b+i.c*4}else o=i;r=r.subarray(o)}return nr(t,s)}function D(r){let e=[],t=0,n=()=>{let s=0,i=1;for(;;){let m=r[t++];if(s+=(m&127)*i,i*=128,!(m&128))return s}},o=s=>Array.from(s,i=>i.toString(16).padStart(2,"0")).join("");for(;t<r.length;){let s=t,i=n(),m=Math.floor(i/8),a=i&7,c;if(a===0){let u=t;n(),c=r.slice(u,t)}else if(a===2){let u=n();c=r.slice(t,t+u),t+=u}else if(a===5)c=r.slice(t,t+4),t+=4;else if(a===1)c=r.slice(t,t+8),t+=8;else throw new Error(`wire type ${a}`);e.push([m,a,o(r.slice(s,t)),c])}return e}var or=r=>Array.from(r,e=>e.toString(16).padStart(2,"0")).join(""),yt=r=>Uint8Array.from(r.match(/../g)??[],e=>parseInt(e,16));function ye(r){let e=r.trim().toLowerCase();if(e.startsWith("80"))return e;if(e.startsWith("81"))return"80"+or(we(yt(e.slice(2))));throw new Error(`grade body: unknown encoding 0x${e.slice(0,2)}`)}function ht(r){let e={};for(let t of r.matchAll(/<ListMgt::LmVersion DbId="[^"]+">([\s\S]*?)<\/ListMgt::LmVersion>/g)){let n=/<Name>([^<]*)<\/Name>/.exec(t[1])?.[1],o=/<Body>([0-9a-fA-F]+)<\/Body>/.exec(t[1])?.[1];n&&o&&(e[n]=ye(o))}return e}function wt(r){let e=new Map;for(let t of r.matchAll(/<ListMgt::LmVersion DbId="([^"]+)">([\s\S]*?)<\/ListMgt::LmVersion>/g)){let n=/<Body>([0-9a-fA-F]+)<\/Body>/.exec(t[2])?.[1];n&&e.set(t[1],ye(n))}return e}function _t(r){let e=Y(r),t=c=>new TextDecoder().decode(e[c]),n=Object.keys(e).find(c=>c.startsWith("SeqContainer/")&&c.endsWith(".xml"));if(!n)throw new Error("grade bodies: no SeqContainer in the .drt");let o=new Map,s=new Map,i=Object.keys(e).filter(c=>c.startsWith("MediaPool/")&&c.endsWith(".xml"));for(let c of i)for(let u of t(c).matchAll(/<Sm2MpVideoClip DbId="([^"]+)">([\s\S]*?)<\/Sm2MpVideoClip>/g)){let d=/<pLmVerTable>([\s\S]*?)<\/pLmVerTable>/.exec(u[2]);d&&(o.set(u[1],ht(d[1])),s.set(u[1],wt(d[1])))}let m=new Map,a=0;for(let c of t(n).matchAll(/<Sm2TiTrack DbId="[^"]+">([\s\S]*?)<\/Sm2TiTrack>/g))if(/<Type>([^<]*)<\/Type>/.exec(c[1])?.[1]==="0"){a++;for(let u of c[1].matchAll(/<Sm2TiVideoClip DbId="[^"]+">([\s\S]*?)<\/Sm2TiVideoClip>/g)){let d=u[1],f=/<Start>(-?\d+)<\/Start>/.exec(d)?.[1],h=/<Name>([^<]*)<\/Name>/.exec(d)?.[1]??"";if(f===void 0)continue;let l=/<pLmVerTable>([\s\S]*?)<\/pLmVerTable>/.exec(d),p=/<MediaRef>([^<]+)<\/MediaRef>/.exec(d)?.[1],g=l&&/<pActive>([^<]+)<\/pActive>/.exec(l[1])?.[1],S=g?wt(l[1]).get(g)??(p?s.get(p)?.get(g):void 0):void 0;m.set(`${a}:${f}`,{name:h,local:l?ht(l[1]):{},remote:p&&o.get(p)||{},...S?{active:S}:{}})}}return m}function on(r){let e=a=>D(a),t=a=>{let c=0,u=1;for(let d of a)if(c+=(d&127)*u,u*=128,!(d&128))break;return c},n=e(yt(r.slice(2))).find(a=>a[0]===3&&a[1]===2&&e(a[3]).some(c=>c[0]===8&&t(c[3])===84)),s=(n?e(n[3]).filter(a=>a[0]===9).flatMap(a=>e(a[3])):[]).find(a=>a[0]===1&&a[1]===2&&e(a[3]).some(c=>c[0]===1&&c[1]===0&&t(c[3])===10));return s?e(s[3]).filter(a=>a[0]===6&&a[1]===2).map(a=>{let c=e(a[3]),u=t(c.find(h=>h[0]===1&&h[1]===0)?.[3]??new Uint8Array([0]))/2,d=c.find(h=>h[0]===2&&h[1]===2)?.[3]??new Uint8Array,f={t:u,zoom:1,height:1,rotation:0,pan:0,tilt:0,flip_x:!1,flip_y:!1};for(let h of e(d)){if(h[0]===5&&h[1]===2){let A=e(h[3]);f.ease_in=t(A.find(x=>x[0]===1)?.[3]??new Uint8Array([1])),f.ease_out=t(A.find(x=>x[0]===2)?.[3]??new Uint8Array([1]));continue}if(h[0]!==3||h[1]!==2)continue;let l=e(h[3]),p=t(l.find(A=>A[0]===1)?.[3]??new Uint8Array),g=l.find(A=>A[0]===2)?.[3],S=g&&e(g).find(A=>A[0]===1&&A[1]===5),_=g&&e(g).find(A=>A[0]===2&&A[1]===0),v=S?new DataView(S[3].buffer,S[3].byteOffset,4).getFloat32(0,!0):_?t(_[3]):void 0;v!==void 0&&(p===271581186?f.height=v:p===271581187?f.zoom=v:p===271581188?f.rotation=v:p===271581189?f.pan=v:p===271581190?f.tilt=v:p===271581191?f.flip_y=!!v:p===271581192&&(f.flip_x=!!v))}return f}).sort((a,c)=>a.t-c.t):[]}var sr=r=>Array.from(r,e=>e.toString(16).padStart(2,"0")).join(""),B=r=>Uint8Array.from(r.match(/../g)??[],e=>parseInt(e,16)),bt=r=>{let e=[];do e.push(r&127|(r>127?128:0)),r=Math.floor(r/128);while(r);return e};function St(r){let e=B(r.trim());if(e.length<9)throw new Error("EffectFiltersBA: too short");if(e[8]===128)return e.slice(9);if(e[8]===129)return we(e.slice(9));throw new Error(`EffectFiltersBA: unknown encoding 0x${e[8].toString(16)}`)}function ir(r){let e=new Uint8Array(9);return new DataView(e.buffer).setUint32(0,2),new DataView(e.buffer).setUint32(4,r.length+1),e[8]=128,sr(new Uint8Array([...e,...r]))}var $e=r=>{let e=D(r).find(t=>t[0]===1&&t[1]===0);return e?ar(e[3]):-1};function ar(r){let e=0,t=1;for(let n of r)if(e+=(n&127)*t,t*=128,!(n&128))break;return e}var Ne=(r,e)=>new Uint8Array([...bt(r<<3|2),...bt(e.length),...e]);function cr(r,e){let t=new DataView(r.buffer,r.byteOffset,r.byteLength),n=-t.getInt32(0)/16;if(!Number.isInteger(n)||n<2||r.length!==4+n*16||r[10]!==12)return r;let o=Array.from({length:n},(a,c)=>({frame:t.getUint32(4+c*16,!0),value:t.getFloat64(4+c*16+8,!0)})),s=o.map(a=>e(a.frame));if(!s.slice(0,-1).some(Boolean))return r;let i=new Uint8Array(4+n*64),m=new DataView(i.buffer);return m.setInt32(0,-(n*64)),o.forEach((a,c)=>{let u=4+c*64;m.setUint32(u,a.frame,!0),i[u+6]=13,m.setFloat64(u+8,a.value,!0);let d=c>0?s[c-1]:void 0,f=c<n-1?s[c]:void 0;d&&m.setFloat64(u+16,-(d.in/10)*(a.frame-o[c-1].frame),!0),f&&m.setFloat64(u+32,f.out/10*(o[c+1].frame-a.frame),!0)}),i}function lr(r,e){let t=[];for(let n of D(r))if(n[0]===9&&n[1]===2&&n[3].length){let o=D(n[3]).map(s=>s[0]===10&&s[1]===2?[...Ne(10,cr(s[3],e))]:[...B(s[2])]).flat();t.push(...Ne(9,new Uint8Array(o)))}else t.push(...B(n[2]));return new Uint8Array(t)}function ur(r){let e=[];for(let t of D(r)){if(t[0]!==9||t[1]!==2||!t[3].length)continue;let n=D(t[3]).find(i=>i[0]===10&&i[1]===2)?.[3];if(!n||n.length<4)continue;let o=new DataView(n.buffer,n.byteOffset,n.byteLength),s=-o.getInt32(0)/16;Number.isInteger(s)&&s>e.length&&n.length===4+s*16&&Array.from({length:s},(i,m)=>n[4+m*16+6]).every(i=>i===12)&&(e=Array.from({length:s},(i,m)=>o.getUint32(4+m*16,!0)))}return e}function pr(r,e){let t=D(e).find(s=>s[0]===1&&s[1]===2&&$e(s[3])===4);if(!t)throw new Error("the written clip carries no Transform group");let n=[],o=!1;for(let s of r?D(r):[]){if(s[0]===1&&s[1]===2&&$e(s[3])===4){o||(n.push(...B(t[2])),o=!0);continue}n.push(...B(s[2]))}return o||n.push(...B(t[2])),new Uint8Array(n)}function vt(r){let e=[],t=0;for(let n of r.matchAll(/<Sm2TiTrack DbId="[^"]+">([\s\S]*?)<\/Sm2TiTrack>/g)){if(/<Type>([^<]*)<\/Type>/.exec(n[1])?.[1]!=="0")continue;t++;let o=n.index+n[0].indexOf(n[1]);for(let s of n[1].matchAll(/<Sm2TiVideoClip DbId="[^"]+">([\s\S]*?)<\/Sm2TiVideoClip>/g)){let i=/<Start>(-?\d+)<\/Start>/.exec(s[1])?.[1];i!==void 0&&e.push({track:t,start:Number(i),at:o+s.index,end:o+s.index+s[0].length,body:s[0]})}}return e}var kt=r=>Object.keys(r).find(e=>e.startsWith("SeqContainer/")&&e.endsWith(".xml"));function xt(r,e,t,n){let o=Y(r),s=Y(e),i=kt(o),m=kt(s);if(!i||!m)throw new Error("no SeqContainer in the .drt");let a=new TextDecoder().decode(o[i]),c=vt(a),u=vt(new TextDecoder().decode(s[m])),d=[],f=[],h=[];for(let p of t){let g=`V${p.item.track}@${p.item.start}`,S=c.find(y=>y.track===p.item.track&&y.start===p.item.start+n),_=S?c.filter(y=>y.track===S.track).indexOf(S):-1,v=_>=0?u.filter(y=>y.track===p.item.track)[_]:void 0,A=v&&/<EffectFiltersBA>([0-9a-fA-F]+)<\/EffectFiltersBA>/.exec(v.body)?.[1];if(!S||!A){f.push(g);continue}let x=/<EffectFiltersBA>([0-9a-fA-F]*)<\/EffectFiltersBA>/.exec(S.body),b=D(St(A)),w=b.find(y=>y[0]===1&&y[1]===2&&$e(y[3])===4),T=w?ur(w[3]):[];if(T.length!==p.keys.length){f.push(`${g} (the engine wrote ${T.length} keys for ${p.keys.length})`);continue}let P=new Map(T.map((y,k)=>[y,p.keys[k].shape])),E=new Uint8Array(b.flatMap(y=>y===w?[...Ne(1,lr(y[3],k=>P.get(k)))]:[...B(y[2])])),N=pr(x?.[1]?St(x[1]):null,E),C=`<EffectFiltersBA>${ir(N)}</EffectFiltersBA>`,M=x?S.body.replace(x[0],C):S.body.replace(/(<\/Sm2TiVideoClip>)$/,`${C}$1`);h.push({at:S.at,end:S.end,body:M}),d.push(g)}for(let p of h.sort((g,S)=>S.at-g.at))a=a.slice(0,p.at)+p.body+a.slice(p.end);let l={...o,[i]:new TextEncoder().encode(a)};return{drt:it(l),keyed:d,missing:f}}function At(r,e,t){let n=r.source_range,o=r.timeline_range,s=n?.start.rate||t,i=n?.start.value??0,m=n?.duration&&o?.duration&&o.duration.value?n.duration.value/n.duration.rate/(o.duration.value/o.duration.rate)*s/t:s/t,a=[],c=0;for(let f of e){let h={value:i+f.t*m,rate:s},l=(p,g)=>a.push({id:`${r.id}-align-${c++}`,parameter_path:p,time:h,value:g,interp:"linear"});l("scale",f.transform.scale_x),e.some(p=>Math.abs(p.transform.scale_y-p.transform.scale_x)>.001)&&l("scale.y",f.transform.scale_y),l("position.x",f.transform.position_x),l("position.y",f.transform.position_y),l("rotation",f.transform.rotation)}let u=e[0].transform,d=(r.keyframes??[]).filter(f=>!/^(scale|position|rotation)/.test(String(f.parameter_path)));Object.assign(r,{scale:u.scale_x,position_x:u.position_x,position_y:u.position_y,rotation:u.rotation,keyframes:[...d,...a]}),Math.abs(u.scale_y-u.scale_x)>.001&&Object.assign(r,{scale_x:u.scale_x,scale_y:u.scale_y}),u.flip_h?r.flip_horizontal=!0:delete r.flip_horizontal,u.flip_v?r.flip_vertical=!0:delete r.flip_vertical}function Tt(r=V()){if(r==="win32"){let e=I("PROGRAMDATA")??"C:\\ProgramData",t=I("PROGRAMFILES")??"C:\\Program Files";return{api:`${e}\\Blackmagic Design\\DaVinci Resolve\\Support\\Developer\\Scripting`,lib:`${t}\\Blackmagic Design\\DaVinci Resolve\\fusionscript.dll`}}return r==="linux"?{api:"/opt/resolve/Developer/Scripting",lib:"/opt/resolve/libs/Fusion/fusionscript.so"}:{api:"/Library/Application Support/Blackmagic Design/DaVinci Resolve/Developer/Scripting",lib:"/Applications/DaVinci Resolve/DaVinci Resolve.app/Contents/Libraries/Fusion/fusionscript.so"}}async function mr(r){let e=I("RESOLVE_SCRIPT_LIB");if(e)return e;if(r==="darwin"){let n=(await me("ps",["-axo","comm="])).stdout.split(`
|
|
4
4
|
`).map(o=>o.trim()).find(o=>/\/Contents\/MacOS\/Resolve$/.test(o));if(n){let o=n.replace(/\/MacOS\/Resolve$/,"/Libraries/Fusion/fusionscript.so");if(await ae(o))return o}}return Tt(r).lib}async function dr(){for(let r of["./bridge.py","./resolve-bridge.py"]){let e=Xe(new URL(r,import.meta.url));if(await ce(e))return e}throw new Error("resolve: bridge.py is missing from this install")}var Ce=new Map;function fr(r){return Ce.has(r)||Ce.set(r,me(r,["-c","import sys; print(sys.base_prefix)"],{timeoutMs:2e4}).then(e=>e.stdout.trim().split(`
|
|
5
5
|
`).pop()||void 0).catch(()=>{})),Ce.get(r)}var gr=["PYTHON3HOME","FUSION_PYTHON3HOME","FUSION_PYTHON3_HOME","FUSION_PYTHON36_HOME"],hr=async(r,e,t)=>{let n=V(),{api:o}=Tt(n),s=Qe(),i=n==="win32"?await fr(s):void 0,m=await G("ct-bridge-"),a=F(m,"args.json"),c;try{await ue(a,JSON.stringify(e)),c=await me(s,[await dr(),r,`@${a}`],{env:{RESOLVE_SCRIPT_API:I("RESOLVE_SCRIPT_API")??o,RESOLVE_SCRIPT_LIB:await mr(n),PYTHONPATH:F(I("RESOLVE_SCRIPT_API")??o,"Modules"),...i?Object.fromEntries(gr.map(d=>[d,i])):{}},timeoutMs:t})}finally{await pe(m).catch(()=>{})}let u=c.stdout.trim().split(`
|
|
6
6
|
`).pop()??"";try{return JSON.parse(u)}catch{return{ok:!1,why:"bridge",detail:c.code==="ENOENT"||/Microsoft Store/.test(c.stderr)?`${s} is not installed (Resolve's scripting needs Python 3: python.org)`:c.stderr.trim().split(`
|
|
7
|
-
`).pop()||(typeof c.code=="string"?`the Resolve bridge could not start: ${c.code}`:`no answer from Resolve within ${Math.round(t/1e3)} s`)}}},q=class extends Error{constructor(t,n){super(n);this.why=t}},wr={module:"Install DaVinci Resolve (its scripting module ships with it).",no_connection:"Start Resolve and set Preferences > System > General > External scripting using: Local (Resolve Studio).",no_project:"Open a project in Resolve."},_e=class{constructor(e=hr){this.runner=e;this.host="resolve";this.restore=new Map;this.startNotes=new Map}async call(e,t={},n=6e4){let o=await this.runner(e,t,n);if(o.ok)return o;throw o.why==="resolve_error"&&/NoneType' object is not callable/.test(String(o.detail))&&!(await this.runner("version",{},1e4)).ok?new q("host_quit",`resolve: Resolve stopped responding during ${e} (it may have quit; see its log, ResolveDebug.txt). Restart Resolve and try again.`):new q(o.why??"unknown",`resolve: ${o.detail||o.why}`)}async support(){let e=await this.runner("version",{},15e3),t=e.ok?e.product==="DaVinci Resolve Studio"?{ok:!0}:{ok:!1,reason:`${e.product} has no external scripting (Resolve Studio has)`}:{ok:!1,reason:e.detail??String(e.why),setup:wr[e.why??""]},n=t;if(t.ok){let o=await ut();n=o.readiness==="ready"||o.readiness==="unknown"?{ok:!0}:{ok:!1,reason:`renderplugin: ${o.readiness}`,setup:o.next}}return{export:t,open:t,render:t,markers:t,renderplugin:n}}async current(){return await this.call("current")}async project(e){return await this.call("project",e,e.export_dir||e.grades?9e5:12e4)}async clipLut(e){return await this.call("clip_lut",e,6e4)}async items(e){return await this.call("items",e,e.selected?15e3:12e4)}async apply(e){let t=e.ops.filter(o=>o.op==="edit_keys");if(t.length){let o=e.ops.filter(a=>a.op!=="edit_keys"),s=o.length?await this.apply({...e,ops:o}):{project:"",timeline:e.timeline??"",results:[],undo:[],applied:0,failed:0},i=await this.alignedCopy(e,t),m=i.results.filter(a=>a.ok).length;return{...s,project:s.project||i.project,timeline:s.timeline||i.timeline,results:[...s.results,...i.results],applied:s.applied+m,failed:s.failed+i.results.length-m}}let n=e.ops.filter(o=>(o.op==="grade_sizing"&&(o.target==="input"||o.target==="node")&&!o.reset||o.op==="node_structure")&&o.item&&"track"in o.item);for(let o of n){let s=o.node_structure??o.structure_path;if(!s)continue;let i=/<Body>([0-9a-fA-F]+)<\/Body>/.exec(new TextDecoder().decode(await le(s)))?.[1];if(!i)throw new q("usage",`${s}: not a Resolve grade still (.drx with a <Body>)`);o.structure=ye(i),o.structure_name=s}if(n.length){let{grades:o,t0:s}=await this.grades(e.timeline,e.into?{into:e.into,scratch_project:e.scratch_project}:{}),i=m=>{let a=m.item;return o.get(`${a.track}:${a.start+s}`)};for(let m of n){let a=i(m);a&&(m.bodies={local:a.local,remote:a.remote})}}return await this.call("apply",e,6e4+e.ops.length*200)}async alignedCopy(e,t){let n=e.into?{into:e.into,scratch_project:e.scratch_project}:{},o=await G("ct-aligned-"),s=i=>({project:"",timeline:e.timeline??"",results:t.map(()=>({op:"edit_keys",ok:!1,refused:["aligned copy"],detail:`refused: ${i}; nothing changed`}))});try{let i=F(o,"export.drt"),m=await this.call("export",{timeline:e.timeline,out_path:i,...n}),a=String(m.timeline),c=Number(m.start_frame??0),{session:u}=await lt(i,"drt"),d=u.timelines[0],f=(d.fps_num??24)/(d.fps_den??1),h=d.tracks.filter(w=>String(w.kind).toLowerCase()==="video"),l=w=>Math.round(w.value*f/w.rate),p=[],g=[];for(let w of t){let T=h[w.item.track-1]?.items.find(P=>{let E=P.timeline_range?.start;return E&&[w.item.start,w.item.start+c].includes(l(E))});T?(At(T,w.keys,f),p.push(w)):g.push(`V${w.item.track}@${w.item.start}`)}let S=await ct("resolve-drt",u),_=typeof S.body=="string"?new TextEncoder().encode(S.body):S.body,v=xt(await le(i),_,p,c);if(!v.keyed.length)return s(`no clip could be keyed (${[...g,...v.missing].join(", ")})`);let A=F(o,`${a.replace(/[^\w.-]+/g,"_").slice(0,100)}_ALIGNED.drt`);await et(A,v.drt);let x=await this.call("open",{path:A,name:`${a} ALIGNED`,link_existing:!0,same_as:a,...n}),b=new Map([...g.map(w=>[w,"not found in the timeline's export"]),...v.missing.map(w=>[w.split(" ")[0],w])]);return{project:String(x.project??""),timeline:String(x.timeline??""),results:t.map(w=>{let T=`V${w.item.track}@${w.item.start}`;return b.has(T)?{op:"edit_keys",ok:!1,refused:["not keyed"],detail:`refused: ${b.get(T)}; nothing changed`}:{op:"edit_keys",ok:!0,detail:`${w.keys.length} Edit-page keyframes on "${x.timeline}" (a copy of "${a}" with every grade and setting; "${a}" itself unchanged)`}})}}catch(i){return s(i instanceof Error?i.message:String(i))}finally{await pe(o).catch(()=>{})}}async grades(e,t){let n=await G("ct-grades-");try{let o=F(n,"grades.drt"),s=await this.call("export",{timeline:e,out_path:o,...t});return{grades:await le(o).then(_t).catch(()=>new Map),t0:Number(s.start_frame??0)}}finally{await pe(n).catch(()=>{})}}async presets(e){return await this.call("presets",e,12e4)}async presetAuthor(e){return await this.call("preset_author",e,6e4)}async export(e){if(!e.out_path)throw new q("usage","resolve: export needs out_path");let t=await this.call("export",{timeline:e.timeline,out_path:e.out_path,...e.clip_id?{clip_id:e.clip_id}:{}});return{path:String(t.path),format:"drt",project:String(t.project),timeline:String(t.timeline)}}async open(e){let t=await this.call("open",{path:e.path,into:e.into??"current",name:e.name,media_dir:e.media_dirs?.[0],stay:e.stay??!1,folder:e.folder,create_folder:e.create_folder??!1,link_existing:e.link_existing??!1,...e.settings_from?{settings_from:e.settings_from}:{}},3e5),n=[...t.notes??[]];return(e.media_dirs?.length??0)>1&&n.push(`Resolve searches one media folder per import; used ${e.media_dirs[0]}`),{project:String(t.project),timeline:String(t.timeline),notes:n,restored:!!t.restored,...t.folder?{folder:String(t.folder)}:{},...t.settings?{settings:String(t.settings)}:{}}}async renderStart(e){let t=await this.call("render_start",{...e}),n=String(t.job_id);if(t.queued)return{job_id:n,state:"queued",percent:0,notes:["left in Resolve's render queue: start it on the Deliver page"]};this.restore.set(n,t.restore);let o=t.rejected_settings??[];return o.length&&this.startNotes.set(n,[`Resolve refused render setting(s) ${o.join(", ")} for this format; the rest were applied`]),{job_id:n,state:"queued",percent:0}}async renderStatus(e){let t=await this.call("render_status",{job_id:e},15e3),n={job_id:e,state:t.state,percent:Number(t.percent??0)};if(t.error&&(n.error=String(t.error)),n.state==="complete"||n.state==="failed"){let o=await this.call("render_finish",{job_id:e,restore:this.restore.get(e)});this.restore.delete(e),o.output&&(n.outputs=[String(o.output)]);let s=[...this.startNotes.get(e)??[],...o.tracks?[Rt(o)]:[]];this.startNotes.delete(e),s.length&&(n.notes=s)}return n}async renderCancel(e){let t=await this.call("render_cancel",{job_id:e,restore:this.restore.get(e)});return this.restore.delete(e),{job_id:e,state:"cancelled",percent:0,...t.output?{outputs:[String(t.output)]}:{},...t.tracks?{notes:[Rt(t)]}:{}}}},Rt=r=>{let e=r.tracks.map(t=>`V${t}`).join(", ");return r.tracks_restored?`video track(s) ${e} switched back on`:`could NOT switch video track(s) ${e} back on: re-enable them on the Edit page`};async function wn(r,e){let t=[];for await(let n of rt(r))n.isFile&&n.name.startsWith(e)&&t.push(F(r,n.name));return t.sort()}var yr="ws://localhost:1985",Pt="localhost",Et="conform_tools",Ot="conform.tools ",Mt="Video_Full",_r=r=>!!r&&typeof r=="object"&&"_handle"in r&&"_id"in r,z=class extends Error{constructor(t,n){super(n);this.code=t}},Fe=class r{constructor(e){this.ws=e;this.next=1;this.waiting=new Map;e.onMessage(t=>{let n;try{n=JSON.parse(t)}catch{return}let o=typeof n.id=="number"?this.waiting.get(n.id):void 0;if(!o)return;if(this.waiting.delete(n.id),n.error===void 0||n.error===null)return o.ok(n.result??null);let s=n.error;o.no(typeof s=="string"?new z(n.code??-1,s):new z(s.code??n.code??-1,s.message??JSON.stringify(s)))}),e.onClose(()=>{for(let t of this.waiting.values())t.no(new z("closed","Baselight closed the FLAPI connection"));this.waiting.clear()})}static async connect(e,t=3e3){let n=new r(await pt(e,{maxBytes:67108864,timeoutMs:t})),o=await br();return o&&await n.call("authenticate",{username:I("USER")??I("USERNAME")??"conform",token:o},null,t).catch(()=>null),n}call(e,t={},n=null,o=12e4){let s=this.next++;return new Promise((i,m)=>{let a=setTimeout(()=>{this.waiting.delete(s),m(new z("timeout",`${e}: no answer from Baselight within ${Math.round(o/1e3)} s`))},o);this.waiting.set(s,{ok:c=>{clearTimeout(a),i(c)},no:c=>{clearTimeout(a),m(c)}}),this.ws.send(JSON.stringify({jsonrpc:"2.0",method:e,target:n?n._id:null,params:t,id:s}))})}async forget(...e){for(let t of e)_r(t)&&await this.call("forget",{},t).catch(()=>null)}close(){this.ws.close()}};async function br(){let r=I("FLAPI_TOKEN");if(r)return r.trim();let e=V()==="darwin"?F(Te(),"Library","Preferences","FilmLight","flapi-token"):F(Te(),".filmlight","flapi-token");try{return(await Ze(e)).trim()||null}catch{return null}}var $t=(...r)=>Object.fromEntries(r.map(e=>[e,1])),Sr={[-30]:30,[-31]:30,[-32]:30,[-34]:25,[-35]:24};function be(r){if(!r||typeof r!="object")return null;let e=typeof r.fps=="string"?{TC_30DF:-30,TC_60HDF:-31}[r.fps]??Number(r.fps):r.fps,t=e>0?e:Sr[e]??30,n=((r.h*60+r.m)*60+r.s)*t+r.f;if(e!==-30&&e!==-31)return n;let o=r.h*60+r.m;return n-2*(o-Math.floor(o/10))}function vr(r,e,t){let n=Math.round(e),o=r;if(t&&n===30){let c=Math.floor(o/17982),u=o%17982;o+=18*c+(u>2?2*Math.floor((u-2)/1798):0)}let s=o%n,i=Math.floor(o/n)%60,m=Math.floor(o/n/60)%60;return{_type:"timecode",h:Math.floor(o/n/3600)%24,m,s:i,f:s,phase:0,fps:t&&n===30?-30:n,wrap:24}}function Nt(r){let e=Math.round(r);return Math.abs(r-e)<.005?e:Math.abs(r-e*1e3/1001)<.01?e*1e3/1001:r}var j=class extends Error{constructor(t,n){super(`baselight: ${n}`);this.why=t}},kr={darwin:"/Applications/Baselight",linux:"/usr/fl/baselight"},Se=class{constructor(e){this.url=e;this.host="baselight";this.jobs=new Map}async conn(e=3e3){let t=this.url??I("CONFORM_BASELIGHT_URL")??yr;try{return await Fe.connect(t,e)}catch(n){let o=await ae(kr[V()]??"/nonexistent");throw new j(o?"not_running":"not_installed",o?`Baselight is not answering FLAPI at ${t} (${n.message})`:"Baselight is not installed on this machine")}}async with(e){let t=await this.conn();try{return await e(t)}catch(n){throw n instanceof j?n:new j("flapi",n.message)}finally{t.close()}}async support(){let e;try{let t=await this.with(n=>n.call("Application.get_application_info"));e=/baselight|daylight/i.test(t.Product??"")?{ok:!0}:{ok:!1,reason:`the FLAPI server is ${t.Product??"unknown"}, not the Baselight app (port 1984 is the headless flapid)`,setup:"Point CONFORM_BASELIGHT_URL at the running Baselight (ws://localhost:1985)."}}catch(t){let n=t instanceof j?t.why:"flapi";e={ok:!1,reason:t.message.replace(/^baselight: /,""),setup:n==="not_installed"?"Install FilmLight Baselight (FLAPI ships with it; nothing else to install).":"Start Baselight. Its API server listens on port 1985 by default (Preferences > Advanced > API Server)."}}return{export:e,open:e,render:e,markers:{ok:!1,reason:"not wired for Baselight yet (FLAPI has marks: Scene.add_mark)"},renderplugin:{ok:!1,reason:"the renderplugin is a DaVinci Resolve plugin"}}}async scenePath(e,t,n){if(t?.includes(":")){let i=await e.call("Scene.parse_path",{str:t});return{host:i.Host,job:i.Job,scene:i.Scene}}let o=await this.current(e),s=n??o?.job;if(t&&s)return{host:o?.host??Pt,job:s,scene:t};if(!o)throw new j("no_scene",t?`no job to find scene "${t}" in: pass project (the job) or "host:job:scene"`:'no scene is open in Baselight: open one, or name it ("host:job:scene")');return o}async current(e){let t=await e.call("Application.get").catch(()=>null);if(!t)return null;try{let n=await e.call("Application.get_current_scene",{},t);if(!n)return null;try{let o=await e.call("Scene.get_scene_pathname",{},n),[s,i,...m]=o.split(":");return m.length?{host:s,job:i,scene:m.join(":")}:null}finally{await e.forget(n)}}finally{await e.forget(t)}}async export(e){if(!e.out_path)throw new j("usage","export needs out_path");return await this.with(async t=>{let n=await this.scenePath(t,e.timeline),o=await t.call("Scene.open_scene",{scenepath:{Host:n.host,Job:n.job,Scene:n.scene},flags:$t("OPENFLAG_READ_ONLY")});try{let s=await Rr(t,o,n.scene);await Q(de(e.out_path)),await ue(e.out_path,JSON.stringify(s,null,1))}finally{await t.call("Scene.close_scene",{},o).catch(()=>null),await t.forget(o)}return{path:e.out_path,format:"otio",project:n.job,timeline:n.scene}})}async open(e){let{readTimeline:t}=await import("./timeline-5TGA5HBY.js"),{session:n}=await t(e.path),o=n.timelines.find(u=>u.kind!=="compound")??n.timelines[0];if(!o)throw new j("usage",`no timeline in ${e.path}`);let s=new Map((n.media_references??[]).map(u=>[u.id,u])),i=o.fps_num/o.fps_den,m=o.tracks.filter(u=>u.kind==="Video").sort((u,d)=>u.track_index-d.track_index),a=[];m.length>1&&a.push(`placed V1 only: Baselight builds layers above a shot, which FLAPI cannot place in time; ${m.slice(1).reduce((u,d)=>u+d.items.filter(f=>f.kind==="clip").length,0)} clip(s) on V2+ not placed`);let c=(m[0]?.items??[]).filter(u=>u.kind==="clip"||u.kind==="gap").sort((u,d)=>u.timeline_range.start.value-d.timeline_range.start.value);return await this.with(async u=>{let d=e.into==="scratch"?null:await this.current(u);e.into!=="scratch"&&!d&&a.push(`no scene open in Baselight, so it went into our job ${Et}`);let f=d?.job??Et,h=d?.host??Pt;await u.call("JobManager.job_exists",{host:h,jobname:f})||await u.call("JobManager.create_job",{host:h,jobname:f});let l=(e.name??o.name??"conform.tools").replace(/[:/\\]+/g,"_"),p=l;for(let w=2;await u.call("JobManager.scene_exists",{host:h,jobname:f,scenename:p});w++)p=`${l} ${w}`;let g=await u.call("FormatSet.factory_formats"),S=o.resolution_w&&o.resolution_h?await u.call("FormatSet.get_basic_format_name",{width:o.resolution_w,height:o.resolution_h},g):null;await u.forget(g);let _=await u.call("Scene.new_scene",{scenepath:{Host:h,Job:f,Scene:p},options:{format:S,colourspace:Mt,frame_rate:i}},null,3e5),v=0,A=0,x=0,b=0;try{await u.call("Scene.start_delta",{name:"conform.tools open"},_);try{let w=0;for(let P of c){let E=P.timeline_range.start.value,N=P.timeline_range.duration.value;if(E>w&&(await Le(u,_,E-w),x++),w=Math.max(w,E+N),P.kind==="gap"){await Le(u,_,N),x++;continue}let M=(P.media_reference_id?s.get(P.media_reference_id):void 0)?.target_url?.replace(/^file:\/\//,""),y=P.source_range,k=M&&y?await Ar(u,M,Math.round(y.start.value),Math.round(y.start.value)+N-1):null;if(!k){await Le(u,_,N),A++;continue}y&&Math.abs(y.duration.value-N)>.5&&b++;let L=await u.call("Scene.insert_sequence",{sequence:k,where:"INSERT_END",relativeTo:null,colourSpace:null,format:null,frameRate:i},_);await u.forget(k,L),v++}let T=await u.call("Scene.get_scene_settings",{},_);await u.call("SceneSettings.set",{values:{StartTimecode:vr(o.start_frame??0,i,!!o.is_drop_frame)}},T),await u.forget(T),await u.call("Scene.end_delta",{},_)}catch(w){throw await u.call("Scene.cancel_delta",{},_).catch(()=>null),w}await u.call("Scene.save_scene",{},_,3e5)}catch(w){throw await u.call("Scene.close_scene",{},_).catch(()=>null),await u.forget(_),await u.call("JobManager.delete_scene",{host:h,jobname:f,scenename:p}).catch(()=>null),w}return await u.call("Scene.close_scene",{},_),await u.forget(_),a.unshift(`new scene ${h}:${f}:${p}: ${v} shot(s)${x?`, ${x} gap(s) as black`:""}`),A&&a.push(`${A} clip(s) had no media on disk at their path: placed as black of the same length (relink in Baselight's Conform view)`),b&&a.push(`${b} retimed clip(s) placed at normal speed: FLAPI has no retime setter`),p!==l&&a.push(`"${l}" was taken in ${f}: named "${p}"`),e.media_dirs?.length&&a.push("media_dirs not used: Baselight places each clip from its own path"),e.stay&&a.push("stay: FLAPI cannot switch the scene the app shows; open it from the Scenes browser"),{project:f,timeline:p,notes:a,restored:!0}})}async renderStart(e){if(e.disable_tracks?.length)throw new j("usage","disable_tracks: a Baselight render takes every layer or one (RenderTrack); leave the tracks out in the scene");if(e.audio_tracks?.length||e.renderplugin)throw new j("usage","audio_tracks and renderplugin are DaVinci Resolve options");return await this.with(async t=>{let n=await this.scenePath(t,e.timeline,e.project),o=await t.call("Scene.open_scene",{scenepath:{Host:n.host,Job:n.job,Scene:n.scene},flags:$t("OPENFLAG_READ_ONLY")}),s=null,i=null;try{s=await t.call("RenderSetup.create_from_scene",{scene:o});let m=await t.call("RenderSetup.get_num_deliverables",{},s),a=0;if(e.preset){let l=await t.call("RenderSetup.get_deliverable_names",{},s);if(a=l.indexOf(e.preset),a<0)throw new j("usage",`no deliverable "${e.preset}" in ${n.scene} (it has: ${l.join(", ")||"none"})`)}let c=await t.call("RenderSetup.get_deliverable",{index:a},s),u=e.name??n.scene.replace(/[^\w.-]+/g,"_");Object.assign(c,{Disabled:0,Container:"",OutputDirectory:e.target_dir,FileNamePrefix:u}),e.preset||Object.assign(c,{Name:"conform.tools",IsMovie:1,FileType:"lqtmov",MovieCodec:"apch",ImageOptions:{},FileNameExtension:".mov",RenderColourSpace:Mt,HandleEmptyFrames:"GMREB_BLACK",HandleIncompleteStacks:"GMREB_BLACK",HandleError:"BLACK",EmbedTimecode:1}),e.audio||(c.AudioCodec=""),await Q(e.target_dir),await t.call("RenderSetup.set_deliverable",{index:a,deliverable:c},s);for(let l=0;l<m;l++)l!==a&&await t.call("RenderSetup.set_deliverable_enabled",{index:l,enabled:0},s);if(e.range){let l=await t.call("Scene.get_scene_settings",{},o),p=be(await t.call("SceneSettings.get_single",{key:"StartTimecode"},l))??0;await t.forget(l);let g=e.range.in>=p?p:0;await t.call("RenderSetup.set_frames",{frames:[{Start:e.range.in-g,End:e.range.out-g}]},s)}else await t.call("RenderSetup.select_all",{},s);let d=await t.call("RenderSetup.get_output_filename_for_deliverable",{index:a},s);i=await t.call("QueueManager.create_local");let f=await t.call("RenderSetup.submit_to_queue",{queue:i,opname:`${Ot}${u}`},s),h=String(f.ID);return this.jobs.set(h,{op:f.ID,out:d,notes:f.Warning?[`Baselight: ${f.Warning}`]:[]}),{job_id:h,state:"queued",percent:0}}finally{await t.forget(s,i),await t.call("Scene.close_scene",{},o).catch(()=>null),await t.forget(o)}})}async ours(e,t,n){let o=Number(n),s=await e.call("QueueManager.get_operation",{id:o},t).catch(()=>null),i=String(s?.Description??s?.Name??"");if(!this.jobs.has(n)&&!i.startsWith(Ot))throw new j("not_ours",`queue operation ${n} is not a conform.tools render: left alone`);return o}async renderStatus(e){return await this.with(async t=>{let n=await t.call("QueueManager.create_local");try{let o=await this.ours(t,n,e),s=await t.call("QueueManager.get_operation_status",{id:o},n),i=xr(s.Status),m=Number(s.Progress??0),a={job_id:e,state:i,percent:i==="complete"?100:Math.round(m<=1?m*100:m)};if(i==="failed"||i==="complete"&&s.Errors){let u=(await t.call("QueueManager.get_operation_log",{id:o},n).catch(()=>[])).filter(d=>/fail|error|warn/i.test(d.Type)).slice(-6).map(d=>`${d.Message}${d.Detail?`: ${d.Detail}`:""}`);a.error=[s.ProgressText,...u].filter(Boolean).join("; ")||"Baselight reported a failed render",i==="complete"&&(a.state="failed")}if(a.state==="complete"||a.state==="failed"||a.state==="cancelled"){let c=this.jobs.get(e);a.state==="complete"&&c&&(a.outputs=[c.out]),c?.notes.length&&(a.notes=c.notes),await t.call("QueueManager.delete_operation",{id:o},n).catch(()=>null),this.jobs.delete(e)}return a}finally{await t.forget(n)}})}async renderCancel(e){return await this.with(async t=>{let n=await t.call("QueueManager.create_local");try{let o=await this.ours(t,n,e);return await t.call("QueueManager.delete_operation",{id:o},n),this.jobs.delete(e),{job_id:e,state:"cancelled",percent:0}}finally{await t.forget(n)}})}};function xr(r){let e=String(r).replace(/^OPSTATUS_/i,"").toLowerCase();return e==="done"?"complete":e==="active"?"rendering":e==="stopped"?"cancelled":e==="failed"||e==="crashed"||e==="toonew"?"failed":"queued"}async function Le(r,e,t){let n=await r.call("Scene.insert_blank",{red:0,green:0,blue:0,duration:t,where:"INSERT_END",relativeTo:null,colourSpace:null},e);await r.forget(n)}async function Ar(r,e,t,n){let o=await r.call("SequenceDescriptor.get_for_template",{template:e,start:null,end:null}).catch(()=>[]);if(!o?.length)return null;let s=await r.call("SequenceDescriptor.get_start_handle",{},o[0]);await r.forget(...o);let i=await r.call("SequenceDescriptor.get_for_template",{template:e,start:s+t,end:s+n});return i?.length?(await r.forget(...i.slice(1)),i[0]):null}var Ie=(r,e)=>({OTIO_SCHEMA:"RationalTime.1",rate:e,value:r}),je=(r,e,t)=>({OTIO_SCHEMA:"TimeRange.1",start_time:Ie(r,t),duration:Ie(e,t)});async function Rr(r,e,t){let n=Nt(await r.call("Scene.get_working_frame_rate",{},e)),o=await r.call("Scene.get_scene_settings",{},e),s=be(await r.call("SceneSettings.get_single",{key:"StartTimecode"},o))??0;await r.forget(o);let i=await r.call("Scene.get_num_shots",{},e),m=i?await r.call("Scene.get_shot_ids",{firstIndex:0,lastIndex:i-1},e):[],a=[];for(let d of m){let f=Math.round(d.StartFrame),h=Math.round(d.EndFrame),l=await r.call("Scene.get_shot",{shot_id:d.ShotId},e);try{let p=await r.call("Shot.get_sequence_descriptor",{},l).catch(()=>null);if(!p){a.push({start:f,end:h,name:`shot ${d.ShotId}`});continue}try{let g=Nt(await r.call("Shot.get_frame_rate",{},l))||n,S=be(await r.call("Shot.get_src_start_timecode",{},l)),_=await r.call("Shot.get_src_start_frame",{},l),v=await r.call("Shot.get_src_end_frame",{},l),x=await r.call("SequenceDescriptor.is_movie",{},p)?Ye(await r.call("SequenceDescriptor.get_path",{},p),await r.call("SequenceDescriptor.get_name",{},p)):await r.call("SequenceDescriptor.get_full_filename_with_d",{},p),b=await r.call("SequenceDescriptor.get_name",{},p),w=await r.call("SequenceDescriptor.get_tape",{index:0},p).catch(()=>""),T=await r.call("SequenceDescriptor.get_start_frame",{},p),P=await r.call("SequenceDescriptor.get_start_handle",{},p),E=await r.call("SequenceDescriptor.get_end_handle",{},p),C=(be(await r.call("SequenceDescriptor.get_start_timecode",{index:0},p))??0)-(T-P),M=Math.round(v-_),y=h-f,k={OTIO_SCHEMA:"Clip.2",name:b,enabled:!0,source_range:je(S??C+(_-P),y,g),media_references:{DEFAULT_MEDIA:{OTIO_SCHEMA:"ExternalReference.1",target_url:x,available_range:je(C,E-P+1,g),available_image_bounds:null,name:b,metadata:{}}},active_media_reference_key:"DEFAULT_MEDIA",effects:M&&M!==y?[{OTIO_SCHEMA:"LinearTimeWarp.1",name:"",effect_name:"LinearTimeWarp",time_scalar:M/y,metadata:{}}]:[],markers:[],metadata:w?{baselight:{tape:w}}:{}};a.push({start:f,end:h,name:b,clip:k})}finally{await r.forget(p)}}finally{await r.forget(l)}}let c=[];for(let d of[...a].sort((f,h)=>f.start-h.start)){if(!d.clip)continue;let f=c.find(h=>h[h.length-1].end<=d.start);f?f.push(d):c.push([d])}let u=c.map((d,f)=>{let h=[],l=0;for(let p of d)p.start>l&&h.push({OTIO_SCHEMA:"Gap.1",name:"",enabled:!0,source_range:je(0,p.start-l,n),effects:[],markers:[],metadata:{}}),h.push(p.clip),l=p.end;return{OTIO_SCHEMA:"Track.1",name:`V${f+1}`,kind:"Video",enabled:!0,children:h,source_range:null,effects:[],markers:[],metadata:{}}});return{OTIO_SCHEMA:"Timeline.1",name:t,metadata:{baselight:{shots:m.length}},global_start_time:Ie(s,n),tracks:{OTIO_SCHEMA:"Stack.1",name:"tracks",enabled:!0,children:u,source_range:null,effects:[],markers:[],metadata:{}}}}var Tr="127.0.0.1:31416",Pr="/ptsl.PTSL/SendGrpcRequest",Er="CONFORM.TOOLS",Or="CONFORM.TOOLS Desktop",De=[2025,6,0],te=[2025,6],Ve=1e4,Ct=5e3,Mr="ConformTools",$r="Start Pro Tools 2025.6 or newer with a session open (PTSL, its scripting door, listens on 127.0.0.1:31416).",Ue={GetTrackList:3,HostReadyCheck:13,ExportSessionInfoAsText:30,GetSessionSampleRate:35,GetSessionTimeCodeRate:38,GetSessionFeetFramesRate:39,GetSessionName:42,GetSessionPath:43,GetSessionStartTime:44,GetSessionLength:45,GetPTSLVersion:55,GetTransportState:59,ClearMemoryLocation:61,EditMemoryLocation:68,GetMemoryLocations:69,RegisterConnection:70,CreateMemoryLocation:71,SetTimelineSelection:81,GetTimelineSelection:82,GetSessionIDs:97,GetMainCounterFormat:102},Nr=[3,6],Cr=[4,7],Lt=106,Lr=new TextEncoder,jr=new TextDecoder;function ve(r,e){for(;r>127;)e.push(r&127|128),r=Math.floor(r/128);e.push(r)}function jt(r){let e=[];for(let[t,n]of r){if(typeof n=="number"){n&&(ve(t<<3,e),ve(n,e));continue}let o=typeof n=="string"?Lr.encode(n):n;if(o.length){ve(t<<3|2,e),ve(o.length,e);for(let s of o)e.push(s)}}return new Uint8Array(e)}function Ft(r){let e=new Map,t=0,n=()=>{let o=0,s=1,i;do i=r[t++],o+=(i&127)*s,s*=128;while(i&128&&t<r.length);return o};for(;t<r.length;){let o=n(),s=Math.floor(o/8),i=o&7;if(i===0)e.set(s,n());else if(i===2){let m=n();e.set(s,r.subarray(t,t+m)),t+=m}else if(i===1)t+=8;else if(i===5)t+=4;else throw new R("bad_answer",`Pro Tools sent a reply that is not protobuf (wire type ${i})`)}return e}var It=r=>r instanceof Uint8Array?jr.decode(r):"",Fr=r=>typeof r=="number"?r:0;function Ir(r,e,t){let n=jt([[2,r],[3,De[0]],[4,e],[5,De[1]],[6,De[2]]]);return jt([[1,n],[2,t]])}function Dr(r){let e=Ft(r),t=e.get(1);return{status:t instanceof Uint8Array?Fr(Ft(t).get(3)):0,body:It(e.get(2)),error:It(e.get(3))}}var R=class extends Error{constructor(t,n,o){super(n);this.code=t;this.errors=o}};function Ur(r){let e=null;try{e=JSON.parse(r)}catch{}let t=Array.isArray(e)?e:e&&typeof e=="object"?Array.isArray(e.errors)?e.errors:[e]:[],n=t.find(a=>!a.is_warning)??t[0],o=String(n?.command_error_message||r.trim()||"Pro Tools refused the command"),s=n?.command_error_type,m=s===Lt||s==="PT_NoOpenedSession"||s==="CEType_PT_NoOpenedSession"||s===String(Lt)?"no_session":/session id|not registered|register/i.test(o)?"not_registered":"command_failed";return new R(m,o,t.length?t:void 0)}var Ge=class{constructor(e=Tr){this.sessionId="";this.version=null;this.queue=Promise.resolve();let t=/^(127\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})$/.exec(e)??/^\[(::1)\]:(\d{1,5})$/.exec(e);if(!t)throw new R("refused",`${e} is not a loopback IP address and port; PTSL is loopback only`);this.host=t[1],this.port=Number(t[2])}async send(e,t,n){let o;try{o=await ot(this.host,this.port,Pr,Ir(e,this.sessionId,t),n)}catch(i){throw this.sessionId="",this.version=null,i instanceof nt?i.code==="unavailable"?new R("not_running",`Pro Tools is not running (nothing answered on ${this.host}:${this.port})`):i.code==="deadline"?new R("timeout",`Pro Tools did not answer in ${n} ms (a modal dialog or a long command?)`):i.grpcStatus===12?new R("not_ptsl",`the program on ${this.host}:${this.port} is not Pro Tools`):new R("transport",`PTSL transport error: ${i.message}`):i}let s=Dr(o);if(Nr.includes(s.status)){if(!s.body.trim())return null;try{return JSON.parse(s.body)}catch{throw new R("bad_answer","Pro Tools sent a body that is not JSON")}}throw Cr.includes(s.status)?Ur(s.error):new R("bad_status",`Pro Tools answered with task status ${s.status}`)}async handshake(){if(!this.sessionId){let e=await this.send(Ue.RegisterConnection,JSON.stringify({company_name:Er,application_name:Or}),Ct);if(!e?.session_id)throw new R("not_registered","Pro Tools did not give conform.tools a session id");this.sessionId=e.session_id}if(!this.version){let e=await this.send(Ue.GetPTSLVersion,"",Ct),t=o=>Number(e?.[o]??0)||0,n=[t("version"),t("version_minor"),t("version_revision")];if(n[0]<te[0]||n[0]===te[0]&&n[1]<te[1])throw this.sessionId="",new R("host_too_old",`Pro Tools ${n[0]}.${n[1]} is too old; conform.tools needs Pro Tools ${te[0]}.${te[1]} or newer`);this.version=n}}call(e,t,n=Ve){let o=async()=>{if(e==="RegisterConnection")throw new R("refused","RegisterConnection is sent by the client itself");let i=Ue[e];if(i===void 0)throw new R("unknown_command",`${e} is not a PTSL command conform.tools sends`);let m=t==null?"":typeof t=="string"?t:JSON.stringify(t);for(let a=0;;a++){if(await this.handshake(),e==="GetPTSLVersion"){let[c,u,d]=this.version;return{version:c,version_minor:u,version_revision:d}}try{return await this.send(i,m,n)}catch(c){if(c instanceof R&&c.code==="not_registered"&&a===0){this.sessionId="";continue}throw c}}},s=this.queue.then(o,o);return this.queue=s.catch(()=>{}),s}},He={23976:24e3/1001,24:24,25:25,2997:3e4/1001,30:30,47952:48e3/1001,48:48,50:50,5994:6e4/1001,60:60,100:100,11988:12e4/1001,120:120},Hr={1:["23976",!1],2:["24",!1],3:["25",!1],4:["2997",!1],5:["2997",!0],6:["30",!1],7:["30",!0],8:["47952",!1],9:["48",!1],10:["50",!1],11:["5994",!1],12:["5994",!0],13:["60",!1],14:["60",!0],15:["100",!1],16:["11988",!1],17:["11988",!0],18:["120",!1],19:["120",!0]};function Br(r){if(typeof r=="number"||typeof r=="string"&&/^\d+$/.test(r.trim())){let t=Hr[Number(r)];return t?{fps:He[t[0]],drop:t[1]}:null}let e=/Fps(\d+)(Drop)?/i.exec(String(r??""));return e&&He[e[1]]?{fps:He[e[1]],drop:!!e[2]}:null}var Vr=/^-?\d{1,2}[:;.]\d{2}[:;.]\d{2}[:;.,]\d{2,3}(\.\d+)?$/,Gr=/^(?:(\d+):)?(\d+):(\d{2}(?:\.\d+)?)$/;function Be(r,e){let t=String(r??"").trim();if(Vr.test(t))return it(t.replace(/\.\d+$/,""),e.rate.fps,e.rate.drop);if(/^-?\d+$/.test(t))return e.start+Math.floor(Number(t)*e.rate.fps/e.sampleRate+1e-9);let n=Gr.exec(t);return n?e.start+Math.floor((Number(n[1]??0)*3600+Number(n[2])*60+Number(n[3]))*e.rate.fps+1e-9):null}var ke=["Blue","Cyan","Green","Yellow","Red","Pink","Purple","Fuchsia","Rose","Lavender","Sky","Mint","Lemon","Sand","Cocoa","Cream"],Dt=r=>{let e=Number(r);return e>=1?ke[(e-1)%ke.length]:ke[0]},qr=r=>Math.max(0,ke.findIndex(e=>e.toLowerCase()===String(r??"").toLowerCase()))+1,Ut=/(?:^| )\[ct:((?:[^[\]\\]|\\.)*)\]$/s;function zr(r,e){return!e&&!Ut.test(r)?r:`${r}${r?" ":""}[ct:${e.replace(/[\\[\]]/g,t=>`\\${t}`)}]`}function Jr(r){let e=Ut.exec(r);return e?{note:r.slice(0,e.index),data:e[1].replace(/\\(.)/gs,"$1")}:{note:r,data:""}}function Wr(r){return!r.includes(":")||r.includes("/")||r.includes("\\")?r:`/Volumes/${r.split(":").filter(Boolean).join("/")}`}var xe=class{constructor(e=new Ge){this.ptsl=e;this.host="protools"}async sessionName(e=Ve){try{return String((await this.ptsl.call("GetSessionName",null,e)).session_name??"")}catch(t){if(t instanceof R&&t.code==="no_session")return"";throw t}}async sessionPath(e=Ve){let t=await this.ptsl.call("GetSessionPath",null,e),n=typeof t.session_path=="string"?t.session_path:t.session_path?.path??"";return n?Wr(n):""}async current(e=2e3){try{let t=await this.sessionName(e);return t?{project:t,project_path:await this.sessionPath(e).catch(()=>"")}:null}catch{return null}}async facts(){let e=await this.sessionName();if(!e)throw new R("no_session","protools: no session is open");let t=(await this.ptsl.call("GetSessionTimeCodeRate")).current_setting,n=Br(t);if(!n)throw new R("bad_answer",`protools: a timecode rate conform.tools does not know (${t})`);let o=/(\d{4,6})/.exec(String((await this.ptsl.call("GetSessionSampleRate")).sample_rate??""));if(!o)throw new R("bad_answer","protools: Pro Tools reported a sample rate conform.tools does not know");let s=(await this.ptsl.call("GetSessionStartTime")).session_start_time,i={name:e,rate:n,sampleRate:Number(o[1]),start:0},m=Be(s,i);if(m==null)throw new R("bad_answer",`protools: a session start conform.tools cannot read (${s})`);return{...i,start:m}}async support(){let e={ok:!1,reason:"Pro Tools holds one session at a time, and importing a timeline changes it; write a .ptx or AAF with timeline_write and open that in Pro Tools"},t={ok:!1,reason:"bouncing from Pro Tools (ExportMix) is not wired"},n={ok:!1,reason:"the renderplugin is a DaVinci Resolve plugin"},o;try{o=await this.sessionName(3e3)?{ok:!0}:{ok:!1,reason:"Pro Tools is running with no session open"}}catch(s){o={ok:!1,reason:s instanceof Error?s.message:String(s),setup:$r}}return{export:o,open:e,render:t,markers:o,renderplugin:n}}async export(e){let t=await this.sessionName();if(!t)throw new R("no_session","protools: no session is open");if(e.timeline&&e.timeline!==t)throw new R("not_found",`protools: the open session is "${t}"; Pro Tools has one timeline per session`);let n=await this.sessionPath();if(!n||!await ce(n))throw new R("no_file",`protools: session "${t}" has no saved .ptx on disk${n?` (${n})`:""}; save it in Pro Tools first`);let o=e.out_path??F(await G("conform-protools-"),st(n));return await Q(de(o)),await tt(n,o),{path:o,format:"ptx",project:t,timeline:t}}open(){return Promise.reject(new R("unsupported","protools: open is not supported: Pro Tools holds one session, and importing a timeline into it changes it"))}renderStart(){return Promise.reject(new R("unsupported","protools: rendering (a bounce) is not wired"))}renderStatus(){return this.renderStart()}renderCancel(){return this.renderStart()}async project(){let e=await this.facts(),t=await this.sessionPath().catch(()=>""),n=[],o=[];try{let i=await this.ptsl.call("GetTrackList",{page_limit:1e3,track_filter_list:[{filter:"All",is_inverted:!1}]}),m={video:0,audio:0};for(let a of i.track_list??[]){let c=/video/i.test(String(a.type))?"video":"audio",u=a.track_attributes??{},d=u.is_inactive===!0||/^(true|.*_?(set|on|inactive))$/i.test(String(u.is_inactive??""));n.push({kind:c,index:++m[c],name:String(a.name??""),enabled:!d})}}catch(i){o.push(`tracks not read: ${i instanceof Error?i.message:String(i)}`)}let s=(await this.locations(e).catch(()=>({locs:[]}))).locs.length;return{project:e.name,timeline:e.name,timelines:[e.name],session_path:t,fps:e.rate.fps,drop_frame:e.rate.drop,sample_rate:e.sampleRate,start_tc:Pe(e.start,e.rate.fps,e.rate.drop),ptsl_version:this.ptsl.version?.join("."),markers:s,notes:o,tracks:n,jobs:[],found:{},pool:{path:"",clips:0,folders:[]}}}async locations(e){let t=[];for(let o=0;;){let s=await this.ptsl.call("GetMemoryLocations",{pagination_request:{limit:1e3,offset:o}}),i=(s.memory_locations??[]).filter(m=>m&&typeof m=="object");if(t.push(...i),o+=i.length,!i.length||o>=Number((s.pagination_response??s.stats)?.total??0))break}let n=[];for(let o of t){let s=o.time_properties,i=typeof s=="number"||/^\d+$/.test(String(s))?{1:"Marker",2:"Selection"}[Number(s)]:String(s??"").split("_").pop();if(i!=="Marker"&&i!=="Selection")continue;let m=Be(o.start_time,e);if(m==null)continue;let a=i==="Selection"?Be(o.end_time,e):null,{note:c,data:u}=Jr(String(o.comments??""));n.push({number:Number(o.number)||0,frame:m-e.start,duration:a==null?1:Math.max(1,a-m),name:String(o.name??""),note:c,data:u,color:Dt(o.color_index),raw:o})}return n.sort((o,s)=>o.frame-s.frame||o.number-s.number),{locs:n.filter((o,s)=>s===0||n[s-1].frame!==o.frame),numbers:t.map(o=>Number(o.number)||0)}}async writeFormat(){let e=await this.ptsl.call("GetMainCounterFormat"),t=e.current_setting??e.current_type,n=typeof t=="number"||/^\d+$/.test(String(t))?{3:"TimeCode",5:"Samples"}[Number(t)]:String(t??"").split("_").pop();if(n==="TimeCode")return"timecode";if(n==="Samples")return"samples";throw new R("counter_format","protools: set Pro Tools' main counter to Timecode or Samples to edit markers from conform.tools")}async apply(e){let t=await this.facts();if(e.timeline&&e.timeline!==t.name)throw new R("not_found",`protools: the open session is "${t.name}"`);let{locs:n,numbers:o}=await this.locations(t),s=new Map(n.map(l=>[l.frame,l])),i=null,m=l=>i==="samples"?String(Math.round(l*t.sampleRate/t.rate.fps)):Pe(t.start+l,t.rate.fps,t.rate.drop),a=async(l,p)=>{let g=Math.max(1,Math.round(l.duration??1)),S=p?.number??Math.max(0,...o)+1,_=p?.raw??{},v={number:S,name:l.name??"",start_time:m(l.frame),end_time:m(l.frame+(g>1?g:0)),time_properties:g>1?"TP_Selection":"TP_Marker",reference:_.reference||"MLR_Absolute",general_properties:_.general_properties||{zoom_settings:!1,pre_post_roll_times:!1,track_visibility:!1,track_heights:!1,group_enables:!1,window_configuration:!1},comments:zr(l.note??"",l.data??""),color_index:qr(l.color),location:_.location||"MLC_MainRuler",..._.track_name?{track_name:_.track_name}:{}};await this.ptsl.call("CreateMemoryLocation",v),o.push(S),s.set(l.frame,{number:S,frame:l.frame,duration:g,name:l.name??"",note:l.note??"",data:l.data??"",color:Dt(v.color_index),raw:v})},c=async l=>{await this.ptsl.call("ClearMemoryLocation",{location_list:[l.number]}),s.delete(l.frame),o.splice(o.indexOf(l.number),1)},u=l=>({op:"marker_add",frame:l.frame,color:l.color,name:l.name,note:l.note,duration:l.duration,...l.data?{data:l.data}:{}}),d=[],f=[];for(let l of e.ops){let p=Number(l.frame);try{if(!l.op.startsWith("marker_")||l.item){d.push({op:l.op,ok:!1,detail:`protools: '${l.op}' is not reachable over PTSL (timeline markers only)`});continue}if(!Number.isInteger(p)){d.push({op:l.op,ok:!1,detail:"frame must be a whole number"});continue}i??=await this.writeFormat();let g=s.get(p);if(l.op==="marker_add")g&&await c(g),await a({frame:p,color:l.color,name:l.name,note:l.note,duration:Number(l.duration??1),data:l.data||Mr}),d.push({op:l.op,ok:!0}),f.unshift({op:"marker_delete",frame:p},...g?[u(g)]:[]);else if(l.op==="marker_update"){if(!g){d.push({op:l.op,ok:!1,detail:`no marker at frame ${p}`});continue}let S=l.to_frame!==void 0?Number(l.to_frame):p;if(!Number.isInteger(S)){d.push({op:l.op,ok:!1,detail:"to_frame must be a whole number"});continue}if(S!==p&&s.has(S)){d.push({op:l.op,ok:!1,detail:`frame ${S} already has a marker`});continue}await c(g);let _=(v,A)=>l[v]!==void 0?l[v]:A;await a({frame:S,color:_("color",g.color),name:_("name",g.name),note:_("note",g.note),duration:Number(_("duration",g.duration)),data:_("data",g.data)},g),d.push({op:l.op,ok:!0}),f.unshift({op:"marker_update",frame:S,color:g.color,name:g.name,note:g.note,duration:g.duration,data:g.data,...S!==p?{to_frame:p}:{}})}else if(l.op==="marker_delete"){if(!g){d.push({op:l.op,ok:!1,detail:`no marker at frame ${p}`});continue}await c(g),d.push({op:l.op,ok:!0}),f.unshift(u(g))}else d.push({op:l.op,ok:!1,detail:`protools: unknown marker op '${l.op}'`})}catch(g){d.push({op:l.op,ok:!1,detail:g instanceof Error?g.message:String(g)})}}let h=d.filter(l=>l.ok).length;return{project:t.name,timeline:t.name,results:d,undo:f,applied:h,failed:d.length-h}}};var Kr="Install the conform.tools panel in Media Composer (mcp/hosts/avid/panel: package it, copy the .avpi into PanelSDKPlugins; an unsigned panel needs Avid's Feature Toggle Files), then open Tools > CONFORM.TOOLS. Its page loads from this engine's host bridge (port 48127) and connects by itself.",Qr="Install the conform.tools hook (host_setup host=flame action=install_panel), then in Flame: Flame menu > Python > Rescan Python Hooks (or restart Flame), then Flame menu > CONFORM.TOOLS > Connect to CONFORM.TOOLS (or Connect Automatically).",Yr="Install the conform.tools panel (host_setup host=nuke action=install_panel) and restart Nuke Studio / Hiero, then CONFORM.TOOLS > Connect (or tick Connect automatically in its panel).",Ht={resolve:new _e,premiere:new mt,avid:new fe({host:"avid",label:"Media Composer",setup:Kr}),flame:new fe({host:"flame",label:"Flame",setup:Qr,items:!0}),nuke:new fe({host:"nuke",label:"Nuke Studio",setup:Yr,items:!0}),baselight:new Se,protools:new xe};function Mn(r,e){Ht[r]=e}function $n(r){return Ht[r]??dt(r,"not wired yet")}export{_t as a,on as b,hr as c,wn as d,xe as e,Kr as f,Qr as g,Yr as h,Mn as i,$n as j};
|
|
7
|
+
`).pop()||(typeof c.code=="string"?`the Resolve bridge could not start: ${c.code}`:`no answer from Resolve within ${Math.round(t/1e3)} s`)}}},q=class extends Error{constructor(t,n){super(n);this.why=t}},wr={module:"Install DaVinci Resolve (its scripting module ships with it).",no_connection:"Start Resolve and set Preferences > System > General > External scripting using: Local (Resolve Studio).",no_project:"Open a project in Resolve."},_e=class{constructor(e=hr){this.runner=e;this.host="resolve";this.restore=new Map;this.startNotes=new Map}async call(e,t={},n=6e4){let o=await this.runner(e,t,n);if(o.ok)return o;throw o.why==="resolve_error"&&/NoneType' object is not callable/.test(String(o.detail))&&!(await this.runner("version",{},1e4)).ok?new q("host_quit",`resolve: Resolve stopped responding during ${e} (it may have quit; see its log, ResolveDebug.txt). Restart Resolve and try again.`):new q(o.why??"unknown",`resolve: ${o.detail||o.why}`)}async support(){let e=await this.runner("version",{},15e3),t=e.ok?e.product==="DaVinci Resolve Studio"?{ok:!0}:{ok:!1,reason:`${e.product} has no external scripting (Resolve Studio has)`}:{ok:!1,reason:e.detail??String(e.why),setup:wr[e.why??""]},n=t;if(t.ok){let o=await ut();n=o.readiness==="ready"||o.readiness==="unknown"?{ok:!0}:{ok:!1,reason:`renderplugin: ${o.readiness}`,setup:o.next}}return{export:t,open:t,render:t,markers:t,renderplugin:n}}async current(){return await this.call("current")}async project(e){return await this.call("project",e,e.export_dir||e.grades?9e5:12e4)}async clipLut(e){return await this.call("clip_lut",e,6e4)}async items(e){return await this.call("items",e,e.selected?15e3:12e4)}async apply(e){let t=e.ops.filter(o=>o.op==="edit_keys");if(t.length){let o=e.ops.filter(a=>a.op!=="edit_keys"),s=o.length?await this.apply({...e,ops:o}):{project:"",timeline:e.timeline??"",results:[],undo:[],applied:0,failed:0},i=await this.alignedCopy(e,t),m=i.results.filter(a=>a.ok).length;return{...s,project:s.project||i.project,timeline:s.timeline||i.timeline,results:[...s.results,...i.results],applied:s.applied+m,failed:s.failed+i.results.length-m}}let n=e.ops.filter(o=>(o.op==="grade_sizing"&&(o.target==="input"||o.target==="node")&&!o.reset||o.op==="node_structure")&&o.item&&"track"in o.item);for(let o of n){let s=o.node_structure??o.structure_path;if(!s)continue;let i=/<Body>([0-9a-fA-F]+)<\/Body>/.exec(new TextDecoder().decode(await le(s)))?.[1];if(!i)throw new q("usage",`${s}: not a Resolve grade still (.drx with a <Body>)`);o.structure=ye(i),o.structure_name=s}if(n.length){let{grades:o,t0:s}=await this.grades(e.timeline,e.into?{into:e.into,scratch_project:e.scratch_project}:{}),i=m=>{let a=m.item;return o.get(`${a.track}:${a.start+s}`)};for(let m of n){let a=i(m);a&&(m.bodies={local:a.local,remote:a.remote})}}return await this.call("apply",e,6e4+e.ops.length*200)}async alignedCopy(e,t){let n=e.into?{into:e.into,scratch_project:e.scratch_project}:{},o=await G("ct-aligned-"),s=i=>({project:"",timeline:e.timeline??"",results:t.map(()=>({op:"edit_keys",ok:!1,refused:["aligned copy"],detail:`refused: ${i}; nothing changed`}))});try{let i=F(o,"export.drt"),m=await this.call("export",{timeline:e.timeline,out_path:i,...n}),a=String(m.timeline),c=Number(m.start_frame??0),{session:u}=await lt(i,"drt"),d=u.timelines[0],f=(d.fps_num??24)/(d.fps_den??1),h=d.tracks.filter(w=>String(w.kind).toLowerCase()==="video"),l=w=>Math.round(w.value*f/w.rate),p=[],g=[];for(let w of t){let T=h[w.item.track-1]?.items.find(P=>{let E=P.timeline_range?.start;return E&&[w.item.start,w.item.start+c].includes(l(E))});T?(At(T,w.keys,f),p.push(w)):g.push(`V${w.item.track}@${w.item.start}`)}let S=await at("resolve-drt",u),_=typeof S.body=="string"?new TextEncoder().encode(S.body):S.body,v=xt(await le(i),_,p,c);if(!v.keyed.length)return s(`no clip could be keyed (${[...g,...v.missing].join(", ")})`);let A=F(o,`${a.replace(/[^\w.-]+/g,"_").slice(0,100)}_ALIGNED.drt`);await et(A,v.drt);let x=await this.call("open",{path:A,name:`${a} ALIGNED`,link_existing:!0,same_as:a,...n}),b=new Map([...g.map(w=>[w,"not found in the timeline's export"]),...v.missing.map(w=>[w.split(" ")[0],w])]);return{project:String(x.project??""),timeline:String(x.timeline??""),results:t.map(w=>{let T=`V${w.item.track}@${w.item.start}`;return b.has(T)?{op:"edit_keys",ok:!1,refused:["not keyed"],detail:`refused: ${b.get(T)}; nothing changed`}:{op:"edit_keys",ok:!0,detail:`${w.keys.length} Edit-page keyframes on "${x.timeline}" (a copy of "${a}" with every grade and setting; "${a}" itself unchanged)`}})}}catch(i){return s(i instanceof Error?i.message:String(i))}finally{await pe(o).catch(()=>{})}}async grades(e,t){let n=await G("ct-grades-");try{let o=F(n,"grades.drt"),s=await this.call("export",{timeline:e,out_path:o,...t});return{grades:await le(o).then(_t).catch(()=>new Map),t0:Number(s.start_frame??0)}}finally{await pe(n).catch(()=>{})}}async presets(e){return await this.call("presets",e,12e4)}async presetAuthor(e){return await this.call("preset_author",e,6e4)}async export(e){if(!e.out_path)throw new q("usage","resolve: export needs out_path");let t=await this.call("export",{timeline:e.timeline,out_path:e.out_path,...e.clip_id?{clip_id:e.clip_id}:{}});return{path:String(t.path),format:"drt",project:String(t.project),timeline:String(t.timeline)}}async open(e){let t=await this.call("open",{path:e.path,into:e.into??"current",name:e.name,media_dir:e.media_dirs?.[0],stay:e.stay??!1,folder:e.folder,create_folder:e.create_folder??!1,link_existing:e.link_existing??!1,...e.settings_from?{settings_from:e.settings_from}:{}},3e5),n=[...t.notes??[]];return(e.media_dirs?.length??0)>1&&n.push(`Resolve searches one media folder per import; used ${e.media_dirs[0]}`),{project:String(t.project),timeline:String(t.timeline),notes:n,restored:!!t.restored,...t.folder?{folder:String(t.folder)}:{},...t.settings?{settings:String(t.settings)}:{}}}async renderStart(e){let t=await this.call("render_start",{...e}),n=String(t.job_id);if(t.queued)return{job_id:n,state:"queued",percent:0,notes:["left in Resolve's render queue: start it on the Deliver page"]};this.restore.set(n,t.restore);let o=t.rejected_settings??[];return o.length&&this.startNotes.set(n,[`Resolve refused render setting(s) ${o.join(", ")} for this format; the rest were applied`]),{job_id:n,state:"queued",percent:0}}async renderStatus(e){let t=await this.call("render_status",{job_id:e},15e3),n={job_id:e,state:t.state,percent:Number(t.percent??0)};if(t.error&&(n.error=String(t.error)),n.state==="complete"||n.state==="failed"){let o=await this.call("render_finish",{job_id:e,restore:this.restore.get(e)});this.restore.delete(e),o.output&&(n.outputs=[String(o.output)]);let s=[...this.startNotes.get(e)??[],...o.tracks?[Rt(o)]:[]];this.startNotes.delete(e),s.length&&(n.notes=s)}return n}async renderCancel(e){let t=await this.call("render_cancel",{job_id:e,restore:this.restore.get(e)});return this.restore.delete(e),{job_id:e,state:"cancelled",percent:0,...t.output?{outputs:[String(t.output)]}:{},...t.tracks?{notes:[Rt(t)]}:{}}}},Rt=r=>{let e=r.tracks.map(t=>`V${t}`).join(", ");return r.tracks_restored?`video track(s) ${e} switched back on`:`could NOT switch video track(s) ${e} back on: re-enable them on the Edit page`};async function wn(r,e){let t=[];for await(let n of rt(r))n.isFile&&n.name.startsWith(e)&&t.push(F(r,n.name));return t.sort()}var yr="ws://localhost:1985",Pt="localhost",Et="conform_tools",Ot="conform.tools ",Mt="Video_Full",_r=r=>!!r&&typeof r=="object"&&"_handle"in r&&"_id"in r,z=class extends Error{constructor(t,n){super(n);this.code=t}},Fe=class r{constructor(e){this.ws=e;this.next=1;this.waiting=new Map;e.onMessage(t=>{let n;try{n=JSON.parse(t)}catch{return}let o=typeof n.id=="number"?this.waiting.get(n.id):void 0;if(!o)return;if(this.waiting.delete(n.id),n.error===void 0||n.error===null)return o.ok(n.result??null);let s=n.error;o.no(typeof s=="string"?new z(n.code??-1,s):new z(s.code??n.code??-1,s.message??JSON.stringify(s)))}),e.onClose(()=>{for(let t of this.waiting.values())t.no(new z("closed","Baselight closed the FLAPI connection"));this.waiting.clear()})}static async connect(e,t=3e3){let n=new r(await pt(e,{maxBytes:67108864,timeoutMs:t})),o=await br();return o&&await n.call("authenticate",{username:I("USER")??I("USERNAME")??"conform",token:o},null,t).catch(()=>null),n}call(e,t={},n=null,o=12e4){let s=this.next++;return new Promise((i,m)=>{let a=setTimeout(()=>{this.waiting.delete(s),m(new z("timeout",`${e}: no answer from Baselight within ${Math.round(o/1e3)} s`))},o);this.waiting.set(s,{ok:c=>{clearTimeout(a),i(c)},no:c=>{clearTimeout(a),m(c)}}),this.ws.send(JSON.stringify({jsonrpc:"2.0",method:e,target:n?n._id:null,params:t,id:s}))})}async forget(...e){for(let t of e)_r(t)&&await this.call("forget",{},t).catch(()=>null)}close(){this.ws.close()}};async function br(){let r=I("FLAPI_TOKEN");if(r)return r.trim();let e=V()==="darwin"?F(Te(),"Library","Preferences","FilmLight","flapi-token"):F(Te(),".filmlight","flapi-token");try{return(await Ze(e)).trim()||null}catch{return null}}var $t=(...r)=>Object.fromEntries(r.map(e=>[e,1])),Sr={[-30]:30,[-31]:30,[-32]:30,[-34]:25,[-35]:24};function be(r){if(!r||typeof r!="object")return null;let e=typeof r.fps=="string"?{TC_30DF:-30,TC_60HDF:-31}[r.fps]??Number(r.fps):r.fps,t=e>0?e:Sr[e]??30,n=((r.h*60+r.m)*60+r.s)*t+r.f;if(e!==-30&&e!==-31)return n;let o=r.h*60+r.m;return n-2*(o-Math.floor(o/10))}function vr(r,e,t){let n=Math.round(e),o=r;if(t&&n===30){let c=Math.floor(o/17982),u=o%17982;o+=18*c+(u>2?2*Math.floor((u-2)/1798):0)}let s=o%n,i=Math.floor(o/n)%60,m=Math.floor(o/n/60)%60;return{_type:"timecode",h:Math.floor(o/n/3600)%24,m,s:i,f:s,phase:0,fps:t&&n===30?-30:n,wrap:24}}function Nt(r){let e=Math.round(r);return Math.abs(r-e)<.005?e:Math.abs(r-e*1e3/1001)<.01?e*1e3/1001:r}var j=class extends Error{constructor(t,n){super(`baselight: ${n}`);this.why=t}},kr={darwin:"/Applications/Baselight",linux:"/usr/fl/baselight"},Se=class{constructor(e){this.url=e;this.host="baselight";this.jobs=new Map}async conn(e=3e3){let t=this.url??I("CONFORM_BASELIGHT_URL")??yr;try{return await Fe.connect(t,e)}catch(n){let o=await ae(kr[V()]??"/nonexistent");throw new j(o?"not_running":"not_installed",o?`Baselight is not answering FLAPI at ${t} (${n.message})`:"Baselight is not installed on this machine")}}async with(e){let t=await this.conn();try{return await e(t)}catch(n){throw n instanceof j?n:new j("flapi",n.message)}finally{t.close()}}async support(){let e;try{let t=await this.with(n=>n.call("Application.get_application_info"));e=/baselight|daylight/i.test(t.Product??"")?{ok:!0}:{ok:!1,reason:`the FLAPI server is ${t.Product??"unknown"}, not the Baselight app (port 1984 is the headless flapid)`,setup:"Point CONFORM_BASELIGHT_URL at the running Baselight (ws://localhost:1985)."}}catch(t){let n=t instanceof j?t.why:"flapi";e={ok:!1,reason:t.message.replace(/^baselight: /,""),setup:n==="not_installed"?"Install FilmLight Baselight (FLAPI ships with it; nothing else to install).":"Start Baselight. Its API server listens on port 1985 by default (Preferences > Advanced > API Server)."}}return{export:e,open:e,render:e,markers:{ok:!1,reason:"not wired for Baselight yet (FLAPI has marks: Scene.add_mark)"},renderplugin:{ok:!1,reason:"the renderplugin is a DaVinci Resolve plugin"}}}async scenePath(e,t,n){if(t?.includes(":")){let i=await e.call("Scene.parse_path",{str:t});return{host:i.Host,job:i.Job,scene:i.Scene}}let o=await this.current(e),s=n??o?.job;if(t&&s)return{host:o?.host??Pt,job:s,scene:t};if(!o)throw new j("no_scene",t?`no job to find scene "${t}" in: pass project (the job) or "host:job:scene"`:'no scene is open in Baselight: open one, or name it ("host:job:scene")');return o}async current(e){let t=await e.call("Application.get").catch(()=>null);if(!t)return null;try{let n=await e.call("Application.get_current_scene",{},t);if(!n)return null;try{let o=await e.call("Scene.get_scene_pathname",{},n),[s,i,...m]=o.split(":");return m.length?{host:s,job:i,scene:m.join(":")}:null}finally{await e.forget(n)}}finally{await e.forget(t)}}async export(e){if(!e.out_path)throw new j("usage","export needs out_path");return await this.with(async t=>{let n=await this.scenePath(t,e.timeline),o=await t.call("Scene.open_scene",{scenepath:{Host:n.host,Job:n.job,Scene:n.scene},flags:$t("OPENFLAG_READ_ONLY")});try{let s=await Rr(t,o,n.scene);await Q(de(e.out_path)),await ue(e.out_path,JSON.stringify(s,null,1))}finally{await t.call("Scene.close_scene",{},o).catch(()=>null),await t.forget(o)}return{path:e.out_path,format:"otio",project:n.job,timeline:n.scene}})}async open(e){let{readTimeline:t}=await import("./timeline-JONFBIA3.js"),{session:n}=await t(e.path),o=n.timelines.find(u=>u.kind!=="compound")??n.timelines[0];if(!o)throw new j("usage",`no timeline in ${e.path}`);let s=new Map((n.media_references??[]).map(u=>[u.id,u])),i=o.fps_num/o.fps_den,m=o.tracks.filter(u=>u.kind==="Video").sort((u,d)=>u.track_index-d.track_index),a=[];m.length>1&&a.push(`placed V1 only: Baselight builds layers above a shot, which FLAPI cannot place in time; ${m.slice(1).reduce((u,d)=>u+d.items.filter(f=>f.kind==="clip").length,0)} clip(s) on V2+ not placed`);let c=(m[0]?.items??[]).filter(u=>u.kind==="clip"||u.kind==="gap").sort((u,d)=>u.timeline_range.start.value-d.timeline_range.start.value);return await this.with(async u=>{let d=e.into==="scratch"?null:await this.current(u);e.into!=="scratch"&&!d&&a.push(`no scene open in Baselight, so it went into our job ${Et}`);let f=d?.job??Et,h=d?.host??Pt;await u.call("JobManager.job_exists",{host:h,jobname:f})||await u.call("JobManager.create_job",{host:h,jobname:f});let l=(e.name??o.name??"conform.tools").replace(/[:/\\]+/g,"_"),p=l;for(let w=2;await u.call("JobManager.scene_exists",{host:h,jobname:f,scenename:p});w++)p=`${l} ${w}`;let g=await u.call("FormatSet.factory_formats"),S=o.resolution_w&&o.resolution_h?await u.call("FormatSet.get_basic_format_name",{width:o.resolution_w,height:o.resolution_h},g):null;await u.forget(g);let _=await u.call("Scene.new_scene",{scenepath:{Host:h,Job:f,Scene:p},options:{format:S,colourspace:Mt,frame_rate:i}},null,3e5),v=0,A=0,x=0,b=0;try{await u.call("Scene.start_delta",{name:"conform.tools open"},_);try{let w=0;for(let P of c){let E=P.timeline_range.start.value,N=P.timeline_range.duration.value;if(E>w&&(await Le(u,_,E-w),x++),w=Math.max(w,E+N),P.kind==="gap"){await Le(u,_,N),x++;continue}let M=(P.media_reference_id?s.get(P.media_reference_id):void 0)?.target_url?.replace(/^file:\/\//,""),y=P.source_range,k=M&&y?await Ar(u,M,Math.round(y.start.value),Math.round(y.start.value)+N-1):null;if(!k){await Le(u,_,N),A++;continue}y&&Math.abs(y.duration.value-N)>.5&&b++;let L=await u.call("Scene.insert_sequence",{sequence:k,where:"INSERT_END",relativeTo:null,colourSpace:null,format:null,frameRate:i},_);await u.forget(k,L),v++}let T=await u.call("Scene.get_scene_settings",{},_);await u.call("SceneSettings.set",{values:{StartTimecode:vr(o.start_frame??0,i,!!o.is_drop_frame)}},T),await u.forget(T),await u.call("Scene.end_delta",{},_)}catch(w){throw await u.call("Scene.cancel_delta",{},_).catch(()=>null),w}await u.call("Scene.save_scene",{},_,3e5)}catch(w){throw await u.call("Scene.close_scene",{},_).catch(()=>null),await u.forget(_),await u.call("JobManager.delete_scene",{host:h,jobname:f,scenename:p}).catch(()=>null),w}return await u.call("Scene.close_scene",{},_),await u.forget(_),a.unshift(`new scene ${h}:${f}:${p}: ${v} shot(s)${x?`, ${x} gap(s) as black`:""}`),A&&a.push(`${A} clip(s) had no media on disk at their path: placed as black of the same length (relink in Baselight's Conform view)`),b&&a.push(`${b} retimed clip(s) placed at normal speed: FLAPI has no retime setter`),p!==l&&a.push(`"${l}" was taken in ${f}: named "${p}"`),e.media_dirs?.length&&a.push("media_dirs not used: Baselight places each clip from its own path"),e.stay&&a.push("stay: FLAPI cannot switch the scene the app shows; open it from the Scenes browser"),{project:f,timeline:p,notes:a,restored:!0}})}async renderStart(e){if(e.disable_tracks?.length)throw new j("usage","disable_tracks: a Baselight render takes every layer or one (RenderTrack); leave the tracks out in the scene");if(e.audio_tracks?.length||e.renderplugin)throw new j("usage","audio_tracks and renderplugin are DaVinci Resolve options");return await this.with(async t=>{let n=await this.scenePath(t,e.timeline,e.project),o=await t.call("Scene.open_scene",{scenepath:{Host:n.host,Job:n.job,Scene:n.scene},flags:$t("OPENFLAG_READ_ONLY")}),s=null,i=null;try{s=await t.call("RenderSetup.create_from_scene",{scene:o});let m=await t.call("RenderSetup.get_num_deliverables",{},s),a=0;if(e.preset){let l=await t.call("RenderSetup.get_deliverable_names",{},s);if(a=l.indexOf(e.preset),a<0)throw new j("usage",`no deliverable "${e.preset}" in ${n.scene} (it has: ${l.join(", ")||"none"})`)}let c=await t.call("RenderSetup.get_deliverable",{index:a},s),u=e.name??n.scene.replace(/[^\w.-]+/g,"_");Object.assign(c,{Disabled:0,Container:"",OutputDirectory:e.target_dir,FileNamePrefix:u}),e.preset||Object.assign(c,{Name:"conform.tools",IsMovie:1,FileType:"lqtmov",MovieCodec:"apch",ImageOptions:{},FileNameExtension:".mov",RenderColourSpace:Mt,HandleEmptyFrames:"GMREB_BLACK",HandleIncompleteStacks:"GMREB_BLACK",HandleError:"BLACK",EmbedTimecode:1}),e.audio||(c.AudioCodec=""),await Q(e.target_dir),await t.call("RenderSetup.set_deliverable",{index:a,deliverable:c},s);for(let l=0;l<m;l++)l!==a&&await t.call("RenderSetup.set_deliverable_enabled",{index:l,enabled:0},s);if(e.range){let l=await t.call("Scene.get_scene_settings",{},o),p=be(await t.call("SceneSettings.get_single",{key:"StartTimecode"},l))??0;await t.forget(l);let g=e.range.in>=p?p:0;await t.call("RenderSetup.set_frames",{frames:[{Start:e.range.in-g,End:e.range.out-g}]},s)}else await t.call("RenderSetup.select_all",{},s);let d=await t.call("RenderSetup.get_output_filename_for_deliverable",{index:a},s);i=await t.call("QueueManager.create_local");let f=await t.call("RenderSetup.submit_to_queue",{queue:i,opname:`${Ot}${u}`},s),h=String(f.ID);return this.jobs.set(h,{op:f.ID,out:d,notes:f.Warning?[`Baselight: ${f.Warning}`]:[]}),{job_id:h,state:"queued",percent:0}}finally{await t.forget(s,i),await t.call("Scene.close_scene",{},o).catch(()=>null),await t.forget(o)}})}async ours(e,t,n){let o=Number(n),s=await e.call("QueueManager.get_operation",{id:o},t).catch(()=>null),i=String(s?.Description??s?.Name??"");if(!this.jobs.has(n)&&!i.startsWith(Ot))throw new j("not_ours",`queue operation ${n} is not a conform.tools render: left alone`);return o}async renderStatus(e){return await this.with(async t=>{let n=await t.call("QueueManager.create_local");try{let o=await this.ours(t,n,e),s=await t.call("QueueManager.get_operation_status",{id:o},n),i=xr(s.Status),m=Number(s.Progress??0),a={job_id:e,state:i,percent:i==="complete"?100:Math.round(m<=1?m*100:m)};if(i==="failed"||i==="complete"&&s.Errors){let u=(await t.call("QueueManager.get_operation_log",{id:o},n).catch(()=>[])).filter(d=>/fail|error|warn/i.test(d.Type)).slice(-6).map(d=>`${d.Message}${d.Detail?`: ${d.Detail}`:""}`);a.error=[s.ProgressText,...u].filter(Boolean).join("; ")||"Baselight reported a failed render",i==="complete"&&(a.state="failed")}if(a.state==="complete"||a.state==="failed"||a.state==="cancelled"){let c=this.jobs.get(e);a.state==="complete"&&c&&(a.outputs=[c.out]),c?.notes.length&&(a.notes=c.notes),await t.call("QueueManager.delete_operation",{id:o},n).catch(()=>null),this.jobs.delete(e)}return a}finally{await t.forget(n)}})}async renderCancel(e){return await this.with(async t=>{let n=await t.call("QueueManager.create_local");try{let o=await this.ours(t,n,e);return await t.call("QueueManager.delete_operation",{id:o},n),this.jobs.delete(e),{job_id:e,state:"cancelled",percent:0}}finally{await t.forget(n)}})}};function xr(r){let e=String(r).replace(/^OPSTATUS_/i,"").toLowerCase();return e==="done"?"complete":e==="active"?"rendering":e==="stopped"?"cancelled":e==="failed"||e==="crashed"||e==="toonew"?"failed":"queued"}async function Le(r,e,t){let n=await r.call("Scene.insert_blank",{red:0,green:0,blue:0,duration:t,where:"INSERT_END",relativeTo:null,colourSpace:null},e);await r.forget(n)}async function Ar(r,e,t,n){let o=await r.call("SequenceDescriptor.get_for_template",{template:e,start:null,end:null}).catch(()=>[]);if(!o?.length)return null;let s=await r.call("SequenceDescriptor.get_start_handle",{},o[0]);await r.forget(...o);let i=await r.call("SequenceDescriptor.get_for_template",{template:e,start:s+t,end:s+n});return i?.length?(await r.forget(...i.slice(1)),i[0]):null}var Ie=(r,e)=>({OTIO_SCHEMA:"RationalTime.1",rate:e,value:r}),je=(r,e,t)=>({OTIO_SCHEMA:"TimeRange.1",start_time:Ie(r,t),duration:Ie(e,t)});async function Rr(r,e,t){let n=Nt(await r.call("Scene.get_working_frame_rate",{},e)),o=await r.call("Scene.get_scene_settings",{},e),s=be(await r.call("SceneSettings.get_single",{key:"StartTimecode"},o))??0;await r.forget(o);let i=await r.call("Scene.get_num_shots",{},e),m=i?await r.call("Scene.get_shot_ids",{firstIndex:0,lastIndex:i-1},e):[],a=[];for(let d of m){let f=Math.round(d.StartFrame),h=Math.round(d.EndFrame),l=await r.call("Scene.get_shot",{shot_id:d.ShotId},e);try{let p=await r.call("Shot.get_sequence_descriptor",{},l).catch(()=>null);if(!p){a.push({start:f,end:h,name:`shot ${d.ShotId}`});continue}try{let g=Nt(await r.call("Shot.get_frame_rate",{},l))||n,S=be(await r.call("Shot.get_src_start_timecode",{},l)),_=await r.call("Shot.get_src_start_frame",{},l),v=await r.call("Shot.get_src_end_frame",{},l),x=await r.call("SequenceDescriptor.is_movie",{},p)?Ye(await r.call("SequenceDescriptor.get_path",{},p),await r.call("SequenceDescriptor.get_name",{},p)):await r.call("SequenceDescriptor.get_full_filename_with_d",{},p),b=await r.call("SequenceDescriptor.get_name",{},p),w=await r.call("SequenceDescriptor.get_tape",{index:0},p).catch(()=>""),T=await r.call("SequenceDescriptor.get_start_frame",{},p),P=await r.call("SequenceDescriptor.get_start_handle",{},p),E=await r.call("SequenceDescriptor.get_end_handle",{},p),C=(be(await r.call("SequenceDescriptor.get_start_timecode",{index:0},p))??0)-(T-P),M=Math.round(v-_),y=h-f,k={OTIO_SCHEMA:"Clip.2",name:b,enabled:!0,source_range:je(S??C+(_-P),y,g),media_references:{DEFAULT_MEDIA:{OTIO_SCHEMA:"ExternalReference.1",target_url:x,available_range:je(C,E-P+1,g),available_image_bounds:null,name:b,metadata:{}}},active_media_reference_key:"DEFAULT_MEDIA",effects:M&&M!==y?[{OTIO_SCHEMA:"LinearTimeWarp.1",name:"",effect_name:"LinearTimeWarp",time_scalar:M/y,metadata:{}}]:[],markers:[],metadata:w?{baselight:{tape:w}}:{}};a.push({start:f,end:h,name:b,clip:k})}finally{await r.forget(p)}}finally{await r.forget(l)}}let c=[];for(let d of[...a].sort((f,h)=>f.start-h.start)){if(!d.clip)continue;let f=c.find(h=>h[h.length-1].end<=d.start);f?f.push(d):c.push([d])}let u=c.map((d,f)=>{let h=[],l=0;for(let p of d)p.start>l&&h.push({OTIO_SCHEMA:"Gap.1",name:"",enabled:!0,source_range:je(0,p.start-l,n),effects:[],markers:[],metadata:{}}),h.push(p.clip),l=p.end;return{OTIO_SCHEMA:"Track.1",name:`V${f+1}`,kind:"Video",enabled:!0,children:h,source_range:null,effects:[],markers:[],metadata:{}}});return{OTIO_SCHEMA:"Timeline.1",name:t,metadata:{baselight:{shots:m.length}},global_start_time:Ie(s,n),tracks:{OTIO_SCHEMA:"Stack.1",name:"tracks",enabled:!0,children:u,source_range:null,effects:[],markers:[],metadata:{}}}}var Tr="127.0.0.1:31416",Pr="/ptsl.PTSL/SendGrpcRequest",Er="CONFORM.TOOLS",Or="CONFORM.TOOLS Desktop",De=[2025,6,0],te=[2025,6],Ve=1e4,Ct=5e3,Mr="ConformTools",$r="Start Pro Tools 2025.6 or newer with a session open (PTSL, its scripting door, listens on 127.0.0.1:31416).",Ue={GetTrackList:3,HostReadyCheck:13,ExportSessionInfoAsText:30,GetSessionSampleRate:35,GetSessionTimeCodeRate:38,GetSessionFeetFramesRate:39,GetSessionName:42,GetSessionPath:43,GetSessionStartTime:44,GetSessionLength:45,GetPTSLVersion:55,GetTransportState:59,ClearMemoryLocation:61,EditMemoryLocation:68,GetMemoryLocations:69,RegisterConnection:70,CreateMemoryLocation:71,SetTimelineSelection:81,GetTimelineSelection:82,GetSessionIDs:97,GetMainCounterFormat:102},Nr=[3,6],Cr=[4,7],Lt=106,Lr=new TextEncoder,jr=new TextDecoder;function ve(r,e){for(;r>127;)e.push(r&127|128),r=Math.floor(r/128);e.push(r)}function jt(r){let e=[];for(let[t,n]of r){if(typeof n=="number"){n&&(ve(t<<3,e),ve(n,e));continue}let o=typeof n=="string"?Lr.encode(n):n;if(o.length){ve(t<<3|2,e),ve(o.length,e);for(let s of o)e.push(s)}}return new Uint8Array(e)}function Ft(r){let e=new Map,t=0,n=()=>{let o=0,s=1,i;do i=r[t++],o+=(i&127)*s,s*=128;while(i&128&&t<r.length);return o};for(;t<r.length;){let o=n(),s=Math.floor(o/8),i=o&7;if(i===0)e.set(s,n());else if(i===2){let m=n();e.set(s,r.subarray(t,t+m)),t+=m}else if(i===1)t+=8;else if(i===5)t+=4;else throw new R("bad_answer",`Pro Tools sent a reply that is not protobuf (wire type ${i})`)}return e}var It=r=>r instanceof Uint8Array?jr.decode(r):"",Fr=r=>typeof r=="number"?r:0;function Ir(r,e,t){let n=jt([[2,r],[3,De[0]],[4,e],[5,De[1]],[6,De[2]]]);return jt([[1,n],[2,t]])}function Dr(r){let e=Ft(r),t=e.get(1);return{status:t instanceof Uint8Array?Fr(Ft(t).get(3)):0,body:It(e.get(2)),error:It(e.get(3))}}var R=class extends Error{constructor(t,n,o){super(n);this.code=t;this.errors=o}};function Ur(r){let e=null;try{e=JSON.parse(r)}catch{}let t=Array.isArray(e)?e:e&&typeof e=="object"?Array.isArray(e.errors)?e.errors:[e]:[],n=t.find(a=>!a.is_warning)??t[0],o=String(n?.command_error_message||r.trim()||"Pro Tools refused the command"),s=n?.command_error_type,m=s===Lt||s==="PT_NoOpenedSession"||s==="CEType_PT_NoOpenedSession"||s===String(Lt)?"no_session":/session id|not registered|register/i.test(o)?"not_registered":"command_failed";return new R(m,o,t.length?t:void 0)}var Ge=class{constructor(e=Tr){this.sessionId="";this.version=null;this.queue=Promise.resolve();let t=/^(127\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})$/.exec(e)??/^\[(::1)\]:(\d{1,5})$/.exec(e);if(!t)throw new R("refused",`${e} is not a loopback IP address and port; PTSL is loopback only`);this.host=t[1],this.port=Number(t[2])}async send(e,t,n){let o;try{o=await ot(this.host,this.port,Pr,Ir(e,this.sessionId,t),n)}catch(i){throw this.sessionId="",this.version=null,i instanceof nt?i.code==="unavailable"?new R("not_running",`Pro Tools is not running (nothing answered on ${this.host}:${this.port})`):i.code==="deadline"?new R("timeout",`Pro Tools did not answer in ${n} ms (a modal dialog or a long command?)`):i.grpcStatus===12?new R("not_ptsl",`the program on ${this.host}:${this.port} is not Pro Tools`):new R("transport",`PTSL transport error: ${i.message}`):i}let s=Dr(o);if(Nr.includes(s.status)){if(!s.body.trim())return null;try{return JSON.parse(s.body)}catch{throw new R("bad_answer","Pro Tools sent a body that is not JSON")}}throw Cr.includes(s.status)?Ur(s.error):new R("bad_status",`Pro Tools answered with task status ${s.status}`)}async handshake(){if(!this.sessionId){let e=await this.send(Ue.RegisterConnection,JSON.stringify({company_name:Er,application_name:Or}),Ct);if(!e?.session_id)throw new R("not_registered","Pro Tools did not give conform.tools a session id");this.sessionId=e.session_id}if(!this.version){let e=await this.send(Ue.GetPTSLVersion,"",Ct),t=o=>Number(e?.[o]??0)||0,n=[t("version"),t("version_minor"),t("version_revision")];if(n[0]<te[0]||n[0]===te[0]&&n[1]<te[1])throw this.sessionId="",new R("host_too_old",`Pro Tools ${n[0]}.${n[1]} is too old; conform.tools needs Pro Tools ${te[0]}.${te[1]} or newer`);this.version=n}}call(e,t,n=Ve){let o=async()=>{if(e==="RegisterConnection")throw new R("refused","RegisterConnection is sent by the client itself");let i=Ue[e];if(i===void 0)throw new R("unknown_command",`${e} is not a PTSL command conform.tools sends`);let m=t==null?"":typeof t=="string"?t:JSON.stringify(t);for(let a=0;;a++){if(await this.handshake(),e==="GetPTSLVersion"){let[c,u,d]=this.version;return{version:c,version_minor:u,version_revision:d}}try{return await this.send(i,m,n)}catch(c){if(c instanceof R&&c.code==="not_registered"&&a===0){this.sessionId="";continue}throw c}}},s=this.queue.then(o,o);return this.queue=s.catch(()=>{}),s}},He={23976:24e3/1001,24:24,25:25,2997:3e4/1001,30:30,47952:48e3/1001,48:48,50:50,5994:6e4/1001,60:60,100:100,11988:12e4/1001,120:120},Hr={1:["23976",!1],2:["24",!1],3:["25",!1],4:["2997",!1],5:["2997",!0],6:["30",!1],7:["30",!0],8:["47952",!1],9:["48",!1],10:["50",!1],11:["5994",!1],12:["5994",!0],13:["60",!1],14:["60",!0],15:["100",!1],16:["11988",!1],17:["11988",!0],18:["120",!1],19:["120",!0]};function Br(r){if(typeof r=="number"||typeof r=="string"&&/^\d+$/.test(r.trim())){let t=Hr[Number(r)];return t?{fps:He[t[0]],drop:t[1]}:null}let e=/Fps(\d+)(Drop)?/i.exec(String(r??""));return e&&He[e[1]]?{fps:He[e[1]],drop:!!e[2]}:null}var Vr=/^-?\d{1,2}[:;.]\d{2}[:;.]\d{2}[:;.,]\d{2,3}(\.\d+)?$/,Gr=/^(?:(\d+):)?(\d+):(\d{2}(?:\.\d+)?)$/;function Be(r,e){let t=String(r??"").trim();if(Vr.test(t))return ct(t.replace(/\.\d+$/,""),e.rate.fps,e.rate.drop);if(/^-?\d+$/.test(t))return e.start+Math.floor(Number(t)*e.rate.fps/e.sampleRate+1e-9);let n=Gr.exec(t);return n?e.start+Math.floor((Number(n[1]??0)*3600+Number(n[2])*60+Number(n[3]))*e.rate.fps+1e-9):null}var ke=["Blue","Cyan","Green","Yellow","Red","Pink","Purple","Fuchsia","Rose","Lavender","Sky","Mint","Lemon","Sand","Cocoa","Cream"],Dt=r=>{let e=Number(r);return e>=1?ke[(e-1)%ke.length]:ke[0]},qr=r=>Math.max(0,ke.findIndex(e=>e.toLowerCase()===String(r??"").toLowerCase()))+1,Ut=/(?:^| )\[ct:((?:[^[\]\\]|\\.)*)\]$/s;function zr(r,e){return!e&&!Ut.test(r)?r:`${r}${r?" ":""}[ct:${e.replace(/[\\[\]]/g,t=>`\\${t}`)}]`}function Jr(r){let e=Ut.exec(r);return e?{note:r.slice(0,e.index),data:e[1].replace(/\\(.)/gs,"$1")}:{note:r,data:""}}function Wr(r){return!r.includes(":")||r.includes("/")||r.includes("\\")?r:`/Volumes/${r.split(":").filter(Boolean).join("/")}`}var xe=class{constructor(e=new Ge){this.ptsl=e;this.host="protools"}async sessionName(e=Ve){try{return String((await this.ptsl.call("GetSessionName",null,e)).session_name??"")}catch(t){if(t instanceof R&&t.code==="no_session")return"";throw t}}async sessionPath(e=Ve){let t=await this.ptsl.call("GetSessionPath",null,e),n=typeof t.session_path=="string"?t.session_path:t.session_path?.path??"";return n?Wr(n):""}async current(e=2e3){try{let t=await this.sessionName(e);return t?{project:t,project_path:await this.sessionPath(e).catch(()=>"")}:null}catch{return null}}async facts(){let e=await this.sessionName();if(!e)throw new R("no_session","protools: no session is open");let t=(await this.ptsl.call("GetSessionTimeCodeRate")).current_setting,n=Br(t);if(!n)throw new R("bad_answer",`protools: a timecode rate conform.tools does not know (${t})`);let o=/(\d{4,6})/.exec(String((await this.ptsl.call("GetSessionSampleRate")).sample_rate??""));if(!o)throw new R("bad_answer","protools: Pro Tools reported a sample rate conform.tools does not know");let s=(await this.ptsl.call("GetSessionStartTime")).session_start_time,i={name:e,rate:n,sampleRate:Number(o[1]),start:0},m=Be(s,i);if(m==null)throw new R("bad_answer",`protools: a session start conform.tools cannot read (${s})`);return{...i,start:m}}async support(){let e={ok:!1,reason:"Pro Tools holds one session at a time, and importing a timeline changes it; write a .ptx or AAF with timeline_write and open that in Pro Tools"},t={ok:!1,reason:"bouncing from Pro Tools (ExportMix) is not wired"},n={ok:!1,reason:"the renderplugin is a DaVinci Resolve plugin"},o;try{o=await this.sessionName(3e3)?{ok:!0}:{ok:!1,reason:"Pro Tools is running with no session open"}}catch(s){o={ok:!1,reason:s instanceof Error?s.message:String(s),setup:$r}}return{export:o,open:e,render:t,markers:o,renderplugin:n}}async export(e){let t=await this.sessionName();if(!t)throw new R("no_session","protools: no session is open");if(e.timeline&&e.timeline!==t)throw new R("not_found",`protools: the open session is "${t}"; Pro Tools has one timeline per session`);let n=await this.sessionPath();if(!n||!await ce(n))throw new R("no_file",`protools: session "${t}" has no saved .ptx on disk${n?` (${n})`:""}; save it in Pro Tools first`);let o=e.out_path??F(await G("conform-protools-"),st(n));return await Q(de(o)),await tt(n,o),{path:o,format:"ptx",project:t,timeline:t}}open(){return Promise.reject(new R("unsupported","protools: open is not supported: Pro Tools holds one session, and importing a timeline into it changes it"))}renderStart(){return Promise.reject(new R("unsupported","protools: rendering (a bounce) is not wired"))}renderStatus(){return this.renderStart()}renderCancel(){return this.renderStart()}async project(){let e=await this.facts(),t=await this.sessionPath().catch(()=>""),n=[],o=[];try{let i=await this.ptsl.call("GetTrackList",{page_limit:1e3,track_filter_list:[{filter:"All",is_inverted:!1}]}),m={video:0,audio:0};for(let a of i.track_list??[]){let c=/video/i.test(String(a.type))?"video":"audio",u=a.track_attributes??{},d=u.is_inactive===!0||/^(true|.*_?(set|on|inactive))$/i.test(String(u.is_inactive??""));n.push({kind:c,index:++m[c],name:String(a.name??""),enabled:!d})}}catch(i){o.push(`tracks not read: ${i instanceof Error?i.message:String(i)}`)}let s=(await this.locations(e).catch(()=>({locs:[]}))).locs.length;return{project:e.name,timeline:e.name,timelines:[e.name],session_path:t,fps:e.rate.fps,drop_frame:e.rate.drop,sample_rate:e.sampleRate,start_tc:Pe(e.start,e.rate.fps,e.rate.drop),ptsl_version:this.ptsl.version?.join("."),markers:s,notes:o,tracks:n,jobs:[],found:{},pool:{path:"",clips:0,folders:[]}}}async locations(e){let t=[];for(let o=0;;){let s=await this.ptsl.call("GetMemoryLocations",{pagination_request:{limit:1e3,offset:o}}),i=(s.memory_locations??[]).filter(m=>m&&typeof m=="object");if(t.push(...i),o+=i.length,!i.length||o>=Number((s.pagination_response??s.stats)?.total??0))break}let n=[];for(let o of t){let s=o.time_properties,i=typeof s=="number"||/^\d+$/.test(String(s))?{1:"Marker",2:"Selection"}[Number(s)]:String(s??"").split("_").pop();if(i!=="Marker"&&i!=="Selection")continue;let m=Be(o.start_time,e);if(m==null)continue;let a=i==="Selection"?Be(o.end_time,e):null,{note:c,data:u}=Jr(String(o.comments??""));n.push({number:Number(o.number)||0,frame:m-e.start,duration:a==null?1:Math.max(1,a-m),name:String(o.name??""),note:c,data:u,color:Dt(o.color_index),raw:o})}return n.sort((o,s)=>o.frame-s.frame||o.number-s.number),{locs:n.filter((o,s)=>s===0||n[s-1].frame!==o.frame),numbers:t.map(o=>Number(o.number)||0)}}async writeFormat(){let e=await this.ptsl.call("GetMainCounterFormat"),t=e.current_setting??e.current_type,n=typeof t=="number"||/^\d+$/.test(String(t))?{3:"TimeCode",5:"Samples"}[Number(t)]:String(t??"").split("_").pop();if(n==="TimeCode")return"timecode";if(n==="Samples")return"samples";throw new R("counter_format","protools: set Pro Tools' main counter to Timecode or Samples to edit markers from conform.tools")}async apply(e){let t=await this.facts();if(e.timeline&&e.timeline!==t.name)throw new R("not_found",`protools: the open session is "${t.name}"`);let{locs:n,numbers:o}=await this.locations(t),s=new Map(n.map(l=>[l.frame,l])),i=null,m=l=>i==="samples"?String(Math.round(l*t.sampleRate/t.rate.fps)):Pe(t.start+l,t.rate.fps,t.rate.drop),a=async(l,p)=>{let g=Math.max(1,Math.round(l.duration??1)),S=p?.number??Math.max(0,...o)+1,_=p?.raw??{},v={number:S,name:l.name??"",start_time:m(l.frame),end_time:m(l.frame+(g>1?g:0)),time_properties:g>1?"TP_Selection":"TP_Marker",reference:_.reference||"MLR_Absolute",general_properties:_.general_properties||{zoom_settings:!1,pre_post_roll_times:!1,track_visibility:!1,track_heights:!1,group_enables:!1,window_configuration:!1},comments:zr(l.note??"",l.data??""),color_index:qr(l.color),location:_.location||"MLC_MainRuler",..._.track_name?{track_name:_.track_name}:{}};await this.ptsl.call("CreateMemoryLocation",v),o.push(S),s.set(l.frame,{number:S,frame:l.frame,duration:g,name:l.name??"",note:l.note??"",data:l.data??"",color:Dt(v.color_index),raw:v})},c=async l=>{await this.ptsl.call("ClearMemoryLocation",{location_list:[l.number]}),s.delete(l.frame),o.splice(o.indexOf(l.number),1)},u=l=>({op:"marker_add",frame:l.frame,color:l.color,name:l.name,note:l.note,duration:l.duration,...l.data?{data:l.data}:{}}),d=[],f=[];for(let l of e.ops){let p=Number(l.frame);try{if(!l.op.startsWith("marker_")||l.item){d.push({op:l.op,ok:!1,detail:`protools: '${l.op}' is not reachable over PTSL (timeline markers only)`});continue}if(!Number.isInteger(p)){d.push({op:l.op,ok:!1,detail:"frame must be a whole number"});continue}i??=await this.writeFormat();let g=s.get(p);if(l.op==="marker_add")g&&await c(g),await a({frame:p,color:l.color,name:l.name,note:l.note,duration:Number(l.duration??1),data:l.data||Mr}),d.push({op:l.op,ok:!0}),f.unshift({op:"marker_delete",frame:p},...g?[u(g)]:[]);else if(l.op==="marker_update"){if(!g){d.push({op:l.op,ok:!1,detail:`no marker at frame ${p}`});continue}let S=l.to_frame!==void 0?Number(l.to_frame):p;if(!Number.isInteger(S)){d.push({op:l.op,ok:!1,detail:"to_frame must be a whole number"});continue}if(S!==p&&s.has(S)){d.push({op:l.op,ok:!1,detail:`frame ${S} already has a marker`});continue}await c(g);let _=(v,A)=>l[v]!==void 0?l[v]:A;await a({frame:S,color:_("color",g.color),name:_("name",g.name),note:_("note",g.note),duration:Number(_("duration",g.duration)),data:_("data",g.data)},g),d.push({op:l.op,ok:!0}),f.unshift({op:"marker_update",frame:S,color:g.color,name:g.name,note:g.note,duration:g.duration,data:g.data,...S!==p?{to_frame:p}:{}})}else if(l.op==="marker_delete"){if(!g){d.push({op:l.op,ok:!1,detail:`no marker at frame ${p}`});continue}await c(g),d.push({op:l.op,ok:!0}),f.unshift(u(g))}else d.push({op:l.op,ok:!1,detail:`protools: unknown marker op '${l.op}'`})}catch(g){d.push({op:l.op,ok:!1,detail:g instanceof Error?g.message:String(g)})}}let h=d.filter(l=>l.ok).length;return{project:t.name,timeline:t.name,results:d,undo:f,applied:h,failed:d.length-h}}};var Kr="Install the conform.tools panel in Media Composer (mcp/hosts/avid/panel: package it, copy the .avpi into PanelSDKPlugins; an unsigned panel needs Avid's Feature Toggle Files), then open Tools > CONFORM.TOOLS. Its page loads from this engine's host bridge (port 48127) and connects by itself.",Qr="Install the conform.tools hook (host_setup host=flame action=install_panel), then in Flame: Flame menu > Python > Rescan Python Hooks (or restart Flame), then Flame menu > CONFORM.TOOLS > Connect to CONFORM.TOOLS (or Connect Automatically).",Yr="Install the conform.tools panel (host_setup host=nuke action=install_panel) and restart Nuke Studio / Hiero, then CONFORM.TOOLS > Connect (or tick Connect automatically in its panel).",Ht={resolve:new _e,premiere:new mt,avid:new fe({host:"avid",label:"Media Composer",setup:Kr}),flame:new fe({host:"flame",label:"Flame",setup:Qr,items:!0}),nuke:new fe({host:"nuke",label:"Nuke Studio",setup:Yr,items:!0}),baselight:new Se,protools:new xe};function Mn(r,e){Ht[r]=e}function $n(r){return Ht[r]??dt(r,"not wired yet")}export{_t as a,on as b,hr as c,wn as d,xe as e,Kr as f,Qr as g,Yr as h,Mn as i,$n as j};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
-
import{
|
|
3
|
+
import{A as O,F as A,G as R,H as q,K as F,L as N,O as f,aa as r,b as _,g as m,i as L,n as x,r as T,s as U,t as $,u as P,v as E,x as k,y as V}from"./chunk-XI6XF7FQ.js";var H="7145B29C33684D8AA1C7E5126F9B405D",w="conform.tools.dvcp.bundle",J="https://raw.githubusercontent.com/tbdpost/conformtools-public/main/plugin/manifest.json";function z(t=m()){return t==="win32"?{system:`${_("PROGRAMDATA")??"C:\\ProgramData"}\\Blackmagic Design\\DaVinci Resolve\\Support\\IOPlugins`,user:`${_("APPDATA")??""}\\Blackmagic Design\\DaVinci Resolve\\Support\\IOPlugins`}:t==="linux"?{system:"/opt/resolve/IOPlugins",user:r(x(),".local/share/DaVinciResolve/IOPlugins")}:{system:"/Library/Application Support/Blackmagic Design/DaVinci Resolve/IOPlugins",user:r(x(),"Library/Application Support/Blackmagic Design/DaVinci Resolve/IOPlugins")}}function W(t=m()){return t==="win32"?`${_("APPDATA")??""}\\Blackmagic Design\\DaVinci Resolve\\Support\\logs\\ResolveDebug.txt`:t==="linux"?r(x(),".local/share/DaVinciResolve/logs/ResolveDebug.txt"):r(x(),"Library/Application Support/Blackmagic Design/DaVinci Resolve/logs/ResolveDebug.txt")}function j(t=m(),e=L()){return t==="darwin"?{key:"darwin-universal",binary:"Contents/MacOS/conform.tools.dvcp"}:t==="linux"&&/x86_64|x64/.test(e)?{key:"linux-x86_64",binary:"Contents/Linux-x86-64/conform.tools.dvcp"}:t==="win32"?{key:"windows-x86_64",binary:"Contents/Win64/conform.tools.dvcp"}:null}async function M(t){let e=r(t,"Contents/Resources/VERSION");if(await P(e))return(await k(e)).trim()||null;let n=r(t,"Contents/Info.plist");return await P(n)?/<key>CFBundleShortVersionString<\/key>\s*<string>([^<]+)</.exec(await k(n))?.[1]??null:null}function K(t,e){let n=t.split(`
|
|
4
4
|
`),s=n.find(l=>l.includes("Running DaVinci Resolve"));if(!s)return null;let i=/(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}),(\d{3})/.exec(s);if(!i)return null;let u=new Date(`${i[1]}T${i[2]}.${i[3]}`),a=n.some(l=>/plugin repository/i.test(l)&&l.toUpperCase().includes(`LOADED PLUGIN [${H}]`));return{launched_at:u.toISOString(),loaded:a,installed_after_launch:e!==void 0&&e>u.getTime()}}async function tt(t=m()){let e=j(t),n=z(t),s=r(n.system,w),i=e?await E(s)&&await $(r(s,e.binary)):!1,u=i?await M(s):null,a=r(n.user,w),l=await E(a)?{path:a,version:await M(a)}:void 0,c=null;try{let D=i&&e?(await U(r(s,e.binary))).mtimeMs:void 0;c=K(await k(W(t)),D)}catch{}let p=e?i?c?c.loaded&&!c.installed_after_launch?"ready":"needs-restart":"unknown":"plugin-missing":"unsupported-platform",g={ready:"The plugin is installed and loaded.","plugin-missing":l?`Only a per-user copy exists (${a}); Resolve loads I/O plugins only from ${n.system}. Install it with host_setup action=install_renderplugin.`:"Install it with host_setup action=install_renderplugin, then restart Resolve.","needs-restart":"Restart Resolve: it loads I/O plugins only at launch.","unsupported-platform":"There is no build of the plugin for this platform.",unknown:"Start Resolve once so its log says whether it loaded the plugin."}[p];return{platform:e?.key??null,installed:i,path:s,version:u,...l?{shadowed:l}:{},resolve:c,readiness:p,next:g}}async function et(){for(let t of["./presets/conform.tools.xml","./resolve-presets/conform.tools.xml"]){let e=T(new URL(t,import.meta.url));if(await P(e))return e}throw new Error("resolve: the conform.tools render preset is missing from this install")}async function X(t){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",t));return Array.from(e,n=>n.toString(16).padStart(2,"0")).join("")}async function G(t,e=3){for await(let n of N(t)){if(!n.isDirectory)continue;let s=r(t,n.name);if(n.name===w)return s;if(e>0&&!n.name.startsWith("__MACOSX")){let i=await G(s,e-1);if(i)return i}}return null}var Q=async t=>{let e=await fetch(t,{signal:AbortSignal.timeout(12e4)});if(!e.ok)throw new Error(`download failed: ${t} answered ${e.status}`);return new Uint8Array(await e.arrayBuffer())};async function nt(t={}){let e=t.os??m(),n=j(e);if(!n)throw new Error("there is no build of the plugin for this platform");let s=t.fetcher??Q,i=JSON.parse(new TextDecoder().decode(await s(t.manifest_url??J))),u=i.platforms?.[n.key]??(e==="darwin"&&i.bundle_url?{bundle_url:i.bundle_url,sha256:i.sha256??""}:void 0);if(!u)throw new Error(`plugin ${i.version} has no ${n.key} build`);let a=await s(u.bundle_url),l=await X(a);if(l!==u.sha256.toLowerCase())throw new Error(`the downloaded plugin failed its checksum (got ${l}, the manifest says ${u.sha256}); nothing was installed`);let c=await F("conform-plugin-"),p=r(c,"plugin.zip");await V(p,a);let g=r(c,"x");await O(g);let D=e==="darwin"?await f("ditto",["-x","-k",p,g]):e==="win32"?await f("powershell",["-NoProfile","-Command",`Expand-Archive -LiteralPath '${p}' -DestinationPath '${g}' -Force`]):await f("unzip",["-q",p,"-d",g]);if(!D.success)throw new Error(`could not unpack the plugin: ${D.stderr.trim()}`);let b=await G(g);if(!b||!await $(r(b,n.binary)))throw new Error(`the ${n.key} download does not contain ${n.binary}`);let h=t.targetDir??z(e).system,d=r(h,w),I=r(h,`.${w}.staging`),y=r(h,`.${w}.previous`),C=[],S=!1;try{await O(h),await R(I),await q(b,I),await R(y),await $(d)&&await A(d,y);try{await A(I,d)}catch(v){throw await $(y)&&await A(y,d),v}await R(y)}catch(v){let B=v.code;if(B!=="EACCES"&&B!=="EPERM")throw v;S=!0,await Y(e,b,h)}return e==="darwin"&&((await f(S?"osascript":"xattr",S?["-e",`do shell script "xattr -dr com.apple.quarantine ${o(d)}" with administrator privileges`]:["-dr","com.apple.quarantine",d])).success||C.push("could not clear the quarantine flag; if Resolve refuses the plugin, run: xattr -dr com.apple.quarantine "+d)),await R(c),{version:i.version,path:d,elevated:S,restart_required:!0,notes:C}}var o=t=>`'${t.replace(/'/g,"'\\''")}'`;async function Y(t,e,n,s=w){let i=r(n,s),u=r(n,`.${s}.staging`),a=r(n,`.${s}.previous`),l=[`mkdir -p ${o(n)}`,`rm -rf ${o(u)} ${o(a)}`,`cp -R ${o(e)} ${o(u)}`,`if [ -e ${o(i)} ]; then mv ${o(i)} ${o(a)}; fi`,`mv ${o(u)} ${o(i)} || { [ -e ${o(a)} ] && mv ${o(a)} ${o(i)}; exit 1; }`,`rm -rf ${o(a)}`].join(" && "),c=t==="darwin"?await f("osascript",["-e",`do shell script ${JSON.stringify(l)} with administrator privileges`]):t==="linux"?await f("pkexec",["sh","-c",l]):{success:!1,stderr:"run this from an administrator prompt",stdout:"",code:1};if(!c.success)throw new Error(`installing into ${n} needs an administrator, and that was refused or failed: ${c.stderr.trim()}`)}export{tt as a,et as b,nt as c,Y as d};
|