conformtools 0.6.28 → 0.6.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{account-RSL4PTDB.js → account-F4ODJBD2.js} +1 -1
- package/dist/{agent-hook-setup-IACTYSVL.js → agent-hook-setup-KBCGZNEE.js} +1 -1
- package/dist/{analysis-engine-BBOSGAB2.js → analysis-engine-LGB4OXG7.js} +1 -1
- package/dist/{bridge-I6VDW7YC.js → bridge-GLW34YZF.js} +1 -1
- package/dist/browser/timeline_core_bg.wasm +0 -0
- package/dist/{chunk-UE76WJ3Y.js → chunk-7DH6DFYL.js} +1 -1
- package/dist/{chunk-QY4QDBIN.js → chunk-BZE7IP6U.js} +91 -91
- package/dist/{chunk-TGLH2JDW.js → chunk-FHCRWOI7.js} +1 -1
- package/dist/{chunk-NRURUPLU.js → chunk-GDPYFRSV.js} +1 -1
- package/dist/chunk-H3FD5KA2.js +7 -0
- package/dist/{chunk-BIX5ETBY.js → chunk-HHOFGYZ7.js} +1 -1
- package/dist/{chunk-X76IIWBH.js → chunk-HZBGG7HI.js} +1 -1
- package/dist/{chunk-AR5BTVBM.js → chunk-KD7UGCLT.js} +1 -1
- package/dist/{chunk-CSH2RRI6.js → chunk-NTPDZOPF.js} +1 -1
- package/dist/chunk-QDL3XYOE.js +545 -0
- package/dist/chunk-QQBDHVUU.js +3 -0
- package/dist/chunk-RKJML7MH.js +10 -0
- package/dist/{chunk-WG75XXKG.js → chunk-RVKNGIE3.js} +2 -2
- package/dist/{chunk-3KS3547B.js → chunk-SSFG7FNI.js} +1 -1
- package/dist/{chunk-UXEL636C.js → chunk-UXVABU6B.js} +1 -1
- package/dist/{chunk-CV7OBWOX.js → chunk-WJS6NM7T.js} +1 -1
- package/dist/{chunk-RL5XRG6O.js → chunk-WWE2FXAQ.js} +1 -1
- package/dist/{chunk-HNEKQMQG.js → chunk-YJREJ2MH.js} +1 -1
- package/dist/{chunk-7CASAJU4.js → chunk-ZE7BP4AE.js} +1 -1
- package/dist/{claude-setup-6RMV3QZM.js → claude-setup-FYWGYBTH.js} +1 -1
- package/dist/cli.js +2 -2
- package/dist/demo-engine-5HWLXPDJ.js +3 -0
- package/dist/{engine-I2NXY2OK.js → engine-LFB243Q6.js} +2 -2
- package/dist/{framing-QC7Z2GRK.js → framing-KHUFARKE.js} +1 -1
- package/dist/gfx-worker.js +1 -1
- package/dist/h264-QGSP23K2.js +3 -0
- package/dist/{h264-mxf-PKSTGNGH.js → h264-mxf-I4YANT5F.js} +1 -1
- package/dist/{host-relink-B3M3B3VF.js → host-relink-L7I75SUH.js} +1 -1
- package/dist/{hosted-26GUD7IU.js → hosted-5Y5VX6X6.js} +1 -1
- package/dist/hosts-QMGBN2E6.js +3 -0
- package/dist/http.js +2 -2
- package/dist/{inspect-RT36GEVU.js → inspect-GP6B6UPD.js} +2 -2
- package/dist/{isobmff-65LRNCQH.js → isobmff-LAXAYC7P.js} +1 -1
- package/dist/{mc-video-2PCAX65A.js → mc-video-KQ7TP4DG.js} +1 -1
- package/dist/mcp.js +7 -7
- package/dist/{media-NCUTSVJ4.js → media-SUPBJX64.js} +1 -1
- package/dist/{mxf-WFJNAX7D.js → mxf-2TQO552L.js} +1 -1
- package/dist/{ops-SH3IUU2Z.js → ops-CVKPID5Z.js} +1 -1
- package/dist/{probe-VB6JH6ZJ.js → probe-HUPB4H4G.js} +1 -1
- package/dist/{r3d-X2O5LUAB.js → r3d-EPSGIBPT.js} +1 -1
- package/dist/resolve-bridge.py +4 -1
- package/dist/{sequence-patch-OHYBBKKZ.js → sequence-patch-GXM3QSJC.js} +1 -1
- package/dist/{store-F2CTSR6E.js → store-K4W2LVRN.js} +1 -1
- package/dist/{timeline-33MJ3HOK.js → timeline-HTG23FEH.js} +1 -1
- package/package.json +5 -5
- package/dist/chunk-7GEOQ4N6.js +0 -537
- package/dist/chunk-IDADYIY6.js +0 -7
- package/dist/chunk-TIZC6IEH.js +0 -10
- package/dist/chunk-ZPIY5DOU.js +0 -3
- package/dist/demo-engine-ITZ7VG6Q.js +0 -3
- package/dist/h264-TVMYQ7EB.js +0 -3
- package/dist/hosts-LVKUUVG7.js +0 -3
|
@@ -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{readFile as O,writeFile as _,appendFile as B,stat as j,readdir as X,mkdir as z,open as T,copyFile as Z,mkdtemp as Q,rm as P,chmod as ee,rename as L,cp as te,statfs as re,realpath as ne}from"node:fs/promises";import{execFile as oe,spawn as J}from"node:child_process";import{createHash as se}from"node:crypto";import{createReadStream as ie,chmodSync as A,cpSync as ae,existsSync as S,mkdirSync as C,readdirSync as ce,statSync as N}from"node:fs";import{homedir as le,hostname as ue,tmpdir as de,platform as me,release as fe,arch as pe,totalmem as ge,availableParallelism as ye}from"node:os";import{fileURLToPath as D}from"node:url";import we from"node:http";import be from"node:http2";import f from"node:process";import{setTimeout as he}from"node:timers";import{Buffer as $}from"node:buffer";import{basename as xe,dirname as q,join as w,resolve as I,sep as v}from"node:path";import{createRequire as ve}from"node:module";import{basename as Ct,dirname as Nt,extname as It,join as Ht,relative as Wt,resolve as _t}from"node:path";{let e=globalThis.fetch,t=typeof globalThis.Deno<"u";e&&!t&&(globalThis.fetch=(async(r,o)=>{let n=typeof r=="string"?r:r instanceof URL?r.href:r.url;if(n.startsWith("file:")){let s=await O(D(n)),i=n.endsWith(".wasm")?"application/wasm":"application/octet-stream";return new Response(s,{status:200,headers:{"content-type":i}})}return e(r,o)}))}var b=e=>f.env[e];function _e(e,t){he(e,t).unref()}var Be=()=>Number(b("CONFORM_MEMORY_GB")??0)*2**30||ge(),je=()=>ye(),ze=()=>f.argv.slice(2),Le=e=>f.exit(e),Pe=()=>f.platform,Je=()=>ue(),qe=()=>b("CONFORM_PYTHON")??(Pe()==="win32"?"python":"python3"),Ge=()=>f.arch,G=()=>`${f.platform}-${f.arch}`;function Ye(e){try{return w(q(ve(import.meta.url).resolve(`${$e(G())}/package.json`)),e)}catch{return null}}var $e=e=>`conformtools-${e==="win32-x64"?"windows-x64":e}`,Ke=e=>`${e} is not in this package for ${G()} (conform.tools builds it for darwin-arm64, darwin-x64, linux-x64 and win32-x64)`;function Ve(){let e=f.versions.deno,t=b("CONFORM_APP_VERSION"),r=e?`deno ${e}`:`node ${f.version}`;return{platform:`${me()} ${fe()} ${pe()}`,runtime:t&&/^[0-9A-Za-z.-]{1,32}$/.test(t)?`${r} app ${t}`:r}}var Re=()=>b("CONFORM_MCP_HOME")??w(U(),".conform-mcp"),U=()=>b("HOME")??le();function Xe(e){let t=e.trim();if(t.length>=2&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))&&(t=t.slice(1,-1)),/^file:\/\//i.test(t))try{t=D(t)}catch{}return t==="~"?t=U():(t.startsWith("~/")||t.startsWith("~\\"))&&(t=w(U(),t.slice(2))),t&&I(t)+(/[\\/]$/.test(t)&&!/[\\/]$/.test(I(t))?v:"")}async function Ze(e,t){let r=await import("node:sqlite").catch(()=>null);if(r?.DatabaseSync){let n=new r.DatabaseSync(e,{readOnly:!0});try{let s=n.prepare(t);return s.setReadBigInts(!0),s.all().map(i=>Object.fromEntries(Object.entries(i).map(([c,l])=>[c,typeof l=="bigint"?Number(l):l])))}finally{n.close()}}let o=await F("sqlite3",["-readonly","-json",e,t]);if(!o.success)throw new Error(`sqlite3 ${xe(e)}: ${o.stderr.trim()||o.stdout.trim()}`);return o.stdout.trim()?JSON.parse(o.stdout):[]}var Qe=(e,t)=>e?`${e.replace(/[\\/]+$/,"")}${e.includes("\\")&&!e.includes("/")?"\\":"/"}${t}`:t;function et(e){let t=D(e),r=t.indexOf(`${v}deno-compile-`);if(r<0||!S(t))return t;let o=t.slice(r+1).split(v).slice(1).join(v),n=w(Re(),"bin",o);try{return Y(t,n,!0),n}catch{return t}}function Y(e,t,r=!1){let o=N(e);if(o.isDirectory()){S(t)||C(t,{recursive:!0}),A(t,493);for(let s of ce(e))Y(w(e,s),w(t,s));return}let n=S(t)?N(t):null;(!n||n.size!==o.size||n.mtimeMs<o.mtimeMs)&&(n?A(t,420):C(q(t),{recursive:!0}),ae(e,t,{force:!0,preserveTimestamps:!0})),A(t,r||o.mode&73?493:420)}var H=null;var x=e=>H?.owns(e)?H:null;async function W(e){let t=await j(e);return{isFile:t.isFile(),isDirectory:t.isDirectory(),size:t.size,mtimeMs:t.mtimeMs}}function R(e){return x(e)?.stat(e,()=>W(e))??W(e)}async function tt(e){try{return await R(e),!0}catch{return!1}}async function rt(e){try{return(await R(e)).isFile}catch{return!1}}async function nt(e){try{return(await R(e)).isDirectory}catch{return!1}}async function ot(e){x(e)?.guard(e,"read whole file");let t=await O(e);return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}var st=e=>O(e,"utf8"),it=(e,t)=>_(e,t),at=(e,t)=>B(e,t),ct=(e,t,r)=>r?.append?B(e,t):_(e,t);async function lt(e){await z(e,{recursive:!0})}async function ut(e,t={}){let r=Date.now()+(t.timeoutMs??5e3),o=t.staleMs??15e3;for(;;)try{await z(e);break}catch(n){if(n.code!=="EEXIST")throw n;try{if(Date.now()-(await R(e)).mtimeMs>o){await P(e,{recursive:!0,force:!0});continue}}catch{}if(Date.now()>r)break;await new Promise(s=>setTimeout(s,25))}return()=>P(e,{recursive:!0,force:!0}).catch(()=>{})}var dt=e=>P(e,{force:!0}),mt=(e,t)=>ee(e,t).catch(()=>{}),ft=(e,t)=>Z(e,t),pt=(e,t)=>L(e,t),gt=e=>P(e,{recursive:!0,force:!0}),yt=(e,t)=>te(e,t,{recursive:!0,verbatimSymlinks:!0});async function wt(e){try{let t=await re(e);return Number(t.bavail)*Number(t.bsize)}catch{return null}}async function bt(e){try{return await ne(e)}catch{return null}}var ht=()=>f.ppid,xt=(e="conform-")=>Q(w(de(),e));async function*vt(e){let t=async()=>(await X(e,{withFileTypes:!0})).map(r=>({name:r.name,isFile:r.isFile(),isDirectory:r.isDirectory()}));yield*await(x(e)?.readDir(e,t)??t())}async function Pt(e){x(e)?.guard(e,"read bytes");let t=await T(e,"r"),r=(await t.stat()).size;return{path:e,size:r,async readAt(o,n){let s=new Uint8Array(n),i=0;for(;i<n;){let{bytesRead:c}=await t.read(s,i,n-i,o+i);if(!c)break;i+=c}return i===n?s:s.subarray(0,i)},close:()=>t.close()}}async function $t(e){let t=await T(e,"w");return{async writeAt(r,o){let n=0;for(;n<o.length;){let{bytesWritten:s}=await t.write(o,n,o.length-n,r+n);n+=s}},truncate:r=>t.truncate(r),close:()=>t.close()}}var K=(e,t)=>{for(let r of t)x(r)?.guard(r,`${e.split(/[\\/]/).pop()} ${t[0]}`)};function F(e,t,r={}){return K(e,t),new Promise(o=>{oe(e,t,{maxBuffer:1<<30,env:r.env?{...f.env,...r.env}:void 0,timeout:r.timeoutMs},(n,s,i)=>{let c=n?.code??0;o({success:!n,code:c,stdout:String(s),stderr:String(i)})})})}var ke="[Console]::OutputEncoding=[Text.Encoding]::UTF8;$t=@{};Get-Process|?{$_.MainWindowTitle}|%{$t[$_.Id]=$_.MainWindowTitle};ConvertTo-Json -Compress -InputObject @(Get-CimInstance Win32_Process|%{[pscustomobject]@{pid=[int]$_.ProcessId;exe=$_.ExecutablePath;cmd=$_.CommandLine;title=$t[[int]$_.ProcessId]}})";async function Rt(){let e=await F("powershell.exe",["-NoProfile","-NonInteractive","-Command",ke],{timeoutMs:3e4});return Ae(e.stdout)}function Ae(e){let t;try{t=JSON.parse(e.replace(/^/,"").trim()||"[]")}catch{return[]}return(Array.isArray(t)?t:[t]).flatMap(r=>{let o=r??{},n=Number(o.pid);return!Number.isInteger(n)||n<=0?[]:[{pid:n,args:String(o.cmd||o.exe||""),title:typeof o.title=="string"?o.title:""}]})}function kt(e,t,r,o={}){return K(e,t),new Promise((n,s)=>{let i=J(e,t,{env:o.env?{...f.env,...o.env}:void 0,stdio:["ignore","pipe","pipe"]}),c="";i.stdout.on("data",l=>r(l)),i.stderr.on("data",l=>{c+=new TextDecoder().decode(l)}),i.on("error",s),i.on("close",l=>n({code:l,stderr:c})),o.signal?.addEventListener("abort",()=>i.kill(),{once:!0})})}function At(e,t,r,o,n={}){let s=J(e,t,{stdio:["pipe","pipe","pipe"],env:n.env?{...f.env,...n.env}:void 0});s.stdin.on("error",()=>{}),s.stdout.on("data",a=>r(a)),s.stderr.on("data",a=>o?.(new TextDecoder().decode(a)));let i=new Promise(a=>{s.on("close",u=>a(u)),s.on("error",()=>a(null))}),c=[s,s.stdout,s.stderr,s.stdin],l=a=>{for(let u of c)(a?u.ref:u.unref)?.call(u)};return l(!1),{write:a=>new Promise((u,p)=>{s.stdin.write(a,m=>m?p(m):u())}),hold:l,close:()=>{try{s.stdin.end(),s.kill()}catch{}},exited:i}}async function St(e){if(b("CONFORM_NO_BROWSER"))return!1;let[t,r]=f.platform==="darwin"?["open",[e]]:f.platform==="win32"?["cmd",["/c","start","",e.replace(/&/g,"^&")]]:["xdg-open",[e]];return(await F(t,r)).success}function Ut(e,t){let r=we.createServer(async(o,n)=>{try{let s=[];if(o.method!=="GET"&&o.method!=="HEAD")for await(let p of o)s.push(p);let i=s.length>0,c=new Headers;for(let[p,m]of Object.entries(o.headers))m!=null&&c.set(p,Array.isArray(m)?m.join(", "):m);let l=`http://${o.headers.host??`${e.hostname}:${e.port}`}${o.url??"/"}`,a=new AbortController;n.on("close",()=>{n.writableEnded||a.abort()});let u=await t(new Request(l,{method:o.method,headers:c,body:i?$.concat(s):void 0,signal:a.signal}));if(n.statusCode=u.status,u.headers.forEach((p,m)=>n.setHeader(m,p)),u.body&&u.headers.get("content-type")?.startsWith("text/event-stream")){n.flushHeaders();let p=u.body.getReader();for(a.signal.addEventListener("abort",()=>void p.cancel(),{once:!0});;){let{value:m,done:g}=await p.read();if(g)break;n.write(m)}n.end();return}n.end($.from(await u.arrayBuffer()))}catch(s){n.statusCode=500,n.end(JSON.stringify({ok:!1,code:"internal",message:s instanceof Error?s.message:String(s)}))}});return r.listen(e.port,e.hostname,()=>{let o=r.address();e.onListen?.(typeof o=="object"&&o?o.port:e.port)}),{close:()=>r.close()}}var y=class extends Error{constructor(r,o,n){super(o);this.code=r;this.grpcStatus=n}};function Ot(e,t,r,o,n){return new Promise((s,i)=>{let c=be.connect(`http://${e}:${t}`),l=!1,a=(d,V)=>{l||(l=!0,clearTimeout(p),c.destroy(),d?i(d):s(V))},u=!1;c.on("connect",()=>{u=!0});let p=setTimeout(()=>a(u?new y("deadline",`no answer from ${e}:${t} in ${n} ms`):new y("unavailable",`${e}:${t}: no connection in ${n} ms`)),n);c.on("error",d=>a(new y("unavailable",`${e}:${t}: ${d.message}`)));let m=$.alloc(5+o.length);m.writeUInt32BE(o.length,1),m.set(o,5);let g=c.request({":method":"POST",":path":r,"content-type":"application/grpc",te:"trailers"}),E=[],h,k="",M=d=>{d["grpc-status"]!=null&&(h=String(d["grpc-status"]),k=decodeURIComponent(String(d["grpc-message"]??"")))};g.on("response",M),g.on("trailers",M),g.on("data",d=>E.push(d)),g.on("error",d=>a(new y("unavailable",`${e}:${t}: ${d.message}`))),g.on("end",()=>{if(h!=="0")return a(new y("grpc",`grpc-status ${h??"missing"}${k?`: ${k}`:""}`,h==null?void 0:Number(h)));let d=$.concat(E);if(d.length<5||d[0]!==0)return a(new y("grpc","reply is not one uncompressed gRPC message"));a(null,new Uint8Array(d.subarray(5,5+d.readUInt32BE(1))))}),g.end(m)})}async function Tt(e){let t=se("sha256");for await(let r of ie(e))t.update(r);return t.digest("hex")}async function Dt(e,t,r){let o=`${t}.part`;for(let n=0;;n++){let s=0;try{s=(await j(o)).size}catch{}try{let i=await fetch(e,{headers:s?{Range:`bytes=${s}-`}:{}});if(i.status===416)break;if(!i.ok||!i.body)throw new Error(`${e} answered ${i.status}`);s&&i.status!==206&&(s=0);let c=s+Number(i.headers.get("content-length")??0),l=await T(o,s?"a":"w");try{let a=s;for await(let u of i.body)await l.write(u),a+=u.length,r?.(a,c)}finally{await l.close()}break}catch(i){if(n>=4)throw i;await new Promise(c=>setTimeout(c,2e3*(n+1)))}}await L(o,t)}function Ft(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}export{D as a,b,_e as c,Be as d,je as e,ze as f,Le as g,Pe as h,Je as i,qe as j,Ge as k,Ye as l,Ke as m,Ve as n,Re as o,U as p,Xe as q,Ze as r,Qe as s,et as t,R as u,tt as v,rt as w,nt as x,ot as y,st as z,it as A,at as B,ct as C,lt as D,ut as E,dt as F,mt as G,ft as H,pt as I,gt as J,yt as K,wt as L,bt as M,ht as N,xt as O,vt as P,Pt as Q,$t as R,F as S,Rt as T,kt as U,At as V,St as W,Ut as X,y as Y,Ot as Z,Tt as _,Dt as $,Ft as aa,Ct as ba,Nt as ca,It as da,Ht as ea,Wt as fa,_t as ga};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
+
import{a as P}from"./chunk-3PVQ5QP4.js";import{b as ge,c as we,f as _e}from"./chunk-VFXMP7IF.js";import{f as X,h as he}from"./chunk-ASFUV3PB.js";import{a as be}from"./chunk-GDPYFRSV.js";import{i as T}from"./chunk-FHCRWOI7.js";import{b as E,d as U,f as O}from"./chunk-NU3X7P4N.js";import{Ja as pe,ea as ce,fa as le,ka as ue,pa as me,ya as de,za as fe}from"./chunk-7Z65WW4I.js";import{a as ae}from"./chunk-E75BCWXY.js";import{A as J,D as K,I as V,P as S,Q as k,R as se,U as ie,b as z,ba as b,ca as $,d as ee,da as N,e as re,ea as y,h as te,l as ne,m as B,t as W,u as L,w as oe,x as F}from"./chunk-QQBDHVUU.js";var G=!1,C=8,De=0,ze=3,I=2;async function ke(e){let t=new Uint8Array(await e.slice(0,16).arrayBuffer()),n=i=>String.fromCharCode(t[i],t[i+1],t[i+2],t[i+3]);if(t[0]===6&&t[1]===14&&t[2]===43&&t[3]===52)return"mxf";if(n(4)==="RED1"||n(4)==="RED2")return"r3d";let r=t[0]<<24|t[1]<<16|t[2]<<8|t[3],s=n(4);return/^[A-Za-z0-9 ]{4}$/.test(s)&&(r>=8||r===1)&&r<=e.size?"isobmff":null}function Ne(e){let t=e.toLowerCase();return t.endsWith(".braw")?"braw":t.endsWith(".crm")?"crm":"mov"}function Te(e){return async(t,n)=>new Uint8Array(await e.slice(t,Math.min(t+n,e.size)).arrayBuffer())}function ye(e){let t=e.timecode;return!t||!t.fps_denominator?null:t.fps_numerator/t.fps_denominator}async function ir(e){return await pe(),xe?xe.clip(e,G?"rec709":"",()=>$e(e)):$e(e)}var xe=null;async function $e(e){let t=await ke(e),n=[];if(t==="r3d"){let r=e,s=r.parts&&r.bases?r.parts:[{name:e.name,size:e.size}],o=r.bases??[0],i=async(u,d,m)=>{let f=o[u]+d;return new Uint8Array(await e.slice(f,Math.min(f+m,o[u]+s[u].size)).arrayBuffer())},c=JSON.stringify(s.map(u=>({name:u.name,size:u.size}))),a=JSON.parse(await fe(i,c)),l=JSON.parse(await ue(i,c));return s.length===1&&/_\d{3}\.r3d$/i.test(e.name)&&!/_001\.r3d$/i.test(e.name)&&n.push("spanned R3D part \u2014 only this part's frames are indexed"),{frames:l.map(u=>({offset:o[u.part??0]+u.essenceOffset,size:u.essenceLength})),w:a.width??0,h:a.height??0,fps:ye(a),startFrame:a.timecode?.start_frame??0,dropFrame:a.timecode?.drop_frame??!1,label:"R3D",spec:{codec:"r3d",subbands:De},geometrySpec:{codec:"r3d",subbands:ze},index:null,warnings:n}}if(t==="mxf"){let r=Te(e),s=JSON.parse(await de(r,e.size));if(!s)throw new Error(`${e.name}: MXF index unreadable`);let o=JSON.parse(await me(r,e.size)),i=[];for(let f=0;f<o.frame_count;f++)i.push({offset:o.frames[f*2],size:o.frames[f*2+1]});let c=i.filter(f=>f.size===0).length;c&&n.push(`${c} frame(s) had no locatable picture KLV`);let a=s.width??0,l=s.height??0,u=(s.inner_codec??"").toLowerCase(),d=null,m="MXF";return u==="arriraw"?(d={codec:"arriraw",w:a,h:l,scale:C},m="ARRIRAW"):u==="xocn"?(d={codec:"xocn",scale:C,...G?{display:"rec709"}:{}},m="X-OCN"):await le(r,e.size)?(d={codec:"vc3",scale:C},m="DNxHR"):await ce(r,e.size)?(d={codec:"prores"},m="ProRes"):n.push(`MXF inner codec ${u||"unknown"} not wired to the fingerprint pool`),{frames:d?i:[],w:a,h:l,fps:ye(s),startFrame:s.timecode?.start_frame??0,dropFrame:s.timecode?.drop_frame??!1,label:m,spec:d,geometrySpec:d&&d.codec==="arriraw"?{...d,scale:I}:d&&d.codec==="xocn"?{codec:"xocn",scale:I,...G?{display:"rec709"}:{}}:d&&d.codec==="vc3"?{codec:"vc3",scale:I}:null,index:null,warnings:n}}if(t==="isobmff"){let r=await he(e),s=Ne(e.name);if(r.kind==="prores")return{frames:r.offs,w:r.w,h:r.h,fps:r.fps,startFrame:r.startFrame,dropFrame:r.dropFrame,label:X(r.kind),spec:{codec:"prores"},geometrySpec:null,index:r,warnings:n};if(r.kind==="h264"||r.kind==="hevc")return{frames:r.offs,w:r.w,h:r.h,fps:r.fps,startFrame:r.startFrame,dropFrame:r.dropFrame,label:X(r.kind),spec:null,geometrySpec:null,index:r,warnings:n};let o=s==="braw"?{codec:"braw",scale:C}:r.codec==="aprh"||r.codec==="aprn"?{codec:"proresraw",scale:C}:null;return o||n.push(`codec ${r.codec} not wired to the fingerprint pool`),{frames:o?r.offs:[],w:r.w,h:r.h,fps:r.fps,startFrame:r.startFrame,dropFrame:r.dropFrame,label:o?s==="braw"?"BRAW":"ProRes RAW":`unsupported (${r.codec})`,spec:o,geometrySpec:o?{...o,scale:I}:null,index:r,warnings:n}}throw new Error(`${e.name}: unrecognised container`)}var Y=null;var Ue=Number(z("CONFORM_DECODERS")??0)||Math.max(2,Math.min(Math.floor(re()/2),Math.floor(ee()/2**31))),Z=0,ve=[],Me=async(...e)=>{Z>=Ue?await new Promise(t=>ve.push(t)):Z++;try{return await ie(...e)}finally{let t=ve.shift();t?t():Z--}};async function Re(){let e=te()==="win32"?"conformtools-decode.exe":"conformtools-decode",t=[z("CONFORM_NATIVE_DECODE"),ne(e),W(new URL(`./${e}`,import.meta.url)),W(new URL(`../../rust/target/release/${e}`,import.meta.url))].filter(Boolean);for(let n of t)if(await oe(n))return n;return null}var M=class extends Error{constructor(n,r){super(r);this.why=n}};function Pr(e){let t=null;try{t=JSON.parse(e.trim().split(`
|
|
4
|
+
`).pop())}catch{}if(t?.why==="not_entitled")throw new ae("not_entitled",t.detail??"this machine is not licensed");return t?.detail??e.trim()}function Fe(e,t){try{let n=JSON.parse(e.trim().split(`
|
|
5
|
+
`).pop()??"");return new M(n.why,n.detail)}catch{return new M("decoder",`the native decoder exited ${t}: ${e.trim().slice(-300)}`)}}function Er(e){return Y?.owns(e)?Y.meta(`probe|${e}`,()=>Se(e)):Se(e)}async function Se(e){let t=await Re();if(!t)throw new M("missing",B("the native decoder (conformtools-decode)"));let n=[],r=await Me(t,["probe",e],s=>n.push(s));if(r.code!==0)throw Fe(r.stderr,r.code);return JSON.parse(new TextDecoder().decode(Pe(n)))}function Pe(e){let t=e.reduce((s,o)=>s+o.length,0),n=new Uint8Array(t),r=0;for(let s of e)n.set(s,r),r+=s.length;return n}async function Ie(e,t,n,r,s){let o=await Re();if(!o)throw new M("missing",B("the native decoder (conformtools-decode)"));let i=null,c=[],a=0,l=m=>{let f=new Uint8Array(m),h=0;for(;h<m;){let p=c[0],g=Math.min(p.length,m-h);f.set(p.subarray(0,g),h),h+=g,g===p.length?c.shift():c[0]=p.subarray(g)}return a-=m,f},u=[e,t,"--width",String(s.width??32768)];s.from!=null&&u.push("--from",String(s.from)),s.count!=null&&u.push("--count",String(s.count)),s.range&&u.push("--range",s.range);let d=await Me(o,u,m=>{if(c.push(m),a+=m.length,!i){let h=Pe(c.splice(0));c.push(h);let p=h.indexOf(10);if(p<0)return;i=JSON.parse(new TextDecoder().decode(h.subarray(0,p))),l(p+1),n(i)}let f=4+i.w*i.h*(i.bpp??(e==="rgb16"?6:4));for(;a>=f;){let h=l(f);r(new DataView(h.buffer).getUint32(0,!0),h.subarray(4))}},{signal:s.signal});if(d.code!==0||!i)throw Fe(d.stderr,d.code)}function Ee(e,t,n,r={}){return Ie("bgra",e,t,n,r)}var He=["none","rle","zips","zip","piz","pxr24","b44","b44a","dwaa","dwab","htj2k"],H=e=>(e>>4)*10+(e&15);function je(e){let t=H(e&63),n=H(e>>>8&127),r=H(e>>>16&127),s=H(e>>>24&63),o=i=>String(i).padStart(2,"0");return`${o(s)}:${o(r)}:${o(n)}${e&64?";":":"}${o(t)}`}function Be(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength);if(e.length<8||t.getUint32(0,!0)!==20000630)return null;let n={fps:null,timecode:null,width:0,height:0,display:null,compression:null,attributes:[]},r=8,s=()=>{let i=r;for(;r<e.length&&e[r]!==0;)r++;let c=new TextDecoder().decode(e.subarray(i,r));return r++,c},o=i=>({width:t.getInt32(i+8,!0)-t.getInt32(i,!0)+1,height:t.getInt32(i+12,!0)-t.getInt32(i+4,!0)+1});for(;r<e.length;){let i=s();if(!i)break;let c=s();if(r+4>e.length)return null;let a=t.getInt32(r,!0);if(r+=4,a<0||r+a>e.length)return null;if(n.attributes.push(`${i}:${c}`),i==="framesPerSecond"&&c==="rational"&&a>=8){let l=t.getInt32(r,!0),u=t.getUint32(r+4,!0);n.fps=u?l/u:null}else i==="timeCode"&&c==="timecode"&&a>=8?n.timecode=je(t.getUint32(r,!0)):i==="dataWindow"&&c==="box2i"&&a>=16?{width:n.width,height:n.height}=o(r):i==="displayWindow"&&c==="box2i"&&a>=16?n.display=o(r):i==="compression"&&a>=1&&(n.compression=He[e[r]]??`type ${e[r]}`);r+=a}return n}async function We(e){let t=e,n=null,r=/^(.*?)\[(\d+)-(\d+)\](.*)$/.exec(b(e));if(await F(e))n=/^(.*?)(\d+)(\.exr)$/i;else{t=$(e);let o=r?[null,r[1],r[2],r[4]]:/^(.*?)(\d+)(\.exr)$/i.exec(b(e));if(!o)return{frames:[e],numbers:[]};let i=c=>c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");n=new RegExp(`^${i(o[1])}(\\d{${o[2].length}})${i(o[3])}$`,"i")}let s=[];for await(let o of S(t)){let i=o.isFile?n.exec(o.name):null;i&&s.push({n:Number(i[i.length===4?2:1]),f:y(t,o.name)})}return s.sort((o,i)=>o.n-i.n),{frames:s.map(o=>o.f),numbers:s.map(o=>o.n)}}async function Q(e){let t=await We(e),n=t.frames[0];if(!n)throw new Error(`no .exr frames for '${b(e)}'`);let r=await k(n),s;try{s=Be(await r.readAt(0,Math.min(r.size,1<<20)))}finally{await r.close()}if(!s)throw new Error(`'${b(n)}' is not an OpenEXR file`);let o=Math.max(1,t.frames.length),i=t.numbers.length>1?t.numbers[t.numbers.length-1]-t.numbers[0]+1-t.numbers.length:0,c=s.fps??0;return{id:b(n),kind:"external",target_url:n,local_path:n,content_kind:o>1?"video":"still",source_fps:s.fps??void 0,source_timecode:s.timecode??void 0,source_resolution_w:s.width,source_resolution_h:s.height,available_range:{start:{value:0,rate:c},duration:{value:o,rate:c}},streams:[{kind:"video",codec:"exr",width:s.width,height:s.height,rate:s.fps??void 0,codec_specific:{compression:s.compression}}],vendor_metadata:{exr:{frames:o,first_frame:t.numbers[0]??null,last_frame:t.numbers[t.numbers.length-1]??null,missing_frames:i,display_window:s.display,attributes:s.attributes,fps_source:s.fps!=null?"header framesPerSecond":"not in the header",timecode_source:s.timecode?"header timeCode (first frame)":"not in the header"}}}}var A=new Set([".mov",".mp4",".m4v",".mxf",".wav",".braw",".crm",".r3d",".aif",".aiff"]);async function Le(e){let t=await k(e);return{path:e,file:t,size:t.size}}function Je(e){return(t,n)=>e.file.readAt(t,n)}async function Ke(e){let t=P(b(e));if(!t)return[e];let n=$(e),r=[];for await(let s of S(n)){if(!s.isFile)continue;let o=P(s.name);o&&o.clipBase===t.clipBase&&r.push({n:o.partNumber,p:y(n,s.name)})}return r.sort((s,o)=>s.n-o.n).map(s=>s.p)}async function Ve(e){let t=[],n=[];for await(let r of S(e))!r.isFile||r.name.startsWith(".")||(P(r.name)?t.push(r.name):A.has(N(r.name).toLowerCase())&&n.push(r.name));if(t.length)return y(e,t.sort()[0]);if(n.length===1)return y(e,n[0]);throw n.length?(n.sort(),new Error(`'${b(e)}' is a folder of ${n.length} clips (${n.slice(0,3).join(", ")}${n.length>3?", \u2026":""}): probe one of them, or media_find to list them all`)):new Error(`'${b(e)}' is a folder with no media file in it (looked for ${[...A].join(" ")}, and RED parts)`)}async function q(e){await F(e)&&(e=await Ve(e));let t=we(b(e));if(!t)throw new Error(`unsupported media file '${b(e)}' (supported: ${[...A].join(" ")})`);let n=await Ke(e),r=await Promise.all(n.map(Le));return{source:_e(t,r.map(o=>ge(b(o.path),{fileSize:o.size,read:Je(o)}))),parts:r,format:t,anchor:n[0],close:()=>r.forEach(o=>o.file.close())}}async function jr(e,t,n,r){if(!/h264|avc|hevc|h265/.test(n)){let s=null,o=await q(e);try{return await T(o.source,{verb:"decode",index:t,intent:"park"})}catch(i){s=i}finally{o.close()}try{return await Oe(e,t,r)}catch(i){throw/no decoder/.test(String(s))?i:s instanceof Error?s:new Error(String(s))}}return Oe(e,t,r)}async function Oe(e,t,n){t=Math.round(t);let r=0,s=0,o=null;if(await Ee(e,c=>{r=c.w,s=c.h},(c,a)=>{c===t&&(o=a)},{from:t,count:1,width:n}),!o)throw new Error(`the OS decoder returned no frame ${t} of ${b(e)}`);let i=o;for(let c=0;c<i.length;c+=4){let a=i[c];i[c]=i[c+2],i[c+2]=a}return{rgba:i,width:r,height:s}}async function D(e){if(await F(e)){let n=[];for await(let r of S(e))r.isFile&&/\.exr$/i.test(r.name)&&!r.name.startsWith(".")&&n.push(r.name);if(n.length)return Q(y(e,n.sort()[0]))}if(/\.exr$/i.test(e))return Q(e);let t=await q(e);try{let n=await T(t.source,{verb:"inspect"});if(!n)throw new Error(`could not read '${b(e)}' as ${t.format}`);return n.target_url=t.anchor,n.local_path=t.anchor,n.id=n.id||b(t.anchor),t.parts.length>1&&((n.vendor_metadata??={}).spanned_parts=t.parts.map(r=>b(r.path))),n.size_bytes=t.parts.reduce((r,s)=>r+s.size,0),n}finally{t.close()}}function Ae(e,t,n,r){let s=Math.abs(r*1001-Math.round(r*1001/1e3)*1e3)<1?Math.round(r)*1e3/1001:r,o=Math.floor(e*s/t+1e-6);return{tc:E(o,r),frames:Math.round(n*s/t)}}var Xe=e=>String(Math.round(e*1e3)/1e3);function Br(e,t){let n=e.streams?.find(p=>p.kind==="video"),r=e.streams?.filter(p=>p.kind==="audio")??[],s=e.vendor_metadata?.bext;if(!n&&e.available_range&&r[0]?.rate){let p=r[0].rate,g=e.available_range.duration.value,_=(t?[t]:[24e3/1001,24]).map(x=>{let v=Ae(s?.time_reference??0,s?.sample_rate||p,g,x);return`${s?`start TC ${v.tc}, `:""}${v.frames} frames @ ${Xe(x)} fps`});return[e.target_url??"",`audio only; ${g} samples (${(g/p).toFixed(3)} s)${s?`; BWF time_reference ${s.time_reference}`:"; no BWF timecode"}`,..._,...t?[]:["(pass fps for the project's rate)"],...r.map((x,v)=>`audio ${r.length>1?`${v+1}: `:""}${x.codec??"pcm"} ${x.channels??"?"}ch ${x.rate} Hz ${x.bit_depth??"?"}-bit`)].join(`
|
|
6
|
+
`)}let o=e.available_range?.duration?.value??e.declared_duration?.value??null,i=e.source_fps??n?.rate??null,c=e.size_bytes,a=e.vendor_metadata?.spanned_parts,l=n?.codec_specific??{},u=[l.profile?`${l.profile} (${l.fourcc})`:l.fourcc,l.pixel_format,n?.bit_depth?`${n.bit_depth}-bit`:null,l.colr?`color ${l.colr.primaries}/${l.colr.transfer}/${l.colr.matrix} (primaries/transfer/matrix)`:null].filter(Boolean).join(", "),d=e.source_pixel_aspect&&Math.abs(e.source_pixel_aspect-1)>.001?e.source_pixel_aspect:null,m=d&&n?.width&&n?.height?`pixel aspect ${Math.round(d*1e3)/1e3}: stored ${n.width}x${n.height}, shown ${(n.width*d/n.height).toFixed(2)}:1 (squeezed; a trim keeps it, a square-pixel copy is a new render)`:null,f=e.raw_extraction?.mov_probe?.every_sample_is_keyframe===!1&&n?"long-GOP (not every frame is a keyframe): media_trim starts on the keyframe at or before the frame asked for":null,h=e.vendor_metadata?.inner_codec??null;return[e.target_url??"",n?`${n.codec??h??"?"} ${n.width??"?"}x${n.height??"?"}${i?` @ ${Math.round(i*1e3)/1e3} fps`:""}${u?`; ${u}`:""}`:"no video track",...[m,f].filter(p=>!!p),`start TC ${e.source_timecode??"none"}; ${o!=null?`${o} frames`:"length unknown"}${o!=null&&i?` (${(o/i).toFixed(2)} s)`:""}`,r.length?r.map((p,g)=>{let w=p.codec_specific?.channel_layout;return`audio ${r.length>1?`${g+1}: `:""}${p.codec??"pcm"} ${p.channels??"?"}ch${w?` (${w})`:""} ${p.rate??"?"} Hz ${p.bit_depth??"?"}-bit`}).join(`
|
|
7
|
+
`):"no audio",`${e.reel_name?`reel ${e.reel_name}; `:""}${c!=null?`${(c/1e6).toFixed(1)} MB`:""}${a?`; spanned ${a.length} parts`:""}`].join(`
|
|
8
|
+
`)}var Ge=8*1024*1024,j=e=>Uint8Array.from(atob(e),t=>t.charCodeAt(0));async function Ye(e,t,n){if(e.executable_locally===!1)throw new Error("this trim plan is server-side only");let r=new Map(t.parts.map(o=>[b(o.path),o]));await K($(n));let s=await se(n);try{await s.truncate(e.total_size),await s.writeAt(0,j(e.dest_header_bytes_base64));for(let o of e.src_byte_ranges){let i=o.src_file_name?r.get(b(o.src_file_name)):t.parts[0];if(!i)throw new Error(`plan references unknown source part '${o.src_file_name}'`);let c=0;for(;c<o.length;){let a=Math.min(Ge,o.length-c),l=await i.file.readAt(o.offset+c,a);if(l.length<a)throw new Error(`short read in ${b(i.path)} at ${o.offset+c}`);await s.writeAt(o.write_to_dest_offset+c,l),c+=a}}e.dest_footer_bytes_base64&&e.dest_footer_offset!=null&&await s.writeAt(e.dest_footer_offset,j(e.dest_footer_bytes_base64));for(let o of e.dest_patches??[])await s.writeAt(o.offset,j(o.bytes_base64))}finally{await s.close()}for(let o of e.dest_sidecar_writes??[])await J(y($(n),o.name),j(o.bytes_base64))}function Ze(e,t){let n=[];for(let r of e){if(r.kind!=="clip"||!r.source_range)continue;let s=r.source_range.start.value,o=r.source_range.duration.value,i=Math.max(0,Math.floor(s)-t),c=Math.floor(s+o-1)+t;c>=i&&n.push({first_frame:i,last_frame:c})}return be(n)}async function Qe(e,t,n,r,s){let o=await q(e);try{let i=Ze(t,n);if(!i.length)throw new Error("no usable frame ranges (items need kind=clip with source_range)");let c=await T(o.source,{verb:"trim",selection:{items:t,handles:n}}),a=N(o.anchor),l=o.format==="r3d",u=l?P(b(o.anchor))?.clipBase??b(o.anchor,a):b(o.anchor,a),d=[];for(let[m,f]of c.entries()){let h=f.output_clip_number??(i.length>1?m+1:void 0),p=i[(h??1)-1]??i[0],g=h&&(f.output_clip_count??i.length)>1?`_S${String(h).padStart(3,"0")}`:"",w;if(l){let _=f.output_part_number??m+1;w=y(r,`${u}${g}.RDC`,`${u}_${String(_).padStart(3,"0")}.R3D`),d.push({path:w,bytes:f.total_size,island:p,part:_,clip:h})}else{let _=s&&c.length===1?s:`${u}${g||`_trim_${p.first_frame}-${p.last_frame}`}${a}`;w=y(r,_),d.push({path:w,bytes:f.total_size,island:p,clip:h})}await Ye(f,o,w)}return l||await qe(e,d,!!s&&c.length===1),{outputs:d,islands:i,format:o.format}}finally{o.close()}}async function qe(e,t,n){let r=await D(e).catch(()=>null),s=r?.source_fps??r?.streams?.find(o=>o.kind==="video")?.rate??null;if(!(!r?.source_timecode||!s))for(let o of t){if(!o.island)continue;let i=await D(o.path).catch(()=>null),c=i?.available_range?.duration?.value??i?.declared_duration?.value;if(!i?.source_timecode||!c)continue;let a=O(i.source_timecode,s,r.source_timecode);if(a===o.island.first_frame&&a+c-1===o.island.last_frame||(o.island={first_frame:a,last_frame:a+c-1},n))continue;let l=o.path.replace(/_trim_\d+-\d+(\.[^./\\]+)$/,`_trim_${a}-${a+c-1}$1`);l!==o.path&&(await V(o.path,l),o.path=l)}}async function Wr(e){let t=await D(e.path),n=t.source_fps??t.streams?.find(w=>w.kind==="video")?.rate??null,r=t.available_range?.duration?.value??t.declared_duration?.value??null,s=t.streams?.find(w=>w.kind==="audio")?.rate;if(!n&&e.fps&&s&&r!=null){let w=t.vendor_metadata?.bext,_=Ae(w?.time_reference??0,w?.sample_rate||s,r,e.fps);n=Math.abs(e.fps*1001-Math.round(e.fps*1001/1e3)*1e3)<1?Math.round(e.fps)*1e3/1001:e.fps,r=_.frames,t.source_timecode=_.tc}if(!n)throw new Error(s?"cannot trim: audio-only file: pass fps (the project's video rate) to count in/out in frames":"cannot trim: no frame rate / timecode track on this file");let o=O(e.in,n,t.source_timecode??null),i=O(e.out,n,t.source_timecode??null);e.out_exclusive&&(i-=1);let c=t.source_timecode??"00:00:00:00",a=r!=null?E((U(c,n)??0)+r-1,n,!!t.vendor_metadata?.drop_frame):null;if(i<o)throw new Error(`out ${e.out} is before in ${e.in}`);if(o<0)throw new Error(`in ${e.in} is before the file starts (${c}, frame 0)`);if(r!=null&&i>r-1)throw new Error(`out ${e.out} is past the end of the file (last frame ${a}, frame ${r-1})`);let l={id:"trim",kind:"clip",source_range:{start:{value:o,rate:n},duration:{value:i-o+1,rate:n}}},u=$(e.path),d;if(e.out_path)try{(await L(e.out_path)).isDirectory?u=e.out_path:(u=$(e.out_path),d=b(e.out_path))}catch{u=$(e.out_path),d=b(e.out_path)}let m=await Qe(e.path,[l],Math.max(0,Math.floor(e.handles??0)),u,d),f=m.islands[0],h=m.outputs.length===1&&m.outputs[0].island?m.outputs[0].island:f,p=h.first_frame,g=h.last_frame;return{outputs:m.outputs,first_frame:p,last_frame:g,frames:g-p+1,fps:n,facts:t,...p!==f.first_frame||g!==f.last_frame?{asked:{first_frame:f.first_frame,last_frame:f.last_frame}}:{}}}function Ce(e){let t=[...A].map(n=>n.slice(1)).join("|");return e.toLowerCase().replace(new RegExp(`\\.(${t})(?=[._\\s-]|$)`,"g"),"").replace(/[^a-z0-9]/g,"")}function er(e,t){let n=Ce(e),r=Ce(t);if(r&&n.includes(r))return"name";let s=t.toLowerCase().split(/[^a-z0-9]+/).filter(o=>/\d/.test(o)&&o.length>=3);return s.length&&s.every(o=>n.includes(o))?"id":null}async function Lr(e,t,n){let r=[],s=0,o=null,i=Date.now()+n.time_limit_s*1e3,c=async(a,l)=>{try{for await(let u of S(a)){if(o&&!o.startsWith("folders"))return;if(++s>n.max_entries){o=`stopped after ${n.max_entries} entries (max_entries)`;return}if(Date.now()>i){o=`stopped after ${n.time_limit_s} s (time_limit_s)`;return}if(u.name.startsWith("."))continue;let d=y(a,u.name);if(u.isDirectory)l<n.max_depth?await c(d,l+1):o??=`folders deeper than max_depth=${n.max_depth} not searched (e.g. ${d})`;else if(u.isFile&&A.has(N(u.name).toLowerCase())){let m=er(u.name,t);m&&r.push({path:d,match:m,size:(await L(d).catch(()=>({size:0}))).size})}}}catch{}};if(await c(e,0),n.probe)for(let a=0;a<r.length;a+=8)await Promise.all(r.slice(a,a+8).map(async l=>{try{l.facts=await D(l.path)}catch(u){l.error=u.message}}));return r.sort((a,l)=>a.path.localeCompare(l.path)),{hits:r,scanned:s,truncated:o}}function rr(e){let t=e.streams?.find(a=>a.kind==="video"),n=e.source_fps??t?.rate??null,r=e.available_range?.duration?.value??e.declared_duration?.value??null,s=t?.codec_specific??{},o=e.source_timecode&&n?U(e.source_timecode,n):null,i=o!=null&&r!=null&&n?E((o+r)%(Math.round(n)*86400),n,e.source_timecode.includes(";")):null,c=e.vendor_metadata?.inner_codec??null;return`${t?`${t.codec??c??"?"}${s.profile?` ${s.profile}`:""} ${t.width??"?"}x${t.height??"?"}`:"no video"}${n?` @ ${Math.round(n*1e3)/1e3} fps`:""}; TC ${e.source_timecode??"none"}${i?`\u2013${i}`:""}; ${r??"?"} fr${r!=null&&n?` (${(r/n).toFixed(2)} s)`:""}`}function Jr(e,t,n,r){let s=e.hits.slice(0,r),o=[];e.truncated&&o.push(`TRUNCATED: ${e.truncated} \u2014 the search did NOT cover all of ${t}; the matches below may be incomplete.`),e.hits.length>s.length&&o.push(`TRUNCATED: showing ${s.length} of ${e.hits.length} matches. Pass limit=${e.hits.length} or narrow the query.`),o.push(`${e.hits.length} file${e.hits.length===1?"":"s"} match "${n}" under ${t} (${e.scanned} entries scanned)`);let i=new Map;for(let a of e.hits)i.set(b(a.path).toLowerCase(),(i.get(b(a.path).toLowerCase())??0)+1);let c=[...i].filter(([,a])=>a>1);c.length&&o.push(`same name in several folders: ${c.map(([a,l])=>`${a} \xD7${l}`).join(", ")} \u2014 they can be DIFFERENT clips; match by TC + duration, never by name alone`);for(let a of s)o.push(`- ${a.path}${a.match==="id"?" (id match)":""}
|
|
9
|
+
${a.facts?rr(a.facts):a.error?`probe failed: ${a.error}`:`${(a.size/1e6).toFixed(1)} MB`}`);return o.join(`
|
|
10
|
+
`)}async function Kr(e,t,n=0){let r=await D(e),s=r.source_fps??r.streams?.find(m=>m.kind==="video")?.rate??null,o=r.available_range?.duration?.value??r.declared_duration?.value??null;if(!s||o==null)throw new Error(`cannot check coverage: ${b(e)} has no frame rate or length`);let i=Math.round(s)*86400,c=r.source_timecode?U(r.source_timecode,s)??0:0,a=!!r.source_timecode?.includes(";"),l=m=>{let f=O(m,s,r.source_timecode??null);return typeof m=="number"||/^\d+$/.test(m.trim())?f:f<-i/2?f+i:f>i/2?f-i:f},u=m=>E(((c+m)%i+i)%i,s,a),d=t.map((m,f)=>{let h=l(m.in),p=l(m.out),g=h,w=o-p,_=g>=0&&w>=0&&p>h,x=Math.max(0,-g),v=Math.max(0,-w),R=[];return p<=h?R.push("out is not after in"):_?R.push(`covered; handles head ${g} / tail ${w} fr`):R.push(`NOT covered: short ${[x?`${x} fr at head`:"",v?`${v} fr at tail`:""].filter(Boolean).join(", ")}`),_&&n&&(g<n||w<n)&&R.push(`handles short of ${n}: ${[g<n?`head by ${n-g}`:"",w<n?`tail by ${n-w}`:""].filter(Boolean).join(", ")}`),{label:m.label??`range ${f+1}`,in_tc:u(h),out_tc:u(p),frames:p-h,covered:_,head:g,tail:w,short_head:x,short_tail:v,note:R.join("; ")}});return{facts:r,rows:d}}export{ir as a,Re as b,Pr as c,Er as d,Ee as e,We as f,A as g,Ke as h,Ve as i,q as j,jr as k,D as l,Ae as m,Br as n,Ze as o,Qe as p,Wr as q,Ce as r,er as s,Lr as t,rr as u,Jr as v,Kr as w};
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
-
import{a as Oe,b as dt}from"./chunk-UE76WJ3Y.js";import{Qb as pt}from"./chunk-QY4QDBIN.js";import{a as mt}from"./chunk-X76IIWBH.js";import{b as Ee,d as ut}from"./chunk-NU3X7P4N.js";import{m as lt}from"./chunk-AR5BTVBM.js";import{A as tt,B as pe,C as Y,G as rt,I as me,N as q,O as nt,R as de,U as ot,X as st,Y as it,aa as at,b as F,ba as fe,da as I,h as H,j as Te,p as Pe,s as Xe,t as Ze,v as ce,w as le,y as ue,z as et}from"./chunk-ZPIY5DOU.js";import{M as ct,S as X}from"./chunk-C2ESM27Z.js";function ft(r,e){let t=async()=>{throw new Error(`${r}: ${e}`)},n={ok:!1,reason:e};return{host:r,wired:!1,support:async()=>({export:n,open:n,render:n,markers:n}),export:t,open:t,renderStart:t,renderStatus:t,renderCancel:t}}async function an(r,e,t,n){let o=new Promise(s=>n?.addEventListener("abort",()=>s(),{once:!0}));for(;e.state==="queued"||e.state==="rendering";){if(t?.(e.percent,100,"rendering"),await Promise.race([o.then(()=>!0),new Promise(i=>setTimeout(()=>i(!1),1e3))]))return await r.renderCancel(e.job_id);e=await r.renderStatus(e.job_id)}return e}var Kt=ArrayBuffer,O=Uint8Array,ge=Uint16Array,Qt=Int16Array;var he=Int32Array,Me=function(r,e,t){if(O.prototype.slice)return O.prototype.slice.call(r,e,t);(e==null||e<0)&&(e=0),(t==null||t>r.length)&&(t=r.length);var n=new O(t-e);return n.set(r.subarray(e,t)),n},ee=function(r,e,t,n){if(O.prototype.fill)return O.prototype.fill.call(r,e,t,n);for((t==null||t<0)&&(t=0),(n==null||n>r.length)&&(n=r.length);t<n;++t)r[t]=e;return r},Yt=function(r,e,t,n){if(O.prototype.copyWithin)return O.prototype.copyWithin.call(r,e,t,n);for((t==null||t<0)&&(t=0),(n==null||n>r.length)&&(n=r.length);t<n;)r[e++]=r[t++]};var Xt=["invalid zstd data","window size too large (>2046MB)","invalid block type","FSE accuracy too high","match distance too far back","unexpected EOF"],$=function(r,e,t){var n=new Error(e||Xt[r]);if(n.code=r,Error.captureStackTrace&&Error.captureStackTrace(n,$),!t)throw n;return n},gt=function(r,e,t){for(var n=0,o=0;n<t;++n)o|=r[e++]<<(n<<3);return o},Zt=function(r,e){return(r[e]|r[e+1]<<8|r[e+2]<<16|r[e+3]<<24)>>>0},er=function(r,e){var t=r[0]|r[1]<<8|r[2]<<16;if(t==3126568&&r[3]==253){var n=r[4],o=n>>5&1,s=n>>2&1,i=n&3,c=n>>6;n&8&&$(0);var a=6-o,l=i==3?4:i,u=gt(r,a,l);a+=l;var d=c?1<<c:o,f=gt(r,a,d)+(c==1&&256),h=f;if(!o){var p=1<<10+(r[5]>>3);h=p+(p>>3)*(r[5]&7)}h>2145386496&&$(1);var m=new O((e==1?f||h:e?0:h)+12);return m[0]=1,m[4]=4,m[8]=8,{b:a+d,y:0,l:0,d:u,w:e&&e!=1?e:m.subarray(12),e:h,o:new he(m.buffer,0,3),u:f,c:s,m:Math.min(131072,h)}}else if((t>>4|r[3]<<20)==25481893)return Zt(r,4)+8;$(0)},B=function(r){for(var e=0;1<<e<=r;++e);return e-1},te=function(r,e,t){var n=(e<<3)+4,o=(r[e]&15)+5;o>t&&$(3);for(var s=1<<o,i=s,c=-1,a=-1,l=-1,u=s,d=new Kt(512+(s<<2)),f=new Qt(d,0,256),h=new ge(d,0,256),p=new ge(d,512,s),m=512+(s<<1),g=new O(d,m,s),S=new O(d,m+s);c<255&&i>0;){var _=B(i+1),v=n>>3,R=(1<<_+1)-1,k=(r[v]|r[v+1]<<8|r[v+2]<<16)>>(n&7)&R,b=(1<<_)-1,w=R-i-1,T=k&b;if(T<w?(n+=_,k=T):(n+=_+1,k>b&&(k-=w)),f[++c]=--k,k==-1?(i+=k,g[--u]=c):i-=k,!k)do{var P=n>>3;a=(r[P]|r[P+1]<<8)>>(n&7)&3,n+=2,c+=a}while(a==3)}(c>255||i)&&$(0);for(var E=0,N=(s>>1)+(s>>3)+3,C=s-1,M=0;M<=c;++M){var y=f[M];if(y<1){h[M]=-y;continue}for(l=0;l<y;++l){g[E]=M;do E=E+N&C;while(E>=u)}}for(E&&$(0),l=0;l<s;++l){var x=h[g[l]]++,L=S[l]=o-B(x);p[l]=(x<<L)-s}return[n+7>>3,{b:o,s:g,n:S,t:p}]},tr=function(r,e){var t=0,n=-1,o=new O(292),s=r[e],i=o.subarray(0,256),c=o.subarray(256,268),a=new ge(o.buffer,268);if(s<128){var l=te(r,e+1,6),u=l[0],d=l[1];e+=s;var f=u<<3,h=r[e];h||$(0);for(var p=0,m=0,g=d.b,S=g,_=(++e<<3)-8+B(h);_-=g,!(_<f);){var v=_>>3;if(p+=(r[v]|r[v+1]<<8)>>(_&7)&(1<<g)-1,i[++n]=d.s[p],_-=S,_<f)break;v=_>>3,m+=(r[v]|r[v+1]<<8)>>(_&7)&(1<<S)-1,i[++n]=d.s[m],g=d.n[p],p=d.t[p],S=d.n[m],m=d.t[m]}++n>255&&$(0)}else{for(n=s-127;t<n;t+=2){var R=r[++e];i[t]=R>>4,i[t+1]=R&15}++e}var k=0;for(t=0;t<n;++t){var b=i[t];b>11&&$(0),k+=b&&1<<b-1}var w=B(k)+1,T=1<<w,P=T-k;for(P&P-1&&$(0),i[n++]=B(P)+1,t=0;t<n;++t){var b=i[t];++c[i[t]=b&&w+1-b]}var E=new O(T<<1),N=E.subarray(0,T),C=E.subarray(T);for(a[w]=0,t=w;t>0;--t){var M=a[t];ee(C,t,M,a[t-1]=M+c[t]*(1<<w-t))}for(a[0]!=T&&$(0),t=0;t<n;++t){var y=i[t];if(y){var x=a[y];ee(N,t,x,a[y]=x+(1<<w-y))}}return[e,{n:C,b:w,s:N}]},rr=te(new O([81,16,99,140,49,198,24,99,12,33,196,24,99,102,102,134,70,146,4]),0,6)[1],nr=te(new O([33,20,196,24,99,140,33,132,16,66,8,33,132,16,66,8,33,68,68,68,68,68,68,68,68,36,9]),0,6)[1],or=te(new O([32,132,16,66,102,70,68,68,68,68,36,73,2]),0,5)[1],ht=function(r,e){for(var t=r.length,n=new he(t),o=0;o<t;++o)n[o]=e,e+=1<<r[o];return n},$e=new O(new he([0,0,0,0,16843009,50528770,134678020,202050057,269422093]).buffer,0,36),sr=ht($e,0),Ne=new O(new he([0,0,0,0,0,0,0,0,16843009,50528770,117769220,185207048,252579084,16]).buffer,0,53),ir=ht(Ne,3),Z=function(r,e,t){var n=r.length,o=e.length,s=r[n-1],i=(1<<t.b)-1,c=-t.b;s||$(0);for(var a=0,l=t.b,u=(n<<3)-8+B(s)-l,d=-1;u>c&&d<o;){var f=u>>3,h=(r[f]|r[f+1]<<8|r[f+2]<<16)>>(u&7);a=(a<<l|h)&i,e[++d]=t.s[a],u-=l=t.n[a]}(u!=c||d+1!=o)&&$(0)},ar=function(r,e,t){var n=6,o=e.length,s=o+3>>2,i=s<<1,c=s+i;Z(r.subarray(n,n+=r[0]|r[1]<<8),e.subarray(0,s),t),Z(r.subarray(n,n+=r[2]|r[3]<<8),e.subarray(s,i),t),Z(r.subarray(n,n+=r[4]|r[5]<<8),e.subarray(i,c),t),Z(r.subarray(n),e.subarray(c),t)},cr=function(r,e,t){var n,o=e.b,s=r[o],i=s>>1&3;e.l=s&1;var c=s>>3|r[o+1]<<5|r[o+2]<<13,a=(o+=3)+c;if(i==1)return o>=r.length?void 0:(e.b=o+1,t?(ee(t,r[o],e.y,e.y+=c),t):ee(new O(c),r[o]));if(!(a>r.length)){if(i==0)return e.b=a,t?(t.set(r.subarray(o,a),e.y),e.y+=c,t):Me(r,o,a);if(i==2){var l=r[o],u=l&3,d=l>>2&3,f=l>>4,h=0,p=0;u<2?d&1?f|=r[++o]<<4|(d&2&&r[++o]<<12):f=l>>3:(p=d,d<2?(f|=(r[++o]&63)<<4,h=r[o]>>6|r[++o]<<2):d==2?(f|=r[++o]<<4|(r[++o]&3)<<12,h=r[o]>>2|r[++o]<<6):(f|=r[++o]<<4|(r[++o]&63)<<12,h=r[o]>>6|r[++o]<<2|r[++o]<<10)),++o;var m=t?t.subarray(e.y,e.y+e.m):new O(e.m),g=m.length-f;if(u==0)m.set(r.subarray(o,o+=f),g);else if(u==1)ee(m,r[o++],g);else{var S=e.h;if(u==2){var _=tr(r,o);h+=o-(o=_[0]),e.h=S=_[1]}else S||$(0);(p?ar:Z)(r.subarray(o,o+=h),m.subarray(g),S)}var v=r[o++];if(v){v==255?v=(r[o++]|r[o++]<<8)+32512:v>127&&(v=v-128<<8|r[o++]);var R=r[o++];R&3&&$(0);for(var k=[nr,or,rr],b=2;b>-1;--b){var w=R>>(b<<1)+2&3;if(w==1){var T=new O([0,0,r[o++]]);k[b]={s:T.subarray(2,3),n:T.subarray(0,1),t:new ge(T.buffer,0,1),b:0}}else w==2?(n=te(r,o,9-(b&1)),o=n[0],k[b]=n[1]):w==3&&(e.t||$(0),k[b]=e.t[b])}var P=e.t=k,E=P[0],N=P[1],C=P[2],M=r[a-1];M||$(0);var y=(a<<3)-8+B(M)-C.b,x=y>>3,L=0,ne=(r[x]|r[x+1]<<8)>>(y&7)&(1<<C.b)-1;x=(y-=N.b)>>3;var oe=(r[x]|r[x+1]<<8)>>(y&7)&(1<<N.b)-1;x=(y-=E.b)>>3;var se=(r[x]|r[x+1]<<8)>>(y&7)&(1<<E.b)-1;for(++v;--v;){var Re=C.s[ne],Je=C.n[ne],Ae=E.s[se],We=E.n[se],Ke=N.s[oe],Qe=N.n[oe];x=(y-=Ke)>>3;var Ye=1<<Ke,U=Ye+((r[x]|r[x+1]<<8|r[x+2]<<16|r[x+3]<<24)>>>(y&7)&Ye-1);x=(y-=Ne[Ae])>>3;var W=ir[Ae]+((r[x]|r[x+1]<<8|r[x+2]<<16)>>(y&7)&(1<<Ne[Ae])-1);x=(y-=$e[Re])>>3;var ie=sr[Re]+((r[x]|r[x+1]<<8|r[x+2]<<16)>>(y&7)&(1<<$e[Re])-1);if(x=(y-=Je)>>3,ne=C.t[ne]+((r[x]|r[x+1]<<8)>>(y&7)&(1<<Je)-1),x=(y-=We)>>3,se=E.t[se]+((r[x]|r[x+1]<<8)>>(y&7)&(1<<We)-1),x=(y-=Qe)>>3,oe=N.t[oe]+((r[x]|r[x+1]<<8)>>(y&7)&(1<<Qe)-1),U>3)e.o[2]=e.o[1],e.o[1]=e.o[0],e.o[0]=U-=3;else{var ae=U-(ie!=0);ae?(U=ae==3?e.o[0]-1:e.o[ae],ae>1&&(e.o[2]=e.o[1]),e.o[1]=e.o[0],e.o[0]=U):U=e.o[0]}for(var b=0;b<ie;++b)m[L+b]=m[g+b];L+=ie,g+=ie;var K=L-U;if(K<0){var Q=-K,Wt=e.e+K;Q>W&&(Q=W);for(var b=0;b<Q;++b)m[L+b]=e.w[Wt+b];L+=Q,W-=Q,K=0}for(var b=0;b<W;++b)m[L+b]=m[K+b];L+=W}if(L!=g)for(;g<m.length;)m[L++]=m[g++];else L=m.length;t?e.y+=L:m=Me(m,0,L)}else if(t){if(e.y+=f,g)for(var b=0;b<f;++b)m[b]=m[g+b]}else g&&(m=Me(m,g));return e.b=a,m}$(2)}},lr=function(r,e){if(r.length==1)return r[0];for(var t=new O(e),n=0,o=0;n<r.length;++n){var s=r[n];t.set(s,o),o+=s.length}return t};function we(r,e){for(var t=[],n=+!e,o=0,s=0;r.length;){var i=er(r,n||e);if(typeof i=="object"){for(n?(e=null,i.w.length==i.u&&(t.push(e=i.w),s+=i.u)):(t.push(e),i.e=0);!i.l;){var c=cr(r,i,e);c||$(5),e?i.e=i.y:(t.push(c),s+=c.length,Yt(i.w,0,c.length),i.w.set(c,i.w.length-c.length))}o=i.b+i.c*4}else o=i;r=r.subarray(o)}return lr(t,s)}function D(r){let e=[],t=0,n=()=>{let s=0,i=1;for(;;){let c=r[t++];if(s+=(c&127)*i,i*=128,!(c&128))return s}},o=s=>Array.from(s,i=>i.toString(16).padStart(2,"0")).join("");for(;t<r.length;){let s=t,i=n(),c=Math.floor(i/8),a=i&7,l;if(a===0){let u=t;n(),l=r.slice(u,t)}else if(a===2){let u=n();l=r.slice(t,t+u),t+=u}else if(a===5)l=r.slice(t,t+4),t+=4;else if(a===1)l=r.slice(t,t+8),t+=8;else throw new Error(`wire type ${a}`);e.push([c,a,o(r.slice(s,t)),l])}return e}var ur=r=>Array.from(r,e=>e.toString(16).padStart(2,"0")).join(""),_t=r=>Uint8Array.from(r.match(/../g)??[],e=>parseInt(e,16));function ye(r){let e=r.trim().toLowerCase();if(e.startsWith("80"))return e;if(e.startsWith("81"))return"80"+ur(we(_t(e.slice(2))));throw new Error(`grade body: unknown encoding 0x${e.slice(0,2)}`)}function wt(r){let e={};for(let t of r.matchAll(/<ListMgt::LmVersion DbId="[^"]+">([\s\S]*?)<\/ListMgt::LmVersion>/g)){let n=/<Name>([^<]*)<\/Name>/.exec(t[1])?.[1],o=/<Body>([0-9a-fA-F]+)<\/Body>/.exec(t[1])?.[1];n&&o&&(e[n]=ye(o))}return e}function yt(r){let e=new Map;for(let t of r.matchAll(/<ListMgt::LmVersion DbId="([^"]+)">([\s\S]*?)<\/ListMgt::LmVersion>/g)){let n=/<Body>([0-9a-fA-F]+)<\/Body>/.exec(t[2])?.[1];n&&e.set(t[1],ye(n))}return e}function bt(r){let e=X(r),t=l=>new TextDecoder().decode(e[l]),n=Object.keys(e).find(l=>l.startsWith("SeqContainer/")&&l.endsWith(".xml"));if(!n)throw new Error("grade bodies: no SeqContainer in the .drt");let o=new Map,s=new Map,i=Object.keys(e).filter(l=>l.startsWith("MediaPool/")&&l.endsWith(".xml"));for(let l of i)for(let u of t(l).matchAll(/<Sm2MpVideoClip DbId="([^"]+)">([\s\S]*?)<\/Sm2MpVideoClip>/g)){let d=/<pLmVerTable>([\s\S]*?)<\/pLmVerTable>/.exec(u[2]);d&&(o.set(u[1],wt(d[1])),s.set(u[1],yt(d[1])))}let c=new Map,a=0;for(let l of t(n).matchAll(/<Sm2TiTrack DbId="[^"]+">([\s\S]*?)<\/Sm2TiTrack>/g))if(/<Type>([^<]*)<\/Type>/.exec(l[1])?.[1]==="0"){a++;for(let u of l[1].matchAll(/<Sm2TiVideoClip DbId="[^"]+">([\s\S]*?)<\/Sm2TiVideoClip>/g)){let d=u[1],f=/<Start>(-?\d+)<\/Start>/.exec(d)?.[1],h=/<Name>([^<]*)<\/Name>/.exec(d)?.[1]??"";if(f===void 0)continue;let p=/<pLmVerTable>([\s\S]*?)<\/pLmVerTable>/.exec(d),m=/<MediaRef>([^<]+)<\/MediaRef>/.exec(d)?.[1],g=p&&/<pActive>([^<]+)<\/pActive>/.exec(p[1])?.[1],S=g?yt(p[1]).get(g)??(m?s.get(m)?.get(g):void 0):void 0;c.set(`${a}:${f}`,{name:h,local:p?wt(p[1]):{},remote:m&&o.get(m)||{},...S?{active:S}:{}})}}return c}function fn(r){let e=a=>D(a),t=a=>{let l=0,u=1;for(let d of a)if(l+=(d&127)*u,u*=128,!(d&128))break;return l},n=e(_t(r.slice(2))).find(a=>a[0]===3&&a[1]===2&&e(a[3]).some(l=>l[0]===8&&t(l[3])===84)),s=(n?e(n[3]).filter(a=>a[0]===9).flatMap(a=>e(a[3])):[]).find(a=>a[0]===1&&a[1]===2&&e(a[3]).some(l=>l[0]===1&&l[1]===0&&t(l[3])===10));return s?e(s[3]).filter(a=>a[0]===6&&a[1]===2).map(a=>{let l=e(a[3]),u=t(l.find(h=>h[0]===1&&h[1]===0)?.[3]??new Uint8Array([0]))/2,d=l.find(h=>h[0]===2&&h[1]===2)?.[3]??new Uint8Array,f={t:u,zoom:1,height:1,rotation:0,pan:0,tilt:0,flip_x:!1,flip_y:!1};for(let h of e(d)){if(h[0]===5&&h[1]===2){let R=e(h[3]);f.ease_in=t(R.find(k=>k[0]===1)?.[3]??new Uint8Array([1])),f.ease_out=t(R.find(k=>k[0]===2)?.[3]??new Uint8Array([1]));continue}if(h[0]!==3||h[1]!==2)continue;let p=e(h[3]),m=t(p.find(R=>R[0]===1)?.[3]??new Uint8Array),g=p.find(R=>R[0]===2)?.[3],S=g&&e(g).find(R=>R[0]===1&&R[1]===5),_=g&&e(g).find(R=>R[0]===2&&R[1]===0),v=S?new DataView(S[3].buffer,S[3].byteOffset,4).getFloat32(0,!0):_?t(_[3]):void 0;v!==void 0&&(m===271581186?f.height=v:m===271581187?f.zoom=v:m===271581188?f.rotation=v:m===271581189?f.pan=v:m===271581190?f.tilt=v:m===271581191?f.flip_y=!!v:m===271581192&&(f.flip_x=!!v))}return f}).sort((a,l)=>a.t-l.t):[]}var pr=r=>Array.from(r,e=>e.toString(16).padStart(2,"0")).join(""),V=r=>Uint8Array.from(r.match(/../g)??[],e=>parseInt(e,16)),St=r=>{let e=[];do e.push(r&127|(r>127?128:0)),r=Math.floor(r/128);while(r);return e};function vt(r){let e=V(r.trim());if(e.length<9)throw new Error("EffectFiltersBA: too short");if(e[8]===128)return e.slice(9);if(e[8]===129)return we(e.slice(9));throw new Error(`EffectFiltersBA: unknown encoding 0x${e[8].toString(16)}`)}function mr(r){let e=new Uint8Array(9);return new DataView(e.buffer).setUint32(0,2),new DataView(e.buffer).setUint32(4,r.length+1),e[8]=128,pr(new Uint8Array([...e,...r]))}var Ce=r=>{let e=D(r).find(t=>t[0]===1&&t[1]===0);return e?dr(e[3]):-1};function dr(r){let e=0,t=1;for(let n of r)if(e+=(n&127)*t,t*=128,!(n&128))break;return e}var Le=(r,e)=>new Uint8Array([...St(r<<3|2),...St(e.length),...e]);function fr(r,e){let t=new DataView(r.buffer,r.byteOffset,r.byteLength),n=-t.getInt32(0)/16;if(!Number.isInteger(n)||n<2||r.length!==4+n*16||r[10]!==12)return r;let o=Array.from({length:n},(a,l)=>({frame:t.getUint32(4+l*16,!0),value:t.getFloat64(4+l*16+8,!0)})),s=o.map(a=>e(a.frame));if(!s.slice(0,-1).some(Boolean))return r;let i=new Uint8Array(4+n*64),c=new DataView(i.buffer);return c.setInt32(0,-(n*64)),o.forEach((a,l)=>{let u=4+l*64;c.setUint32(u,a.frame,!0),i[u+6]=13,c.setFloat64(u+8,a.value,!0);let d=l>0?s[l-1]:void 0,f=l<n-1?s[l]:void 0;d&&c.setFloat64(u+16,-(d.in/10)*(a.frame-o[l-1].frame),!0),f&&c.setFloat64(u+32,f.out/10*(o[l+1].frame-a.frame),!0)}),i}function gr(r,e){let t=[];for(let n of D(r))if(n[0]===9&&n[1]===2&&n[3].length){let o=D(n[3]).map(s=>s[0]===10&&s[1]===2?[...Le(10,fr(s[3],e))]:[...V(s[2])]).flat();t.push(...Le(9,new Uint8Array(o)))}else t.push(...V(n[2]));return new Uint8Array(t)}function hr(r){let e=[];for(let t of D(r)){if(t[0]!==9||t[1]!==2||!t[3].length)continue;let n=D(t[3]).find(i=>i[0]===10&&i[1]===2)?.[3];if(!n||n.length<4)continue;let o=new DataView(n.buffer,n.byteOffset,n.byteLength),s=-o.getInt32(0)/16;Number.isInteger(s)&&s>e.length&&n.length===4+s*16&&Array.from({length:s},(i,c)=>n[4+c*16+6]).every(i=>i===12)&&(e=Array.from({length:s},(i,c)=>o.getUint32(4+c*16,!0)))}return e}function wr(r,e){let t=D(e).find(s=>s[0]===1&&s[1]===2&&Ce(s[3])===4);if(!t)throw new Error("the written clip carries no Transform group");let n=[],o=!1;for(let s of r?D(r):[]){if(s[0]===1&&s[1]===2&&Ce(s[3])===4){o||(n.push(...V(t[2])),o=!0);continue}n.push(...V(s[2]))}return o||n.push(...V(t[2])),new Uint8Array(n)}function xt(r){let e=[],t=0;for(let n of r.matchAll(/<Sm2TiTrack DbId="[^"]+">([\s\S]*?)<\/Sm2TiTrack>/g)){if(/<Type>([^<]*)<\/Type>/.exec(n[1])?.[1]!=="0")continue;t++;let o=n.index+n[0].indexOf(n[1]);for(let s of n[1].matchAll(/<Sm2TiVideoClip DbId="[^"]+">([\s\S]*?)<\/Sm2TiVideoClip>/g)){let i=/<Start>(-?\d+)<\/Start>/.exec(s[1])?.[1];i!==void 0&&e.push({track:t,start:Number(i),at:o+s.index,end:o+s.index+s[0].length,body:s[0]})}}return e}var kt=r=>Object.keys(r).find(e=>e.startsWith("SeqContainer/")&&e.endsWith(".xml"));function Rt(r,e,t,n){let o=X(r),s=X(e),i=kt(o),c=kt(s);if(!i||!c)throw new Error("no SeqContainer in the .drt");let a=new TextDecoder().decode(o[i]),l=xt(a),u=xt(new TextDecoder().decode(s[c])),d=[],f=[],h=[];for(let m of t){let g=`V${m.item.track}@${m.item.start}`,S=l.find(y=>y.track===m.item.track&&y.start===m.item.start+n),_=S?l.filter(y=>y.track===S.track).indexOf(S):-1,v=_>=0?u.filter(y=>y.track===m.item.track)[_]:void 0,R=v&&/<EffectFiltersBA>([0-9a-fA-F]+)<\/EffectFiltersBA>/.exec(v.body)?.[1];if(!S||!R){f.push(g);continue}let k=/<EffectFiltersBA>([0-9a-fA-F]*)<\/EffectFiltersBA>/.exec(S.body),b=D(vt(R)),w=b.find(y=>y[0]===1&&y[1]===2&&Ce(y[3])===4),T=w?hr(w[3]):[];if(T.length!==m.keys.length){f.push(`${g} (the engine wrote ${T.length} keys for ${m.keys.length})`);continue}let P=new Map(T.map((y,x)=>[y,m.keys[x].shape])),E=new Uint8Array(b.flatMap(y=>y===w?[...Le(1,gr(y[3],x=>P.get(x)))]:[...V(y[2])])),N=wr(k?.[1]?vt(k[1]):null,E),C=`<EffectFiltersBA>${mr(N)}</EffectFiltersBA>`,M=k?S.body.replace(k[0],C):S.body.replace(/(<\/Sm2TiVideoClip>)$/,`${C}$1`);h.push({at:S.at,end:S.end,body:M}),d.push(g)}for(let m of h.sort((g,S)=>S.at-g.at))a=a.slice(0,m.at)+m.body+a.slice(m.end);let p={...o,[i]:new TextEncoder().encode(a)};return{drt:ct(p),keyed:d,missing:f}}function At(r,e,t){let n=r.source_range,o=r.timeline_range,s=n?.start.rate||t,i=n?.start.value??0,c=n?.duration&&o?.duration&&o.duration.value?n.duration.value/n.duration.rate/(o.duration.value/o.duration.rate)*s/t:s/t,a=[],l=0;for(let f of e){let h={value:i+f.t*c,rate:s},p=(m,g)=>a.push({id:`${r.id}-align-${l++}`,parameter_path:m,time:h,value:g,interp:"linear"});p("scale",f.transform.scale_x),e.some(m=>Math.abs(m.transform.scale_y-m.transform.scale_x)>.001)&&p("scale.y",f.transform.scale_y),p("position.x",f.transform.position_x),p("position.y",f.transform.position_y),p("rotation",f.transform.rotation)}let u=e[0].transform,d=(r.keyframes??[]).filter(f=>!/^(scale|position|rotation)/.test(String(f.parameter_path)));Object.assign(r,{scale:u.scale_x,position_x:u.position_x,position_y:u.position_y,rotation:u.rotation,keyframes:[...d,...a]}),Math.abs(u.scale_y-u.scale_x)>.001&&Object.assign(r,{scale_x:u.scale_x,scale_y:u.scale_y}),u.flip_h?r.flip_horizontal=!0:delete r.flip_horizontal,u.flip_v?r.flip_vertical=!0:delete r.flip_vertical}function Ot(r=H()){if(r==="win32"){let e=F("PROGRAMDATA")??"C:\\ProgramData",t=F("PROGRAMFILES")??"C:\\Program Files";return{api:`${e}\\Blackmagic Design\\DaVinci Resolve\\Support\\Developer\\Scripting`,lib:`${t}\\Blackmagic Design\\DaVinci Resolve\\fusionscript.dll`}}return r==="linux"?{api:"/opt/resolve/Developer/Scripting",lib:"/opt/resolve/libs/Fusion/fusionscript.so"}:{api:"/Library/Application Support/Blackmagic Design/DaVinci Resolve/Developer/Scripting",lib:"/Applications/DaVinci Resolve/DaVinci Resolve.app/Contents/Libraries/Fusion/fusionscript.so"}}async function yr(r){let e=F("RESOLVE_SCRIPT_LIB");if(e)return e;if(r==="darwin"){let n=(await de("ps",["-axo","comm="])).stdout.split(`
|
|
3
|
+
import{a as Oe,b as dt}from"./chunk-7DH6DFYL.js";import{Qb as pt}from"./chunk-BZE7IP6U.js";import{a as mt}from"./chunk-HZBGG7HI.js";import{b as Ee,d as ut}from"./chunk-NU3X7P4N.js";import{m as lt}from"./chunk-KD7UGCLT.js";import{A as tt,C as pe,D as Y,H as rt,J as me,O as q,P as nt,S as de,V as ot,Y as st,Z as it,b as F,ba as at,ca as fe,ea as I,h as H,j as Te,p as Pe,s as Xe,t as Ze,v as ce,w as le,y as ue,z as et}from"./chunk-QQBDHVUU.js";import{M as ct,S as X}from"./chunk-C2ESM27Z.js";function ft(r,e){let t=async()=>{throw new Error(`${r}: ${e}`)},n={ok:!1,reason:e};return{host:r,wired:!1,support:async()=>({export:n,open:n,render:n,markers:n}),export:t,open:t,renderStart:t,renderStatus:t,renderCancel:t}}async function an(r,e,t,n){let o=new Promise(s=>n?.addEventListener("abort",()=>s(),{once:!0}));for(;e.state==="queued"||e.state==="rendering";){if(t?.(e.percent,100,"rendering"),await Promise.race([o.then(()=>!0),new Promise(i=>setTimeout(()=>i(!1),1e3))]))return await r.renderCancel(e.job_id);e=await r.renderStatus(e.job_id)}return e}var Kt=ArrayBuffer,O=Uint8Array,ge=Uint16Array,Qt=Int16Array;var he=Int32Array,Me=function(r,e,t){if(O.prototype.slice)return O.prototype.slice.call(r,e,t);(e==null||e<0)&&(e=0),(t==null||t>r.length)&&(t=r.length);var n=new O(t-e);return n.set(r.subarray(e,t)),n},ee=function(r,e,t,n){if(O.prototype.fill)return O.prototype.fill.call(r,e,t,n);for((t==null||t<0)&&(t=0),(n==null||n>r.length)&&(n=r.length);t<n;++t)r[t]=e;return r},Yt=function(r,e,t,n){if(O.prototype.copyWithin)return O.prototype.copyWithin.call(r,e,t,n);for((t==null||t<0)&&(t=0),(n==null||n>r.length)&&(n=r.length);t<n;)r[e++]=r[t++]};var Xt=["invalid zstd data","window size too large (>2046MB)","invalid block type","FSE accuracy too high","match distance too far back","unexpected EOF"],$=function(r,e,t){var n=new Error(e||Xt[r]);if(n.code=r,Error.captureStackTrace&&Error.captureStackTrace(n,$),!t)throw n;return n},gt=function(r,e,t){for(var n=0,o=0;n<t;++n)o|=r[e++]<<(n<<3);return o},Zt=function(r,e){return(r[e]|r[e+1]<<8|r[e+2]<<16|r[e+3]<<24)>>>0},er=function(r,e){var t=r[0]|r[1]<<8|r[2]<<16;if(t==3126568&&r[3]==253){var n=r[4],o=n>>5&1,s=n>>2&1,i=n&3,c=n>>6;n&8&&$(0);var a=6-o,l=i==3?4:i,u=gt(r,a,l);a+=l;var d=c?1<<c:o,f=gt(r,a,d)+(c==1&&256),h=f;if(!o){var p=1<<10+(r[5]>>3);h=p+(p>>3)*(r[5]&7)}h>2145386496&&$(1);var m=new O((e==1?f||h:e?0:h)+12);return m[0]=1,m[4]=4,m[8]=8,{b:a+d,y:0,l:0,d:u,w:e&&e!=1?e:m.subarray(12),e:h,o:new he(m.buffer,0,3),u:f,c:s,m:Math.min(131072,h)}}else if((t>>4|r[3]<<20)==25481893)return Zt(r,4)+8;$(0)},B=function(r){for(var e=0;1<<e<=r;++e);return e-1},te=function(r,e,t){var n=(e<<3)+4,o=(r[e]&15)+5;o>t&&$(3);for(var s=1<<o,i=s,c=-1,a=-1,l=-1,u=s,d=new Kt(512+(s<<2)),f=new Qt(d,0,256),h=new ge(d,0,256),p=new ge(d,512,s),m=512+(s<<1),g=new O(d,m,s),S=new O(d,m+s);c<255&&i>0;){var _=B(i+1),v=n>>3,R=(1<<_+1)-1,k=(r[v]|r[v+1]<<8|r[v+2]<<16)>>(n&7)&R,b=(1<<_)-1,w=R-i-1,T=k&b;if(T<w?(n+=_,k=T):(n+=_+1,k>b&&(k-=w)),f[++c]=--k,k==-1?(i+=k,g[--u]=c):i-=k,!k)do{var P=n>>3;a=(r[P]|r[P+1]<<8)>>(n&7)&3,n+=2,c+=a}while(a==3)}(c>255||i)&&$(0);for(var E=0,N=(s>>1)+(s>>3)+3,C=s-1,M=0;M<=c;++M){var y=f[M];if(y<1){h[M]=-y;continue}for(l=0;l<y;++l){g[E]=M;do E=E+N&C;while(E>=u)}}for(E&&$(0),l=0;l<s;++l){var x=h[g[l]]++,L=S[l]=o-B(x);p[l]=(x<<L)-s}return[n+7>>3,{b:o,s:g,n:S,t:p}]},tr=function(r,e){var t=0,n=-1,o=new O(292),s=r[e],i=o.subarray(0,256),c=o.subarray(256,268),a=new ge(o.buffer,268);if(s<128){var l=te(r,e+1,6),u=l[0],d=l[1];e+=s;var f=u<<3,h=r[e];h||$(0);for(var p=0,m=0,g=d.b,S=g,_=(++e<<3)-8+B(h);_-=g,!(_<f);){var v=_>>3;if(p+=(r[v]|r[v+1]<<8)>>(_&7)&(1<<g)-1,i[++n]=d.s[p],_-=S,_<f)break;v=_>>3,m+=(r[v]|r[v+1]<<8)>>(_&7)&(1<<S)-1,i[++n]=d.s[m],g=d.n[p],p=d.t[p],S=d.n[m],m=d.t[m]}++n>255&&$(0)}else{for(n=s-127;t<n;t+=2){var R=r[++e];i[t]=R>>4,i[t+1]=R&15}++e}var k=0;for(t=0;t<n;++t){var b=i[t];b>11&&$(0),k+=b&&1<<b-1}var w=B(k)+1,T=1<<w,P=T-k;for(P&P-1&&$(0),i[n++]=B(P)+1,t=0;t<n;++t){var b=i[t];++c[i[t]=b&&w+1-b]}var E=new O(T<<1),N=E.subarray(0,T),C=E.subarray(T);for(a[w]=0,t=w;t>0;--t){var M=a[t];ee(C,t,M,a[t-1]=M+c[t]*(1<<w-t))}for(a[0]!=T&&$(0),t=0;t<n;++t){var y=i[t];if(y){var x=a[y];ee(N,t,x,a[y]=x+(1<<w-y))}}return[e,{n:C,b:w,s:N}]},rr=te(new O([81,16,99,140,49,198,24,99,12,33,196,24,99,102,102,134,70,146,4]),0,6)[1],nr=te(new O([33,20,196,24,99,140,33,132,16,66,8,33,132,16,66,8,33,68,68,68,68,68,68,68,68,36,9]),0,6)[1],or=te(new O([32,132,16,66,102,70,68,68,68,68,36,73,2]),0,5)[1],ht=function(r,e){for(var t=r.length,n=new he(t),o=0;o<t;++o)n[o]=e,e+=1<<r[o];return n},$e=new O(new he([0,0,0,0,16843009,50528770,134678020,202050057,269422093]).buffer,0,36),sr=ht($e,0),Ne=new O(new he([0,0,0,0,0,0,0,0,16843009,50528770,117769220,185207048,252579084,16]).buffer,0,53),ir=ht(Ne,3),Z=function(r,e,t){var n=r.length,o=e.length,s=r[n-1],i=(1<<t.b)-1,c=-t.b;s||$(0);for(var a=0,l=t.b,u=(n<<3)-8+B(s)-l,d=-1;u>c&&d<o;){var f=u>>3,h=(r[f]|r[f+1]<<8|r[f+2]<<16)>>(u&7);a=(a<<l|h)&i,e[++d]=t.s[a],u-=l=t.n[a]}(u!=c||d+1!=o)&&$(0)},ar=function(r,e,t){var n=6,o=e.length,s=o+3>>2,i=s<<1,c=s+i;Z(r.subarray(n,n+=r[0]|r[1]<<8),e.subarray(0,s),t),Z(r.subarray(n,n+=r[2]|r[3]<<8),e.subarray(s,i),t),Z(r.subarray(n,n+=r[4]|r[5]<<8),e.subarray(i,c),t),Z(r.subarray(n),e.subarray(c),t)},cr=function(r,e,t){var n,o=e.b,s=r[o],i=s>>1&3;e.l=s&1;var c=s>>3|r[o+1]<<5|r[o+2]<<13,a=(o+=3)+c;if(i==1)return o>=r.length?void 0:(e.b=o+1,t?(ee(t,r[o],e.y,e.y+=c),t):ee(new O(c),r[o]));if(!(a>r.length)){if(i==0)return e.b=a,t?(t.set(r.subarray(o,a),e.y),e.y+=c,t):Me(r,o,a);if(i==2){var l=r[o],u=l&3,d=l>>2&3,f=l>>4,h=0,p=0;u<2?d&1?f|=r[++o]<<4|(d&2&&r[++o]<<12):f=l>>3:(p=d,d<2?(f|=(r[++o]&63)<<4,h=r[o]>>6|r[++o]<<2):d==2?(f|=r[++o]<<4|(r[++o]&3)<<12,h=r[o]>>2|r[++o]<<6):(f|=r[++o]<<4|(r[++o]&63)<<12,h=r[o]>>6|r[++o]<<2|r[++o]<<10)),++o;var m=t?t.subarray(e.y,e.y+e.m):new O(e.m),g=m.length-f;if(u==0)m.set(r.subarray(o,o+=f),g);else if(u==1)ee(m,r[o++],g);else{var S=e.h;if(u==2){var _=tr(r,o);h+=o-(o=_[0]),e.h=S=_[1]}else S||$(0);(p?ar:Z)(r.subarray(o,o+=h),m.subarray(g),S)}var v=r[o++];if(v){v==255?v=(r[o++]|r[o++]<<8)+32512:v>127&&(v=v-128<<8|r[o++]);var R=r[o++];R&3&&$(0);for(var k=[nr,or,rr],b=2;b>-1;--b){var w=R>>(b<<1)+2&3;if(w==1){var T=new O([0,0,r[o++]]);k[b]={s:T.subarray(2,3),n:T.subarray(0,1),t:new ge(T.buffer,0,1),b:0}}else w==2?(n=te(r,o,9-(b&1)),o=n[0],k[b]=n[1]):w==3&&(e.t||$(0),k[b]=e.t[b])}var P=e.t=k,E=P[0],N=P[1],C=P[2],M=r[a-1];M||$(0);var y=(a<<3)-8+B(M)-C.b,x=y>>3,L=0,ne=(r[x]|r[x+1]<<8)>>(y&7)&(1<<C.b)-1;x=(y-=N.b)>>3;var oe=(r[x]|r[x+1]<<8)>>(y&7)&(1<<N.b)-1;x=(y-=E.b)>>3;var se=(r[x]|r[x+1]<<8)>>(y&7)&(1<<E.b)-1;for(++v;--v;){var Re=C.s[ne],Je=C.n[ne],Ae=E.s[se],We=E.n[se],Ke=N.s[oe],Qe=N.n[oe];x=(y-=Ke)>>3;var Ye=1<<Ke,U=Ye+((r[x]|r[x+1]<<8|r[x+2]<<16|r[x+3]<<24)>>>(y&7)&Ye-1);x=(y-=Ne[Ae])>>3;var W=ir[Ae]+((r[x]|r[x+1]<<8|r[x+2]<<16)>>(y&7)&(1<<Ne[Ae])-1);x=(y-=$e[Re])>>3;var ie=sr[Re]+((r[x]|r[x+1]<<8|r[x+2]<<16)>>(y&7)&(1<<$e[Re])-1);if(x=(y-=Je)>>3,ne=C.t[ne]+((r[x]|r[x+1]<<8)>>(y&7)&(1<<Je)-1),x=(y-=We)>>3,se=E.t[se]+((r[x]|r[x+1]<<8)>>(y&7)&(1<<We)-1),x=(y-=Qe)>>3,oe=N.t[oe]+((r[x]|r[x+1]<<8)>>(y&7)&(1<<Qe)-1),U>3)e.o[2]=e.o[1],e.o[1]=e.o[0],e.o[0]=U-=3;else{var ae=U-(ie!=0);ae?(U=ae==3?e.o[0]-1:e.o[ae],ae>1&&(e.o[2]=e.o[1]),e.o[1]=e.o[0],e.o[0]=U):U=e.o[0]}for(var b=0;b<ie;++b)m[L+b]=m[g+b];L+=ie,g+=ie;var K=L-U;if(K<0){var Q=-K,Wt=e.e+K;Q>W&&(Q=W);for(var b=0;b<Q;++b)m[L+b]=e.w[Wt+b];L+=Q,W-=Q,K=0}for(var b=0;b<W;++b)m[L+b]=m[K+b];L+=W}if(L!=g)for(;g<m.length;)m[L++]=m[g++];else L=m.length;t?e.y+=L:m=Me(m,0,L)}else if(t){if(e.y+=f,g)for(var b=0;b<f;++b)m[b]=m[g+b]}else g&&(m=Me(m,g));return e.b=a,m}$(2)}},lr=function(r,e){if(r.length==1)return r[0];for(var t=new O(e),n=0,o=0;n<r.length;++n){var s=r[n];t.set(s,o),o+=s.length}return t};function we(r,e){for(var t=[],n=+!e,o=0,s=0;r.length;){var i=er(r,n||e);if(typeof i=="object"){for(n?(e=null,i.w.length==i.u&&(t.push(e=i.w),s+=i.u)):(t.push(e),i.e=0);!i.l;){var c=cr(r,i,e);c||$(5),e?i.e=i.y:(t.push(c),s+=c.length,Yt(i.w,0,c.length),i.w.set(c,i.w.length-c.length))}o=i.b+i.c*4}else o=i;r=r.subarray(o)}return lr(t,s)}function D(r){let e=[],t=0,n=()=>{let s=0,i=1;for(;;){let c=r[t++];if(s+=(c&127)*i,i*=128,!(c&128))return s}},o=s=>Array.from(s,i=>i.toString(16).padStart(2,"0")).join("");for(;t<r.length;){let s=t,i=n(),c=Math.floor(i/8),a=i&7,l;if(a===0){let u=t;n(),l=r.slice(u,t)}else if(a===2){let u=n();l=r.slice(t,t+u),t+=u}else if(a===5)l=r.slice(t,t+4),t+=4;else if(a===1)l=r.slice(t,t+8),t+=8;else throw new Error(`wire type ${a}`);e.push([c,a,o(r.slice(s,t)),l])}return e}var ur=r=>Array.from(r,e=>e.toString(16).padStart(2,"0")).join(""),_t=r=>Uint8Array.from(r.match(/../g)??[],e=>parseInt(e,16));function ye(r){let e=r.trim().toLowerCase();if(e.startsWith("80"))return e;if(e.startsWith("81"))return"80"+ur(we(_t(e.slice(2))));throw new Error(`grade body: unknown encoding 0x${e.slice(0,2)}`)}function wt(r){let e={};for(let t of r.matchAll(/<ListMgt::LmVersion DbId="[^"]+">([\s\S]*?)<\/ListMgt::LmVersion>/g)){let n=/<Name>([^<]*)<\/Name>/.exec(t[1])?.[1],o=/<Body>([0-9a-fA-F]+)<\/Body>/.exec(t[1])?.[1];n&&o&&(e[n]=ye(o))}return e}function yt(r){let e=new Map;for(let t of r.matchAll(/<ListMgt::LmVersion DbId="([^"]+)">([\s\S]*?)<\/ListMgt::LmVersion>/g)){let n=/<Body>([0-9a-fA-F]+)<\/Body>/.exec(t[2])?.[1];n&&e.set(t[1],ye(n))}return e}function bt(r){let e=X(r),t=l=>new TextDecoder().decode(e[l]),n=Object.keys(e).find(l=>l.startsWith("SeqContainer/")&&l.endsWith(".xml"));if(!n)throw new Error("grade bodies: no SeqContainer in the .drt");let o=new Map,s=new Map,i=Object.keys(e).filter(l=>l.startsWith("MediaPool/")&&l.endsWith(".xml"));for(let l of i)for(let u of t(l).matchAll(/<Sm2MpVideoClip DbId="([^"]+)">([\s\S]*?)<\/Sm2MpVideoClip>/g)){let d=/<pLmVerTable>([\s\S]*?)<\/pLmVerTable>/.exec(u[2]);d&&(o.set(u[1],wt(d[1])),s.set(u[1],yt(d[1])))}let c=new Map,a=0;for(let l of t(n).matchAll(/<Sm2TiTrack DbId="[^"]+">([\s\S]*?)<\/Sm2TiTrack>/g))if(/<Type>([^<]*)<\/Type>/.exec(l[1])?.[1]==="0"){a++;for(let u of l[1].matchAll(/<Sm2TiVideoClip DbId="[^"]+">([\s\S]*?)<\/Sm2TiVideoClip>/g)){let d=u[1],f=/<Start>(-?\d+)<\/Start>/.exec(d)?.[1],h=/<Name>([^<]*)<\/Name>/.exec(d)?.[1]??"";if(f===void 0)continue;let p=/<pLmVerTable>([\s\S]*?)<\/pLmVerTable>/.exec(d),m=/<MediaRef>([^<]+)<\/MediaRef>/.exec(d)?.[1],g=p&&/<pActive>([^<]+)<\/pActive>/.exec(p[1])?.[1],S=g?yt(p[1]).get(g)??(m?s.get(m)?.get(g):void 0):void 0;c.set(`${a}:${f}`,{name:h,local:p?wt(p[1]):{},remote:m&&o.get(m)||{},...S?{active:S}:{}})}}return c}function fn(r){let e=a=>D(a),t=a=>{let l=0,u=1;for(let d of a)if(l+=(d&127)*u,u*=128,!(d&128))break;return l},n=e(_t(r.slice(2))).find(a=>a[0]===3&&a[1]===2&&e(a[3]).some(l=>l[0]===8&&t(l[3])===84)),s=(n?e(n[3]).filter(a=>a[0]===9).flatMap(a=>e(a[3])):[]).find(a=>a[0]===1&&a[1]===2&&e(a[3]).some(l=>l[0]===1&&l[1]===0&&t(l[3])===10));return s?e(s[3]).filter(a=>a[0]===6&&a[1]===2).map(a=>{let l=e(a[3]),u=t(l.find(h=>h[0]===1&&h[1]===0)?.[3]??new Uint8Array([0]))/2,d=l.find(h=>h[0]===2&&h[1]===2)?.[3]??new Uint8Array,f={t:u,zoom:1,height:1,rotation:0,pan:0,tilt:0,flip_x:!1,flip_y:!1};for(let h of e(d)){if(h[0]===5&&h[1]===2){let R=e(h[3]);f.ease_in=t(R.find(k=>k[0]===1)?.[3]??new Uint8Array([1])),f.ease_out=t(R.find(k=>k[0]===2)?.[3]??new Uint8Array([1]));continue}if(h[0]!==3||h[1]!==2)continue;let p=e(h[3]),m=t(p.find(R=>R[0]===1)?.[3]??new Uint8Array),g=p.find(R=>R[0]===2)?.[3],S=g&&e(g).find(R=>R[0]===1&&R[1]===5),_=g&&e(g).find(R=>R[0]===2&&R[1]===0),v=S?new DataView(S[3].buffer,S[3].byteOffset,4).getFloat32(0,!0):_?t(_[3]):void 0;v!==void 0&&(m===271581186?f.height=v:m===271581187?f.zoom=v:m===271581188?f.rotation=v:m===271581189?f.pan=v:m===271581190?f.tilt=v:m===271581191?f.flip_y=!!v:m===271581192&&(f.flip_x=!!v))}return f}).sort((a,l)=>a.t-l.t):[]}var pr=r=>Array.from(r,e=>e.toString(16).padStart(2,"0")).join(""),V=r=>Uint8Array.from(r.match(/../g)??[],e=>parseInt(e,16)),St=r=>{let e=[];do e.push(r&127|(r>127?128:0)),r=Math.floor(r/128);while(r);return e};function vt(r){let e=V(r.trim());if(e.length<9)throw new Error("EffectFiltersBA: too short");if(e[8]===128)return e.slice(9);if(e[8]===129)return we(e.slice(9));throw new Error(`EffectFiltersBA: unknown encoding 0x${e[8].toString(16)}`)}function mr(r){let e=new Uint8Array(9);return new DataView(e.buffer).setUint32(0,2),new DataView(e.buffer).setUint32(4,r.length+1),e[8]=128,pr(new Uint8Array([...e,...r]))}var Ce=r=>{let e=D(r).find(t=>t[0]===1&&t[1]===0);return e?dr(e[3]):-1};function dr(r){let e=0,t=1;for(let n of r)if(e+=(n&127)*t,t*=128,!(n&128))break;return e}var Le=(r,e)=>new Uint8Array([...St(r<<3|2),...St(e.length),...e]);function fr(r,e){let t=new DataView(r.buffer,r.byteOffset,r.byteLength),n=-t.getInt32(0)/16;if(!Number.isInteger(n)||n<2||r.length!==4+n*16||r[10]!==12)return r;let o=Array.from({length:n},(a,l)=>({frame:t.getUint32(4+l*16,!0),value:t.getFloat64(4+l*16+8,!0)})),s=o.map(a=>e(a.frame));if(!s.slice(0,-1).some(Boolean))return r;let i=new Uint8Array(4+n*64),c=new DataView(i.buffer);return c.setInt32(0,-(n*64)),o.forEach((a,l)=>{let u=4+l*64;c.setUint32(u,a.frame,!0),i[u+6]=13,c.setFloat64(u+8,a.value,!0);let d=l>0?s[l-1]:void 0,f=l<n-1?s[l]:void 0;d&&c.setFloat64(u+16,-(d.in/10)*(a.frame-o[l-1].frame),!0),f&&c.setFloat64(u+32,f.out/10*(o[l+1].frame-a.frame),!0)}),i}function gr(r,e){let t=[];for(let n of D(r))if(n[0]===9&&n[1]===2&&n[3].length){let o=D(n[3]).map(s=>s[0]===10&&s[1]===2?[...Le(10,fr(s[3],e))]:[...V(s[2])]).flat();t.push(...Le(9,new Uint8Array(o)))}else t.push(...V(n[2]));return new Uint8Array(t)}function hr(r){let e=[];for(let t of D(r)){if(t[0]!==9||t[1]!==2||!t[3].length)continue;let n=D(t[3]).find(i=>i[0]===10&&i[1]===2)?.[3];if(!n||n.length<4)continue;let o=new DataView(n.buffer,n.byteOffset,n.byteLength),s=-o.getInt32(0)/16;Number.isInteger(s)&&s>e.length&&n.length===4+s*16&&Array.from({length:s},(i,c)=>n[4+c*16+6]).every(i=>i===12)&&(e=Array.from({length:s},(i,c)=>o.getUint32(4+c*16,!0)))}return e}function wr(r,e){let t=D(e).find(s=>s[0]===1&&s[1]===2&&Ce(s[3])===4);if(!t)throw new Error("the written clip carries no Transform group");let n=[],o=!1;for(let s of r?D(r):[]){if(s[0]===1&&s[1]===2&&Ce(s[3])===4){o||(n.push(...V(t[2])),o=!0);continue}n.push(...V(s[2]))}return o||n.push(...V(t[2])),new Uint8Array(n)}function xt(r){let e=[],t=0;for(let n of r.matchAll(/<Sm2TiTrack DbId="[^"]+">([\s\S]*?)<\/Sm2TiTrack>/g)){if(/<Type>([^<]*)<\/Type>/.exec(n[1])?.[1]!=="0")continue;t++;let o=n.index+n[0].indexOf(n[1]);for(let s of n[1].matchAll(/<Sm2TiVideoClip DbId="[^"]+">([\s\S]*?)<\/Sm2TiVideoClip>/g)){let i=/<Start>(-?\d+)<\/Start>/.exec(s[1])?.[1];i!==void 0&&e.push({track:t,start:Number(i),at:o+s.index,end:o+s.index+s[0].length,body:s[0]})}}return e}var kt=r=>Object.keys(r).find(e=>e.startsWith("SeqContainer/")&&e.endsWith(".xml"));function Rt(r,e,t,n){let o=X(r),s=X(e),i=kt(o),c=kt(s);if(!i||!c)throw new Error("no SeqContainer in the .drt");let a=new TextDecoder().decode(o[i]),l=xt(a),u=xt(new TextDecoder().decode(s[c])),d=[],f=[],h=[];for(let m of t){let g=`V${m.item.track}@${m.item.start}`,S=l.find(y=>y.track===m.item.track&&y.start===m.item.start+n),_=S?l.filter(y=>y.track===S.track).indexOf(S):-1,v=_>=0?u.filter(y=>y.track===m.item.track)[_]:void 0,R=v&&/<EffectFiltersBA>([0-9a-fA-F]+)<\/EffectFiltersBA>/.exec(v.body)?.[1];if(!S||!R){f.push(g);continue}let k=/<EffectFiltersBA>([0-9a-fA-F]*)<\/EffectFiltersBA>/.exec(S.body),b=D(vt(R)),w=b.find(y=>y[0]===1&&y[1]===2&&Ce(y[3])===4),T=w?hr(w[3]):[];if(T.length!==m.keys.length){f.push(`${g} (the engine wrote ${T.length} keys for ${m.keys.length})`);continue}let P=new Map(T.map((y,x)=>[y,m.keys[x].shape])),E=new Uint8Array(b.flatMap(y=>y===w?[...Le(1,gr(y[3],x=>P.get(x)))]:[...V(y[2])])),N=wr(k?.[1]?vt(k[1]):null,E),C=`<EffectFiltersBA>${mr(N)}</EffectFiltersBA>`,M=k?S.body.replace(k[0],C):S.body.replace(/(<\/Sm2TiVideoClip>)$/,`${C}$1`);h.push({at:S.at,end:S.end,body:M}),d.push(g)}for(let m of h.sort((g,S)=>S.at-g.at))a=a.slice(0,m.at)+m.body+a.slice(m.end);let p={...o,[i]:new TextEncoder().encode(a)};return{drt:ct(p),keyed:d,missing:f}}function At(r,e,t){let n=r.source_range,o=r.timeline_range,s=n?.start.rate||t,i=n?.start.value??0,c=n?.duration&&o?.duration&&o.duration.value?n.duration.value/n.duration.rate/(o.duration.value/o.duration.rate)*s/t:s/t,a=[],l=0;for(let f of e){let h={value:i+f.t*c,rate:s},p=(m,g)=>a.push({id:`${r.id}-align-${l++}`,parameter_path:m,time:h,value:g,interp:"linear"});p("scale",f.transform.scale_x),e.some(m=>Math.abs(m.transform.scale_y-m.transform.scale_x)>.001)&&p("scale.y",f.transform.scale_y),p("position.x",f.transform.position_x),p("position.y",f.transform.position_y),p("rotation",f.transform.rotation)}let u=e[0].transform,d=(r.keyframes??[]).filter(f=>!/^(scale|position|rotation)/.test(String(f.parameter_path)));Object.assign(r,{scale:u.scale_x,position_x:u.position_x,position_y:u.position_y,rotation:u.rotation,keyframes:[...d,...a]}),Math.abs(u.scale_y-u.scale_x)>.001&&Object.assign(r,{scale_x:u.scale_x,scale_y:u.scale_y}),u.flip_h?r.flip_horizontal=!0:delete r.flip_horizontal,u.flip_v?r.flip_vertical=!0:delete r.flip_vertical}function Ot(r=H()){if(r==="win32"){let e=F("PROGRAMDATA")??"C:\\ProgramData",t=F("PROGRAMFILES")??"C:\\Program Files";return{api:`${e}\\Blackmagic Design\\DaVinci Resolve\\Support\\Developer\\Scripting`,lib:`${t}\\Blackmagic Design\\DaVinci Resolve\\fusionscript.dll`}}return r==="linux"?{api:"/opt/resolve/Developer/Scripting",lib:"/opt/resolve/libs/Fusion/fusionscript.so"}:{api:"/Library/Application Support/Blackmagic Design/DaVinci Resolve/Developer/Scripting",lib:"/Applications/DaVinci Resolve/DaVinci Resolve.app/Contents/Libraries/Fusion/fusionscript.so"}}async function yr(r){let e=F("RESOLVE_SCRIPT_LIB");if(e)return e;if(r==="darwin"){let n=(await de("ps",["-axo","comm="])).stdout.split(`
|
|
4
4
|
`).map(o=>o.trim()).find(o=>/\/Contents\/MacOS\/Resolve$/.test(o));if(n){let o=n.replace(/\/MacOS\/Resolve$/,"/Libraries/Fusion/fusionscript.so");if(await ce(o))return o}}return Ot(r).lib}async function Mt(){for(let r of["./bridge.py","./resolve-bridge.py"]){let e=Ze(new URL(r,import.meta.url));if(await le(e))return e}throw new Error("resolve: bridge.py is missing from this install")}var je=new Map;function _r(r){return je.has(r)||je.set(r,de(r,["-c","import sys; print(sys.base_prefix)"],{timeoutMs:2e4}).then(e=>e.stdout.trim().split(`
|
|
5
5
|
`).pop()||void 0).catch(()=>{})),je.get(r)}var br=["PYTHON3HOME","FUSION_PYTHON3HOME","FUSION_PYTHON3_HOME","FUSION_PYTHON36_HOME"];async function $t(r,e){let{api:t}=Ot(r),n=r==="win32"?await _r(e):void 0;return{RESOLVE_SCRIPT_API:F("RESOLVE_SCRIPT_API")??t,RESOLVE_SCRIPT_LIB:await yr(r),PYTHONPATH:I(F("RESOLVE_SCRIPT_API")??t,"Modules"),...n?Object.fromEntries(br.map(o=>[o,n])):{}}}function Nt(r,e=""){let t=r.match(/^Fatal Python error: (.+)$/m)?.[1]?.trim();return t?`the Resolve bridge crashed inside Resolve's scripting library (${t}); the next call starts a fresh one`:r.trim().split(`
|
|
6
6
|
`).map(o=>o.trim()).filter(o=>o&&o!=="<no Python frame>"&&!/^(Current thread|Thread) 0x/.test(o)).pop()||e}var G=null;async function Sr(r,e,t){if(G?.busy)return null;if(!G){let s=H(),i=Te(),c="",a={io:null,busy:!1,waiting:null,last:""};if(a.io=ot(i,[await Mt(),"serve"],l=>{c+=new TextDecoder().decode(l);let u;for(;(u=c.indexOf(`
|
|
7
7
|
`))>=0;){let d=c.slice(0,u);c=c.slice(u+1);let f=a.waiting;a.waiting=null,f?.(d)}},l=>{a.last=/^the Resolve bridge crashed/.test(a.last)?a.last:Nt(l,a.last)},{env:await $t(s,i)}),a.io.exited.then(()=>{G===a&&(G=null),a.waiting?.("")}),G)return a.io.close(),null;G=a}let n=G;n.busy=!0,n.io.hold(!0);let o;try{let s=new Promise(a=>{n.waiting=a}),c=await n.io.write(new TextEncoder().encode(JSON.stringify({action:r,args:e})+`
|
|
8
8
|
`)).then(()=>!0,()=>!1)?await Promise.race([s,new Promise(a=>{o=setTimeout(()=>a(null),t)})]):"";if(c===null)return n.io.close(),{ok:!1,why:"bridge",detail:`no answer from Resolve within ${Math.round(t/1e3)} s`};try{return JSON.parse(c)}catch{return{ok:!1,why:"bridge",detail:n.last||"the Resolve bridge stopped"}}}finally{clearTimeout(o),n.waiting=null,n.busy=!1,n.io.hold(!1)}}var vr=async(r,e,t)=>(F("CONFORM_RESOLVE_ONESHOT")!=="1"?await Sr(r,e,t).catch(()=>null):null)??xr(r,e,t),xr=async(r,e,t)=>{let n=H(),o=Te(),s=await q("ct-bridge-"),i=I(s,"args.json"),c;try{await pe(i,JSON.stringify(e)),c=await de(o,[await Mt(),r,`@${i}`],{env:await $t(n,o),timeoutMs:t})}finally{await me(s).catch(()=>{})}let a=c.stdout.trim().split(`
|
|
9
|
-
`).pop()??"";try{return JSON.parse(a)}catch{return{ok:!1,why:"bridge",detail:c.code==="ENOENT"||/Microsoft Store/.test(c.stderr)?`${o} is not installed (Resolve's scripting needs Python 3: python.org)`:Nt(c.stderr)||(typeof c.code=="string"?`the Resolve bridge could not start: ${c.code}`:`no answer from Resolve within ${Math.round(t/1e3)} s`)}}},kr=1500,Tt=Promise.resolve(),Pt=0;function Rr(r){let e=Tt.catch(()=>{}).then(async()=>{let t=Pt+kr-Date.now();t>0&&await new Promise(n=>setTimeout(n,t));try{return await r()}finally{Pt=Date.now()}});return Tt=e,e}var z=class extends Error{constructor(t,n){super(n);this.why=t}},Ar={module:"Install DaVinci Resolve (its scripting module ships with it).",no_connection:"Start Resolve and set Preferences > System > General > External scripting using: Local (Resolve Studio).",no_project:"Open a project in Resolve."},_e=class{constructor(e=vr){this.runner=e;this.host="resolve";this.restore=new Map;this.startNotes=new Map}async call(e,t={},n=6e4){let o=await this.runner(e,t,n);if(o.ok)return o;throw o.why==="resolve_error"&&/NoneType' object is not callable/.test(String(o.detail))&&!(await this.runner("version",{},1e4)).ok?new z("host_quit",`resolve: Resolve stopped responding during ${e} (it may have quit; see its log, ResolveDebug.txt). Restart Resolve and try again.`):new z(o.why??"unknown",`resolve: ${o.detail||o.why}`)}async support(){let e=await this.runner("version",{},15e3),t=e.ok?e.product==="DaVinci Resolve Studio"?{ok:!0}:{ok:!1,reason:`${e.product} has no external scripting (Resolve Studio has)`}:{ok:!1,reason:e.detail??String(e.why),setup:Ar[e.why??""]};return{export:t,open:t,render:t,markers:t}}async current(){return await this.call("current")}async project(e){return await this.call("project",e,e.export_dir||e.grades?9e5:12e4)}async clipLut(e){return await this.call("clip_lut",e,6e4)}async items(e){return e.selected?await Rr(()=>this.call("items",e,15e3)):await this.call("items",e,e.follow?15e3:12e4)}async apply(e){let t=e.ops.filter(o=>o.op==="edit_keys");if(t.length){let o=e.ops.filter(a=>a.op!=="edit_keys"),s=o.length?await this.apply({...e,ops:o}):{project:"",timeline:e.timeline??"",results:[],undo:[],applied:0,failed:0},i=await this.alignedCopy(e,t),c=i.results.filter(a=>a.ok).length;return{...s,project:s.project||i.project,timeline:s.timeline||i.timeline,results:[...s.results,...i.results],applied:s.applied+c,failed:s.failed+i.results.length-c}}let n=e.ops.filter(o=>(o.op==="grade_sizing"&&(o.target==="input"||o.target==="node")&&!o.reset||o.op==="node_structure"||o.op==="copy_nodes")&&o.item&&"track"in o.item);for(let o of n){let s=o.node_structure??o.structure_path;if(!s)continue;let i=/<Body>([0-9a-fA-F]+)<\/Body>/.exec(new TextDecoder().decode(await ue(s)))?.[1];if(!i)throw new z("usage",`${s}: not a Resolve grade still (.drx with a <Body>)`);o.structure=ye(i),o.structure_name=s}if(n.length){let{grades:o,t0:s}=await this.grades(e.timeline,e.into?{into:e.into,scratch_project:e.scratch_project}:{}),i=c=>{let a=c.item;return o.get(`${a.track}:${a.start+s}`)};for(let c of n){let a=i(c);if(a&&(c.bodies={local:a.local,remote:a.remote}),c.op==="copy_nodes"){let l=c.from;c.from_body=o.get(`${l.track}:${l.start+s}`)?.active}}}return await this.call("apply",e,6e4+e.ops.length*200)}async alignedCopy(e,t){let n=e.into?{into:e.into,scratch_project:e.scratch_project}:{},o=await q("ct-aligned-"),s=i=>({project:"",timeline:e.timeline??"",results:t.map(()=>({op:"edit_keys",ok:!1,refused:["aligned copy"],detail:`refused: ${i}; nothing changed`}))});try{let i=I(o,"export.drt"),c=await this.call("export",{timeline:e.timeline,out_path:i,...n}),a=String(c.timeline),l=Number(c.start_frame??0),{session:u}=await pt(i,"drt"),d=u.timelines[0],f=(d.fps_num??24)/(d.fps_den??1),h=d.tracks.filter(w=>String(w.kind).toLowerCase()==="video"),p=w=>Math.round(w.value*f/w.rate),m=[],g=[];for(let w of t){let T=h[w.item.track-1]?.items.find(P=>{let E=P.timeline_range?.start;return E&&[w.item.start,w.item.start+l].includes(p(E))});T?(At(T,w.keys,f),m.push(w)):g.push(`V${w.item.track}@${w.item.start}`)}let S=await lt("resolve-drt",u),_=typeof S.body=="string"?new TextEncoder().encode(S.body):S.body,v=Rt(await ue(i),_,m,l);if(!v.keyed.length)return s(`no clip could be keyed (${[...g,...v.missing].join(", ")})`);let R=I(o,`${a.replace(/[^\w.-]+/g,"_").slice(0,100)}_ALIGNED.drt`);await tt(R,v.drt);let k=await this.call("open",{path:R,name:`${a} ALIGNED`,link_existing:!0,same_as:a,...n}),b=new Map([...g.map(w=>[w,"not found in the timeline's export"]),...v.missing.map(w=>[w.split(" ")[0],w])]);return{project:String(k.project??""),timeline:String(k.timeline??""),results:t.map(w=>{let T=`V${w.item.track}@${w.item.start}`;return b.has(T)?{op:"edit_keys",ok:!1,refused:["not keyed"],detail:`refused: ${b.get(T)}; nothing changed`}:{op:"edit_keys",ok:!0,detail:`${w.keys.length} Edit-page keyframes on "${k.timeline}" (a copy of "${a}" with every grade and setting; "${a}" itself unchanged)`}})}}catch(i){return s(i instanceof Error?i.message:String(i))}finally{await me(o).catch(()=>{})}}async grades(e,t){let n=await q("ct-grades-");try{let o=I(n,"grades.drt"),s=await this.call("export",{timeline:e,out_path:o,...t});return{grades:await ue(o).then(bt).catch(()=>new Map),t0:Number(s.start_frame??0)}}finally{await me(n).catch(()=>{})}}async presets(e){return await this.call("presets",e,12e4)}async presetAuthor(e){return await this.call("preset_author",e,6e4)}async export(e){if(!e.out_path)throw new z("usage","resolve: export needs out_path");let t=await this.call("export",{timeline:e.timeline,out_path:e.out_path,...e.clip_id?{clip_id:e.clip_id}:{}});return{path:String(t.path),format:"drt",project:String(t.project),timeline:String(t.timeline)}}async open(e){let t=await this.call("open",{path:e.path,into:e.into??"current",name:e.name,media_dir:e.media_dirs?.[0],stay:e.stay??!1,folder:e.folder,create_folder:e.create_folder??!1,link_existing:e.link_existing??!1,...e.settings_from?{settings_from:e.settings_from}:{}},3e5),n=[...t.notes??[]];return(e.media_dirs?.length??0)>1&&n.push(`Resolve searches one media folder per import; used ${e.media_dirs[0]}`),{project:String(t.project),timeline:String(t.timeline),notes:n,restored:!!t.restored,...t.folder?{folder:String(t.folder)}:{},...t.settings?{settings:String(t.settings)}:{}}}async renderStart(e){let t=await this.call("render_start",{...e}),n=String(t.job_id);if(t.queued)return{job_id:n,state:"queued",percent:0,notes:["left in Resolve's render queue: start it on the Deliver page"]};this.restore.set(n,t.restore);let o=t.rejected_settings??[];return o.length&&this.startNotes.set(n,[`Resolve refused render setting(s) ${o.join(", ")} for this format; the rest were applied`]),{job_id:n,state:"queued",percent:0}}async renderStatus(e){let t=await this.call("render_status",{job_id:e},15e3),n={job_id:e,state:t.state,percent:Number(t.percent??0)};if(t.error&&(n.error=String(t.error)),n.state==="complete"||n.state==="failed"){let o=await this.call("render_finish",{job_id:e,restore:this.restore.get(e)});this.restore.delete(e),o.output&&(n.outputs=[String(o.output)]);let s=[...this.startNotes.get(e)??[],...o.tracks?[Et(o)]:[]];this.startNotes.delete(e),s.length&&(n.notes=s)}return n}async renderCancel(e){let t=await this.call("render_cancel",{job_id:e,restore:this.restore.get(e)});return this.restore.delete(e),{job_id:e,state:"cancelled",percent:0,...t.output?{outputs:[String(t.output)]}:{},...t.tracks?{notes:[Et(t)]}:{}}}},Et=r=>{let e=r.tracks.map(t=>`V${t}`).join(", ");return r.tracks_restored?`video track(s) ${e} switched back on`:`could NOT switch video track(s) ${e} back on: re-enable them on the Edit page`};async function Rn(r,e){let t=[];for await(let n of nt(r))n.isFile&&n.name.startsWith(e)&&t.push(I(r,n.name));return t.sort()}var Tr="ws://localhost:1985",Ct="localhost",Lt="conform_tools",jt="conform.tools ",Ft="Video_Full",Pr=r=>!!r&&typeof r=="object"&&"_handle"in r&&"_id"in r,J=class extends Error{constructor(t,n){super(n);this.code=t}},De=class r{constructor(e){this.ws=e;this.next=1;this.waiting=new Map;e.onMessage(t=>{let n;try{n=JSON.parse(t)}catch{return}let o=typeof n.id=="number"?this.waiting.get(n.id):void 0;if(!o)return;if(this.waiting.delete(n.id),n.error===void 0||n.error===null)return o.ok(n.result??null);let s=n.error;o.no(typeof s=="string"?new J(n.code??-1,s):new J(s.code??n.code??-1,s.message??JSON.stringify(s)))}),e.onClose(()=>{for(let t of this.waiting.values())t.no(new J("closed","Baselight closed the FLAPI connection"));this.waiting.clear()})}static async connect(e,t=3e3){let n=new r(await mt(e,{maxBytes:67108864,timeoutMs:t})),o=await Er();return o&&await n.call("authenticate",{username:F("USER")??F("USERNAME")??"conform",token:o},null,t).catch(()=>null),n}call(e,t={},n=null,o=12e4){let s=this.next++;return new Promise((i,c)=>{let a=setTimeout(()=>{this.waiting.delete(s),c(new J("timeout",`${e}: no answer from Baselight within ${Math.round(o/1e3)} s`))},o);this.waiting.set(s,{ok:l=>{clearTimeout(a),i(l)},no:l=>{clearTimeout(a),c(l)}}),this.ws.send(JSON.stringify({jsonrpc:"2.0",method:e,target:n?n._id:null,params:t,id:s}))})}async forget(...e){for(let t of e)Pr(t)&&await this.call("forget",{},t).catch(()=>null)}close(){this.ws.close()}};async function Er(){let r=F("FLAPI_TOKEN");if(r)return r.trim();let e=H()==="darwin"?I(Pe(),"Library","Preferences","FilmLight","flapi-token"):I(Pe(),".filmlight","flapi-token");try{return(await et(e)).trim()||null}catch{return null}}var It=(...r)=>Object.fromEntries(r.map(e=>[e,1])),Or={[-30]:30,[-31]:30,[-32]:30,[-34]:25,[-35]:24};function be(r){if(!r||typeof r!="object")return null;let e=typeof r.fps=="string"?{TC_30DF:-30,TC_60HDF:-31}[r.fps]??Number(r.fps):r.fps,t=e>0?e:Or[e]??30,n=((r.h*60+r.m)*60+r.s)*t+r.f;if(e!==-30&&e!==-31)return n;let o=r.h*60+r.m;return n-2*(o-Math.floor(o/10))}function Mr(r,e,t){let n=Math.round(e),o=r;if(t&&n===30){let l=Math.floor(o/17982),u=o%17982;o+=18*l+(u>2?2*Math.floor((u-2)/1798):0)}let s=o%n,i=Math.floor(o/n)%60,c=Math.floor(o/n/60)%60;return{_type:"timecode",h:Math.floor(o/n/3600)%24,m:c,s:i,f:s,phase:0,fps:t&&n===30?-30:n,wrap:24}}function Dt(r){let e=Math.round(r);return Math.abs(r-e)<.005?e:Math.abs(r-e*1e3/1001)<.01?e*1e3/1001:r}var j=class extends Error{constructor(t,n){super(`baselight: ${n}`);this.why=t}},$r={darwin:"/Applications/Baselight",linux:"/usr/fl/baselight"},Se=class{constructor(e){this.url=e;this.host="baselight";this.jobs=new Map}async conn(e=3e3){let t=this.url??F("CONFORM_BASELIGHT_URL")??Tr;try{return await De.connect(t,e)}catch(n){let o=await ce($r[H()]??"/nonexistent");throw new j(o?"not_running":"not_installed",o?`Baselight is not answering FLAPI at ${t} (${n.message})`:"Baselight is not installed on this machine")}}async with(e){let t=await this.conn();try{return await e(t)}catch(n){throw n instanceof j?n:new j("flapi",n.message)}finally{t.close()}}async support(){let e;try{let t=await this.with(n=>n.call("Application.get_application_info"));e=/baselight|daylight/i.test(t.Product??"")?{ok:!0}:{ok:!1,reason:`the FLAPI server is ${t.Product??"unknown"}, not the Baselight app (port 1984 is the headless flapid)`,setup:"Point CONFORM_BASELIGHT_URL at the running Baselight (ws://localhost:1985)."}}catch(t){let n=t instanceof j?t.why:"flapi";e={ok:!1,reason:t.message.replace(/^baselight: /,""),setup:n==="not_installed"?"Install FilmLight Baselight (FLAPI ships with it; nothing else to install).":"Start Baselight. Its API server listens on port 1985 by default (Preferences > Advanced > API Server)."}}return{export:e,open:e,render:e,markers:{ok:!1,reason:"not wired for Baselight yet (FLAPI has marks: Scene.add_mark)"}}}async scenePath(e,t,n){if(t?.includes(":")){let i=await e.call("Scene.parse_path",{str:t});return{host:i.Host,job:i.Job,scene:i.Scene}}let o=await this.current(e),s=n??o?.job;if(t&&s)return{host:o?.host??Ct,job:s,scene:t};if(!o)throw new j("no_scene",t?`no job to find scene "${t}" in: pass project (the job) or "host:job:scene"`:'no scene is open in Baselight: open one, or name it ("host:job:scene")');return o}async current(e){let t=await e.call("Application.get").catch(()=>null);if(!t)return null;try{let n=await e.call("Application.get_current_scene",{},t);if(!n)return null;try{let o=await e.call("Scene.get_scene_pathname",{},n),[s,i,...c]=o.split(":");return c.length?{host:s,job:i,scene:c.join(":")}:null}finally{await e.forget(n)}}finally{await e.forget(t)}}async export(e){if(!e.out_path)throw new j("usage","export needs out_path");return await this.with(async t=>{let n=await this.scenePath(t,e.timeline),o=await t.call("Scene.open_scene",{scenepath:{Host:n.host,Job:n.job,Scene:n.scene},flags:It("OPENFLAG_READ_ONLY")});try{let s=await Lr(t,o,n.scene);await Y(fe(e.out_path)),await pe(e.out_path,JSON.stringify(s,null,1))}finally{await t.call("Scene.close_scene",{},o).catch(()=>null),await t.forget(o)}return{path:e.out_path,format:"otio",project:n.job,timeline:n.scene}})}async open(e){let{readTimeline:t}=await import("./timeline-33MJ3HOK.js"),{session:n}=await t(e.path),o=n.timelines.find(u=>u.kind!=="compound")??n.timelines[0];if(!o)throw new j("usage",`no timeline in ${e.path}`);let s=new Map((n.media_references??[]).map(u=>[u.id,u])),i=o.fps_num/o.fps_den,c=o.tracks.filter(u=>u.kind==="Video").sort((u,d)=>u.track_index-d.track_index),a=[];c.length>1&&a.push(`placed V1 only: Baselight builds layers above a shot, which FLAPI cannot place in time; ${c.slice(1).reduce((u,d)=>u+d.items.filter(f=>f.kind==="clip").length,0)} clip(s) on V2+ not placed`);let l=(c[0]?.items??[]).filter(u=>u.kind==="clip"||u.kind==="gap").sort((u,d)=>u.timeline_range.start.value-d.timeline_range.start.value);return await this.with(async u=>{let d=e.into==="scratch"?null:await this.current(u);e.into!=="scratch"&&!d&&a.push(`no scene open in Baselight, so it went into our job ${Lt}`);let f=d?.job??Lt,h=d?.host??Ct;await u.call("JobManager.job_exists",{host:h,jobname:f})||await u.call("JobManager.create_job",{host:h,jobname:f});let p=(e.name??o.name??"conform.tools").replace(/[:/\\]+/g,"_"),m=p;for(let w=2;await u.call("JobManager.scene_exists",{host:h,jobname:f,scenename:m});w++)m=`${p} ${w}`;let g=await u.call("FormatSet.factory_formats"),S=o.resolution_w&&o.resolution_h?await u.call("FormatSet.get_basic_format_name",{width:o.resolution_w,height:o.resolution_h},g):null;await u.forget(g);let _=await u.call("Scene.new_scene",{scenepath:{Host:h,Job:f,Scene:m},options:{format:S,colourspace:Ft,frame_rate:i}},null,3e5),v=0,R=0,k=0,b=0;try{await u.call("Scene.start_delta",{name:"conform.tools open"},_);try{let w=0;for(let P of l){let E=P.timeline_range.start.value,N=P.timeline_range.duration.value;if(E>w&&(await Fe(u,_,E-w),k++),w=Math.max(w,E+N),P.kind==="gap"){await Fe(u,_,N),k++;continue}let M=(P.media_reference_id?s.get(P.media_reference_id):void 0)?.target_url?.replace(/^file:\/\//,""),y=P.source_range,x=M&&y?await Cr(u,M,Math.round(y.start.value),Math.round(y.start.value)+N-1):null;if(!x){await Fe(u,_,N),R++;continue}y&&Math.abs(y.duration.value-N)>.5&&b++;let L=await u.call("Scene.insert_sequence",{sequence:x,where:"INSERT_END",relativeTo:null,colourSpace:null,format:null,frameRate:i},_);await u.forget(x,L),v++}let T=await u.call("Scene.get_scene_settings",{},_);await u.call("SceneSettings.set",{values:{StartTimecode:Mr(o.start_frame??0,i,!!o.is_drop_frame)}},T),await u.forget(T),await u.call("Scene.end_delta",{},_)}catch(w){throw await u.call("Scene.cancel_delta",{},_).catch(()=>null),w}await u.call("Scene.save_scene",{},_,3e5)}catch(w){throw await u.call("Scene.close_scene",{},_).catch(()=>null),await u.forget(_),await u.call("JobManager.delete_scene",{host:h,jobname:f,scenename:m}).catch(()=>null),w}return await u.call("Scene.close_scene",{},_),await u.forget(_),a.unshift(`new scene ${h}:${f}:${m}: ${v} shot(s)${k?`, ${k} gap(s) as black`:""}`),R&&a.push(`${R} clip(s) had no media on disk at their path: placed as black of the same length (relink in Baselight's Conform view)`),b&&a.push(`${b} retimed clip(s) placed at normal speed: FLAPI has no retime setter`),m!==p&&a.push(`"${p}" was taken in ${f}: named "${m}"`),e.media_dirs?.length&&a.push("media_dirs not used: Baselight places each clip from its own path"),e.stay&&a.push("stay: FLAPI cannot switch the scene the app shows; open it from the Scenes browser"),{project:f,timeline:m,notes:a,restored:!0}})}async renderStart(e){if(e.disable_tracks?.length)throw new j("usage","disable_tracks: a Baselight render takes every layer or one (RenderTrack); leave the tracks out in the scene");if(e.audio_tracks?.length)throw new j("usage","audio_tracks is a DaVinci Resolve option");return await this.with(async t=>{let n=await this.scenePath(t,e.timeline,e.project),o=await t.call("Scene.open_scene",{scenepath:{Host:n.host,Job:n.job,Scene:n.scene},flags:It("OPENFLAG_READ_ONLY")}),s=null,i=null;try{s=await t.call("RenderSetup.create_from_scene",{scene:o});let c=await t.call("RenderSetup.get_num_deliverables",{},s),a=0;if(e.preset){let p=await t.call("RenderSetup.get_deliverable_names",{},s);if(a=p.indexOf(e.preset),a<0)throw new j("usage",`no deliverable "${e.preset}" in ${n.scene} (it has: ${p.join(", ")||"none"})`)}let l=await t.call("RenderSetup.get_deliverable",{index:a},s),u=e.name??n.scene.replace(/[^\w.-]+/g,"_");Object.assign(l,{Disabled:0,Container:"",OutputDirectory:e.target_dir,FileNamePrefix:u}),e.preset||Object.assign(l,{Name:"conform.tools",IsMovie:1,FileType:"lqtmov",MovieCodec:"apch",ImageOptions:{},FileNameExtension:".mov",RenderColourSpace:Ft,HandleEmptyFrames:"GMREB_BLACK",HandleIncompleteStacks:"GMREB_BLACK",HandleError:"BLACK",EmbedTimecode:1}),e.audio||(l.AudioCodec=""),await Y(e.target_dir),await t.call("RenderSetup.set_deliverable",{index:a,deliverable:l},s);for(let p=0;p<c;p++)p!==a&&await t.call("RenderSetup.set_deliverable_enabled",{index:p,enabled:0},s);if(e.range){let p=await t.call("Scene.get_scene_settings",{},o),m=be(await t.call("SceneSettings.get_single",{key:"StartTimecode"},p))??0;await t.forget(p);let g=e.range.in>=m?m:0;await t.call("RenderSetup.set_frames",{frames:[{Start:e.range.in-g,End:e.range.out-g}]},s)}else await t.call("RenderSetup.select_all",{},s);let d=await t.call("RenderSetup.get_output_filename_for_deliverable",{index:a},s);i=await t.call("QueueManager.create_local");let f=await t.call("RenderSetup.submit_to_queue",{queue:i,opname:`${jt}${u}`},s),h=String(f.ID);return this.jobs.set(h,{op:f.ID,out:d,notes:f.Warning?[`Baselight: ${f.Warning}`]:[]}),{job_id:h,state:"queued",percent:0}}finally{await t.forget(s,i),await t.call("Scene.close_scene",{},o).catch(()=>null),await t.forget(o)}})}async ours(e,t,n){let o=Number(n),s=await e.call("QueueManager.get_operation",{id:o},t).catch(()=>null),i=String(s?.Description??s?.Name??"");if(!this.jobs.has(n)&&!i.startsWith(jt))throw new j("not_ours",`queue operation ${n} is not a conform.tools render: left alone`);return o}async renderStatus(e){return await this.with(async t=>{let n=await t.call("QueueManager.create_local");try{let o=await this.ours(t,n,e),s=await t.call("QueueManager.get_operation_status",{id:o},n),i=Nr(s.Status),c=Number(s.Progress??0),a={job_id:e,state:i,percent:i==="complete"?100:Math.round(c<=1?c*100:c)};if(i==="failed"||i==="complete"&&s.Errors){let u=(await t.call("QueueManager.get_operation_log",{id:o},n).catch(()=>[])).filter(d=>/fail|error|warn/i.test(d.Type)).slice(-6).map(d=>`${d.Message}${d.Detail?`: ${d.Detail}`:""}`);a.error=[s.ProgressText,...u].filter(Boolean).join("; ")||"Baselight reported a failed render",i==="complete"&&(a.state="failed")}if(a.state==="complete"||a.state==="failed"||a.state==="cancelled"){let l=this.jobs.get(e);a.state==="complete"&&l&&(a.outputs=[l.out]),l?.notes.length&&(a.notes=l.notes),await t.call("QueueManager.delete_operation",{id:o},n).catch(()=>null),this.jobs.delete(e)}return a}finally{await t.forget(n)}})}async renderCancel(e){return await this.with(async t=>{let n=await t.call("QueueManager.create_local");try{let o=await this.ours(t,n,e);return await t.call("QueueManager.delete_operation",{id:o},n),this.jobs.delete(e),{job_id:e,state:"cancelled",percent:0}}finally{await t.forget(n)}})}};function Nr(r){let e=String(r).replace(/^OPSTATUS_/i,"").toLowerCase();return e==="done"?"complete":e==="active"?"rendering":e==="stopped"?"cancelled":e==="failed"||e==="crashed"||e==="toonew"?"failed":"queued"}async function Fe(r,e,t){let n=await r.call("Scene.insert_blank",{red:0,green:0,blue:0,duration:t,where:"INSERT_END",relativeTo:null,colourSpace:null},e);await r.forget(n)}async function Cr(r,e,t,n){let o=await r.call("SequenceDescriptor.get_for_template",{template:e,start:null,end:null}).catch(()=>[]);if(!o?.length)return null;let s=await r.call("SequenceDescriptor.get_start_handle",{},o[0]);await r.forget(...o);let i=await r.call("SequenceDescriptor.get_for_template",{template:e,start:s+t,end:s+n});return i?.length?(await r.forget(...i.slice(1)),i[0]):null}var Ue=(r,e)=>({OTIO_SCHEMA:"RationalTime.1",rate:e,value:r}),Ie=(r,e,t)=>({OTIO_SCHEMA:"TimeRange.1",start_time:Ue(r,t),duration:Ue(e,t)});async function Lr(r,e,t){let n=Dt(await r.call("Scene.get_working_frame_rate",{},e)),o=await r.call("Scene.get_scene_settings",{},e),s=be(await r.call("SceneSettings.get_single",{key:"StartTimecode"},o))??0;await r.forget(o);let i=await r.call("Scene.get_num_shots",{},e),c=i?await r.call("Scene.get_shot_ids",{firstIndex:0,lastIndex:i-1},e):[],a=[];for(let d of c){let f=Math.round(d.StartFrame),h=Math.round(d.EndFrame),p=await r.call("Scene.get_shot",{shot_id:d.ShotId},e);try{let m=await r.call("Shot.get_sequence_descriptor",{},p).catch(()=>null);if(!m){a.push({start:f,end:h,name:`shot ${d.ShotId}`});continue}try{let g=Dt(await r.call("Shot.get_frame_rate",{},p))||n,S=be(await r.call("Shot.get_src_start_timecode",{},p)),_=await r.call("Shot.get_src_start_frame",{},p),v=await r.call("Shot.get_src_end_frame",{},p),k=await r.call("SequenceDescriptor.is_movie",{},m)?Xe(await r.call("SequenceDescriptor.get_path",{},m),await r.call("SequenceDescriptor.get_name",{},m)):await r.call("SequenceDescriptor.get_full_filename_with_d",{},m),b=await r.call("SequenceDescriptor.get_name",{},m),w=await r.call("SequenceDescriptor.get_tape",{index:0},m).catch(()=>""),T=await r.call("SequenceDescriptor.get_start_frame",{},m),P=await r.call("SequenceDescriptor.get_start_handle",{},m),E=await r.call("SequenceDescriptor.get_end_handle",{},m),C=(be(await r.call("SequenceDescriptor.get_start_timecode",{index:0},m))??0)-(T-P),M=Math.round(v-_),y=h-f,x={OTIO_SCHEMA:"Clip.2",name:b,enabled:!0,source_range:Ie(S??C+(_-P),y,g),media_references:{DEFAULT_MEDIA:{OTIO_SCHEMA:"ExternalReference.1",target_url:k,available_range:Ie(C,E-P+1,g),available_image_bounds:null,name:b,metadata:{}}},active_media_reference_key:"DEFAULT_MEDIA",effects:M&&M!==y?[{OTIO_SCHEMA:"LinearTimeWarp.1",name:"",effect_name:"LinearTimeWarp",time_scalar:M/y,metadata:{}}]:[],markers:[],metadata:w?{baselight:{tape:w}}:{}};a.push({start:f,end:h,name:b,clip:x})}finally{await r.forget(m)}}finally{await r.forget(p)}}let l=[];for(let d of[...a].sort((f,h)=>f.start-h.start)){if(!d.clip)continue;let f=l.find(h=>h[h.length-1].end<=d.start);f?f.push(d):l.push([d])}let u=l.map((d,f)=>{let h=[],p=0;for(let m of d)m.start>p&&h.push({OTIO_SCHEMA:"Gap.1",name:"",enabled:!0,source_range:Ie(0,m.start-p,n),effects:[],markers:[],metadata:{}}),h.push(m.clip),p=m.end;return{OTIO_SCHEMA:"Track.1",name:`V${f+1}`,kind:"Video",enabled:!0,children:h,source_range:null,effects:[],markers:[],metadata:{}}});return{OTIO_SCHEMA:"Timeline.1",name:t,metadata:{baselight:{shots:c.length}},global_start_time:Ue(s,n),tracks:{OTIO_SCHEMA:"Stack.1",name:"tracks",enabled:!0,children:u,source_range:null,effects:[],markers:[],metadata:{}}}}var jr="127.0.0.1:31416",Fr="/ptsl.PTSL/SendGrpcRequest",Ir="CONFORM.TOOLS",Dr="CONFORM.TOOLS Desktop",He=[2025,6,0],re=[2025,6],qe=1e4,Ut=5e3,Ur="ConformTools",Hr="Start Pro Tools 2025.6 or newer with a session open (PTSL, its scripting door, listens on 127.0.0.1:31416).",Be={GetTrackList:3,HostReadyCheck:13,ExportSessionInfoAsText:30,GetSessionSampleRate:35,GetSessionTimeCodeRate:38,GetSessionFeetFramesRate:39,GetSessionName:42,GetSessionPath:43,GetSessionStartTime:44,GetSessionLength:45,GetPTSLVersion:55,GetTransportState:59,ClearMemoryLocation:61,EditMemoryLocation:68,GetMemoryLocations:69,RegisterConnection:70,CreateMemoryLocation:71,SetTimelineSelection:81,GetTimelineSelection:82,GetSessionIDs:97,GetMainCounterFormat:102},Br=[3,6],Vr=[4,7],Ht=106,Gr=new TextEncoder,qr=new TextDecoder;function ve(r,e){for(;r>127;)e.push(r&127|128),r=Math.floor(r/128);e.push(r)}function Bt(r){let e=[];for(let[t,n]of r){if(typeof n=="number"){n&&(ve(t<<3,e),ve(n,e));continue}let o=typeof n=="string"?Gr.encode(n):n;if(o.length){ve(t<<3|2,e),ve(o.length,e);for(let s of o)e.push(s)}}return new Uint8Array(e)}function Vt(r){let e=new Map,t=0,n=()=>{let o=0,s=1,i;do i=r[t++],o+=(i&127)*s,s*=128;while(i&128&&t<r.length);return o};for(;t<r.length;){let o=n(),s=Math.floor(o/8),i=o&7;if(i===0)e.set(s,n());else if(i===2){let c=n();e.set(s,r.subarray(t,t+c)),t+=c}else if(i===1)t+=8;else if(i===5)t+=4;else throw new A("bad_answer",`Pro Tools sent a reply that is not protobuf (wire type ${i})`)}return e}var Gt=r=>r instanceof Uint8Array?qr.decode(r):"",zr=r=>typeof r=="number"?r:0;function Jr(r,e,t){let n=Bt([[2,r],[3,He[0]],[4,e],[5,He[1]],[6,He[2]]]);return Bt([[1,n],[2,t]])}function Wr(r){let e=Vt(r),t=e.get(1);return{status:t instanceof Uint8Array?zr(Vt(t).get(3)):0,body:Gt(e.get(2)),error:Gt(e.get(3))}}var A=class extends Error{constructor(t,n,o){super(n);this.code=t;this.errors=o}};function Kr(r){let e=null;try{e=JSON.parse(r)}catch{}let t=Array.isArray(e)?e:e&&typeof e=="object"?Array.isArray(e.errors)?e.errors:[e]:[],n=t.find(a=>!a.is_warning)??t[0],o=String(n?.command_error_message||r.trim()||"Pro Tools refused the command"),s=n?.command_error_type,c=s===Ht||s==="PT_NoOpenedSession"||s==="CEType_PT_NoOpenedSession"||s===String(Ht)?"no_session":/session id|not registered|register/i.test(o)?"not_registered":"command_failed";return new A(c,o,t.length?t:void 0)}var ze=class{constructor(e=jr){this.sessionId="";this.version=null;this.queue=Promise.resolve();let t=/^(127\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})$/.exec(e)??/^\[(::1)\]:(\d{1,5})$/.exec(e);if(!t)throw new A("refused",`${e} is not a loopback IP address and port; PTSL is loopback only`);this.host=t[1],this.port=Number(t[2])}async send(e,t,n){let o;try{o=await it(this.host,this.port,Fr,Jr(e,this.sessionId,t),n)}catch(i){throw this.sessionId="",this.version=null,i instanceof st?i.code==="unavailable"?new A("not_running",`Pro Tools is not running (nothing answered on ${this.host}:${this.port})`):i.code==="deadline"?new A("timeout",`Pro Tools did not answer in ${n} ms (a modal dialog or a long command?)`):i.grpcStatus===12?new A("not_ptsl",`the program on ${this.host}:${this.port} is not Pro Tools`):new A("transport",`PTSL transport error: ${i.message}`):i}let s=Wr(o);if(Br.includes(s.status)){if(!s.body.trim())return null;try{return JSON.parse(s.body)}catch{throw new A("bad_answer","Pro Tools sent a body that is not JSON")}}throw Vr.includes(s.status)?Kr(s.error):new A("bad_status",`Pro Tools answered with task status ${s.status}`)}async handshake(){if(!this.sessionId){let e=await this.send(Be.RegisterConnection,JSON.stringify({company_name:Ir,application_name:Dr}),Ut);if(!e?.session_id)throw new A("not_registered","Pro Tools did not give conform.tools a session id");this.sessionId=e.session_id}if(!this.version){let e=await this.send(Be.GetPTSLVersion,"",Ut),t=o=>Number(e?.[o]??0)||0,n=[t("version"),t("version_minor"),t("version_revision")];if(n[0]<re[0]||n[0]===re[0]&&n[1]<re[1])throw this.sessionId="",new A("host_too_old",`Pro Tools ${n[0]}.${n[1]} is too old; conform.tools needs Pro Tools ${re[0]}.${re[1]} or newer`);this.version=n}}call(e,t,n=qe){let o=async()=>{if(e==="RegisterConnection")throw new A("refused","RegisterConnection is sent by the client itself");let i=Be[e];if(i===void 0)throw new A("unknown_command",`${e} is not a PTSL command conform.tools sends`);let c=t==null?"":typeof t=="string"?t:JSON.stringify(t);for(let a=0;;a++){if(await this.handshake(),e==="GetPTSLVersion"){let[l,u,d]=this.version;return{version:l,version_minor:u,version_revision:d}}try{return await this.send(i,c,n)}catch(l){if(l instanceof A&&l.code==="not_registered"&&a===0){this.sessionId="";continue}throw l}}},s=this.queue.then(o,o);return this.queue=s.catch(()=>{}),s}},Ve={23976:24e3/1001,24:24,25:25,2997:3e4/1001,30:30,47952:48e3/1001,48:48,50:50,5994:6e4/1001,60:60,100:100,11988:12e4/1001,120:120},Qr={1:["23976",!1],2:["24",!1],3:["25",!1],4:["2997",!1],5:["2997",!0],6:["30",!1],7:["30",!0],8:["47952",!1],9:["48",!1],10:["50",!1],11:["5994",!1],12:["5994",!0],13:["60",!1],14:["60",!0],15:["100",!1],16:["11988",!1],17:["11988",!0],18:["120",!1],19:["120",!0]};function Yr(r){if(typeof r=="number"||typeof r=="string"&&/^\d+$/.test(r.trim())){let t=Qr[Number(r)];return t?{fps:Ve[t[0]],drop:t[1]}:null}let e=/Fps(\d+)(Drop)?/i.exec(String(r??""));return e&&Ve[e[1]]?{fps:Ve[e[1]],drop:!!e[2]}:null}var Xr=/^-?\d{1,2}[:;.]\d{2}[:;.]\d{2}[:;.,]\d{2,3}(\.\d+)?$/,Zr=/^(?:(\d+):)?(\d+):(\d{2}(?:\.\d+)?)$/;function Ge(r,e){let t=String(r??"").trim();if(Xr.test(t))return ut(t.replace(/\.\d+$/,""),e.rate.fps,e.rate.drop);if(/^-?\d+$/.test(t))return e.start+Math.floor(Number(t)*e.rate.fps/e.sampleRate+1e-9);let n=Zr.exec(t);return n?e.start+Math.floor((Number(n[1]??0)*3600+Number(n[2])*60+Number(n[3]))*e.rate.fps+1e-9):null}var xe=["Blue","Cyan","Green","Yellow","Red","Pink","Purple","Fuchsia","Rose","Lavender","Sky","Mint","Lemon","Sand","Cocoa","Cream"],qt=r=>{let e=Number(r);return e>=1?xe[(e-1)%xe.length]:xe[0]},en=r=>Math.max(0,xe.findIndex(e=>e.toLowerCase()===String(r??"").toLowerCase()))+1,zt=/(?:^| )\[ct:((?:[^[\]\\]|\\.)*)\]$/s;function tn(r,e){return!e&&!zt.test(r)?r:`${r}${r?" ":""}[ct:${e.replace(/[\\[\]]/g,t=>`\\${t}`)}]`}function rn(r){let e=zt.exec(r);return e?{note:r.slice(0,e.index),data:e[1].replace(/\\(.)/gs,"$1")}:{note:r,data:""}}function nn(r){return!r.includes(":")||r.includes("/")||r.includes("\\")?r:`/Volumes/${r.split(":").filter(Boolean).join("/")}`}var ke=class{constructor(e=new ze){this.ptsl=e;this.host="protools"}async sessionName(e=qe){try{return String((await this.ptsl.call("GetSessionName",null,e)).session_name??"")}catch(t){if(t instanceof A&&t.code==="no_session")return"";throw t}}async sessionPath(e=qe){let t=await this.ptsl.call("GetSessionPath",null,e),n=typeof t.session_path=="string"?t.session_path:t.session_path?.path??"";return n?nn(n):""}async current(e=2e3){try{let t=await this.sessionName(e);return t?{project:t,project_path:await this.sessionPath(e).catch(()=>"")}:null}catch{return null}}async facts(){let e=await this.sessionName();if(!e)throw new A("no_session","protools: no session is open");let t=(await this.ptsl.call("GetSessionTimeCodeRate")).current_setting,n=Yr(t);if(!n)throw new A("bad_answer",`protools: a timecode rate conform.tools does not know (${t})`);let o=/(\d{4,6})/.exec(String((await this.ptsl.call("GetSessionSampleRate")).sample_rate??""));if(!o)throw new A("bad_answer","protools: Pro Tools reported a sample rate conform.tools does not know");let s=(await this.ptsl.call("GetSessionStartTime")).session_start_time,i={name:e,rate:n,sampleRate:Number(o[1]),start:0},c=Ge(s,i);if(c==null)throw new A("bad_answer",`protools: a session start conform.tools cannot read (${s})`);return{...i,start:c}}async support(){let e={ok:!1,reason:"Pro Tools holds one session at a time, and importing a timeline changes it; write a .ptx or AAF with timeline_write and open that in Pro Tools"},t={ok:!1,reason:"bouncing from Pro Tools (ExportMix) is not wired"},n;try{n=await this.sessionName(3e3)?{ok:!0}:{ok:!1,reason:"Pro Tools is running with no session open"}}catch(o){n={ok:!1,reason:o instanceof Error?o.message:String(o),setup:Hr}}return{export:n,open:e,render:t,markers:n}}async export(e){let t=await this.sessionName();if(!t)throw new A("no_session","protools: no session is open");if(e.timeline&&e.timeline!==t)throw new A("not_found",`protools: the open session is "${t}"; Pro Tools has one timeline per session`);let n=await this.sessionPath();if(!n||!await le(n))throw new A("no_file",`protools: session "${t}" has no saved .ptx on disk${n?` (${n})`:""}; save it in Pro Tools first`);let o=e.out_path??I(await q("conform-protools-"),at(n));return await Y(fe(o)),await rt(n,o),{path:o,format:"ptx",project:t,timeline:t}}open(){return Promise.reject(new A("unsupported","protools: open is not supported: Pro Tools holds one session, and importing a timeline into it changes it"))}renderStart(){return Promise.reject(new A("unsupported","protools: rendering (a bounce) is not wired"))}renderStatus(){return this.renderStart()}renderCancel(){return this.renderStart()}async project(){let e=await this.facts(),t=await this.sessionPath().catch(()=>""),n=[],o=[];try{let i=await this.ptsl.call("GetTrackList",{page_limit:1e3,track_filter_list:[{filter:"All",is_inverted:!1}]}),c={video:0,audio:0};for(let a of i.track_list??[]){let l=/video/i.test(String(a.type))?"video":"audio",u=a.track_attributes??{},d=u.is_inactive===!0||/^(true|.*_?(set|on|inactive))$/i.test(String(u.is_inactive??""));n.push({kind:l,index:++c[l],name:String(a.name??""),enabled:!d})}}catch(i){o.push(`tracks not read: ${i instanceof Error?i.message:String(i)}`)}let s=(await this.locations(e).catch(()=>({locs:[]}))).locs.length;return{project:e.name,timeline:e.name,timelines:[e.name],session_path:t,fps:e.rate.fps,drop_frame:e.rate.drop,sample_rate:e.sampleRate,start_tc:Ee(e.start,e.rate.fps,e.rate.drop),ptsl_version:this.ptsl.version?.join("."),markers:s,notes:o,tracks:n,jobs:[],found:{},pool:{path:"",clips:0,folders:[]}}}async locations(e){let t=[];for(let o=0;;){let s=await this.ptsl.call("GetMemoryLocations",{pagination_request:{limit:1e3,offset:o}}),i=(s.memory_locations??[]).filter(c=>c&&typeof c=="object");if(t.push(...i),o+=i.length,!i.length||o>=Number((s.pagination_response??s.stats)?.total??0))break}let n=[];for(let o of t){let s=o.time_properties,i=typeof s=="number"||/^\d+$/.test(String(s))?{1:"Marker",2:"Selection"}[Number(s)]:String(s??"").split("_").pop();if(i!=="Marker"&&i!=="Selection")continue;let c=Ge(o.start_time,e);if(c==null)continue;let a=i==="Selection"?Ge(o.end_time,e):null,{note:l,data:u}=rn(String(o.comments??""));n.push({number:Number(o.number)||0,frame:c-e.start,duration:a==null?1:Math.max(1,a-c),name:String(o.name??""),note:l,data:u,color:qt(o.color_index),raw:o})}return n.sort((o,s)=>o.frame-s.frame||o.number-s.number),{locs:n.filter((o,s)=>s===0||n[s-1].frame!==o.frame),numbers:t.map(o=>Number(o.number)||0)}}async writeFormat(){let e=await this.ptsl.call("GetMainCounterFormat"),t=e.current_setting??e.current_type,n=typeof t=="number"||/^\d+$/.test(String(t))?{3:"TimeCode",5:"Samples"}[Number(t)]:String(t??"").split("_").pop();if(n==="TimeCode")return"timecode";if(n==="Samples")return"samples";throw new A("counter_format","protools: set Pro Tools' main counter to Timecode or Samples to edit markers from conform.tools")}async apply(e){let t=await this.facts();if(e.timeline&&e.timeline!==t.name)throw new A("not_found",`protools: the open session is "${t.name}"`);let{locs:n,numbers:o}=await this.locations(t),s=new Map(n.map(p=>[p.frame,p])),i=null,c=p=>i==="samples"?String(Math.round(p*t.sampleRate/t.rate.fps)):Ee(t.start+p,t.rate.fps,t.rate.drop),a=async(p,m)=>{let g=Math.max(1,Math.round(p.duration??1)),S=m?.number??Math.max(0,...o)+1,_=m?.raw??{},v={number:S,name:p.name??"",start_time:c(p.frame),end_time:c(p.frame+(g>1?g:0)),time_properties:g>1?"TP_Selection":"TP_Marker",reference:_.reference||"MLR_Absolute",general_properties:_.general_properties||{zoom_settings:!1,pre_post_roll_times:!1,track_visibility:!1,track_heights:!1,group_enables:!1,window_configuration:!1},comments:tn(p.note??"",p.data??""),color_index:en(p.color),location:_.location||"MLC_MainRuler",..._.track_name?{track_name:_.track_name}:{}};await this.ptsl.call("CreateMemoryLocation",v),o.push(S),s.set(p.frame,{number:S,frame:p.frame,duration:g,name:p.name??"",note:p.note??"",data:p.data??"",color:qt(v.color_index),raw:v})},l=async p=>{await this.ptsl.call("ClearMemoryLocation",{location_list:[p.number]}),s.delete(p.frame),o.splice(o.indexOf(p.number),1)},u=p=>({op:"marker_add",frame:p.frame,color:p.color,name:p.name,note:p.note,duration:p.duration,...p.data?{data:p.data}:{}}),d=[],f=[];for(let p of e.ops){let m=Number(p.frame);try{if(!p.op.startsWith("marker_")||p.item){d.push({op:p.op,ok:!1,detail:`protools: '${p.op}' is not reachable over PTSL (timeline markers only)`});continue}if(!Number.isInteger(m)){d.push({op:p.op,ok:!1,detail:"frame must be a whole number"});continue}i??=await this.writeFormat();let g=s.get(m);if(p.op==="marker_add")g&&await l(g),await a({frame:m,color:p.color,name:p.name,note:p.note,duration:Number(p.duration??1),data:p.data||Ur}),d.push({op:p.op,ok:!0}),f.unshift({op:"marker_delete",frame:m},...g?[u(g)]:[]);else if(p.op==="marker_update"){if(!g){d.push({op:p.op,ok:!1,detail:`no marker at frame ${m}`});continue}let S=p.to_frame!==void 0?Number(p.to_frame):m;if(!Number.isInteger(S)){d.push({op:p.op,ok:!1,detail:"to_frame must be a whole number"});continue}if(S!==m&&s.has(S)){d.push({op:p.op,ok:!1,detail:`frame ${S} already has a marker`});continue}await l(g);let _=(v,R)=>p[v]!==void 0?p[v]:R;await a({frame:S,color:_("color",g.color),name:_("name",g.name),note:_("note",g.note),duration:Number(_("duration",g.duration)),data:_("data",g.data)},g),d.push({op:p.op,ok:!0}),f.unshift({op:"marker_update",frame:S,color:g.color,name:g.name,note:g.note,duration:g.duration,data:g.data,...S!==m?{to_frame:m}:{}})}else if(p.op==="marker_delete"){if(!g){d.push({op:p.op,ok:!1,detail:`no marker at frame ${m}`});continue}await l(g),d.push({op:p.op,ok:!0}),f.unshift(u(g))}else d.push({op:p.op,ok:!1,detail:`protools: unknown marker op '${p.op}'`})}catch(g){d.push({op:p.op,ok:!1,detail:g instanceof Error?g.message:String(g)})}}let h=d.filter(p=>p.ok).length;return{project:t.name,timeline:t.name,results:d,undo:f,applied:h,failed:d.length-h}}};var on="Install the conform.tools panel in Media Composer (mcp/hosts/avid/panel: package it, copy the .avpi into PanelSDKPlugins; an unsigned panel needs Avid's Feature Toggle Files), then open Tools > CONFORM.TOOLS. Its page loads from this engine's host bridge (port 48127) and connects by itself.",sn="Install the conform.tools hook (host_setup host=flame action=install_panel), then in Flame: Flame menu > Python > Rescan Python Hooks (or restart Flame), then Flame menu > CONFORM.TOOLS > Connect to CONFORM.TOOLS (or Connect Automatically).",Jt={resolve:new _e,premiere:new dt,avid:new Oe({host:"avid",label:"Media Composer",setup:on}),flame:new Oe({host:"flame",label:"Flame",setup:sn,items:!0}),baselight:new Se,protools:new ke};function Dn(r,e){Jt[r]=e}function Un(r){return Jt[r]??ft(r,"not wired yet")}export{bt as a,fn as b,vr as c,Rn as d,ke as e,an as f,on as g,sn as h,Dn as i,Un as j};
|
|
9
|
+
`).pop()??"";try{return JSON.parse(a)}catch{return{ok:!1,why:"bridge",detail:c.code==="ENOENT"||/Microsoft Store/.test(c.stderr)?`${o} is not installed (Resolve's scripting needs Python 3: python.org)`:Nt(c.stderr)||(typeof c.code=="string"?`the Resolve bridge could not start: ${c.code}`:`no answer from Resolve within ${Math.round(t/1e3)} s`)}}},kr=1500,Tt=Promise.resolve(),Pt=0;function Rr(r){let e=Tt.catch(()=>{}).then(async()=>{let t=Pt+kr-Date.now();t>0&&await new Promise(n=>setTimeout(n,t));try{return await r()}finally{Pt=Date.now()}});return Tt=e,e}var z=class extends Error{constructor(t,n){super(n);this.why=t}},Ar={module:"Install DaVinci Resolve (its scripting module ships with it).",no_connection:"Start Resolve and set Preferences > System > General > External scripting using: Local (Resolve Studio).",no_project:"Open a project in Resolve."},_e=class{constructor(e=vr){this.runner=e;this.host="resolve";this.restore=new Map;this.startNotes=new Map}async call(e,t={},n=6e4){let o=await this.runner(e,t,n);if(o.ok)return o;throw o.why==="resolve_error"&&/NoneType' object is not callable/.test(String(o.detail))&&!(await this.runner("version",{},1e4)).ok?new z("host_quit",`resolve: Resolve stopped responding during ${e} (it may have quit; see its log, ResolveDebug.txt). Restart Resolve and try again.`):new z(o.why??"unknown",`resolve: ${o.detail||o.why}`)}async support(){let e=await this.runner("version",{},15e3),t=e.ok?e.product==="DaVinci Resolve Studio"?{ok:!0}:{ok:!1,reason:`${e.product} has no external scripting (Resolve Studio has)`}:{ok:!1,reason:e.detail??String(e.why),setup:Ar[e.why??""]};return{export:t,open:t,render:t,markers:t}}async current(){return await this.call("current")}async project(e){return await this.call("project",e,e.export_dir||e.grades?9e5:12e4)}async clipLut(e){return await this.call("clip_lut",e,6e4)}async items(e){return e.selected?await Rr(()=>this.call("items",e,15e3)):await this.call("items",e,e.follow?15e3:12e4)}async apply(e){let t=e.ops.filter(o=>o.op==="edit_keys");if(t.length){let o=e.ops.filter(a=>a.op!=="edit_keys"),s=o.length?await this.apply({...e,ops:o}):{project:"",timeline:e.timeline??"",results:[],undo:[],applied:0,failed:0},i=await this.alignedCopy(e,t),c=i.results.filter(a=>a.ok).length;return{...s,project:s.project||i.project,timeline:s.timeline||i.timeline,results:[...s.results,...i.results],applied:s.applied+c,failed:s.failed+i.results.length-c}}let n=e.ops.filter(o=>(o.op==="grade_sizing"&&(o.target==="input"||o.target==="node")&&!o.reset||o.op==="node_structure"||o.op==="copy_nodes")&&o.item&&"track"in o.item);for(let o of n){let s=o.node_structure??o.structure_path;if(!s)continue;let i=/<Body>([0-9a-fA-F]+)<\/Body>/.exec(new TextDecoder().decode(await ue(s)))?.[1];if(!i)throw new z("usage",`${s}: not a Resolve grade still (.drx with a <Body>)`);o.structure=ye(i),o.structure_name=s}if(n.length){let{grades:o,t0:s}=await this.grades(e.timeline,e.into?{into:e.into,scratch_project:e.scratch_project}:{}),i=c=>{let a=c.item;return o.get(`${a.track}:${a.start+s}`)};for(let c of n){let a=i(c);if(a&&(c.bodies={local:a.local,remote:a.remote}),c.op==="copy_nodes"){let l=c.from;c.from_body=o.get(`${l.track}:${l.start+s}`)?.active}}}return await this.call("apply",e,6e4+e.ops.length*200)}async alignedCopy(e,t){let n=e.into?{into:e.into,scratch_project:e.scratch_project}:{},o=await q("ct-aligned-"),s=i=>({project:"",timeline:e.timeline??"",results:t.map(()=>({op:"edit_keys",ok:!1,refused:["aligned copy"],detail:`refused: ${i}; nothing changed`}))});try{let i=I(o,"export.drt"),c=await this.call("export",{timeline:e.timeline,out_path:i,...n}),a=String(c.timeline),l=Number(c.start_frame??0),{session:u}=await pt(i,"drt"),d=u.timelines[0],f=(d.fps_num??24)/(d.fps_den??1),h=d.tracks.filter(w=>String(w.kind).toLowerCase()==="video"),p=w=>Math.round(w.value*f/w.rate),m=[],g=[];for(let w of t){let T=h[w.item.track-1]?.items.find(P=>{let E=P.timeline_range?.start;return E&&[w.item.start,w.item.start+l].includes(p(E))});T?(At(T,w.keys,f),m.push(w)):g.push(`V${w.item.track}@${w.item.start}`)}let S=await lt("resolve-drt",u),_=typeof S.body=="string"?new TextEncoder().encode(S.body):S.body,v=Rt(await ue(i),_,m,l);if(!v.keyed.length)return s(`no clip could be keyed (${[...g,...v.missing].join(", ")})`);let R=I(o,`${a.replace(/[^\w.-]+/g,"_").slice(0,100)}_ALIGNED.drt`);await tt(R,v.drt);let k=await this.call("open",{path:R,name:`${a} ALIGNED`,link_existing:!0,same_as:a,...n}),b=new Map([...g.map(w=>[w,"not found in the timeline's export"]),...v.missing.map(w=>[w.split(" ")[0],w])]);return{project:String(k.project??""),timeline:String(k.timeline??""),results:t.map(w=>{let T=`V${w.item.track}@${w.item.start}`;return b.has(T)?{op:"edit_keys",ok:!1,refused:["not keyed"],detail:`refused: ${b.get(T)}; nothing changed`}:{op:"edit_keys",ok:!0,detail:`${w.keys.length} Edit-page keyframes on "${k.timeline}" (a copy of "${a}" with every grade and setting; "${a}" itself unchanged)`}})}}catch(i){return s(i instanceof Error?i.message:String(i))}finally{await me(o).catch(()=>{})}}async grades(e,t){let n=await q("ct-grades-");try{let o=I(n,"grades.drt"),s=await this.call("export",{timeline:e,out_path:o,...t});return{grades:await ue(o).then(bt).catch(()=>new Map),t0:Number(s.start_frame??0)}}finally{await me(n).catch(()=>{})}}async presets(e){return await this.call("presets",e,12e4)}async presetAuthor(e){return await this.call("preset_author",e,6e4)}async export(e){if(!e.out_path)throw new z("usage","resolve: export needs out_path");let t=await this.call("export",{timeline:e.timeline,out_path:e.out_path,...e.clip_id?{clip_id:e.clip_id}:{}});return{path:String(t.path),format:"drt",project:String(t.project),timeline:String(t.timeline)}}async open(e){let t=await this.call("open",{path:e.path,into:e.into??"current",name:e.name,media_dir:e.media_dirs?.[0],stay:e.stay??!1,folder:e.folder,create_folder:e.create_folder??!1,link_existing:e.link_existing??!1,...e.settings_from?{settings_from:e.settings_from}:{}},3e5),n=[...t.notes??[]];return(e.media_dirs?.length??0)>1&&n.push(`Resolve searches one media folder per import; used ${e.media_dirs[0]}`),{project:String(t.project),timeline:String(t.timeline),notes:n,restored:!!t.restored,...t.folder?{folder:String(t.folder)}:{},...t.settings?{settings:String(t.settings)}:{}}}async renderStart(e){let t=await this.call("render_start",{...e}),n=String(t.job_id);if(t.queued)return{job_id:n,state:"queued",percent:0,notes:["left in Resolve's render queue: start it on the Deliver page"]};this.restore.set(n,t.restore);let o=t.rejected_settings??[];return o.length&&this.startNotes.set(n,[`Resolve refused render setting(s) ${o.join(", ")} for this format; the rest were applied`]),{job_id:n,state:"queued",percent:0}}async renderStatus(e){let t=await this.call("render_status",{job_id:e},15e3),n={job_id:e,state:t.state,percent:Number(t.percent??0)};if(t.error&&(n.error=String(t.error)),n.state==="complete"||n.state==="failed"){let o=await this.call("render_finish",{job_id:e,restore:this.restore.get(e)});this.restore.delete(e),o.output&&(n.outputs=[String(o.output)]);let s=[...this.startNotes.get(e)??[],...o.tracks?[Et(o)]:[]];this.startNotes.delete(e),s.length&&(n.notes=s)}return n}async renderCancel(e){let t=await this.call("render_cancel",{job_id:e,restore:this.restore.get(e)});return this.restore.delete(e),{job_id:e,state:"cancelled",percent:0,...t.output?{outputs:[String(t.output)]}:{},...t.tracks?{notes:[Et(t)]}:{}}}},Et=r=>{let e=r.tracks.map(t=>`V${t}`).join(", ");return r.tracks_restored?`video track(s) ${e} switched back on`:`could NOT switch video track(s) ${e} back on: re-enable them on the Edit page`};async function Rn(r,e){let t=[];for await(let n of nt(r))n.isFile&&n.name.startsWith(e)&&t.push(I(r,n.name));return t.sort()}var Tr="ws://localhost:1985",Ct="localhost",Lt="conform_tools",jt="conform.tools ",Ft="Video_Full",Pr=r=>!!r&&typeof r=="object"&&"_handle"in r&&"_id"in r,J=class extends Error{constructor(t,n){super(n);this.code=t}},De=class r{constructor(e){this.ws=e;this.next=1;this.waiting=new Map;e.onMessage(t=>{let n;try{n=JSON.parse(t)}catch{return}let o=typeof n.id=="number"?this.waiting.get(n.id):void 0;if(!o)return;if(this.waiting.delete(n.id),n.error===void 0||n.error===null)return o.ok(n.result??null);let s=n.error;o.no(typeof s=="string"?new J(n.code??-1,s):new J(s.code??n.code??-1,s.message??JSON.stringify(s)))}),e.onClose(()=>{for(let t of this.waiting.values())t.no(new J("closed","Baselight closed the FLAPI connection"));this.waiting.clear()})}static async connect(e,t=3e3){let n=new r(await mt(e,{maxBytes:67108864,timeoutMs:t})),o=await Er();return o&&await n.call("authenticate",{username:F("USER")??F("USERNAME")??"conform",token:o},null,t).catch(()=>null),n}call(e,t={},n=null,o=12e4){let s=this.next++;return new Promise((i,c)=>{let a=setTimeout(()=>{this.waiting.delete(s),c(new J("timeout",`${e}: no answer from Baselight within ${Math.round(o/1e3)} s`))},o);this.waiting.set(s,{ok:l=>{clearTimeout(a),i(l)},no:l=>{clearTimeout(a),c(l)}}),this.ws.send(JSON.stringify({jsonrpc:"2.0",method:e,target:n?n._id:null,params:t,id:s}))})}async forget(...e){for(let t of e)Pr(t)&&await this.call("forget",{},t).catch(()=>null)}close(){this.ws.close()}};async function Er(){let r=F("FLAPI_TOKEN");if(r)return r.trim();let e=H()==="darwin"?I(Pe(),"Library","Preferences","FilmLight","flapi-token"):I(Pe(),".filmlight","flapi-token");try{return(await et(e)).trim()||null}catch{return null}}var It=(...r)=>Object.fromEntries(r.map(e=>[e,1])),Or={[-30]:30,[-31]:30,[-32]:30,[-34]:25,[-35]:24};function be(r){if(!r||typeof r!="object")return null;let e=typeof r.fps=="string"?{TC_30DF:-30,TC_60HDF:-31}[r.fps]??Number(r.fps):r.fps,t=e>0?e:Or[e]??30,n=((r.h*60+r.m)*60+r.s)*t+r.f;if(e!==-30&&e!==-31)return n;let o=r.h*60+r.m;return n-2*(o-Math.floor(o/10))}function Mr(r,e,t){let n=Math.round(e),o=r;if(t&&n===30){let l=Math.floor(o/17982),u=o%17982;o+=18*l+(u>2?2*Math.floor((u-2)/1798):0)}let s=o%n,i=Math.floor(o/n)%60,c=Math.floor(o/n/60)%60;return{_type:"timecode",h:Math.floor(o/n/3600)%24,m:c,s:i,f:s,phase:0,fps:t&&n===30?-30:n,wrap:24}}function Dt(r){let e=Math.round(r);return Math.abs(r-e)<.005?e:Math.abs(r-e*1e3/1001)<.01?e*1e3/1001:r}var j=class extends Error{constructor(t,n){super(`baselight: ${n}`);this.why=t}},$r={darwin:"/Applications/Baselight",linux:"/usr/fl/baselight"},Se=class{constructor(e){this.url=e;this.host="baselight";this.jobs=new Map}async conn(e=3e3){let t=this.url??F("CONFORM_BASELIGHT_URL")??Tr;try{return await De.connect(t,e)}catch(n){let o=await ce($r[H()]??"/nonexistent");throw new j(o?"not_running":"not_installed",o?`Baselight is not answering FLAPI at ${t} (${n.message})`:"Baselight is not installed on this machine")}}async with(e){let t=await this.conn();try{return await e(t)}catch(n){throw n instanceof j?n:new j("flapi",n.message)}finally{t.close()}}async support(){let e;try{let t=await this.with(n=>n.call("Application.get_application_info"));e=/baselight|daylight/i.test(t.Product??"")?{ok:!0}:{ok:!1,reason:`the FLAPI server is ${t.Product??"unknown"}, not the Baselight app (port 1984 is the headless flapid)`,setup:"Point CONFORM_BASELIGHT_URL at the running Baselight (ws://localhost:1985)."}}catch(t){let n=t instanceof j?t.why:"flapi";e={ok:!1,reason:t.message.replace(/^baselight: /,""),setup:n==="not_installed"?"Install FilmLight Baselight (FLAPI ships with it; nothing else to install).":"Start Baselight. Its API server listens on port 1985 by default (Preferences > Advanced > API Server)."}}return{export:e,open:e,render:e,markers:{ok:!1,reason:"not wired for Baselight yet (FLAPI has marks: Scene.add_mark)"}}}async scenePath(e,t,n){if(t?.includes(":")){let i=await e.call("Scene.parse_path",{str:t});return{host:i.Host,job:i.Job,scene:i.Scene}}let o=await this.current(e),s=n??o?.job;if(t&&s)return{host:o?.host??Ct,job:s,scene:t};if(!o)throw new j("no_scene",t?`no job to find scene "${t}" in: pass project (the job) or "host:job:scene"`:'no scene is open in Baselight: open one, or name it ("host:job:scene")');return o}async current(e){let t=await e.call("Application.get").catch(()=>null);if(!t)return null;try{let n=await e.call("Application.get_current_scene",{},t);if(!n)return null;try{let o=await e.call("Scene.get_scene_pathname",{},n),[s,i,...c]=o.split(":");return c.length?{host:s,job:i,scene:c.join(":")}:null}finally{await e.forget(n)}}finally{await e.forget(t)}}async export(e){if(!e.out_path)throw new j("usage","export needs out_path");return await this.with(async t=>{let n=await this.scenePath(t,e.timeline),o=await t.call("Scene.open_scene",{scenepath:{Host:n.host,Job:n.job,Scene:n.scene},flags:It("OPENFLAG_READ_ONLY")});try{let s=await Lr(t,o,n.scene);await Y(fe(e.out_path)),await pe(e.out_path,JSON.stringify(s,null,1))}finally{await t.call("Scene.close_scene",{},o).catch(()=>null),await t.forget(o)}return{path:e.out_path,format:"otio",project:n.job,timeline:n.scene}})}async open(e){let{readTimeline:t}=await import("./timeline-HTG23FEH.js"),{session:n}=await t(e.path),o=n.timelines.find(u=>u.kind!=="compound")??n.timelines[0];if(!o)throw new j("usage",`no timeline in ${e.path}`);let s=new Map((n.media_references??[]).map(u=>[u.id,u])),i=o.fps_num/o.fps_den,c=o.tracks.filter(u=>u.kind==="Video").sort((u,d)=>u.track_index-d.track_index),a=[];c.length>1&&a.push(`placed V1 only: Baselight builds layers above a shot, which FLAPI cannot place in time; ${c.slice(1).reduce((u,d)=>u+d.items.filter(f=>f.kind==="clip").length,0)} clip(s) on V2+ not placed`);let l=(c[0]?.items??[]).filter(u=>u.kind==="clip"||u.kind==="gap").sort((u,d)=>u.timeline_range.start.value-d.timeline_range.start.value);return await this.with(async u=>{let d=e.into==="scratch"?null:await this.current(u);e.into!=="scratch"&&!d&&a.push(`no scene open in Baselight, so it went into our job ${Lt}`);let f=d?.job??Lt,h=d?.host??Ct;await u.call("JobManager.job_exists",{host:h,jobname:f})||await u.call("JobManager.create_job",{host:h,jobname:f});let p=(e.name??o.name??"conform.tools").replace(/[:/\\]+/g,"_"),m=p;for(let w=2;await u.call("JobManager.scene_exists",{host:h,jobname:f,scenename:m});w++)m=`${p} ${w}`;let g=await u.call("FormatSet.factory_formats"),S=o.resolution_w&&o.resolution_h?await u.call("FormatSet.get_basic_format_name",{width:o.resolution_w,height:o.resolution_h},g):null;await u.forget(g);let _=await u.call("Scene.new_scene",{scenepath:{Host:h,Job:f,Scene:m},options:{format:S,colourspace:Ft,frame_rate:i}},null,3e5),v=0,R=0,k=0,b=0;try{await u.call("Scene.start_delta",{name:"conform.tools open"},_);try{let w=0;for(let P of l){let E=P.timeline_range.start.value,N=P.timeline_range.duration.value;if(E>w&&(await Fe(u,_,E-w),k++),w=Math.max(w,E+N),P.kind==="gap"){await Fe(u,_,N),k++;continue}let M=(P.media_reference_id?s.get(P.media_reference_id):void 0)?.target_url?.replace(/^file:\/\//,""),y=P.source_range,x=M&&y?await Cr(u,M,Math.round(y.start.value),Math.round(y.start.value)+N-1):null;if(!x){await Fe(u,_,N),R++;continue}y&&Math.abs(y.duration.value-N)>.5&&b++;let L=await u.call("Scene.insert_sequence",{sequence:x,where:"INSERT_END",relativeTo:null,colourSpace:null,format:null,frameRate:i},_);await u.forget(x,L),v++}let T=await u.call("Scene.get_scene_settings",{},_);await u.call("SceneSettings.set",{values:{StartTimecode:Mr(o.start_frame??0,i,!!o.is_drop_frame)}},T),await u.forget(T),await u.call("Scene.end_delta",{},_)}catch(w){throw await u.call("Scene.cancel_delta",{},_).catch(()=>null),w}await u.call("Scene.save_scene",{},_,3e5)}catch(w){throw await u.call("Scene.close_scene",{},_).catch(()=>null),await u.forget(_),await u.call("JobManager.delete_scene",{host:h,jobname:f,scenename:m}).catch(()=>null),w}return await u.call("Scene.close_scene",{},_),await u.forget(_),a.unshift(`new scene ${h}:${f}:${m}: ${v} shot(s)${k?`, ${k} gap(s) as black`:""}`),R&&a.push(`${R} clip(s) had no media on disk at their path: placed as black of the same length (relink in Baselight's Conform view)`),b&&a.push(`${b} retimed clip(s) placed at normal speed: FLAPI has no retime setter`),m!==p&&a.push(`"${p}" was taken in ${f}: named "${m}"`),e.media_dirs?.length&&a.push("media_dirs not used: Baselight places each clip from its own path"),e.stay&&a.push("stay: FLAPI cannot switch the scene the app shows; open it from the Scenes browser"),{project:f,timeline:m,notes:a,restored:!0}})}async renderStart(e){if(e.disable_tracks?.length)throw new j("usage","disable_tracks: a Baselight render takes every layer or one (RenderTrack); leave the tracks out in the scene");if(e.audio_tracks?.length)throw new j("usage","audio_tracks is a DaVinci Resolve option");return await this.with(async t=>{let n=await this.scenePath(t,e.timeline,e.project),o=await t.call("Scene.open_scene",{scenepath:{Host:n.host,Job:n.job,Scene:n.scene},flags:It("OPENFLAG_READ_ONLY")}),s=null,i=null;try{s=await t.call("RenderSetup.create_from_scene",{scene:o});let c=await t.call("RenderSetup.get_num_deliverables",{},s),a=0;if(e.preset){let p=await t.call("RenderSetup.get_deliverable_names",{},s);if(a=p.indexOf(e.preset),a<0)throw new j("usage",`no deliverable "${e.preset}" in ${n.scene} (it has: ${p.join(", ")||"none"})`)}let l=await t.call("RenderSetup.get_deliverable",{index:a},s),u=e.name??n.scene.replace(/[^\w.-]+/g,"_");Object.assign(l,{Disabled:0,Container:"",OutputDirectory:e.target_dir,FileNamePrefix:u}),e.preset||Object.assign(l,{Name:"conform.tools",IsMovie:1,FileType:"lqtmov",MovieCodec:"apch",ImageOptions:{},FileNameExtension:".mov",RenderColourSpace:Ft,HandleEmptyFrames:"GMREB_BLACK",HandleIncompleteStacks:"GMREB_BLACK",HandleError:"BLACK",EmbedTimecode:1}),e.audio||(l.AudioCodec=""),await Y(e.target_dir),await t.call("RenderSetup.set_deliverable",{index:a,deliverable:l},s);for(let p=0;p<c;p++)p!==a&&await t.call("RenderSetup.set_deliverable_enabled",{index:p,enabled:0},s);if(e.range){let p=await t.call("Scene.get_scene_settings",{},o),m=be(await t.call("SceneSettings.get_single",{key:"StartTimecode"},p))??0;await t.forget(p);let g=e.range.in>=m?m:0;await t.call("RenderSetup.set_frames",{frames:[{Start:e.range.in-g,End:e.range.out-g}]},s)}else await t.call("RenderSetup.select_all",{},s);let d=await t.call("RenderSetup.get_output_filename_for_deliverable",{index:a},s);i=await t.call("QueueManager.create_local");let f=await t.call("RenderSetup.submit_to_queue",{queue:i,opname:`${jt}${u}`},s),h=String(f.ID);return this.jobs.set(h,{op:f.ID,out:d,notes:f.Warning?[`Baselight: ${f.Warning}`]:[]}),{job_id:h,state:"queued",percent:0}}finally{await t.forget(s,i),await t.call("Scene.close_scene",{},o).catch(()=>null),await t.forget(o)}})}async ours(e,t,n){let o=Number(n),s=await e.call("QueueManager.get_operation",{id:o},t).catch(()=>null),i=String(s?.Description??s?.Name??"");if(!this.jobs.has(n)&&!i.startsWith(jt))throw new j("not_ours",`queue operation ${n} is not a conform.tools render: left alone`);return o}async renderStatus(e){return await this.with(async t=>{let n=await t.call("QueueManager.create_local");try{let o=await this.ours(t,n,e),s=await t.call("QueueManager.get_operation_status",{id:o},n),i=Nr(s.Status),c=Number(s.Progress??0),a={job_id:e,state:i,percent:i==="complete"?100:Math.round(c<=1?c*100:c)};if(i==="failed"||i==="complete"&&s.Errors){let u=(await t.call("QueueManager.get_operation_log",{id:o},n).catch(()=>[])).filter(d=>/fail|error|warn/i.test(d.Type)).slice(-6).map(d=>`${d.Message}${d.Detail?`: ${d.Detail}`:""}`);a.error=[s.ProgressText,...u].filter(Boolean).join("; ")||"Baselight reported a failed render",i==="complete"&&(a.state="failed")}if(a.state==="complete"||a.state==="failed"||a.state==="cancelled"){let l=this.jobs.get(e);a.state==="complete"&&l&&(a.outputs=[l.out]),l?.notes.length&&(a.notes=l.notes),await t.call("QueueManager.delete_operation",{id:o},n).catch(()=>null),this.jobs.delete(e)}return a}finally{await t.forget(n)}})}async renderCancel(e){return await this.with(async t=>{let n=await t.call("QueueManager.create_local");try{let o=await this.ours(t,n,e);return await t.call("QueueManager.delete_operation",{id:o},n),this.jobs.delete(e),{job_id:e,state:"cancelled",percent:0}}finally{await t.forget(n)}})}};function Nr(r){let e=String(r).replace(/^OPSTATUS_/i,"").toLowerCase();return e==="done"?"complete":e==="active"?"rendering":e==="stopped"?"cancelled":e==="failed"||e==="crashed"||e==="toonew"?"failed":"queued"}async function Fe(r,e,t){let n=await r.call("Scene.insert_blank",{red:0,green:0,blue:0,duration:t,where:"INSERT_END",relativeTo:null,colourSpace:null},e);await r.forget(n)}async function Cr(r,e,t,n){let o=await r.call("SequenceDescriptor.get_for_template",{template:e,start:null,end:null}).catch(()=>[]);if(!o?.length)return null;let s=await r.call("SequenceDescriptor.get_start_handle",{},o[0]);await r.forget(...o);let i=await r.call("SequenceDescriptor.get_for_template",{template:e,start:s+t,end:s+n});return i?.length?(await r.forget(...i.slice(1)),i[0]):null}var Ue=(r,e)=>({OTIO_SCHEMA:"RationalTime.1",rate:e,value:r}),Ie=(r,e,t)=>({OTIO_SCHEMA:"TimeRange.1",start_time:Ue(r,t),duration:Ue(e,t)});async function Lr(r,e,t){let n=Dt(await r.call("Scene.get_working_frame_rate",{},e)),o=await r.call("Scene.get_scene_settings",{},e),s=be(await r.call("SceneSettings.get_single",{key:"StartTimecode"},o))??0;await r.forget(o);let i=await r.call("Scene.get_num_shots",{},e),c=i?await r.call("Scene.get_shot_ids",{firstIndex:0,lastIndex:i-1},e):[],a=[];for(let d of c){let f=Math.round(d.StartFrame),h=Math.round(d.EndFrame),p=await r.call("Scene.get_shot",{shot_id:d.ShotId},e);try{let m=await r.call("Shot.get_sequence_descriptor",{},p).catch(()=>null);if(!m){a.push({start:f,end:h,name:`shot ${d.ShotId}`});continue}try{let g=Dt(await r.call("Shot.get_frame_rate",{},p))||n,S=be(await r.call("Shot.get_src_start_timecode",{},p)),_=await r.call("Shot.get_src_start_frame",{},p),v=await r.call("Shot.get_src_end_frame",{},p),k=await r.call("SequenceDescriptor.is_movie",{},m)?Xe(await r.call("SequenceDescriptor.get_path",{},m),await r.call("SequenceDescriptor.get_name",{},m)):await r.call("SequenceDescriptor.get_full_filename_with_d",{},m),b=await r.call("SequenceDescriptor.get_name",{},m),w=await r.call("SequenceDescriptor.get_tape",{index:0},m).catch(()=>""),T=await r.call("SequenceDescriptor.get_start_frame",{},m),P=await r.call("SequenceDescriptor.get_start_handle",{},m),E=await r.call("SequenceDescriptor.get_end_handle",{},m),C=(be(await r.call("SequenceDescriptor.get_start_timecode",{index:0},m))??0)-(T-P),M=Math.round(v-_),y=h-f,x={OTIO_SCHEMA:"Clip.2",name:b,enabled:!0,source_range:Ie(S??C+(_-P),y,g),media_references:{DEFAULT_MEDIA:{OTIO_SCHEMA:"ExternalReference.1",target_url:k,available_range:Ie(C,E-P+1,g),available_image_bounds:null,name:b,metadata:{}}},active_media_reference_key:"DEFAULT_MEDIA",effects:M&&M!==y?[{OTIO_SCHEMA:"LinearTimeWarp.1",name:"",effect_name:"LinearTimeWarp",time_scalar:M/y,metadata:{}}]:[],markers:[],metadata:w?{baselight:{tape:w}}:{}};a.push({start:f,end:h,name:b,clip:x})}finally{await r.forget(m)}}finally{await r.forget(p)}}let l=[];for(let d of[...a].sort((f,h)=>f.start-h.start)){if(!d.clip)continue;let f=l.find(h=>h[h.length-1].end<=d.start);f?f.push(d):l.push([d])}let u=l.map((d,f)=>{let h=[],p=0;for(let m of d)m.start>p&&h.push({OTIO_SCHEMA:"Gap.1",name:"",enabled:!0,source_range:Ie(0,m.start-p,n),effects:[],markers:[],metadata:{}}),h.push(m.clip),p=m.end;return{OTIO_SCHEMA:"Track.1",name:`V${f+1}`,kind:"Video",enabled:!0,children:h,source_range:null,effects:[],markers:[],metadata:{}}});return{OTIO_SCHEMA:"Timeline.1",name:t,metadata:{baselight:{shots:c.length}},global_start_time:Ue(s,n),tracks:{OTIO_SCHEMA:"Stack.1",name:"tracks",enabled:!0,children:u,source_range:null,effects:[],markers:[],metadata:{}}}}var jr="127.0.0.1:31416",Fr="/ptsl.PTSL/SendGrpcRequest",Ir="CONFORM.TOOLS",Dr="CONFORM.TOOLS Desktop",He=[2025,6,0],re=[2025,6],qe=1e4,Ut=5e3,Ur="ConformTools",Hr="Start Pro Tools 2025.6 or newer with a session open (PTSL, its scripting door, listens on 127.0.0.1:31416).",Be={GetTrackList:3,HostReadyCheck:13,ExportSessionInfoAsText:30,GetSessionSampleRate:35,GetSessionTimeCodeRate:38,GetSessionFeetFramesRate:39,GetSessionName:42,GetSessionPath:43,GetSessionStartTime:44,GetSessionLength:45,GetPTSLVersion:55,GetTransportState:59,ClearMemoryLocation:61,EditMemoryLocation:68,GetMemoryLocations:69,RegisterConnection:70,CreateMemoryLocation:71,SetTimelineSelection:81,GetTimelineSelection:82,GetSessionIDs:97,GetMainCounterFormat:102},Br=[3,6],Vr=[4,7],Ht=106,Gr=new TextEncoder,qr=new TextDecoder;function ve(r,e){for(;r>127;)e.push(r&127|128),r=Math.floor(r/128);e.push(r)}function Bt(r){let e=[];for(let[t,n]of r){if(typeof n=="number"){n&&(ve(t<<3,e),ve(n,e));continue}let o=typeof n=="string"?Gr.encode(n):n;if(o.length){ve(t<<3|2,e),ve(o.length,e);for(let s of o)e.push(s)}}return new Uint8Array(e)}function Vt(r){let e=new Map,t=0,n=()=>{let o=0,s=1,i;do i=r[t++],o+=(i&127)*s,s*=128;while(i&128&&t<r.length);return o};for(;t<r.length;){let o=n(),s=Math.floor(o/8),i=o&7;if(i===0)e.set(s,n());else if(i===2){let c=n();e.set(s,r.subarray(t,t+c)),t+=c}else if(i===1)t+=8;else if(i===5)t+=4;else throw new A("bad_answer",`Pro Tools sent a reply that is not protobuf (wire type ${i})`)}return e}var Gt=r=>r instanceof Uint8Array?qr.decode(r):"",zr=r=>typeof r=="number"?r:0;function Jr(r,e,t){let n=Bt([[2,r],[3,He[0]],[4,e],[5,He[1]],[6,He[2]]]);return Bt([[1,n],[2,t]])}function Wr(r){let e=Vt(r),t=e.get(1);return{status:t instanceof Uint8Array?zr(Vt(t).get(3)):0,body:Gt(e.get(2)),error:Gt(e.get(3))}}var A=class extends Error{constructor(t,n,o){super(n);this.code=t;this.errors=o}};function Kr(r){let e=null;try{e=JSON.parse(r)}catch{}let t=Array.isArray(e)?e:e&&typeof e=="object"?Array.isArray(e.errors)?e.errors:[e]:[],n=t.find(a=>!a.is_warning)??t[0],o=String(n?.command_error_message||r.trim()||"Pro Tools refused the command"),s=n?.command_error_type,c=s===Ht||s==="PT_NoOpenedSession"||s==="CEType_PT_NoOpenedSession"||s===String(Ht)?"no_session":/session id|not registered|register/i.test(o)?"not_registered":"command_failed";return new A(c,o,t.length?t:void 0)}var ze=class{constructor(e=jr){this.sessionId="";this.version=null;this.queue=Promise.resolve();let t=/^(127\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})$/.exec(e)??/^\[(::1)\]:(\d{1,5})$/.exec(e);if(!t)throw new A("refused",`${e} is not a loopback IP address and port; PTSL is loopback only`);this.host=t[1],this.port=Number(t[2])}async send(e,t,n){let o;try{o=await it(this.host,this.port,Fr,Jr(e,this.sessionId,t),n)}catch(i){throw this.sessionId="",this.version=null,i instanceof st?i.code==="unavailable"?new A("not_running",`Pro Tools is not running (nothing answered on ${this.host}:${this.port})`):i.code==="deadline"?new A("timeout",`Pro Tools did not answer in ${n} ms (a modal dialog or a long command?)`):i.grpcStatus===12?new A("not_ptsl",`the program on ${this.host}:${this.port} is not Pro Tools`):new A("transport",`PTSL transport error: ${i.message}`):i}let s=Wr(o);if(Br.includes(s.status)){if(!s.body.trim())return null;try{return JSON.parse(s.body)}catch{throw new A("bad_answer","Pro Tools sent a body that is not JSON")}}throw Vr.includes(s.status)?Kr(s.error):new A("bad_status",`Pro Tools answered with task status ${s.status}`)}async handshake(){if(!this.sessionId){let e=await this.send(Be.RegisterConnection,JSON.stringify({company_name:Ir,application_name:Dr}),Ut);if(!e?.session_id)throw new A("not_registered","Pro Tools did not give conform.tools a session id");this.sessionId=e.session_id}if(!this.version){let e=await this.send(Be.GetPTSLVersion,"",Ut),t=o=>Number(e?.[o]??0)||0,n=[t("version"),t("version_minor"),t("version_revision")];if(n[0]<re[0]||n[0]===re[0]&&n[1]<re[1])throw this.sessionId="",new A("host_too_old",`Pro Tools ${n[0]}.${n[1]} is too old; conform.tools needs Pro Tools ${re[0]}.${re[1]} or newer`);this.version=n}}call(e,t,n=qe){let o=async()=>{if(e==="RegisterConnection")throw new A("refused","RegisterConnection is sent by the client itself");let i=Be[e];if(i===void 0)throw new A("unknown_command",`${e} is not a PTSL command conform.tools sends`);let c=t==null?"":typeof t=="string"?t:JSON.stringify(t);for(let a=0;;a++){if(await this.handshake(),e==="GetPTSLVersion"){let[l,u,d]=this.version;return{version:l,version_minor:u,version_revision:d}}try{return await this.send(i,c,n)}catch(l){if(l instanceof A&&l.code==="not_registered"&&a===0){this.sessionId="";continue}throw l}}},s=this.queue.then(o,o);return this.queue=s.catch(()=>{}),s}},Ve={23976:24e3/1001,24:24,25:25,2997:3e4/1001,30:30,47952:48e3/1001,48:48,50:50,5994:6e4/1001,60:60,100:100,11988:12e4/1001,120:120},Qr={1:["23976",!1],2:["24",!1],3:["25",!1],4:["2997",!1],5:["2997",!0],6:["30",!1],7:["30",!0],8:["47952",!1],9:["48",!1],10:["50",!1],11:["5994",!1],12:["5994",!0],13:["60",!1],14:["60",!0],15:["100",!1],16:["11988",!1],17:["11988",!0],18:["120",!1],19:["120",!0]};function Yr(r){if(typeof r=="number"||typeof r=="string"&&/^\d+$/.test(r.trim())){let t=Qr[Number(r)];return t?{fps:Ve[t[0]],drop:t[1]}:null}let e=/Fps(\d+)(Drop)?/i.exec(String(r??""));return e&&Ve[e[1]]?{fps:Ve[e[1]],drop:!!e[2]}:null}var Xr=/^-?\d{1,2}[:;.]\d{2}[:;.]\d{2}[:;.,]\d{2,3}(\.\d+)?$/,Zr=/^(?:(\d+):)?(\d+):(\d{2}(?:\.\d+)?)$/;function Ge(r,e){let t=String(r??"").trim();if(Xr.test(t))return ut(t.replace(/\.\d+$/,""),e.rate.fps,e.rate.drop);if(/^-?\d+$/.test(t))return e.start+Math.floor(Number(t)*e.rate.fps/e.sampleRate+1e-9);let n=Zr.exec(t);return n?e.start+Math.floor((Number(n[1]??0)*3600+Number(n[2])*60+Number(n[3]))*e.rate.fps+1e-9):null}var xe=["Blue","Cyan","Green","Yellow","Red","Pink","Purple","Fuchsia","Rose","Lavender","Sky","Mint","Lemon","Sand","Cocoa","Cream"],qt=r=>{let e=Number(r);return e>=1?xe[(e-1)%xe.length]:xe[0]},en=r=>Math.max(0,xe.findIndex(e=>e.toLowerCase()===String(r??"").toLowerCase()))+1,zt=/(?:^| )\[ct:((?:[^[\]\\]|\\.)*)\]$/s;function tn(r,e){return!e&&!zt.test(r)?r:`${r}${r?" ":""}[ct:${e.replace(/[\\[\]]/g,t=>`\\${t}`)}]`}function rn(r){let e=zt.exec(r);return e?{note:r.slice(0,e.index),data:e[1].replace(/\\(.)/gs,"$1")}:{note:r,data:""}}function nn(r){return!r.includes(":")||r.includes("/")||r.includes("\\")?r:`/Volumes/${r.split(":").filter(Boolean).join("/")}`}var ke=class{constructor(e=new ze){this.ptsl=e;this.host="protools"}async sessionName(e=qe){try{return String((await this.ptsl.call("GetSessionName",null,e)).session_name??"")}catch(t){if(t instanceof A&&t.code==="no_session")return"";throw t}}async sessionPath(e=qe){let t=await this.ptsl.call("GetSessionPath",null,e),n=typeof t.session_path=="string"?t.session_path:t.session_path?.path??"";return n?nn(n):""}async current(e=2e3){try{let t=await this.sessionName(e);return t?{project:t,project_path:await this.sessionPath(e).catch(()=>"")}:null}catch{return null}}async facts(){let e=await this.sessionName();if(!e)throw new A("no_session","protools: no session is open");let t=(await this.ptsl.call("GetSessionTimeCodeRate")).current_setting,n=Yr(t);if(!n)throw new A("bad_answer",`protools: a timecode rate conform.tools does not know (${t})`);let o=/(\d{4,6})/.exec(String((await this.ptsl.call("GetSessionSampleRate")).sample_rate??""));if(!o)throw new A("bad_answer","protools: Pro Tools reported a sample rate conform.tools does not know");let s=(await this.ptsl.call("GetSessionStartTime")).session_start_time,i={name:e,rate:n,sampleRate:Number(o[1]),start:0},c=Ge(s,i);if(c==null)throw new A("bad_answer",`protools: a session start conform.tools cannot read (${s})`);return{...i,start:c}}async support(){let e={ok:!1,reason:"Pro Tools holds one session at a time, and importing a timeline changes it; write a .ptx or AAF with timeline_write and open that in Pro Tools"},t={ok:!1,reason:"bouncing from Pro Tools (ExportMix) is not wired"},n;try{n=await this.sessionName(3e3)?{ok:!0}:{ok:!1,reason:"Pro Tools is running with no session open"}}catch(o){n={ok:!1,reason:o instanceof Error?o.message:String(o),setup:Hr}}return{export:n,open:e,render:t,markers:n}}async export(e){let t=await this.sessionName();if(!t)throw new A("no_session","protools: no session is open");if(e.timeline&&e.timeline!==t)throw new A("not_found",`protools: the open session is "${t}"; Pro Tools has one timeline per session`);let n=await this.sessionPath();if(!n||!await le(n))throw new A("no_file",`protools: session "${t}" has no saved .ptx on disk${n?` (${n})`:""}; save it in Pro Tools first`);let o=e.out_path??I(await q("conform-protools-"),at(n));return await Y(fe(o)),await rt(n,o),{path:o,format:"ptx",project:t,timeline:t}}open(){return Promise.reject(new A("unsupported","protools: open is not supported: Pro Tools holds one session, and importing a timeline into it changes it"))}renderStart(){return Promise.reject(new A("unsupported","protools: rendering (a bounce) is not wired"))}renderStatus(){return this.renderStart()}renderCancel(){return this.renderStart()}async project(){let e=await this.facts(),t=await this.sessionPath().catch(()=>""),n=[],o=[];try{let i=await this.ptsl.call("GetTrackList",{page_limit:1e3,track_filter_list:[{filter:"All",is_inverted:!1}]}),c={video:0,audio:0};for(let a of i.track_list??[]){let l=/video/i.test(String(a.type))?"video":"audio",u=a.track_attributes??{},d=u.is_inactive===!0||/^(true|.*_?(set|on|inactive))$/i.test(String(u.is_inactive??""));n.push({kind:l,index:++c[l],name:String(a.name??""),enabled:!d})}}catch(i){o.push(`tracks not read: ${i instanceof Error?i.message:String(i)}`)}let s=(await this.locations(e).catch(()=>({locs:[]}))).locs.length;return{project:e.name,timeline:e.name,timelines:[e.name],session_path:t,fps:e.rate.fps,drop_frame:e.rate.drop,sample_rate:e.sampleRate,start_tc:Ee(e.start,e.rate.fps,e.rate.drop),ptsl_version:this.ptsl.version?.join("."),markers:s,notes:o,tracks:n,jobs:[],found:{},pool:{path:"",clips:0,folders:[]}}}async locations(e){let t=[];for(let o=0;;){let s=await this.ptsl.call("GetMemoryLocations",{pagination_request:{limit:1e3,offset:o}}),i=(s.memory_locations??[]).filter(c=>c&&typeof c=="object");if(t.push(...i),o+=i.length,!i.length||o>=Number((s.pagination_response??s.stats)?.total??0))break}let n=[];for(let o of t){let s=o.time_properties,i=typeof s=="number"||/^\d+$/.test(String(s))?{1:"Marker",2:"Selection"}[Number(s)]:String(s??"").split("_").pop();if(i!=="Marker"&&i!=="Selection")continue;let c=Ge(o.start_time,e);if(c==null)continue;let a=i==="Selection"?Ge(o.end_time,e):null,{note:l,data:u}=rn(String(o.comments??""));n.push({number:Number(o.number)||0,frame:c-e.start,duration:a==null?1:Math.max(1,a-c),name:String(o.name??""),note:l,data:u,color:qt(o.color_index),raw:o})}return n.sort((o,s)=>o.frame-s.frame||o.number-s.number),{locs:n.filter((o,s)=>s===0||n[s-1].frame!==o.frame),numbers:t.map(o=>Number(o.number)||0)}}async writeFormat(){let e=await this.ptsl.call("GetMainCounterFormat"),t=e.current_setting??e.current_type,n=typeof t=="number"||/^\d+$/.test(String(t))?{3:"TimeCode",5:"Samples"}[Number(t)]:String(t??"").split("_").pop();if(n==="TimeCode")return"timecode";if(n==="Samples")return"samples";throw new A("counter_format","protools: set Pro Tools' main counter to Timecode or Samples to edit markers from conform.tools")}async apply(e){let t=await this.facts();if(e.timeline&&e.timeline!==t.name)throw new A("not_found",`protools: the open session is "${t.name}"`);let{locs:n,numbers:o}=await this.locations(t),s=new Map(n.map(p=>[p.frame,p])),i=null,c=p=>i==="samples"?String(Math.round(p*t.sampleRate/t.rate.fps)):Ee(t.start+p,t.rate.fps,t.rate.drop),a=async(p,m)=>{let g=Math.max(1,Math.round(p.duration??1)),S=m?.number??Math.max(0,...o)+1,_=m?.raw??{},v={number:S,name:p.name??"",start_time:c(p.frame),end_time:c(p.frame+(g>1?g:0)),time_properties:g>1?"TP_Selection":"TP_Marker",reference:_.reference||"MLR_Absolute",general_properties:_.general_properties||{zoom_settings:!1,pre_post_roll_times:!1,track_visibility:!1,track_heights:!1,group_enables:!1,window_configuration:!1},comments:tn(p.note??"",p.data??""),color_index:en(p.color),location:_.location||"MLC_MainRuler",..._.track_name?{track_name:_.track_name}:{}};await this.ptsl.call("CreateMemoryLocation",v),o.push(S),s.set(p.frame,{number:S,frame:p.frame,duration:g,name:p.name??"",note:p.note??"",data:p.data??"",color:qt(v.color_index),raw:v})},l=async p=>{await this.ptsl.call("ClearMemoryLocation",{location_list:[p.number]}),s.delete(p.frame),o.splice(o.indexOf(p.number),1)},u=p=>({op:"marker_add",frame:p.frame,color:p.color,name:p.name,note:p.note,duration:p.duration,...p.data?{data:p.data}:{}}),d=[],f=[];for(let p of e.ops){let m=Number(p.frame);try{if(!p.op.startsWith("marker_")||p.item){d.push({op:p.op,ok:!1,detail:`protools: '${p.op}' is not reachable over PTSL (timeline markers only)`});continue}if(!Number.isInteger(m)){d.push({op:p.op,ok:!1,detail:"frame must be a whole number"});continue}i??=await this.writeFormat();let g=s.get(m);if(p.op==="marker_add")g&&await l(g),await a({frame:m,color:p.color,name:p.name,note:p.note,duration:Number(p.duration??1),data:p.data||Ur}),d.push({op:p.op,ok:!0}),f.unshift({op:"marker_delete",frame:m},...g?[u(g)]:[]);else if(p.op==="marker_update"){if(!g){d.push({op:p.op,ok:!1,detail:`no marker at frame ${m}`});continue}let S=p.to_frame!==void 0?Number(p.to_frame):m;if(!Number.isInteger(S)){d.push({op:p.op,ok:!1,detail:"to_frame must be a whole number"});continue}if(S!==m&&s.has(S)){d.push({op:p.op,ok:!1,detail:`frame ${S} already has a marker`});continue}await l(g);let _=(v,R)=>p[v]!==void 0?p[v]:R;await a({frame:S,color:_("color",g.color),name:_("name",g.name),note:_("note",g.note),duration:Number(_("duration",g.duration)),data:_("data",g.data)},g),d.push({op:p.op,ok:!0}),f.unshift({op:"marker_update",frame:S,color:g.color,name:g.name,note:g.note,duration:g.duration,data:g.data,...S!==m?{to_frame:m}:{}})}else if(p.op==="marker_delete"){if(!g){d.push({op:p.op,ok:!1,detail:`no marker at frame ${m}`});continue}await l(g),d.push({op:p.op,ok:!0}),f.unshift(u(g))}else d.push({op:p.op,ok:!1,detail:`protools: unknown marker op '${p.op}'`})}catch(g){d.push({op:p.op,ok:!1,detail:g instanceof Error?g.message:String(g)})}}let h=d.filter(p=>p.ok).length;return{project:t.name,timeline:t.name,results:d,undo:f,applied:h,failed:d.length-h}}};var on="Install the conform.tools panel in Media Composer (mcp/hosts/avid/panel: package it, copy the .avpi into PanelSDKPlugins; an unsigned panel needs Avid's Feature Toggle Files), then open Tools > CONFORM.TOOLS. Its page loads from this engine's host bridge (port 48127) and connects by itself.",sn="Install the conform.tools hook (host_setup host=flame action=install_panel), then in Flame: Flame menu > Python > Rescan Python Hooks (or restart Flame), then Flame menu > CONFORM.TOOLS > Connect to CONFORM.TOOLS (or Connect Automatically).",Jt={resolve:new _e,premiere:new dt,avid:new Oe({host:"avid",label:"Media Composer",setup:on}),flame:new Oe({host:"flame",label:"Flame",setup:sn,items:!0}),baselight:new Se,protools:new ke};function Dn(r,e){Jt[r]=e}function Un(r){return Jt[r]??ft(r,"not wired yet")}export{bt as a,fn as b,vr as c,Rn as d,ke as e,an as f,on as g,sn as h,Dn as i,Un as j};
|
|
@@ -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{a as F}from"./chunk-E75BCWXY.js";import{
|
|
3
|
+
import{a as F}from"./chunk-E75BCWXY.js";import{C as S,D as m,F as v,H as x,I as g,J as D,P as $,ea as a,o as _,u as b,v as p}from"./chunk-QQBDHVUU.js";var R="_originalframes",y="zAPPLIED_PATCHES",u=t=>t.replace(/[\\/][^\\/]+[\\/]?$/,""),k=()=>a(_(),"move-undo");async function P(t){let n=[];for await(let o of $(t))o.isFile&&!o.name.startsWith(".")&&n.push(o.name);return n.sort()}async function T(t){let n=[];for await(let o of $(u(t)))o.isDirectory&&/patch/i.test(o.name)&&o.name!==y&&n.push(o.name);return n.sort()}async function A(t,n){let o=new Set(await P(t)),e=[];for(let r of n){let s=a(u(t),r);if(await p(s))for(let w of await P(s))e.push({file:w,folder:r,replaces:o.has(w)})}return e}async function j(t,n,o){if(!await p(t)||!(await b(t)).isDirectory)throw new F("invalid_args",`not a folder: ${t}`);let e=u(t),r=[],s=[];for(let i of await A(t,n)){if(o&&!o.has(`${i.folder}/${i.file}`))continue;if(!i.replaces){r.push(`${i.file}: not in the sequence`);continue}let f=a(t,i.file),c=a(e,i.folder,i.file),l=`${t}${R}`,h=a(l,i.file);for(let d=1;await p(h);d++)h=a(`${t}${R}${String(d).padStart(2,"0")}`,i.file);await m(u(h));try{await g(f,h)}catch(d){r.push(`${i.file}: ${d.message}`);continue}try{await x(c,f)}catch(d){await g(h,f).catch(()=>{}),r.push(`${i.file}: ${d.message}`);continue}s.push({file:i.file,backup:h,patch_src:c,applied:c,folder:i.folder}),l=""}let w=[];if(s.length){let i=a(e,y);await m(i);for(let f of new Set(s.map(c=>c.folder))){let c=a(i,f);for(let l=1;await p(c);l++)c=a(i,`${f}_${l}`);try{await g(a(e,f),c),w.push({from:a(e,f),to:c});for(let l of s)l.folder===f&&(l.applied=a(c,l.file))}catch(l){r.push(`${f}: not filed under ${y} (${l.message})`)}}}if(!s.length)return{patched:0,errors:r};let E=`files-${Date.now().toString(36)}`;return await m(k()),await S(a(k(),`${E}.json`),JSON.stringify({patch:!0,sequence:t,entries:s.map(({folder:i,...f})=>f),folders:w})),{patched:s.length,errors:r,undo_id:E}}async function L(t){let n=[];for(let e of t.folders)await p(e.to)&&!await p(e.from)&&await g(e.to,e.from).catch(r=>n.push({path:e.to,error:r.message}));let o=0;for(let e of t.entries){let r=a(t.sequence,e.file);if(await p(e.backup))try{await p(r)&&await v(r),await g(e.backup,r),o++}catch(s){n.push({path:r,error:s.message})}}for(let e of new Set([...t.entries.map(r=>u(r.backup)),...t.folders.map(r=>u(r.to))]))if(await p(e)&&!(await P(e)).length){let r=!0;for await(let s of $(e)){r=!1;break}r&&await D(e).catch(()=>{})}return{restored:o,failed:n}}export{R as a,y as b,T as c,A as d,j as e,L 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-VFXMP7IF.js";import{i}from"./chunk-
|
|
3
|
+
import{c as r,d as t}from"./chunk-VFXMP7IF.js";import{i}from"./chunk-FHCRWOI7.js";async function d(e){if(!r(e.name))return null;try{return await i(t(e),{verb:"inspect"})}catch(n){return console.warn(`[probeMedia] ${e.name} probe failed:`,n),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 o}from"./chunk-
|
|
3
|
+
import{b as o}from"./chunk-QQBDHVUU.js";var r="0.6.29";function a(t,n){let s=t.split("-")[0].split(".").map(Number),l=n.split("-")[0].split(".").map(Number);for(let e=0;e<Math.max(s.length,l.length);e++){let i=(s[e]||0)-(l[e]||0);if(i)return i>0}return!1}var m=()=>o("CONFORM_APP_VERSION")||r,p=null;function u(){return o("CONFORM_UPDATE_CHECK")==="off"?Promise.resolve(null):p??=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 g(){let t=o("CONFORM_APP_VERSION");if(t)return`conform.tools app ${t}`;let n=await u();return`conformtools ${r}`+(n&&a(n,r)?` \u2014 update available: ${n} \u2192 ${c}`:"")}export{r as a,a as b,m as c,u as d,c as e,g as f};
|
|
@@ -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{p as Q,v as mt}from"./chunk-AR5BTVBM.js";import{a as j}from"./chunk-E75BCWXY.js";import{B as P,C as k,O as pt,da as y,o as R,z as S}from"./chunk-ZPIY5DOU.js";import{createHash as qt}from"node:crypto";import{open as Zt}from"node:fs/promises";var Mt=new Uint16Array(256);for(let e=0;e<256;e++){let t=0,n=e<<8;for(let r=0;r<8;r++)(t^n)&32768?t=t<<1^4129:t=t<<1,n=n<<1;Mt[e]=t&65535}var tt=0,wt=2;var ne=Date.UTC(2020,0,1,0,0,0);function ht(e,t,n,r,o,s,a,i,f,c,u,_,p,w,l,b){let F=z(o,d.__wbindgen_export3,d.__wbindgen_export4),A=x,v=rt(a,d.__wbindgen_export3),W=x,Dt=d.udf_add_file_stream(g(e),g(t),g(n),g(r),F,A,s,v,W,i,f,c,u,_,p,w,l,b);return M(Dt)}function oe(e,t,n,r){let o,s;try{let p=d.__wbindgen_add_to_stack_pointer(-16),w=z(e,d.__wbindgen_export3,d.__wbindgen_export4),l=x,b=z(t,d.__wbindgen_export3,d.__wbindgen_export4),F=x,A=z(n,d.__wbindgen_export3,d.__wbindgen_export4),v=x;d.udf_build_layout(p,w,l,b,F,A,v,r);var a=h().getInt32(p+0,!0),i=h().getInt32(p+4,!0),f=h().getInt32(p+8,!0),c=h().getInt32(p+12,!0),u=a,_=i;if(c)throw u=0,_=0,M(f);return o=u,s=_,C(u,_)}finally{d.__wbindgen_add_to_stack_pointer(16),d.__wbindgen_export5(o,s,1)}}function xt(e,t,n,r,o,s,a){let i=z(o,d.__wbindgen_export3,d.__wbindgen_export4),f=x,c=rt(a,d.__wbindgen_export3),u=x,_=d.udf_fill_sparse_stream(g(e),g(t),g(n),g(r),i,f,s,c,u);return M(_)}function ae(){let e,t;try{let o=d.__wbindgen_add_to_stack_pointer(-16);d.udf_last_panic(o);var n=h().getInt32(o+0,!0),r=h().getInt32(o+4,!0);return e=n,t=r,C(n,r)}finally{d.__wbindgen_add_to_stack_pointer(16),d.__wbindgen_export5(e,t,1)}}function St(e,t){let n=d.udf_parse_stream(g(e),g(t));return M(n)}function se(e){let t,n;try{let s=d.__wbindgen_add_to_stack_pointer(-16),a=rt(e,d.__wbindgen_export3),i=x;d.udf_read_conform_iuvd(s,a,i);var r=h().getInt32(s+0,!0),o=h().getInt32(s+4,!0);return t=r,n=o,C(r,o)}finally{d.__wbindgen_add_to_stack_pointer(16),d.__wbindgen_export5(t,n,1)}}function Lt(){return{__proto__:null,"./udf_bg.js":{__proto__:null,__wbg___wbindgen_is_function_acc5528be2b923f2:function(t){return typeof m(t)=="function"},__wbg___wbindgen_is_undefined_721f8decd50c87a3:function(t){return m(t)===void 0},__wbg___wbindgen_number_get_1cc01dd708740256:function(t,n){let r=m(n),o=typeof r=="number"?r:void 0;h().setFloat64(t+8,O(o)?0:o,!0),h().setInt32(t+0,!O(o),!0)},__wbg___wbindgen_throw_ea4887a5f8f9a9db:function(t,n){throw new Error(C(t,n))},__wbg__wbg_cb_unref_33c39e13d73b25f6:function(t){m(t)._wbg_cb_unref()},__wbg_call_0e855b388e315e17:function(){return et(function(t,n,r,o){let s=m(t).call(m(n),m(r),m(o));return g(s)},arguments)},__wbg_call_5575218572ead796:function(){return et(function(t,n,r){let o=m(t).call(m(n),m(r));return g(o)},arguments)},__wbg_call_8e98ed2f3c86c4b5:function(){return et(function(t,n){let r=m(t).call(m(n));return g(r)},arguments)},__wbg_error_2b5d73c4c4804cfd:function(t,n){console.error(C(t,n))},__wbg_length_589238bdcf171f0e:function(t){return m(t).length},__wbg_new_81880fb5002cb255:function(t){let n=new Uint8Array(m(t));return g(n)},__wbg_new_from_slice_543b875b27789a8f:function(t,n){let r=new Uint8Array(yt(t,n));return g(r)},__wbg_new_no_args_2d7333de60de5ac7:function(t,n){let r=new Function(C(t,n));return g(r)},__wbg_new_typed_00a409eb4ec4f2d9:function(t,n){try{var r={a:t,b:n},o=(a,i)=>{let f=r.a;r.a=0;try{return $t(f,r.b,a,i)}finally{r.a=f}};let s=new Promise(o);return g(s)}finally{r.a=0}},__wbg_prototypesetcall_d721637c7ca66eb8:function(t,n,r){Uint8Array.prototype.set.call(yt(t,n),m(r))},__wbg_queueMicrotask_1c9b3800e321a967:function(t){let n=m(t).queueMicrotask;return g(n)},__wbg_queueMicrotask_311744e534a929a3:function(t){queueMicrotask(m(t))},__wbg_resolve_d82363d90af6928a:function(t){let n=Promise.resolve(m(t));return g(n)},__wbg_static_accessor_GLOBAL_THIS_2fee5048bcca5938:function(){let t=typeof globalThis>"u"?null:globalThis;return O(t)?0:g(t)},__wbg_static_accessor_GLOBAL_ce44e66a4935da8c:function(){let t=typeof global>"u"?null:global;return O(t)?0:g(t)},__wbg_static_accessor_SELF_44f6e0cb5e67cdad:function(){let t=typeof self>"u"?null:self;return O(t)?0:g(t)},__wbg_static_accessor_WINDOW_168f178805d978fe:function(){let t=typeof window>"u"?null:window;return O(t)?0:g(t)},__wbg_then_05edfc8a4fea5106:function(t,n,r){let o=m(t).then(m(n),m(r));return g(o)},__wbg_then_591b6b3a75ee817a:function(t,n){let r=m(t).then(m(n));return g(r)},__wbindgen_cast_0000000000000001:function(t,n){let r=zt(t,n,jt);return g(r)},__wbindgen_cast_0000000000000002:function(t){return g(t)},__wbindgen_cast_0000000000000003:function(t,n){let r=C(t,n);return g(r)},__wbindgen_object_clone_ref:function(t){let n=m(t);return g(n)},__wbindgen_object_drop_ref:function(t){M(t)}}}}function jt(e,t,n){try{let s=d.__wbindgen_add_to_stack_pointer(-16);d.__wasm_bindgen_func_elem_268(s,e,t,g(n));var r=h().getInt32(s+0,!0),o=h().getInt32(s+4,!0);if(o)throw M(r)}finally{d.__wbindgen_add_to_stack_pointer(16)}}function $t(e,t,n,r){d.__wasm_bindgen_func_elem_282(e,t,g(n),g(r))}function g(e){N===E.length&&E.push(E.length+1);let t=N;return N=E[t],E[t]=e,t}var bt=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>d.__wbindgen_export2(e.a,e.b));function Nt(e){e<1028||(E[e]=N,N=e)}function yt(e,t){return e=e>>>0,D().subarray(e/1,e/1+t)}var U=null;function h(){return(U===null||U.buffer.detached===!0||U.buffer.detached===void 0&&U.buffer!==d.memory.buffer)&&(U=new DataView(d.memory.buffer)),U}function C(e,t){return Wt(e>>>0,t)}var $=null;function D(){return($===null||$.byteLength===0)&&($=new Uint8Array(d.memory.buffer)),$}function m(e){return E[e]}function et(e,t){try{return e.apply(this,t)}catch(n){d.__wbindgen_export(g(n))}}var E=new Array(1024).fill(void 0);E.push(void 0,null,!0,!1);var N=E.length;function O(e){return e==null}function zt(e,t,n){let r={a:e,b:t,cnt:1},o=(...s)=>{r.cnt++;let a=r.a;r.a=0;try{return n(a,r.b,...s)}finally{r.a=a,o._wbg_cb_unref()}};return o._wbg_cb_unref=()=>{--r.cnt===0&&(d.__wbindgen_export2(r.a,r.b),r.a=0,bt.unregister(r))},bt.register(o,r,r),o}function rt(e,t){let n=t(e.length*1,1)>>>0;return D().set(e,n/1),x=e.length,n}function z(e,t,n){if(n===void 0){let i=B.encode(e),f=t(i.length,1)>>>0;return D().subarray(f,f+i.length).set(i),x=i.length,f}let r=e.length,o=t(r,1)>>>0,s=D(),a=0;for(;a<r;a++){let i=e.charCodeAt(a);if(i>127)break;s[o+a]=i}if(a!==r){a!==0&&(e=e.slice(a)),o=n(o,r,r=a+e.length*3,1)>>>0;let i=D().subarray(o+a,o+r),f=B.encodeInto(e,i);a+=f.written,o=n(o,r,a,1)>>>0}return x=a,o}function M(e){let t=m(e);return Nt(e),t}var H=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});H.decode();var Bt=2146435072,nt=0;function Wt(e,t){return nt+=t,nt>=Bt&&(H=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),H.decode(),nt=t),H.decode(D().subarray(e,e+t))}var B=new TextEncoder;"encodeInto"in B||(B.encodeInto=function(e,t){let n=B.encode(e);return t.set(n),{read:e.length,written:n.length}});var x=0,Ht,Gt,d;function Jt(e,t){return Gt=e,d=e.exports,Ht=t,U=null,$=null,d.__wbindgen_start(),d}async function Vt(e,t){if(typeof Response=="function"&&e instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(e,t)}catch(o){if(e.ok&&n(e.type)&&e.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",o);else throw o}let r=await e.arrayBuffer();return await WebAssembly.instantiate(r,t)}else{let r=await WebAssembly.instantiate(e,t);return r instanceof WebAssembly.Instance?{instance:r,module:e}:r}function n(r){switch(r){case"basic":case"cors":case"default":return!0}return!1}}async function G(e){if(d!==void 0)return d;e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),e===void 0&&(e=new URL("udf_bg.wasm",import.meta.url));let t=Lt();(typeof e=="string"||typeof Request=="function"&&e instanceof Request||typeof URL=="function"&&e instanceof URL)&&(e=fetch(e));let{instance:n,module:r}=await Vt(await e,t);return Jt(n,r)}var ot=null;function Xt(e){return ot||(ot=(async()=>{if(e!==void 0)return G(e);if(typeof process<"u"&&process.versions?.node){let n="node:fs/promises",{readFile:r}=await import(n),o=await r(new URL("./wasm/udf_bg.wasm",import.meta.url));return G({module_or_path:o})}let{default:t}=await import("./udf_bg-HOHEKAVF.js");return G({module_or_path:t})})()),ot}function J(){return Xt()}function V(e){return(t,n)=>e.read(t,n)}function at(e){return(t,n)=>e.write(t,n)}function X(e){return()=>e.getSize()}function st(e){return t=>e.setSize?e.setSize(t):Promise.resolve()}async function It(e){await J();let t=JSON.parse(await St(V(e),X(e)));if(t.error)throw new Error(t.error);let n=null;if(t.iuvdPayload)try{n=JSON.parse(t.iuvdPayload)}catch{}let r=null,o=t.files.find(s=>s.name===".i2o-manifest.json");if(o&&o.extents.length>0&&o.extents[0].type===tt){let s=o.extents[0].position,a=await e.read((t.partitionStartSector+s)*2048,o.totalSize);try{r=JSON.parse(new TextDecoder().decode(a))}catch{}}return{totalSectors:t.totalSectors,partitionStartSector:t.partitionStartSector,partitionLength:t.partitionLength,volumeName:t.volumeName,files:t.files,manifest:r,iuvdPayload:n,rootIcbSector:t.rootIcbSector,rootDataSector:t.rootDataSector,rootDataLength:t.rootDataLength,rootDataSectors:t.rootDataSectors,vdsStartSector:t.vdsStartSector,partitionDescVdsSector:t.partitionDescVdsSector}}function me(e){let t=[],n=0;for(let r of e.extents)r.type===wt&&t.push({offset:n,length:r.length}),n+=r.length;return t}function At(e){let t=[],n=0;for(let r of e.extents)r.type===tt&&t.push({offset:n,length:r.length,imageSector:r.position}),n+=r.length;return t}async function we(e,t,n,r,o){return await J(),await xt(V(e),at(e),X(e),st(e),n,r,o),It(e)}async function be(e,t,n,r,o,s=0){await J();let a=new Date,i=!!(o&&o.length>0);return await ht(V(e),at(e),X(e),st(e),n,r,i?o:new Uint8Array(0),i,s,a.getFullYear(),a.getMonth()+1,a.getDate(),a.getHours(),a.getMinutes(),a.getSeconds(),-a.getTimezoneOffset()),It(e)}var Y=1<<20,T=5*Y,Et=5*1024*Y,it=1e4,ct=8*Y,Kt=2048;function Ae(e,t,n=Math.max(16*Y,Math.ceil(e/(it-500)))){let r=[...t].filter(c=>c.len>0).sort((c,u)=>c.at-u.at),o=[];for(let c of r){let u=o[o.length-1];u&&c.at<u.at+u.len||(u&&u.at+u.len===c.at&&u.key===c.key&&u.offset+u.len===c.offset?u.len+=c.len:o.push({...c}))}let s=[],a=0;for(let c of o.filter(u=>u.len>=T))c.at>a&&s.push({at:a,len:c.at-a}),s.push({at:c.at,len:c.len,copy:c}),a=c.at+c.len;a<e&&s.push({at:a,len:e-a});let i=c=>c.reduce((u,_)=>{let p=u[u.length-1];return p&&!p.copy&&!_.copy?p.len+=_.len:u.push({..._}),u},[]);for(let c=!0;c;){c=!1,s=i(s);for(let u=0;u<s.length-1;u++){let _=s[u];if(_.len>=T)continue;let p=T-_.len,w=s[u+1],l=s[u-1];if(_.copy){delete _.copy,c=!0;break}w?.copy&&w.len-p>=T?(_.len+=p,w.at+=p,w.len-=p,w.copy={...w.copy,at:w.at,len:w.len,offset:w.copy.offset+p}):l?.copy&&l.len-p>=T?(l.len-=p,l.copy={...l.copy,len:l.len},_.at-=p,_.len+=p):w?.copy?delete w.copy:l?.copy&&delete l.copy,c=!0;break}}let f=[];for(let c of s){let u=c.copy?Math.min(Et,Math.max(n,T)):n;for(let _=c.at,p=c.at+c.len;_<p;){let w=Math.min(u,p-_);p-(_+w)>0&&p-(_+w)<T&&(w=p-_<=Et?p-_:w-T),f.push(c.copy?{kind:"copy",at:_,len:w,key:c.copy.key,offset:c.copy.offset+(_-c.at)}:{kind:"upload",at:_,len:w}),_+=w}}if(f.length>it)throw new Error(`the image needs ${f.length} pieces (S3 allows ${it})`);return f}function Ee(e,t,n,r){let o=[...r].sort((i,f)=>i.offset-f.offset),s=[],a=0;for(let i of o){let f=Math.min(i.offset,t);f>a&&s.push({at:a,len:f-a,key:e,offset:a}),a=Math.max(a,i.offset+i.length)}return a<Math.min(t,n)&&s.push({at:a,len:Math.min(t,n)-a,key:e,offset:a}),s}async function ve(e,t,n,r,o){let s=[];for(let a of t.files)for(let i of At(a)){let f=(t.partitionStartSector+i.imageSector)*Kt;for(let c=i.offset;c<i.offset+i.length;){let u=Math.min(i.offset+i.length,(Math.floor(c/ct)+1)*ct),_=f+(c-i.offset);s.push(o?.(_,u-c)??[qt("sha256").update(await e.read(_,u-c)).digest("hex"),_,u-c]),r?.(u-c),c=u}}return{v:1,block:ct,size:n,blocks:s}}function Pe(e,t){let n=new Map;for(let o of t)for(let[s,a,i]of o.index.blocks)n.set(`${s}:${i}`,{key:o.key,offset:a});let r=[];for(let[o,s,a]of e.blocks){let i=n.get(`${o}:${a}`);i&&r.push({at:s,len:a,key:i.key,offset:i.offset})}return r}var vt=(e,t)=>`${Q().supabaseUrl}/functions/v1/${e}${t}`;async function dt(e,t,n={}){let{token:r,error:o}=await mt();if(!r)throw o;let s=await fetch(vt(e,t),{method:n.method??(n.body?"POST":"GET"),headers:{authorization:`Bearer ${r}`,apikey:Q().anonKey,...n.body?{"content-type":"application/json"}:{}},...n.body?{body:JSON.stringify(n.body)}:{},signal:AbortSignal.timeout(2e4)}),a=await s.text();if(!s.ok){let i=a;try{let f=JSON.parse(a);i=f.error?.message??f.message??f.error??a}catch{}throw s.status===404&&/Requested function was not found/i.test(String(i))?new Error(`${e} isn't deployed on ${new URL(vt(e,t)).host}: this server doesn't have that feature yet (an older server, or a staging/production mismatch)`):new Error(`${n.method??"GET"} ${t}: ${s.status} ${i}`)}return a?JSON.parse(a):{}}function ke(e,t="org"){let n=`/v1/sessions/${e}/storage/multipart`,r=(o,s,a)=>dt("v1-sessions",o,{body:s,method:a});return{start:async o=>String((await r(`${n}/start`,{key:o,content_type:"application/x-iso9660-image"})).upload_id),partUrls:async(o,s,a,i)=>(await r(`${n}/${s}/part-urls`,{key:o,first_part:a,count:i})).parts,copyPart:async(o,s,a,i)=>String((await r(`${n}/${s}/copy-part`,{key:o,part_number:a,source_ref:{scheme:t,bucket:"i2o",key:i.key},byte_range:{offset:i.offset,length:i.length}})).etag),complete:async(o,s,a)=>{await r(`${n}/${s}/complete`,{key:o,parts:a})},abort:async(o,s)=>{await r(`${n}/${encodeURIComponent(s)}?key=${encodeURIComponent(o)}`,void 0,"DELETE")},readUrl:async o=>String((await r(`/v1/sessions/${e}/download-url`,{storage_path:o})).download_url)}}async function ut(e,t,n=4){for(let r=1;;r++)try{return await t()}catch(o){if(r>=n)throw new Error(`${e} failed after ${n} tries: ${o instanceof Error?o.message:o}`);await new Promise(s=>setTimeout(s,500*2**r))}}async function Te(e,t,n,r,o={}){let s=o.fetchFn??fetch,a=await e.start(t),i=n.reduce((l,b)=>l+b.len,0),f=new Array(n.length),c=0,u=0,_=new Map,p=async l=>(_.has(l)||(await e.partUrls(t,a,l+1,Math.min(100,n.length-l))).forEach((F,A)=>_.set(l+A,F)),_.get(l)),w=async l=>{let b=n[l];if(b.kind==="copy")f[l]=await ut(`copy piece ${l+1}`,()=>e.copyPart(t,a,l+1,{key:b.key,offset:b.offset,length:b.len}));else{let F=await r(b.at,b.len);f[l]=await ut(`upload piece ${l+1}`,async()=>{let A=await p(l),v=await s(A.upload_url,{method:A.method,headers:A.headers,body:F,signal:o.signal});if(!v.ok)throw _.delete(l),new Error(`${v.status} ${(await v.text()).slice(0,200)}`);let W=v.headers.get("etag");if(!W)throw new Error("the bucket returned no ETag (expose it in the bucket's CORS / response headers)");return W})}c+=b.len,o.onProgress?.(c,i)};try{await Promise.all(Array.from({length:Math.min(6,n.length)},async()=>{for(;u<n.length;)o.signal?.throwIfAborted(),await w(u++)})),await ut("complete",()=>e.complete(t,a,f.map((l,b)=>({part_number:b+1,etag:l}))))}catch(l){throw await e.abort(t,a).catch(()=>{}),l}return{uploaded:n.filter(l=>l.kind==="upload").reduce((l,b)=>l+b.len,0),copied:n.filter(l=>l.kind==="copy").reduce((l,b)=>l+b.len,0),pieces:n.length}}function Fe(e){let t=Zt(e,"r");return{read:async(n,r)=>{let o=new Uint8Array(r);return await(await t).read(o,0,r,n),o},close:async()=>{await(await t).close()}}}var gt="local",kt=/^[A-Za-z0-9_-]{1,64}$/,I=e=>{if(!kt.test(e))throw new j("invalid_args",`bad project_id '${e}'`);return y(R(),"projects",e)},lt=(e,t={})=>dt("v1-projects",e,t),Tt=e=>Number(/: (\d{3}) /.exec(String(e?.message))?.[1]??0);async function Ft(e){let t="",n={base:null,by:null};try{t=await S(y(I(e),"CONTEXT.md"))}catch{}try{n=JSON.parse(await S(y(I(e),"context.json")))}catch{}return{text:t,meta:n}}async function _t(e,t,n){await k(I(e)),await P(y(I(e),"CONTEXT.md"),t),await P(y(I(e),"context.json"),JSON.stringify(n))}var ft=async(e,t)=>(await _t(e,t.context,{base:t.context_updated_at,by:t.context_updated_by_name??null}),{text:t.context,updated_at:t.context_updated_at,updated_by:t.context_updated_by_name??null});async function Me(e){I(e);let t=await Ft(e);if(e===gt)return{text:t.text,updated_at:null,updated_by:null};if(t.meta.pending)try{return await Pt(e,t.text,t.meta.base)}catch(n){if(!(n instanceof j&&n.code==="context_conflict"))return{text:t.text,updated_at:t.meta.base,updated_by:t.meta.by,offline:!0,pending:!0};let r=n.data?.current??{context:"",context_updated_at:null},o=`${r.context.trimEnd()}
|
|
3
|
+
import{p as Q,v as mt}from"./chunk-KD7UGCLT.js";import{a as j}from"./chunk-E75BCWXY.js";import{C as P,D as k,P as pt,ea as y,o as R,z as S}from"./chunk-QQBDHVUU.js";import{createHash as qt}from"node:crypto";import{open as Zt}from"node:fs/promises";var Mt=new Uint16Array(256);for(let e=0;e<256;e++){let t=0,n=e<<8;for(let r=0;r<8;r++)(t^n)&32768?t=t<<1^4129:t=t<<1,n=n<<1;Mt[e]=t&65535}var tt=0,wt=2;var ne=Date.UTC(2020,0,1,0,0,0);function ht(e,t,n,r,o,s,a,i,f,c,u,_,p,w,l,b){let F=z(o,d.__wbindgen_export3,d.__wbindgen_export4),A=x,v=rt(a,d.__wbindgen_export3),W=x,Dt=d.udf_add_file_stream(g(e),g(t),g(n),g(r),F,A,s,v,W,i,f,c,u,_,p,w,l,b);return M(Dt)}function oe(e,t,n,r){let o,s;try{let p=d.__wbindgen_add_to_stack_pointer(-16),w=z(e,d.__wbindgen_export3,d.__wbindgen_export4),l=x,b=z(t,d.__wbindgen_export3,d.__wbindgen_export4),F=x,A=z(n,d.__wbindgen_export3,d.__wbindgen_export4),v=x;d.udf_build_layout(p,w,l,b,F,A,v,r);var a=h().getInt32(p+0,!0),i=h().getInt32(p+4,!0),f=h().getInt32(p+8,!0),c=h().getInt32(p+12,!0),u=a,_=i;if(c)throw u=0,_=0,M(f);return o=u,s=_,C(u,_)}finally{d.__wbindgen_add_to_stack_pointer(16),d.__wbindgen_export5(o,s,1)}}function xt(e,t,n,r,o,s,a){let i=z(o,d.__wbindgen_export3,d.__wbindgen_export4),f=x,c=rt(a,d.__wbindgen_export3),u=x,_=d.udf_fill_sparse_stream(g(e),g(t),g(n),g(r),i,f,s,c,u);return M(_)}function ae(){let e,t;try{let o=d.__wbindgen_add_to_stack_pointer(-16);d.udf_last_panic(o);var n=h().getInt32(o+0,!0),r=h().getInt32(o+4,!0);return e=n,t=r,C(n,r)}finally{d.__wbindgen_add_to_stack_pointer(16),d.__wbindgen_export5(e,t,1)}}function St(e,t){let n=d.udf_parse_stream(g(e),g(t));return M(n)}function se(e){let t,n;try{let s=d.__wbindgen_add_to_stack_pointer(-16),a=rt(e,d.__wbindgen_export3),i=x;d.udf_read_conform_iuvd(s,a,i);var r=h().getInt32(s+0,!0),o=h().getInt32(s+4,!0);return t=r,n=o,C(r,o)}finally{d.__wbindgen_add_to_stack_pointer(16),d.__wbindgen_export5(t,n,1)}}function Lt(){return{__proto__:null,"./udf_bg.js":{__proto__:null,__wbg___wbindgen_is_function_acc5528be2b923f2:function(t){return typeof m(t)=="function"},__wbg___wbindgen_is_undefined_721f8decd50c87a3:function(t){return m(t)===void 0},__wbg___wbindgen_number_get_1cc01dd708740256:function(t,n){let r=m(n),o=typeof r=="number"?r:void 0;h().setFloat64(t+8,O(o)?0:o,!0),h().setInt32(t+0,!O(o),!0)},__wbg___wbindgen_throw_ea4887a5f8f9a9db:function(t,n){throw new Error(C(t,n))},__wbg__wbg_cb_unref_33c39e13d73b25f6:function(t){m(t)._wbg_cb_unref()},__wbg_call_0e855b388e315e17:function(){return et(function(t,n,r,o){let s=m(t).call(m(n),m(r),m(o));return g(s)},arguments)},__wbg_call_5575218572ead796:function(){return et(function(t,n,r){let o=m(t).call(m(n),m(r));return g(o)},arguments)},__wbg_call_8e98ed2f3c86c4b5:function(){return et(function(t,n){let r=m(t).call(m(n));return g(r)},arguments)},__wbg_error_2b5d73c4c4804cfd:function(t,n){console.error(C(t,n))},__wbg_length_589238bdcf171f0e:function(t){return m(t).length},__wbg_new_81880fb5002cb255:function(t){let n=new Uint8Array(m(t));return g(n)},__wbg_new_from_slice_543b875b27789a8f:function(t,n){let r=new Uint8Array(yt(t,n));return g(r)},__wbg_new_no_args_2d7333de60de5ac7:function(t,n){let r=new Function(C(t,n));return g(r)},__wbg_new_typed_00a409eb4ec4f2d9:function(t,n){try{var r={a:t,b:n},o=(a,i)=>{let f=r.a;r.a=0;try{return $t(f,r.b,a,i)}finally{r.a=f}};let s=new Promise(o);return g(s)}finally{r.a=0}},__wbg_prototypesetcall_d721637c7ca66eb8:function(t,n,r){Uint8Array.prototype.set.call(yt(t,n),m(r))},__wbg_queueMicrotask_1c9b3800e321a967:function(t){let n=m(t).queueMicrotask;return g(n)},__wbg_queueMicrotask_311744e534a929a3:function(t){queueMicrotask(m(t))},__wbg_resolve_d82363d90af6928a:function(t){let n=Promise.resolve(m(t));return g(n)},__wbg_static_accessor_GLOBAL_THIS_2fee5048bcca5938:function(){let t=typeof globalThis>"u"?null:globalThis;return O(t)?0:g(t)},__wbg_static_accessor_GLOBAL_ce44e66a4935da8c:function(){let t=typeof global>"u"?null:global;return O(t)?0:g(t)},__wbg_static_accessor_SELF_44f6e0cb5e67cdad:function(){let t=typeof self>"u"?null:self;return O(t)?0:g(t)},__wbg_static_accessor_WINDOW_168f178805d978fe:function(){let t=typeof window>"u"?null:window;return O(t)?0:g(t)},__wbg_then_05edfc8a4fea5106:function(t,n,r){let o=m(t).then(m(n),m(r));return g(o)},__wbg_then_591b6b3a75ee817a:function(t,n){let r=m(t).then(m(n));return g(r)},__wbindgen_cast_0000000000000001:function(t,n){let r=zt(t,n,jt);return g(r)},__wbindgen_cast_0000000000000002:function(t){return g(t)},__wbindgen_cast_0000000000000003:function(t,n){let r=C(t,n);return g(r)},__wbindgen_object_clone_ref:function(t){let n=m(t);return g(n)},__wbindgen_object_drop_ref:function(t){M(t)}}}}function jt(e,t,n){try{let s=d.__wbindgen_add_to_stack_pointer(-16);d.__wasm_bindgen_func_elem_268(s,e,t,g(n));var r=h().getInt32(s+0,!0),o=h().getInt32(s+4,!0);if(o)throw M(r)}finally{d.__wbindgen_add_to_stack_pointer(16)}}function $t(e,t,n,r){d.__wasm_bindgen_func_elem_282(e,t,g(n),g(r))}function g(e){N===E.length&&E.push(E.length+1);let t=N;return N=E[t],E[t]=e,t}var bt=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>d.__wbindgen_export2(e.a,e.b));function Nt(e){e<1028||(E[e]=N,N=e)}function yt(e,t){return e=e>>>0,D().subarray(e/1,e/1+t)}var U=null;function h(){return(U===null||U.buffer.detached===!0||U.buffer.detached===void 0&&U.buffer!==d.memory.buffer)&&(U=new DataView(d.memory.buffer)),U}function C(e,t){return Wt(e>>>0,t)}var $=null;function D(){return($===null||$.byteLength===0)&&($=new Uint8Array(d.memory.buffer)),$}function m(e){return E[e]}function et(e,t){try{return e.apply(this,t)}catch(n){d.__wbindgen_export(g(n))}}var E=new Array(1024).fill(void 0);E.push(void 0,null,!0,!1);var N=E.length;function O(e){return e==null}function zt(e,t,n){let r={a:e,b:t,cnt:1},o=(...s)=>{r.cnt++;let a=r.a;r.a=0;try{return n(a,r.b,...s)}finally{r.a=a,o._wbg_cb_unref()}};return o._wbg_cb_unref=()=>{--r.cnt===0&&(d.__wbindgen_export2(r.a,r.b),r.a=0,bt.unregister(r))},bt.register(o,r,r),o}function rt(e,t){let n=t(e.length*1,1)>>>0;return D().set(e,n/1),x=e.length,n}function z(e,t,n){if(n===void 0){let i=B.encode(e),f=t(i.length,1)>>>0;return D().subarray(f,f+i.length).set(i),x=i.length,f}let r=e.length,o=t(r,1)>>>0,s=D(),a=0;for(;a<r;a++){let i=e.charCodeAt(a);if(i>127)break;s[o+a]=i}if(a!==r){a!==0&&(e=e.slice(a)),o=n(o,r,r=a+e.length*3,1)>>>0;let i=D().subarray(o+a,o+r),f=B.encodeInto(e,i);a+=f.written,o=n(o,r,a,1)>>>0}return x=a,o}function M(e){let t=m(e);return Nt(e),t}var H=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});H.decode();var Bt=2146435072,nt=0;function Wt(e,t){return nt+=t,nt>=Bt&&(H=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),H.decode(),nt=t),H.decode(D().subarray(e,e+t))}var B=new TextEncoder;"encodeInto"in B||(B.encodeInto=function(e,t){let n=B.encode(e);return t.set(n),{read:e.length,written:n.length}});var x=0,Ht,Gt,d;function Jt(e,t){return Gt=e,d=e.exports,Ht=t,U=null,$=null,d.__wbindgen_start(),d}async function Vt(e,t){if(typeof Response=="function"&&e instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(e,t)}catch(o){if(e.ok&&n(e.type)&&e.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",o);else throw o}let r=await e.arrayBuffer();return await WebAssembly.instantiate(r,t)}else{let r=await WebAssembly.instantiate(e,t);return r instanceof WebAssembly.Instance?{instance:r,module:e}:r}function n(r){switch(r){case"basic":case"cors":case"default":return!0}return!1}}async function G(e){if(d!==void 0)return d;e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),e===void 0&&(e=new URL("udf_bg.wasm",import.meta.url));let t=Lt();(typeof e=="string"||typeof Request=="function"&&e instanceof Request||typeof URL=="function"&&e instanceof URL)&&(e=fetch(e));let{instance:n,module:r}=await Vt(await e,t);return Jt(n,r)}var ot=null;function Xt(e){return ot||(ot=(async()=>{if(e!==void 0)return G(e);if(typeof process<"u"&&process.versions?.node){let n="node:fs/promises",{readFile:r}=await import(n),o=await r(new URL("./wasm/udf_bg.wasm",import.meta.url));return G({module_or_path:o})}let{default:t}=await import("./udf_bg-HOHEKAVF.js");return G({module_or_path:t})})()),ot}function J(){return Xt()}function V(e){return(t,n)=>e.read(t,n)}function at(e){return(t,n)=>e.write(t,n)}function X(e){return()=>e.getSize()}function st(e){return t=>e.setSize?e.setSize(t):Promise.resolve()}async function It(e){await J();let t=JSON.parse(await St(V(e),X(e)));if(t.error)throw new Error(t.error);let n=null;if(t.iuvdPayload)try{n=JSON.parse(t.iuvdPayload)}catch{}let r=null,o=t.files.find(s=>s.name===".i2o-manifest.json");if(o&&o.extents.length>0&&o.extents[0].type===tt){let s=o.extents[0].position,a=await e.read((t.partitionStartSector+s)*2048,o.totalSize);try{r=JSON.parse(new TextDecoder().decode(a))}catch{}}return{totalSectors:t.totalSectors,partitionStartSector:t.partitionStartSector,partitionLength:t.partitionLength,volumeName:t.volumeName,files:t.files,manifest:r,iuvdPayload:n,rootIcbSector:t.rootIcbSector,rootDataSector:t.rootDataSector,rootDataLength:t.rootDataLength,rootDataSectors:t.rootDataSectors,vdsStartSector:t.vdsStartSector,partitionDescVdsSector:t.partitionDescVdsSector}}function me(e){let t=[],n=0;for(let r of e.extents)r.type===wt&&t.push({offset:n,length:r.length}),n+=r.length;return t}function At(e){let t=[],n=0;for(let r of e.extents)r.type===tt&&t.push({offset:n,length:r.length,imageSector:r.position}),n+=r.length;return t}async function we(e,t,n,r,o){return await J(),await xt(V(e),at(e),X(e),st(e),n,r,o),It(e)}async function be(e,t,n,r,o,s=0){await J();let a=new Date,i=!!(o&&o.length>0);return await ht(V(e),at(e),X(e),st(e),n,r,i?o:new Uint8Array(0),i,s,a.getFullYear(),a.getMonth()+1,a.getDate(),a.getHours(),a.getMinutes(),a.getSeconds(),-a.getTimezoneOffset()),It(e)}var Y=1<<20,T=5*Y,Et=5*1024*Y,it=1e4,ct=8*Y,Kt=2048;function Ae(e,t,n=Math.max(16*Y,Math.ceil(e/(it-500)))){let r=[...t].filter(c=>c.len>0).sort((c,u)=>c.at-u.at),o=[];for(let c of r){let u=o[o.length-1];u&&c.at<u.at+u.len||(u&&u.at+u.len===c.at&&u.key===c.key&&u.offset+u.len===c.offset?u.len+=c.len:o.push({...c}))}let s=[],a=0;for(let c of o.filter(u=>u.len>=T))c.at>a&&s.push({at:a,len:c.at-a}),s.push({at:c.at,len:c.len,copy:c}),a=c.at+c.len;a<e&&s.push({at:a,len:e-a});let i=c=>c.reduce((u,_)=>{let p=u[u.length-1];return p&&!p.copy&&!_.copy?p.len+=_.len:u.push({..._}),u},[]);for(let c=!0;c;){c=!1,s=i(s);for(let u=0;u<s.length-1;u++){let _=s[u];if(_.len>=T)continue;let p=T-_.len,w=s[u+1],l=s[u-1];if(_.copy){delete _.copy,c=!0;break}w?.copy&&w.len-p>=T?(_.len+=p,w.at+=p,w.len-=p,w.copy={...w.copy,at:w.at,len:w.len,offset:w.copy.offset+p}):l?.copy&&l.len-p>=T?(l.len-=p,l.copy={...l.copy,len:l.len},_.at-=p,_.len+=p):w?.copy?delete w.copy:l?.copy&&delete l.copy,c=!0;break}}let f=[];for(let c of s){let u=c.copy?Math.min(Et,Math.max(n,T)):n;for(let _=c.at,p=c.at+c.len;_<p;){let w=Math.min(u,p-_);p-(_+w)>0&&p-(_+w)<T&&(w=p-_<=Et?p-_:w-T),f.push(c.copy?{kind:"copy",at:_,len:w,key:c.copy.key,offset:c.copy.offset+(_-c.at)}:{kind:"upload",at:_,len:w}),_+=w}}if(f.length>it)throw new Error(`the image needs ${f.length} pieces (S3 allows ${it})`);return f}function Ee(e,t,n,r){let o=[...r].sort((i,f)=>i.offset-f.offset),s=[],a=0;for(let i of o){let f=Math.min(i.offset,t);f>a&&s.push({at:a,len:f-a,key:e,offset:a}),a=Math.max(a,i.offset+i.length)}return a<Math.min(t,n)&&s.push({at:a,len:Math.min(t,n)-a,key:e,offset:a}),s}async function ve(e,t,n,r,o){let s=[];for(let a of t.files)for(let i of At(a)){let f=(t.partitionStartSector+i.imageSector)*Kt;for(let c=i.offset;c<i.offset+i.length;){let u=Math.min(i.offset+i.length,(Math.floor(c/ct)+1)*ct),_=f+(c-i.offset);s.push(o?.(_,u-c)??[qt("sha256").update(await e.read(_,u-c)).digest("hex"),_,u-c]),r?.(u-c),c=u}}return{v:1,block:ct,size:n,blocks:s}}function Pe(e,t){let n=new Map;for(let o of t)for(let[s,a,i]of o.index.blocks)n.set(`${s}:${i}`,{key:o.key,offset:a});let r=[];for(let[o,s,a]of e.blocks){let i=n.get(`${o}:${a}`);i&&r.push({at:s,len:a,key:i.key,offset:i.offset})}return r}var vt=(e,t)=>`${Q().supabaseUrl}/functions/v1/${e}${t}`;async function dt(e,t,n={}){let{token:r,error:o}=await mt();if(!r)throw o;let s=await fetch(vt(e,t),{method:n.method??(n.body?"POST":"GET"),headers:{authorization:`Bearer ${r}`,apikey:Q().anonKey,...n.body?{"content-type":"application/json"}:{}},...n.body?{body:JSON.stringify(n.body)}:{},signal:AbortSignal.timeout(2e4)}),a=await s.text();if(!s.ok){let i=a;try{let f=JSON.parse(a);i=f.error?.message??f.message??f.error??a}catch{}throw s.status===404&&/Requested function was not found/i.test(String(i))?new Error(`${e} isn't deployed on ${new URL(vt(e,t)).host}: this server doesn't have that feature yet (an older server, or a staging/production mismatch)`):new Error(`${n.method??"GET"} ${t}: ${s.status} ${i}`)}return a?JSON.parse(a):{}}function ke(e,t="org"){let n=`/v1/sessions/${e}/storage/multipart`,r=(o,s,a)=>dt("v1-sessions",o,{body:s,method:a});return{start:async o=>String((await r(`${n}/start`,{key:o,content_type:"application/x-iso9660-image"})).upload_id),partUrls:async(o,s,a,i)=>(await r(`${n}/${s}/part-urls`,{key:o,first_part:a,count:i})).parts,copyPart:async(o,s,a,i)=>String((await r(`${n}/${s}/copy-part`,{key:o,part_number:a,source_ref:{scheme:t,bucket:"i2o",key:i.key},byte_range:{offset:i.offset,length:i.length}})).etag),complete:async(o,s,a)=>{await r(`${n}/${s}/complete`,{key:o,parts:a})},abort:async(o,s)=>{await r(`${n}/${encodeURIComponent(s)}?key=${encodeURIComponent(o)}`,void 0,"DELETE")},readUrl:async o=>String((await r(`/v1/sessions/${e}/download-url`,{storage_path:o})).download_url)}}async function ut(e,t,n=4){for(let r=1;;r++)try{return await t()}catch(o){if(r>=n)throw new Error(`${e} failed after ${n} tries: ${o instanceof Error?o.message:o}`);await new Promise(s=>setTimeout(s,500*2**r))}}async function Te(e,t,n,r,o={}){let s=o.fetchFn??fetch,a=await e.start(t),i=n.reduce((l,b)=>l+b.len,0),f=new Array(n.length),c=0,u=0,_=new Map,p=async l=>(_.has(l)||(await e.partUrls(t,a,l+1,Math.min(100,n.length-l))).forEach((F,A)=>_.set(l+A,F)),_.get(l)),w=async l=>{let b=n[l];if(b.kind==="copy")f[l]=await ut(`copy piece ${l+1}`,()=>e.copyPart(t,a,l+1,{key:b.key,offset:b.offset,length:b.len}));else{let F=await r(b.at,b.len);f[l]=await ut(`upload piece ${l+1}`,async()=>{let A=await p(l),v=await s(A.upload_url,{method:A.method,headers:A.headers,body:F,signal:o.signal});if(!v.ok)throw _.delete(l),new Error(`${v.status} ${(await v.text()).slice(0,200)}`);let W=v.headers.get("etag");if(!W)throw new Error("the bucket returned no ETag (expose it in the bucket's CORS / response headers)");return W})}c+=b.len,o.onProgress?.(c,i)};try{await Promise.all(Array.from({length:Math.min(6,n.length)},async()=>{for(;u<n.length;)o.signal?.throwIfAborted(),await w(u++)})),await ut("complete",()=>e.complete(t,a,f.map((l,b)=>({part_number:b+1,etag:l}))))}catch(l){throw await e.abort(t,a).catch(()=>{}),l}return{uploaded:n.filter(l=>l.kind==="upload").reduce((l,b)=>l+b.len,0),copied:n.filter(l=>l.kind==="copy").reduce((l,b)=>l+b.len,0),pieces:n.length}}function Fe(e){let t=Zt(e,"r");return{read:async(n,r)=>{let o=new Uint8Array(r);return await(await t).read(o,0,r,n),o},close:async()=>{await(await t).close()}}}var gt="local",kt=/^[A-Za-z0-9_-]{1,64}$/,I=e=>{if(!kt.test(e))throw new j("invalid_args",`bad project_id '${e}'`);return y(R(),"projects",e)},lt=(e,t={})=>dt("v1-projects",e,t),Tt=e=>Number(/: (\d{3}) /.exec(String(e?.message))?.[1]??0);async function Ft(e){let t="",n={base:null,by:null};try{t=await S(y(I(e),"CONTEXT.md"))}catch{}try{n=JSON.parse(await S(y(I(e),"context.json")))}catch{}return{text:t,meta:n}}async function _t(e,t,n){await k(I(e)),await P(y(I(e),"CONTEXT.md"),t),await P(y(I(e),"context.json"),JSON.stringify(n))}var ft=async(e,t)=>(await _t(e,t.context,{base:t.context_updated_at,by:t.context_updated_by_name??null}),{text:t.context,updated_at:t.context_updated_at,updated_by:t.context_updated_by_name??null});async function Me(e){I(e);let t=await Ft(e);if(e===gt)return{text:t.text,updated_at:null,updated_by:null};if(t.meta.pending)try{return await Pt(e,t.text,t.meta.base)}catch(n){if(!(n instanceof j&&n.code==="context_conflict"))return{text:t.text,updated_at:t.meta.base,updated_by:t.meta.by,offline:!0,pending:!0};let r=n.data?.current??{context:"",context_updated_at:null},o=`${r.context.trimEnd()}
|
|
4
4
|
|
|
5
5
|
## Saved offline on this machine (merge into the notes above)
|
|
6
6
|
|
|
@@ -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-E75BCWXY.js";import{
|
|
3
|
+
import{a as E}from"./chunk-E75BCWXY.js";import{V as x,b as y,g,h as f,l as w,m as h,t as p,w as b}from"./chunk-QQBDHVUU.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};
|
|
@@ -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{Rc as d}from"./chunk-
|
|
3
|
+
import{Rc as d}from"./chunk-BZE7IP6U.js";import{C as l,D as p,G as m,ea as f,o as c,z as u}from"./chunk-QQBDHVUU.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};
|