forge-terminal 0.5.7 → 0.5.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +11 -6
  2. package/dist/chunks/{about-credits-4DHA4HMT.js → about-credits-32BUKO4K.js} +1 -1
  3. package/dist/chunks/{args-5CQKOHYO.js → args-ZVZQR23M.js} +1 -1
  4. package/dist/chunks/{boot-XX2TLD3Q.js → boot-2YFTQOMG.js} +1 -1
  5. package/dist/chunks/{chunk-U3D3EU33.js → chunk-3374PCO5.js} +1 -1
  6. package/dist/chunks/{chunk-6FXF6ALB.js → chunk-6KUWZQGG.js} +1 -1
  7. package/dist/chunks/{chunk-GYERZAZU.js → chunk-6MWJO3GB.js} +2 -2
  8. package/dist/chunks/{chunk-RM3XA72H.js → chunk-6PEIZZNE.js} +1 -1
  9. package/dist/chunks/{chunk-JMIKUWLY.js → chunk-7FW7JX74.js} +2 -2
  10. package/dist/chunks/{chunk-NRMLO5TP.js → chunk-7XDMC7FL.js} +1 -1
  11. package/dist/chunks/{chunk-UGYBXR4V.js → chunk-AR3M2PLK.js} +1 -1
  12. package/dist/chunks/{chunk-7MC3LDNP.js → chunk-ASLKQXZ2.js} +1 -1
  13. package/dist/chunks/{chunk-VDQMK2B2.js → chunk-BKLPRILS.js} +1 -1
  14. package/dist/chunks/{chunk-6HQKTDGG.js → chunk-FBVRKMAF.js} +1 -1
  15. package/dist/chunks/{chunk-PUGNBNSV.js → chunk-GHYODKA3.js} +1 -1
  16. package/dist/chunks/{chunk-WMK3IKW6.js → chunk-GVVQP3LF.js} +1 -1
  17. package/dist/chunks/{chunk-RRVD63NF.js → chunk-K253E723.js} +1 -1
  18. package/dist/chunks/chunk-L44NRTP4.js +3 -0
  19. package/dist/chunks/{chunk-L57UZTYE.js → chunk-NDYMC3HY.js} +2 -2
  20. package/dist/chunks/{chunk-MPSLPE4C.js → chunk-OQBIYNGK.js} +1 -1
  21. package/dist/chunks/{chunk-4YK4XWYS.js → chunk-QQV7CCAY.js} +1 -1
  22. package/dist/chunks/{chunk-SUB2JM7G.js → chunk-RCWFUBTG.js} +1 -1
  23. package/dist/chunks/{chunk-P6JX5ZQT.js → chunk-TGC24JEW.js} +1 -1
  24. package/dist/chunks/{chunk-X6PZIFFX.js → chunk-VJMOZPHW.js} +1 -1
  25. package/dist/chunks/chunk-YPAFAG4W.js +6 -0
  26. package/dist/chunks/{chunk-AET63NOB.js → chunk-YRXJDFP3.js} +1 -1
  27. package/dist/chunks/{clip-command-3CMQ6A5D.js → clip-command-MDSM6KJP.js} +1 -1
  28. package/dist/chunks/{colour-VBHJAKAX.js → colour-2MYODUDY.js} +1 -1
  29. package/dist/chunks/{entry-SOHEQPXT.js → entry-BZYPZONY.js} +1 -1
  30. package/dist/chunks/{execute-KTLXJTU2.js → execute-7M6WA4W7.js} +1 -1
  31. package/dist/chunks/{extensions-YF2KGD66.js → extensions-E3OUBT36.js} +1 -1
  32. package/dist/chunks/{extensions-command-VT4M2JQW.js → extensions-command-JZSOQJEV.js} +1 -1
  33. package/dist/chunks/{ffmpeg-Q2WJH2OP.js → ffmpeg-KDZEPLNA.js} +1 -1
  34. package/dist/chunks/{launch-SOQTCV2D.js → launch-VNW4YQ4Z.js} +5 -5
  35. package/dist/chunks/{manager-HBAXHJL4.js → manager-L753MI7U.js} +1 -1
  36. package/dist/chunks/{needed-GMZEKBH4.js → needed-DYERJ72M.js} +1 -1
  37. package/dist/chunks/{own-IICGHC4K.js → own-2QGMHSKL.js} +1 -1
  38. package/dist/chunks/{preset-command-4OVFEH7Y.js → preset-command-UNMXHW5A.js} +1 -1
  39. package/dist/chunks/{registry-TO6HJQJ4.js → registry-RS7LQ3UA.js} +1 -1
  40. package/dist/chunks/server-PIXRL5PA.js +77 -0
  41. package/dist/chunks/{theme-ISNQEBTS.js → theme-P3ZE2ZYB.js} +1 -1
  42. package/dist/chunks/{transcribe-QC2E7ETQ.js → transcribe-KXQXEVBJ.js} +1 -1
  43. package/dist/chunks/transcribe-command-JHWN4RWU.js +3 -0
  44. package/dist/chunks/{update-note-T4LVCD25.js → update-note-CY3LCBCJ.js} +1 -1
  45. package/dist/chunks/{watch-command-EYEZKROF.js → watch-command-QGVXM23I.js} +1 -1
  46. package/dist/index.js +6 -6
  47. package/package.json +3 -7
  48. package/skills/forge/SKILL.md +67 -4
  49. package/dist/chunks/chunk-GBA5DFEO.js +0 -6
  50. package/dist/chunks/server-6275TY3O.js +0 -74
  51. package/dist/chunks/transcribe-command-GAKYFBWQ.js +0 -3
@@ -1,3 +1,3 @@
1
1
  import { createRequire as __forgeCreateRequire } from 'node:module';
2
2
  const require = __forgeCreateRequire(import.meta.url);
3
- import{c as re,g as at,h as ct}from"./chunk-EEQSUBBL.js";import{c as ge,d as ft,f as he,g as pt,k as dt}from"./chunk-MPSLPE4C.js";import{b as st,c as it}from"./chunk-FAUL5L2W.js";import{b as Ue,c as ze,d as qe,f as He,m as tt,n as ot,o as nt,t as rt}from"./chunk-TLHUFIXD.js";import{n as Ge,o as Ve,q as Ke,r as $}from"./chunk-V6GWPR2A.js";import{G as Te,H as Y,I as le,K as Ne,O as Le,X as Je,a as T,ca as oe,ja as We,ka as Ce,ma as C,t as Be,v as ee,x as te}from"./chunk-ZBMJTIYR.js";import{a as Ae}from"./chunk-J7FLFHQJ.js";import{c as B}from"./chunk-VLVNA4T3.js";import{a as S}from"./chunk-H3DIRJFE.js";import{a as Ye,b as ne,c as O,e as Ze,f as Qe,g as Xe,h as je,i as et}from"./chunk-KXKQDFHX.js";import{mkdtemp as Jt,rm as Wt}from"node:fs/promises";import{tmpdir as Ct}from"node:os";import{join as se}from"node:path";var mt=(e,t,o)=>He(e,t,o)===void 0;function ut(e,t,o=Number.POSITIVE_INFINITY,n=[2,4]){return[...n].reverse().find(s=>s<o&&mt(e,t,s))??0}async function Ut(e,t,o){if(e.op!=="boost"&&e.op!=="remove-background")throw new Error(`the extension engine cannot ${e.op}`);if(o?.aborted)throw o.reason??new Error("aborted");let n=e.sources[0],s=e.outputs[0],r=e.op,{assetFor:i,catalogEntry:a,offeredHere:f}=await import("./catalog-FMHWWMUX.js");if(!f(r,process.platform,process.arch))throw Le(a(r)?.title??r);let{installed:p,extensionsRoot:u}=await import("./paths-6OENILJ4.js"),h=await p(r);if(!h)throw Ne(r);let l=ze(h.version);if(e.op==="boost"){let y=a(r),x=qe(e.scale,h.version,y&&i(y)?.version);if(x)throw x}if(e.op==="boost"&&!mt(n.width,n.height,e.scale))throw Je(n.path,ut(n.width,n.height,Number.POSITIVE_INFINITY,l),e.scale);let{runExtension:w}=await import("./run-GUFPETHF.js"),g=[];n.frames>1&&g.push({code:"animation-flattened",message:`${B(n.path)} has ${n.frames} frames. Only the first frame was used.`});let I=await Jt(se(Ct(),"forge-ext-"));try{t({phase:"decoding"});let y=se(I,"in.png"),x=se(I,"out.png");await nt(n,y);let _=e.op==="boost"?["--in",y,"--out",x,"--scale",String(e.scale),"--cache",se(u(),"boost","cache")]:[y,x],R=e.op==="boost"&&Ue(h.version);await w({...h,serve:R},_,{subject:n.path,what:`${zt(e)} is running on ${B(n.path)}`,onWait:()=>t({phase:"waiting"}),onStart:()=>t({phase:"encoding"}),onProgress:(P,E)=>t({phase:"tiles",done:P,total:E}),...e.op==="boost"?{maxScale:ut(n.width,n.height,e.scale,l)}:{},...o===void 0?{}:{signal:o}});let b=(await ne())(x);S[e.target].hasAlpha||(b=b.flatten({background:e.options.background}));let F=await tt(b,e.target,e.options.quality).toBuffer();t({phase:"writing"});let v=await ot(F,s);return{job:e,outputBytes:v,warnings:g}}catch(y){throw T(y)?y:C(n.path,y)}finally{await Wt(I,{recursive:!0,force:!0}).catch(()=>{})}}function zt(e){return e.op!=="boost"?"Remove background":e.scale===1?"Sharpen":`Boost resolution ${e.scale}\xD7`}var lt={id:"extension",reads:new Set,writes:new Set,ops:new Set(["boost","remove-background"]),probe:()=>Promise.reject(new Error("the extension engine reads no files")),run:Ut};import{randomBytes as mo}from"node:crypto";import{rm as lo,stat as ie}from"node:fs/promises";import{dirname as go,join as ho}from"node:path";import{open as qt}from"node:fs/promises";async function U(e,t){let o=await qt(e,"r");try{let n=Buffer.alloc(t),{bytesRead:s}=await o.read(n,0,t,0);return n.subarray(0,s)}finally{await o.close()}}var we="%NOISE_FLOOR%",Ht=["highpass=f=80",`afftdn=nr=12:nf=${we}`],Gt="highpass=f=80,astats=measure_perchannel=none:measure_overall=RMS_trough";function vt(e){let t=/RMS trough dB:\s*(-?[\d.]+|-?inf)/i.exec(e)?.[1],o=t===void 0?Number.NaN:Number(t);return Number.isFinite(o)?Math.min(-30,Math.max(-70,Math.round(o+8))):-50}var be="%LOUDNORM_MEASURED%",Vt={mp4:"mp4",hevc:"mp4",mov:"mov",webm:"webm",mkv:"matroska",avi:"avi",gif:"gif",mp3:"mp3",m4a:"ipod",opus:"opus",flac:"flac",wav:"wav",aiff:"aiff",ogg:"ogg"},Kt={mp4:["h264","hevc","mpeg4","av1"],mov:["h264","hevc","mpeg4","prores","av1"],mkv:["h264","hevc","mpeg4","vp8","vp9","av1"],hevc:["hevc"],webm:["vp8","vp9","av1"],avi:["mpeg4","h264","mjpeg","msmpeg4v3"]},Yt={mp4:["aac","alac","mp3"],hevc:["aac","alac","mp3"],mov:["aac","alac","mp3","pcm_s16le","pcm_s16be","pcm_s24le"],m4a:["aac","alac"],mkv:["aac","mp3","opus","vorbis","flac","ac3","eac3"],webm:["opus","vorbis"],opus:["opus"],mp3:["mp3"],flac:["flac"],wav:["pcm_s16le"],aiff:["pcm_s16be"],ogg:["vorbis","opus","flac"],avi:["mp3","ac3","aac","pcm_s16le"]},gt=[48e3,24e3,16e3,12e3,8e3];function Zt(e,t,o){let n={encoder:"opus",kbps:96,args:["-strict","-2"],rates:[48e3]};switch(e){case"webm":return o("libopus")?{encoder:"libopus",kbps:96,rates:gt}:o("libvorbis")?{encoder:"libvorbis",kbps:128}:o("opus")?n:{codec:"Opus or Vorbis",encoders:["libopus","libvorbis","opus"],sound:!0};case"opus":return o("libopus")?{encoder:"libopus",kbps:96,rates:gt}:o("opus")?n:{codec:"Opus",encoders:["libopus","opus"]};case"mp3":return o("libmp3lame")?{encoder:"libmp3lame",kbps:128}:{codec:"MP3",encoders:["libmp3lame"]};case"flac":return{encoder:"flac"};case"wav":return{encoder:"pcm_s16le"};case"aiff":return{encoder:"pcm_s16be"};case"ogg":return o("libvorbis")?{encoder:"libvorbis",kbps:128}:{encoder:"vorbis",kbps:128,args:["-strict","-2","-ac","2"]};default:return{encoder:t==="darwin"&&o("aac_at")?"aac_at":"aac",kbps:128}}}var Z=e=>Math.max(2,Math.floor(e/2)*2),Qt=e=>String(Math.round(e*1e3)/1e3),Xt=e=>String(Math.ceil(e*1e3)/1e3),jt=e=>Math.round(38-(e-1)*20/99),eo=e=>Math.round(50-(e-1)*30/99),to=e=>Math.round(40-(e-1)*18/99),ht=e=>Math.round(20+e*60/100),oo=e=>Math.round(31-(e-1)*29/99);function no(e,t){let o=.15*2**((18-e)/6);return Math.max(64,Math.round(t*o/1e3))}function ro(e,t,o,n,s){let r=e.width,i=e.height;if(o)r=o.width,i=o.height;else{t.crop?.box&&(r=t.crop.box.width,i=t.crop.box.height);let a=t.resize;if(a&&"width"in a){let f=Math.min(a.width,r)/r;r*=f,i*=f}else if(a&&"height"in a){let f=Math.min(a.height,i)/i;r*=f,i*=f}else a&&(r*=a.percent/100,i*=a.percent/100)}return r*i*(n??e.fps*s)}var so="zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709,tonemap=tonemap=hable:desat=0,zscale=t=bt709:m=bt709:r=tv,format=yuv420p";function wt(e){let t=[],o=e;for(;o>2;)t.push("atempo=2"),o/=2;for(;o<.5;)t.push("atempo=0.5"),o/=.5;return t.push(`atempo=${Math.round(o*1e3)/1e3}`),t}var io=800,ao=15,bt=32;function ve(e){let{facts:t,options:o,target:n,platform:s}=e,r=o.media??{},i=t.video,a=t.audio,f=S[n].media==="sound",p=n==="gif",u=o.compress!==void 0,h=s==="darwin",l=c=>e.has===void 0||e.has.has(c),w=c=>Ce(n,c,e.os??s),g=r.cut?.start??0,I=Math.min(r.cut?.end??t.duration,t.duration),y=Math.max(0,I-g),x=r.speed??1,_=y/x,R=i!==void 0&&!f,d=a!==void 0&&!r.mute&&!p,b,F,v,P;if(r.targetBytes!==void 0&&_>0){if(R&&i){let c=at({duration:_,width:i.width,height:i.height,fps:i.fps,hasAudio:d,targetBytes:r.targetBytes});"videoKbps"in c&&(b={width:c.width,height:c.height,fps:c.fps},v=c.videoKbps,F=c.audioKbps)}else if(d){let c=Math.floor(r.targetBytes*8/_/1e3*.98);P=Math.max(bt,Math.min(320,c))}}let E=[];if(R&&i){if(i.hdr&&n!=="hevc"&&l("zscale")&&E.push(so),o.crop?.box){let c=o.crop.box;E.push(`crop=${Z(c.width)}:${Z(c.height)}:${c.left}:${c.top}`)}if(b)E.push(`scale=${b.width}:${b.height}`);else if(o.resize){let c=o.resize;"width"in c?E.push(`scale=trunc(min(${Z(c.width)}\\,iw)/2)*2:-2`):"height"in c?E.push(`scale=-2:trunc(min(${Z(c.height)}\\,ih)/2)*2`):E.push(`scale=trunc(iw*${c.percent/100}/2)*2:-2`)}if(o.rotate&&E.push(o.rotate===90?"transpose=1":o.rotate===270?"transpose=2":"hflip,vflip"),x!==1&&E.push(`setpts=PTS/${x}`),p){let c=Math.min(io,Z(i.width));E.push(`fps=${Math.min(ao,i.fps)},scale=${c}:-2:flags=lanczos,split[s0][s1];[s0]palettegen=stats_mode=diff[p];[s1][p]paletteuse=dither=bayer:bayer_scale=4`)}}let D=b?.fps??r.fps,L=R&&i!==void 0&&E.length===0&&D===void 0&&!u&&r.targetBytes===void 0&&(Kt[n]??[]).includes(i.codec),m=[],pe=!1;if(!R)m.push("-vn");else if(L)m.push("-c:v","copy");else{if(E.length&&m.push("-vf",E.join(",")),p)m.push("-c:v","gif","-loop","0");else if(n==="webm"){if(!l("libvpx-vp9"))throw w({codec:"VP9",encoders:["libvpx-vp9"]});if(pe=v!==void 0,m.push("-c:v","libvpx-vp9","-row-mt","1","-deadline","good","-cpu-used","4"),i?.codec==="gif"&&m.push("-pix_fmt","yuva420p"),v!==void 0)m.push("-b:v",`${v}k`);else{let c=u?eo(o.quality??60):33;m.push("-crf",String(c),"-b:v","0")}}else if(n==="hevc"){let c=l("libx265"),k=h&&l("hevc_videotoolbox");if(!c&&!k)throw w({codec:"HEVC",encoders:["libx265",...h?["hevc_videotoolbox"]:[]]});if(v!==void 0)c?m.push("-c:v","libx265","-preset","fast","-b:v",`${v}k`):m.push("-c:v","hevc_videotoolbox","-b:v",`${v}k`);else if(k&&(!u||!c)){let A=u?ht(o.quality??60):60;m.push("-c:v","hevc_videotoolbox","-q:v",String(A))}else{let A=u?to(o.quality??60):26;m.push("-c:v","libx265","-crf",String(A),"-preset","fast")}m.push("-tag:v","hvc1","-pix_fmt",i?.hdr?"p010le":"yuv420p")}else{let c=u?jt(o.quality??60):21,k=()=>`${v??no(c,i?ro(i,o,b,D,x):0)}k`;if(v===void 0&&!u&&h&&l("h264_videotoolbox"))m.push("-c:v","h264_videotoolbox","-q:v","65");else if(l("libx264"))pe=v!==void 0,v!==void 0?m.push("-c:v","libx264","-preset","medium","-b:v",`${v}k`):u?m.push("-c:v","libx264","-preset","medium","-crf",String(c)):m.push("-c:v","libx264","-preset","veryfast","-crf","21");else if(h&&l("h264_videotoolbox"))v!==void 0?m.push("-c:v","h264_videotoolbox","-b:v",k()):m.push("-c:v","h264_videotoolbox","-q:v",String(ht(o.quality??60)));else if(l("libopenh264"))m.push("-c:v","libopenh264","-b:v",k());else if(s==="win32"&&l("h264_mf"))m.push("-c:v","h264_mf","-b:v",k());else if(n==="avi")if(v!==void 0)m.push("-c:v","mpeg4","-b:v",`${v}k`);else{let A=u?oo(o.quality??60):3;m.push("-c:v","mpeg4","-q:v",String(A))}else throw w({codec:"H.264",encoders:["libx264",...h?["h264_videotoolbox"]:[],"libopenh264",...s==="win32"?["h264_mf"]:[]]});m.push("-pix_fmt","yuv420p")}D!==void 0?m.push("-r",String(D)):n==="avi"?m.push("-fps_mode","cfr"):p||m.push("-fps_mode","passthrough")}let $e=r.cleanup?[...Ht]:[],j=[...$e,...x!==1?wt(x):[]],J=r.loudness;J!==void 0&&j.push(`loudnorm=I=${J}:TP=-1.5:LRA=11:${be}:linear=true`);let _e=r.bitrate??F??P,Me=d&&a!==void 0&&j.length===0&&_e===void 0&&!(u&&f)&&(Yt[n]??[]).includes(a.codec),M=[];if(!d)M.push("-an");else if(Me)M.push("-c:a","copy");else{j.length&&M.push("-af",j.join(","));let c=Zt(n,s,l);if("codec"in c)throw w(c);M.push("-c:a",c.encoder);let k=_e??c.kbps;if(k!==void 0&&c.kbps!==void 0&&M.push("-b:a",`${k}k`),c.args&&M.push(...c.args),!c.args?.includes("-ac")&&F!==void 0&&F<=bt&&M.push("-ac","1"),J!==void 0&&a){let A=!c.rates||c.rates.includes(a.sampleRate);M.push("-ar",String(A?a.sampleRate:c.rates?.[0]))}}let de=[];g>0&&de.push("-ss",Xt(g)),r.cut&&de.push("-t",Qt(y));let V=[...de,"-i",e.input],K=[],ue=[...R?["-map","0:v:0"]:[],...d?["-map","0:a:0"]:[]],ke=o.keepMetadata?[]:["-map_metadata","-1"],Lt=Vt[n]??n,Oe=["mp4","hevc","mov","m4a"].includes(n)?["-movflags","+faststart"]:[],De=["-f",Lt,"-y",e.output],me=s==="win32"?"NUL":"/dev/null",W=[];return r.cleanup&&W.push({args:[...V,...K,"-vn","-af",Gt,"-f","null",me],measures:"noise"}),J!==void 0&&W.push({args:[...V,...K,"-vn","-af",`${[...$e,...x!==1?wt(x):[]].map(c=>`${c},`).join("")}loudnorm=I=${J}:TP=-1.5:LRA=11:print_format=json`,"-f","null",me],measures:"loudness",pass:{at:1,of:2}}),pe?(W.push({args:[...V,...K,...ue.slice(0,2),...m,"-pass","1","-passlogfile",e.passlog,"-an","-f","null",me],pass:{at:1,of:2}}),W.push({args:[...V,...K,...ue,...m,"-pass","2","-passlogfile",e.passlog,...M,...ke,...Oe,...De],pass:{at:2,of:2}})):W.push({args:[...V,...K,...ue,...m,...M,...ke,...Oe,...De],...J!==void 0?{pass:{at:2,of:2}}:{}}),{steps:W,duration:_,copies:{video:L,audio:Me},...b?{fitted:b}:{}}}var z=(e,t,o)=>e.subarray(t,t+o).toString("latin1"),co=new Set(["heic","heix","hevc","hevx","heim","heis","mif1","msf1","avif","avis","crx "]),fo=new Set(["M4A ","M4B ","M4P ","F4A ","F4B "]);function po(e){let t=z(e,8,4);if(!co.has(t))return t==="qt "?"mov":fo.has(t)?"m4a":"mp4"}function yt(e){if(e.length<4)return;if(z(e,4,4)==="ftyp")return po(e);if(e[0]===26&&e[1]===69&&e[2]===223&&e[3]===163)return e.includes("webm",0,"latin1")?"webm":"mkv";let t=z(e,0,4);if(t==="RIFF"){let o=z(e,8,4);return o==="WAVE"?"wav":o==="AVI "?"avi":void 0}if(t==="FORM"){let o=z(e,8,4);return o==="AIFF"||o==="AIFC"?"aiff":void 0}if(t==="fLaC")return"flac";if(t==="OggS")return e.includes("OpusHead",0,"latin1")?"opus":"ogg";if(z(e,0,3)==="ID3"||e[0]===255&&((e[1]??0)&224)===224&&((e[1]??0)&6)===2)return"mp3"}var wo=["mp4","mov","webm","mkv","avi","gif"],Pt=["mp4","mov","hevc","webm","mkv","avi","gif","mp3","m4a","wav"],bo=["mp3","m4a","wav","aiff","flac","opus","ogg"],vo=["mp3","m4a","opus","flac","aiff","wav"];function yo(e){return U(e,64)}function xo(e,t){return t&&!t.video&&(e==="mp4"||e==="mov")?"m4a":e}async function Et(e,t){let o=yt(await yo(e));if(!o)throw new Error("not video or sound");if(o!=="mp4"&&o!=="mov"&&S[o].media!==t)throw new Error(`not ${t}`);let n=(await ie(e)).size,s=await ge(),r;if(s){try{r=await he(e,s)}catch(a){throw ee(e,a)}if(r.duration<=0||!r.video&&!r.audio)throw ee(e,r)}let i=xo(o,r);if(S[i].media!==t)throw new Error(`not ${t}`);return{kind:"media",path:e,format:i,bytes:n,...r?{facts:r}:{}}}async function Po(){let{assetFor:e,catalogEntry:t}=await import("./catalog-FMHWWMUX.js"),o=t("video");return o!==void 0&&e(o)!==void 0}async function Eo(e,t){if(e.kind==="media"&&e.facts)return e.facts;try{return await he(e.path,t)}catch(o){throw ee(e.path,o)}}function Fo(e,t){let o=e.options.media??{},n=o.cut?.start??0,s=Math.min(o.cut?.end??t,t);return Math.max(0,s-n)/(o.speed??1)}function Ft(e,t){if(e.op!=="convert")return;let o=e.sources[0],n=o.kind==="media"?o.facts:void 0;if(!n)return;let s=e.options.media??{},r=ct({...n,duration:Fo(e,n.duration)},{soundOnly:S[e.target].media==="sound",mute:s.mute===!0||e.target==="gif"});return t<r?{floor:r}:void 0}function So(e){let t=e.slice(e.lastIndexOf("{"),e.lastIndexOf("}")+1),o=JSON.parse(t);return[`measured_I=${o.input_i}`,`measured_TP=${o.input_tp}`,`measured_LRA=${o.input_lra}`,`measured_thresh=${o.input_thresh}`,`offset=${o.target_offset}`].join(":")}async function xt(e){await Promise.all(e.map(t=>lo(t,{force:!0}).catch(()=>{})))}async function St(e,t,o){if(e.op!=="convert")throw new Error(`media engines only convert, not ${e.op}`);if(o?.aborted)throw o.reason??new Error("aborted");let n=e.sources[0],s=e.outputs[0],r=await ge();if(!r)throw We(n.path,process.platform,await Po());let i=await Eo(n,r),a=mo(6).toString("hex"),f=Ge(s,a),p=ho(go(s),`.forge-pass-${a}`),u=[f,`${p}-0.log`,`${p}-0.log.temp`,`${p}-0.log.mbtree`,`${p}-0.log.mbtree.temp`],h=[],l=(d,b=e.options)=>ve({input:n.path,output:f,target:e.target,facts:i,options:b,platform:d,os:process.platform,passlog:p,...r.has?{has:r.has}:{}}),w=e.options,g=l(process.platform);if(g.duration<=0)throw Te(`The cut keeps nothing of ${B(n.path)}: it starts at or after its end.`,`It is ${re(i.duration)} long.`);await Ve(s);let I=process.platform,y=w.media?.cut;if(g.copies.video&&y&&y.start>0){let d=await pt(n.path,y.start,r);d!==void 0&&y.start-d>.05&&(w={...w,media:{...w.media,cut:{...y,start:d}}},g=l(process.platform,w),h.push({code:"media-cut-keyframe",message:`It starts at ${re(d)}, the keyframe just before ${re(y.start)}.`}))}let x=0,_=async d=>{let b=x,F="",v="";for(let P of d.steps){let E=P.args.map(L=>L.replace(be,F).replace(we,v)),D=await dt(E,{tools:r,signal:o,report:P.measures!==void 0,onTime:L=>t({phase:"time",done:Math.min(L,d.duration),total:d.duration,...P.pass?{pass:{at:b+P.pass.at,of:b+P.pass.of}}:{}})});P.measures==="loudness"&&(F=So(D)),P.measures==="noise"&&(v=String(vt(D)))}x=b+Math.max(0,...d.steps.map(P=>P.pass?.of??0))};try{try{await _(g)}catch(F){if(o?.aborted||!g.steps.some(v=>v.args.some(P=>P.endsWith("_videotoolbox"))))throw F;I="linux",g=l(I,w),x=0,await _(g)}let d=w.media?.targetBytes;for(let F of[.95,.9]){if(d===void 0||(await ie(f)).size<=d)break;w={...w,media:{...w.media,targetBytes:Math.floor(d*F)}},g=l(I,w),await _(g)}let b=(await ie(f)).size;if(d!==void 0&&b>d)throw Be(n,e.options.media?.targetBytes??d,b);if(e.options.compress!==void 0&&b>=n.bytes)throw oe(n.path,n.bytes,b);await Ke(f,s)}catch(d){throw await xt(u),o?.aborted||T(d)?d:C(n.path,d)}await xt(u.slice(1));let R=i.video;if(g.fitted&&R&&(g.fitted.width<R.width-2||g.fitted.fps<R.fps)){let d=Ae(e.options.media?.targetBytes??0);h.push({code:"media-fitted",message:`To fit ${d} it is now ${g.fitted.width}\xD7${g.fitted.height} at ${g.fitted.fps} fps.`})}return{job:e,outputBytes:(await ie(s)).size,warnings:h}}function Zn(e,t){if(e.kind!=="media"||!e.facts)return;let o=ft()?.has;if(o)try{ve({input:e.path,output:e.path,target:t,facts:e.facts,options:{background:"#ffffff",keepMetadata:!1},platform:process.platform,passlog:"",has:o});return}catch(n){return T(n)&&n.code==="encoder-missing"?n:void 0}}var Q=e=>new Set(e);function Io(e){let t=e.kind==="media"?e.facts:void 0,o=e.kind==="image"||t!==void 0&&t.audio===void 0;return Q(Pt.filter(n=>!(o&&S[n].media==="sound"||n==="hevc"&&t?.video?.codec==="hevc")))}var It={id:"video",reads:Q(wo),writes:Q(Pt),ops:new Set(["convert"]),probe:e=>Et(e,"video"),alone:!0,run:St,sizeTo:Ft,writesFor:Io},Rt={id:"sound",reads:Q(bo),writes:Q(vo),ops:new Set(["convert"]),probe:e=>Et(e,"sound"),alone:!0,run:St,sizeTo:Ft};import{readFile as ae,rm as kt,stat as Ro}from"node:fs/promises";function jn(e,t){let o=e.split(",").map(r=>r.trim()).filter(r=>r!=="");if(o.length===0)throw Y(e,"That selects no pages.",t);let n=new Set,s=(r,i)=>{if(!Number.isInteger(r)||r<1||r>t)throw Y(i,`"${i}" is outside 1 and ${t}.`,t);return r};for(let r of o){let i=r.match(/^(\d+)\s*-\s*(\d*)$/);if(i?.[1]!==void 0){let a=s(Number(i[1]),r),f=i[2]===""?t:s(Number(i[2]),r);if(f<a)throw Y(r,`"${r}" ends before it starts.`,t);for(let p=a;p<=f;p++)n.add(p-1);continue}if(!/^\d+$/.test(r))throw Y(r,`"${r}" is not a page number.`,t);n.add(s(Number(r),r)-1)}return[...n].sort((r,i)=>r-i)}function $t(e){return[...new Set(e)].sort((t,o)=>t-o)}function er(e){if(e.length===0)return"";let t=[...new Set(e)].sort((r,i)=>r-i),o=[],n=t[0],s=n;for(let r of t.slice(1)){if(r===s+1){s=r;continue}o.push(n===s?`${n+1}`:`${n+1}-${s+1}`),n=r,s=r}return o.push(n===s?`${n+1}`:`${n+1}-${s+1}`),o.join(", ")}function _t(e,t){let o=[...new Set(e)].sort((r,i)=>r-i).filter(r=>r>=0&&r<t-1),n=[],s=0;for(let r of o)n.push({from:s,to:r}),s=r+1;return n.push({from:s,to:t-1}),n}var xe=Ye(()=>import("./pdf-compress-U2E3CNXG.js")),$o=new Set(["pdf","jpeg","png","webp","avif","gif","tiff"]),_o=new Set(["pdf"]);async function q(e){return(await O()).PDFDocument.load(await ae(e),{ignoreEncryption:!0})}var Mo=1024,Mt=Buffer.from("%PDF-","latin1");async function ko(e){return(await U(e,Mo+Mt.length)).indexOf(Mt)!==-1}async function Oo(e){if(!await ko(e))throw new Error(`${e} is not a PDF`);let{surveyDocument:t}=await xe(),o=await q(e),{size:n}=await Ro(e);return{kind:"document",path:e,format:"pdf",bytes:n,pages:o.getPageCount(),encrypted:o.isEncrypted,images:t(o)}}function H(e){for(let t of e)if(t.encrypted)throw te(t.path)}async function Do(e,t,o){let n=await ne(),s=t.format==="jpeg"||t.format==="png",r=s?(await n(o).metadata()).orientation:void 0;if(s&&(r===void 0||r===1))return t.format==="jpeg"?e.embedJpg(o):e.embedPng(o);if(t.format==="jpeg"){let i=await n(o).rotate().jpeg({quality:S.jpeg.defaultQuality,mozjpeg:!0}).toBuffer();return e.embedJpg(i)}return e.embedPng(await n(o).rotate().png().toBuffer())}async function Ao(e,t){let o=e.sources[0];if(o.kind!=="image")throw new Error("the pdf engine cannot embed a document source");let n=[];o.frames>1&&n.push({code:"animation-flattened",message:`${B(o.path)} has ${o.frames} frames, and ${S.pdf.label} cannot animate. Only the first frame was converted.`}),t({phase:"reading"});let s=await ae(o.path);t({phase:"encoding"});let i=await(await O()).PDFDocument.create(),a=await Do(i,o,s);i.addPage([a.width,a.height]).drawImage(a,{x:0,y:0,width:a.width,height:a.height}),t({phase:"writing"});let p=await $(e.outputs[0],await i.save());return{job:e,outputBytes:p,warnings:n}}async function Bo(e,t){H(e.sources.filter(i=>i.kind==="document"));let n=await(await O()).PDFDocument.create();for(let i of e.sources){t({phase:"reading"});let a=await q(i.path),f=await n.copyPages(a,a.getPageIndices());for(let p of f)n.addPage(p)}t({phase:"writing"});let s=await n.save(),r=await $(e.outputs[0],s);return{job:e,outputBytes:r,warnings:[]}}async function To(e,t){let o=e.sources[0];H([o]);let n=await O();t({phase:"reading"});let s=await q(o.path),r=_t(e.cuts,s.getPageCount()),i=[],a=0;try{for(let[f,p]of r.entries()){let u=await n.PDFDocument.create(),h=Array.from({length:p.to-p.from+1},(g,I)=>p.from+I),l=await u.copyPages(s,h);for(let g of l)u.addPage(g);let w=e.outputs[f];if(w===void 0)throw new Error(`split produced ${r.length} parts but was given ${e.outputs.length} outputs`);a+=await $(w,await u.save()),i.push(w),t({phase:"page",done:f+1,total:r.length})}}catch(f){throw await Promise.all(i.map(p=>kt(p,{force:!0}))),f}return{job:e,outputBytes:a,warnings:[]}}async function ye(e,t){let n=await(await O()).PDFDocument.create(),s=await n.copyPages(e,t);for(let r of s)n.addPage(r);return n.save()}async function No(e,t){let o=e.sources[0];if(H([o]),e.pages.length===0)throw le("That extract selects no pages.");t({phase:"reading"});let n=await q(o.path),s=$t(e.pages),r=[],i=0;try{if(e.separate)for(let[a,f]of s.entries()){let p=e.outputs[a];i+=await $(p,await ye(n,[f])),r.push(p),t({phase:"page",done:a+1,total:s.length})}else{t({phase:"writing"});let a=e.outputs[0];i=await $(a,await ye(n,s)),r.push(a)}}catch(a){throw await Promise.all(r.map(f=>kt(f,{force:!0}))),a}return{job:e,outputBytes:i,warnings:[]}}async function Lo(e,t){let o=e.sources[0];H([o]),t({phase:"reading"});let n=await q(o.path),s=new Set(e.pages),r=n.getPageIndices().filter(a=>!s.has(a));if(r.length===0)throw le("That would delete every page.");t({phase:"writing"});let i=await $(e.outputs[0],await ye(n,r));return{job:e,outputBytes:i,warnings:[]}}async function Jo(e,t){let o=e.sources[0];H([o]);let n=await O();t({phase:"reading"});let s=await q(o.path);for(let i of s.getPages()){let f=((i.getRotation().angle+e.turns*90)%360+360)%360;i.setRotation(n.degrees(f))}t({phase:"writing"});let r=await $(e.outputs[0],await s.save());return{job:e,outputBytes:r,warnings:[]}}async function Wo(e,t){let o=e.sources[0];H([o]);let{compressPdf:n}=await xe();t({phase:"reading"});let s=await ae(o.path);t({phase:"encoding"});let{bytes:r,recompressed:i,skipped:a,fromDpi:f,toDpi:p}=await n(s,{quality:e.options.quality??60,dpi:e.options.dpi??150});if(e.options.compress&&r.length>=o.bytes)throw oe(o.path,o.bytes,r.length);t({phase:"writing"});let u=await $(e.outputs[0],r),h=w=>w===1?"":"s",l=[];return i===0&&a===0?l.push({code:"pdf-no-images",message:"This PDF has no images to re-encode, so its size is almost unchanged."}):i===0?l.push({code:"pdf-no-images",message:`None of its ${a} image${h(a)} could be re-encoded \u2014 they are not JPEG data.`}):a>0&&l.push({code:"pdf-images-skipped",message:`${i} image${h(i)} recompressed, ${a} skipped (not JPEG).`}),f!==void 0&&p!==void 0&&l.push({code:"pdf-downsampled",message:`Images reduced from ${f} to ${p} dpi. Pass --dpi ${f} to keep them.`}),{job:e,outputBytes:u,warnings:l}}async function Co(e){if(e.op!=="convert")return;let t=e.sources[0];if(t.kind!=="document")return;let{compressPdf:o}=await xe(),n=await ae(t.path);return{ladder:[e.options.dpi??150,120,96,72].map(s=>({dpi:s})),measure:async s=>(await o(n,{quality:s.quality??60,...s.dpi===void 0?{}:{dpi:s.dpi}})).bytes.byteLength}}var Ot={id:"pdf",measurer:Co,reads:$o,writes:_o,ops:new Set(["convert","merge","split","extract","delete","rotate"]),probe:Oo,async run(e,t){switch(e.op){case"convert":if(e.target!=="pdf")throw new Error("the pdf engine only converts to pdf");return e.sources[0].kind==="document"?Wo(e,t):Ao(e,t);case"merge":return Bo(e,t);case"split":return To(e,t);case"extract":return No(e,t);case"delete":return Lo(e,t);case"rotate":return Jo(e,t);default:throw new Error(`the pdf engine cannot ${e.op}`)}}};import{execFile as Uo}from"node:child_process";import{mkdtemp as zo,readFile as Ie,rm as qo}from"node:fs/promises";import{tmpdir as Ho}from"node:os";import{basename as Go,extname as Vo,join as Dt,win32 as Fe}from"node:path";import{pathToFileURL as Ko}from"node:url";import{promisify as Yo}from"node:util";var Se=Yo(Uo),G=Buffer.from([208,207,17,224,161,177,26,225]);async function Zo(e){if(e.length<G.length||!e.subarray(0,G.length).equals(G))return!1;let t=await je();try{return t.find(t.parse(e),"WordDocument")!==null}catch{return!1}}async function Qo(e){let t=await Xe();try{let o=new t(e);if(!o.getEntry("word/document.xml"))return;let n=0,s=o.getEntry("docProps/app.xml");if(s){let r=/<Pages>(\d+)<\/Pages>/.exec(o.readAsText(s));r?.[1]&&(n=Number(r[1]))}return{pages:n}}catch{return}}var At=Buffer.from([80,75,3,4]);async function Xo(e){let t=await U(e,G.length);return t.subarray(0,At.length).equals(At)||t.subarray(0,G.length).equals(G)}async function jo(e){if(!await Xo(e))throw new Error(`${e} is not a Word document`);let t=await Ie(e),o=await Qo(t);if(o)return{kind:"document",path:e,format:"docx",bytes:t.byteLength,pages:o.pages,encrypted:!1};if(await Zo(t))return{kind:"document",path:e,format:"doc",bytes:t.byteLength,pages:0,encrypted:!1};throw new Error(`${e} is not a Word document`)}function en(e,t){return e==="win32"?[Fe.join(t.ProgramFiles??"C:\\Program Files","LibreOffice","program","soffice.exe"),Fe.join(t["ProgramFiles(x86)"]??"C:\\Program Files (x86)","LibreOffice","program","soffice.exe")]:["/Applications/LibreOffice.app/Contents/MacOS/soffice"]}var tn=0;async function on(){tn++;try{return await Se("soffice",["--version"],{timeout:5e3}),"soffice"}catch{}for(let e of en(process.platform,process.env))try{return await Se(e,["--version"],{timeout:5e3}),e}catch{}}var Bt,nn=!1,rn;async function sn(){return nn?rn:(Bt??=on(),Bt)}var Re="\f";function ce(e){return e.split(/\r?\n/).map(t=>t.trim()).filter(t=>t.length>0)}async function an(e){if(e.format==="docx"){let o=await Ze(),{value:n}=await o.extractRawText({path:e.path});return ce(n)}if(e.format==="doc"){let o=await Qe(),s=await new o().extract(e.path);return ce(s.getBody())}return(await st(await Ie(e.path))).flatMap((o,n)=>n===0?ce(o):[Re,...ce(o)])}var Pe=612,fe=792,N=54,Ee=11,Tt=14;async function cn(e){let{PDFDocument:t,StandardFonts:o}=await O(),n=await t.create(),s=await n.embedFont(o.Helvetica),r=Pe-N*2,i=n.addPage([Pe,fe]),a=fe-N,f=()=>{i=n.addPage([Pe,fe]),a=fe-N};for(let p of e){if(p===Re){f();continue}let u="";for(let h of p.split(/\s+/).filter(Boolean)){let l=u?`${u} ${h}`:h;u&&s.widthOfTextAtSize(l,Ee)>r?(a<N&&f(),i.drawText(u,{x:N,y:a,size:Ee,font:s}),a-=Tt,u=h):u=l}u&&(a<N&&f(),i.drawText(u,{x:N,y:a,size:Ee,font:s}),a-=Tt)}return n.save()}async function fn(e){let{Document:t,Packer:o,PageBreak:n,Paragraph:s}=await et(),r=e.map(a=>a===Re?new s({children:[new n]}):new s(a)),i=new t({sections:[{children:r}]});return o.toBuffer(i)}var pn=new Set(["docx","doc","pdf"]),dn=new Set(["docx","pdf"]),un=new Set(["convert"]),mn={code:"word-basic-fidelity",message:"Converted with basic formatting only \u2014 tables, images, and complex layouts weren't preserved. Install LibreOffice for full-fidelity conversion: brew install --cask libreoffice"};function ln(e=process.platform){return e==="linux"?{code:"word-basic-fidelity",message:"Converted with basic formatting only \u2014 tables, images, and complex layouts weren't preserved. Install LibreOffice for full-fidelity conversion: sudo apt install libreoffice"}:e!=="win32"?mn:{code:"word-basic-fidelity",message:"Converted with basic formatting only \u2014 tables, images, and complex layouts weren't preserved. Install LibreOffice from libreoffice.org for full-fidelity conversion."}}function gn(e,t,o,n=process.platform){return[`-env:UserInstallation=${n==="win32"?Ko(Fe.join(e,"profile"),{windows:!0}).href:`file://${e}/profile`}`,"--headless","--convert-to",o,"--outdir",e,t]}async function hn(e,t,o){let n=await zo(Dt(Ho(),"forge-word-"));try{await Se(e,gn(n,t,o),{timeout:12e4});let s=Go(t,Vo(t));return await Ie(Dt(n,`${s}.${o}`))}finally{await qo(n,{recursive:!0,force:!0})}}async function wn(e,t){if(e.op!=="convert")throw new Error(`the word engine cannot ${e.op}`);let o=e.sources[0];if(o.kind!=="document")throw new Error("the word engine can only convert a document source");if(o.encrypted)throw te(o.path);t({phase:"reading"});let n=await sn();t({phase:"encoding"});let s=[],r;try{if(n!==void 0)r=await hn(n,o.path,e.target);else{let a=await an(o);r=e.target==="pdf"?await cn(a):await fn(a),s.push(ln())}}catch(a){throw C(o.path,a)}t({phase:"writing"});let i=await $(e.outputs[0],r);return{job:e,outputBytes:i,warnings:s}}var Nt={id:"word",reads:pn,writes:dn,ops:un,probe:jo,run:wn};var X=[rt,It,Rt,Ot,Nt,lt,it];function Mr(e){return X.find(t=>t.reads.has(e))}function kr(e){return X.find(t=>t.writes.has(e))}function Or(e){if(e.op==="convert"){let t=e.sources[0].format;return X.find(o=>o.reads.has(t)&&o.writes.has(e.target))}return X.find(t=>t.ops.has(e.op))}async function Dr(e){let t;for(let o of X)try{return await o.probe(e)}catch(n){T(t)||(t=n)}throw t}export{jn as a,$t as b,er as c,_t as d,Zn as e,X as f,Mr as g,kr as h,Or as i,Dr as j};
3
+ import{c as re,g as at,h as ct}from"./chunk-EEQSUBBL.js";import{c as ge,d as ft,f as he,g as pt,k as dt}from"./chunk-OQBIYNGK.js";import{b as st,c as it}from"./chunk-FAUL5L2W.js";import{b as Ue,c as ze,d as qe,f as He,m as tt,n as ot,o as nt,t as rt}from"./chunk-TLHUFIXD.js";import{n as Ge,o as Ve,q as Ke,r as $}from"./chunk-V6GWPR2A.js";import{G as Te,H as Y,I as le,K as Ne,O as Le,X as Je,a as T,ca as oe,ja as We,ka as Ce,ma as C,t as Be,v as ee,x as te}from"./chunk-ZBMJTIYR.js";import{a as Ae}from"./chunk-J7FLFHQJ.js";import{c as B}from"./chunk-VLVNA4T3.js";import{a as S}from"./chunk-H3DIRJFE.js";import{a as Ye,b as ne,c as O,e as Ze,f as Qe,g as Xe,h as je,i as et}from"./chunk-KXKQDFHX.js";import{mkdtemp as Jt,rm as Wt}from"node:fs/promises";import{tmpdir as Ct}from"node:os";import{join as se}from"node:path";var mt=(e,t,o)=>He(e,t,o)===void 0;function ut(e,t,o=Number.POSITIVE_INFINITY,n=[2,4]){return[...n].reverse().find(s=>s<o&&mt(e,t,s))??0}async function Ut(e,t,o){if(e.op!=="boost"&&e.op!=="remove-background")throw new Error(`the extension engine cannot ${e.op}`);if(o?.aborted)throw o.reason??new Error("aborted");let n=e.sources[0],s=e.outputs[0],r=e.op,{assetFor:i,catalogEntry:a,offeredHere:f}=await import("./catalog-FMHWWMUX.js");if(!f(r,process.platform,process.arch))throw Le(a(r)?.title??r);let{installed:p,extensionsRoot:u}=await import("./paths-6OENILJ4.js"),h=await p(r);if(!h)throw Ne(r);let l=ze(h.version);if(e.op==="boost"){let y=a(r),x=qe(e.scale,h.version,y&&i(y)?.version);if(x)throw x}if(e.op==="boost"&&!mt(n.width,n.height,e.scale))throw Je(n.path,ut(n.width,n.height,Number.POSITIVE_INFINITY,l),e.scale);let{runExtension:w}=await import("./run-GUFPETHF.js"),g=[];n.frames>1&&g.push({code:"animation-flattened",message:`${B(n.path)} has ${n.frames} frames. Only the first frame was used.`});let I=await Jt(se(Ct(),"forge-ext-"));try{t({phase:"decoding"});let y=se(I,"in.png"),x=se(I,"out.png");await nt(n,y);let _=e.op==="boost"?["--in",y,"--out",x,"--scale",String(e.scale),"--cache",se(u(),"boost","cache")]:[y,x],R=e.op==="boost"&&Ue(h.version);await w({...h,serve:R},_,{subject:n.path,what:`${zt(e)} is running on ${B(n.path)}`,onWait:()=>t({phase:"waiting"}),onStart:()=>t({phase:"encoding"}),onProgress:(P,E)=>t({phase:"tiles",done:P,total:E}),...e.op==="boost"?{maxScale:ut(n.width,n.height,e.scale,l)}:{},...o===void 0?{}:{signal:o}});let b=(await ne())(x);S[e.target].hasAlpha||(b=b.flatten({background:e.options.background}));let F=await tt(b,e.target,e.options.quality).toBuffer();t({phase:"writing"});let v=await ot(F,s);return{job:e,outputBytes:v,warnings:g}}catch(y){throw T(y)?y:C(n.path,y)}finally{await Wt(I,{recursive:!0,force:!0}).catch(()=>{})}}function zt(e){return e.op!=="boost"?"Remove background":e.scale===1?"Sharpen":`Boost resolution ${e.scale}\xD7`}var lt={id:"extension",reads:new Set,writes:new Set,ops:new Set(["boost","remove-background"]),probe:()=>Promise.reject(new Error("the extension engine reads no files")),run:Ut};import{randomBytes as mo}from"node:crypto";import{rm as lo,stat as ie}from"node:fs/promises";import{dirname as go,join as ho}from"node:path";import{open as qt}from"node:fs/promises";async function U(e,t){let o=await qt(e,"r");try{let n=Buffer.alloc(t),{bytesRead:s}=await o.read(n,0,t,0);return n.subarray(0,s)}finally{await o.close()}}var we="%NOISE_FLOOR%",Ht=["highpass=f=80",`afftdn=nr=12:nf=${we}`],Gt="highpass=f=80,astats=measure_perchannel=none:measure_overall=RMS_trough";function vt(e){let t=/RMS trough dB:\s*(-?[\d.]+|-?inf)/i.exec(e)?.[1],o=t===void 0?Number.NaN:Number(t);return Number.isFinite(o)?Math.min(-30,Math.max(-70,Math.round(o+8))):-50}var be="%LOUDNORM_MEASURED%",Vt={mp4:"mp4",hevc:"mp4",mov:"mov",webm:"webm",mkv:"matroska",avi:"avi",gif:"gif",mp3:"mp3",m4a:"ipod",opus:"opus",flac:"flac",wav:"wav",aiff:"aiff",ogg:"ogg"},Kt={mp4:["h264","hevc","mpeg4","av1"],mov:["h264","hevc","mpeg4","prores","av1"],mkv:["h264","hevc","mpeg4","vp8","vp9","av1"],hevc:["hevc"],webm:["vp8","vp9","av1"],avi:["mpeg4","h264","mjpeg","msmpeg4v3"]},Yt={mp4:["aac","alac","mp3"],hevc:["aac","alac","mp3"],mov:["aac","alac","mp3","pcm_s16le","pcm_s16be","pcm_s24le"],m4a:["aac","alac"],mkv:["aac","mp3","opus","vorbis","flac","ac3","eac3"],webm:["opus","vorbis"],opus:["opus"],mp3:["mp3"],flac:["flac"],wav:["pcm_s16le"],aiff:["pcm_s16be"],ogg:["vorbis","opus","flac"],avi:["mp3","ac3","aac","pcm_s16le"]},gt=[48e3,24e3,16e3,12e3,8e3];function Zt(e,t,o){let n={encoder:"opus",kbps:96,args:["-strict","-2"],rates:[48e3]};switch(e){case"webm":return o("libopus")?{encoder:"libopus",kbps:96,rates:gt}:o("libvorbis")?{encoder:"libvorbis",kbps:128}:o("opus")?n:{codec:"Opus or Vorbis",encoders:["libopus","libvorbis","opus"],sound:!0};case"opus":return o("libopus")?{encoder:"libopus",kbps:96,rates:gt}:o("opus")?n:{codec:"Opus",encoders:["libopus","opus"]};case"mp3":return o("libmp3lame")?{encoder:"libmp3lame",kbps:128}:{codec:"MP3",encoders:["libmp3lame"]};case"flac":return{encoder:"flac"};case"wav":return{encoder:"pcm_s16le"};case"aiff":return{encoder:"pcm_s16be"};case"ogg":return o("libvorbis")?{encoder:"libvorbis",kbps:128}:{encoder:"vorbis",kbps:128,args:["-strict","-2","-ac","2"]};default:return{encoder:t==="darwin"&&o("aac_at")?"aac_at":"aac",kbps:128}}}var Z=e=>Math.max(2,Math.floor(e/2)*2),Qt=e=>String(Math.round(e*1e3)/1e3),Xt=e=>String(Math.ceil(e*1e3)/1e3),jt=e=>Math.round(38-(e-1)*20/99),eo=e=>Math.round(50-(e-1)*30/99),to=e=>Math.round(40-(e-1)*18/99),ht=e=>Math.round(20+e*60/100),oo=e=>Math.round(31-(e-1)*29/99);function no(e,t){let o=.15*2**((18-e)/6);return Math.max(64,Math.round(t*o/1e3))}function ro(e,t,o,n,s){let r=e.width,i=e.height;if(o)r=o.width,i=o.height;else{t.crop?.box&&(r=t.crop.box.width,i=t.crop.box.height);let a=t.resize;if(a&&"width"in a){let f=Math.min(a.width,r)/r;r*=f,i*=f}else if(a&&"height"in a){let f=Math.min(a.height,i)/i;r*=f,i*=f}else a&&(r*=a.percent/100,i*=a.percent/100)}return r*i*(n??e.fps*s)}var so="zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709,tonemap=tonemap=hable:desat=0,zscale=t=bt709:m=bt709:r=tv,format=yuv420p";function wt(e){let t=[],o=e;for(;o>2;)t.push("atempo=2"),o/=2;for(;o<.5;)t.push("atempo=0.5"),o/=.5;return t.push(`atempo=${Math.round(o*1e3)/1e3}`),t}var io=800,ao=15,bt=32;function ve(e){let{facts:t,options:o,target:n,platform:s}=e,r=o.media??{},i=t.video,a=t.audio,f=S[n].media==="sound",p=n==="gif",u=o.compress!==void 0,h=s==="darwin",l=c=>e.has===void 0||e.has.has(c),w=c=>Ce(n,c,e.os??s),g=r.cut?.start??0,I=Math.min(r.cut?.end??t.duration,t.duration),y=Math.max(0,I-g),x=r.speed??1,_=y/x,R=i!==void 0&&!f,d=a!==void 0&&!r.mute&&!p,b,F,v,P;if(r.targetBytes!==void 0&&_>0){if(R&&i){let c=at({duration:_,width:i.width,height:i.height,fps:i.fps,hasAudio:d,targetBytes:r.targetBytes});"videoKbps"in c&&(b={width:c.width,height:c.height,fps:c.fps},v=c.videoKbps,F=c.audioKbps)}else if(d){let c=Math.floor(r.targetBytes*8/_/1e3*.98);P=Math.max(bt,Math.min(320,c))}}let E=[];if(R&&i){if(i.hdr&&n!=="hevc"&&l("zscale")&&E.push(so),o.crop?.box){let c=o.crop.box;E.push(`crop=${Z(c.width)}:${Z(c.height)}:${c.left}:${c.top}`)}if(b)E.push(`scale=${b.width}:${b.height}`);else if(o.resize){let c=o.resize;"width"in c?E.push(`scale=trunc(min(${Z(c.width)}\\,iw)/2)*2:-2`):"height"in c?E.push(`scale=-2:trunc(min(${Z(c.height)}\\,ih)/2)*2`):E.push(`scale=trunc(iw*${c.percent/100}/2)*2:-2`)}if(o.rotate&&E.push(o.rotate===90?"transpose=1":o.rotate===270?"transpose=2":"hflip,vflip"),x!==1&&E.push(`setpts=PTS/${x}`),p){let c=Math.min(io,Z(i.width));E.push(`fps=${Math.min(ao,i.fps)},scale=${c}:-2:flags=lanczos,split[s0][s1];[s0]palettegen=stats_mode=diff[p];[s1][p]paletteuse=dither=bayer:bayer_scale=4`)}}let D=b?.fps??r.fps,L=R&&i!==void 0&&E.length===0&&D===void 0&&!u&&r.targetBytes===void 0&&(Kt[n]??[]).includes(i.codec),m=[],pe=!1;if(!R)m.push("-vn");else if(L)m.push("-c:v","copy");else{if(E.length&&m.push("-vf",E.join(",")),p)m.push("-c:v","gif","-loop","0");else if(n==="webm"){if(!l("libvpx-vp9"))throw w({codec:"VP9",encoders:["libvpx-vp9"]});if(pe=v!==void 0,m.push("-c:v","libvpx-vp9","-row-mt","1","-deadline","good","-cpu-used","4"),i?.codec==="gif"&&m.push("-pix_fmt","yuva420p"),v!==void 0)m.push("-b:v",`${v}k`);else{let c=u?eo(o.quality??60):33;m.push("-crf",String(c),"-b:v","0")}}else if(n==="hevc"){let c=l("libx265"),k=h&&l("hevc_videotoolbox");if(!c&&!k)throw w({codec:"HEVC",encoders:["libx265",...h?["hevc_videotoolbox"]:[]]});if(v!==void 0)c?m.push("-c:v","libx265","-preset","fast","-b:v",`${v}k`):m.push("-c:v","hevc_videotoolbox","-b:v",`${v}k`);else if(k&&(!u||!c)){let A=u?ht(o.quality??60):60;m.push("-c:v","hevc_videotoolbox","-q:v",String(A))}else{let A=u?to(o.quality??60):26;m.push("-c:v","libx265","-crf",String(A),"-preset","fast")}m.push("-tag:v","hvc1","-pix_fmt",i?.hdr?"p010le":"yuv420p")}else{let c=u?jt(o.quality??60):21,k=()=>`${v??no(c,i?ro(i,o,b,D,x):0)}k`;if(v===void 0&&!u&&h&&l("h264_videotoolbox"))m.push("-c:v","h264_videotoolbox","-q:v","65");else if(l("libx264"))pe=v!==void 0,v!==void 0?m.push("-c:v","libx264","-preset","medium","-b:v",`${v}k`):u?m.push("-c:v","libx264","-preset","medium","-crf",String(c)):m.push("-c:v","libx264","-preset","veryfast","-crf","21");else if(h&&l("h264_videotoolbox"))v!==void 0?m.push("-c:v","h264_videotoolbox","-b:v",k()):m.push("-c:v","h264_videotoolbox","-q:v",String(ht(o.quality??60)));else if(l("libopenh264"))m.push("-c:v","libopenh264","-b:v",k());else if(s==="win32"&&l("h264_mf"))m.push("-c:v","h264_mf","-b:v",k());else if(n==="avi")if(v!==void 0)m.push("-c:v","mpeg4","-b:v",`${v}k`);else{let A=u?oo(o.quality??60):3;m.push("-c:v","mpeg4","-q:v",String(A))}else throw w({codec:"H.264",encoders:["libx264",...h?["h264_videotoolbox"]:[],"libopenh264",...s==="win32"?["h264_mf"]:[]]});m.push("-pix_fmt","yuv420p")}D!==void 0?m.push("-r",String(D)):n==="avi"?m.push("-fps_mode","cfr"):p||m.push("-fps_mode","passthrough")}let $e=r.cleanup?[...Ht]:[],j=[...$e,...x!==1?wt(x):[]],J=r.loudness;J!==void 0&&j.push(`loudnorm=I=${J}:TP=-1.5:LRA=11:${be}:linear=true`);let _e=r.bitrate??F??P,Me=d&&a!==void 0&&j.length===0&&_e===void 0&&!(u&&f)&&(Yt[n]??[]).includes(a.codec),M=[];if(!d)M.push("-an");else if(Me)M.push("-c:a","copy");else{j.length&&M.push("-af",j.join(","));let c=Zt(n,s,l);if("codec"in c)throw w(c);M.push("-c:a",c.encoder);let k=_e??c.kbps;if(k!==void 0&&c.kbps!==void 0&&M.push("-b:a",`${k}k`),c.args&&M.push(...c.args),!c.args?.includes("-ac")&&F!==void 0&&F<=bt&&M.push("-ac","1"),J!==void 0&&a){let A=!c.rates||c.rates.includes(a.sampleRate);M.push("-ar",String(A?a.sampleRate:c.rates?.[0]))}}let de=[];g>0&&de.push("-ss",Xt(g)),r.cut&&de.push("-t",Qt(y));let V=[...de,"-i",e.input],K=[],ue=[...R?["-map","0:v:0"]:[],...d?["-map","0:a:0"]:[]],ke=o.keepMetadata?[]:["-map_metadata","-1"],Lt=Vt[n]??n,Oe=["mp4","hevc","mov","m4a"].includes(n)?["-movflags","+faststart"]:[],De=["-f",Lt,"-y",e.output],me=s==="win32"?"NUL":"/dev/null",W=[];return r.cleanup&&W.push({args:[...V,...K,"-vn","-af",Gt,"-f","null",me],measures:"noise"}),J!==void 0&&W.push({args:[...V,...K,"-vn","-af",`${[...$e,...x!==1?wt(x):[]].map(c=>`${c},`).join("")}loudnorm=I=${J}:TP=-1.5:LRA=11:print_format=json`,"-f","null",me],measures:"loudness",pass:{at:1,of:2}}),pe?(W.push({args:[...V,...K,...ue.slice(0,2),...m,"-pass","1","-passlogfile",e.passlog,"-an","-f","null",me],pass:{at:1,of:2}}),W.push({args:[...V,...K,...ue,...m,"-pass","2","-passlogfile",e.passlog,...M,...ke,...Oe,...De],pass:{at:2,of:2}})):W.push({args:[...V,...K,...ue,...m,...M,...ke,...Oe,...De],...J!==void 0?{pass:{at:2,of:2}}:{}}),{steps:W,duration:_,copies:{video:L,audio:Me},...b?{fitted:b}:{}}}var z=(e,t,o)=>e.subarray(t,t+o).toString("latin1"),co=new Set(["heic","heix","hevc","hevx","heim","heis","mif1","msf1","avif","avis","crx "]),fo=new Set(["M4A ","M4B ","M4P ","F4A ","F4B "]);function po(e){let t=z(e,8,4);if(!co.has(t))return t==="qt "?"mov":fo.has(t)?"m4a":"mp4"}function yt(e){if(e.length<4)return;if(z(e,4,4)==="ftyp")return po(e);if(e[0]===26&&e[1]===69&&e[2]===223&&e[3]===163)return e.includes("webm",0,"latin1")?"webm":"mkv";let t=z(e,0,4);if(t==="RIFF"){let o=z(e,8,4);return o==="WAVE"?"wav":o==="AVI "?"avi":void 0}if(t==="FORM"){let o=z(e,8,4);return o==="AIFF"||o==="AIFC"?"aiff":void 0}if(t==="fLaC")return"flac";if(t==="OggS")return e.includes("OpusHead",0,"latin1")?"opus":"ogg";if(z(e,0,3)==="ID3"||e[0]===255&&((e[1]??0)&224)===224&&((e[1]??0)&6)===2)return"mp3"}var wo=["mp4","mov","webm","mkv","avi","gif"],Pt=["mp4","mov","hevc","webm","mkv","avi","gif","mp3","m4a","wav"],bo=["mp3","m4a","wav","aiff","flac","opus","ogg"],vo=["mp3","m4a","opus","flac","aiff","wav"];function yo(e){return U(e,64)}function xo(e,t){return t&&!t.video&&(e==="mp4"||e==="mov")?"m4a":e}async function Et(e,t){let o=yt(await yo(e));if(!o)throw new Error("not video or sound");if(o!=="mp4"&&o!=="mov"&&S[o].media!==t)throw new Error(`not ${t}`);let n=(await ie(e)).size,s=await ge(),r;if(s){try{r=await he(e,s)}catch(a){throw ee(e,a)}if(r.duration<=0||!r.video&&!r.audio)throw ee(e,r)}let i=xo(o,r);if(S[i].media!==t)throw new Error(`not ${t}`);return{kind:"media",path:e,format:i,bytes:n,...r?{facts:r}:{}}}async function Po(){let{assetFor:e,catalogEntry:t}=await import("./catalog-FMHWWMUX.js"),o=t("video");return o!==void 0&&e(o)!==void 0}async function Eo(e,t){if(e.kind==="media"&&e.facts)return e.facts;try{return await he(e.path,t)}catch(o){throw ee(e.path,o)}}function Fo(e,t){let o=e.options.media??{},n=o.cut?.start??0,s=Math.min(o.cut?.end??t,t);return Math.max(0,s-n)/(o.speed??1)}function Ft(e,t){if(e.op!=="convert")return;let o=e.sources[0],n=o.kind==="media"?o.facts:void 0;if(!n)return;let s=e.options.media??{},r=ct({...n,duration:Fo(e,n.duration)},{soundOnly:S[e.target].media==="sound",mute:s.mute===!0||e.target==="gif"});return t<r?{floor:r}:void 0}function So(e){let t=e.slice(e.lastIndexOf("{"),e.lastIndexOf("}")+1),o=JSON.parse(t);return[`measured_I=${o.input_i}`,`measured_TP=${o.input_tp}`,`measured_LRA=${o.input_lra}`,`measured_thresh=${o.input_thresh}`,`offset=${o.target_offset}`].join(":")}async function xt(e){await Promise.all(e.map(t=>lo(t,{force:!0}).catch(()=>{})))}async function St(e,t,o){if(e.op!=="convert")throw new Error(`media engines only convert, not ${e.op}`);if(o?.aborted)throw o.reason??new Error("aborted");let n=e.sources[0],s=e.outputs[0],r=await ge();if(!r)throw We(n.path,process.platform,await Po());let i=await Eo(n,r),a=mo(6).toString("hex"),f=Ge(s,a),p=ho(go(s),`.forge-pass-${a}`),u=[f,`${p}-0.log`,`${p}-0.log.temp`,`${p}-0.log.mbtree`,`${p}-0.log.mbtree.temp`],h=[],l=(d,b=e.options)=>ve({input:n.path,output:f,target:e.target,facts:i,options:b,platform:d,os:process.platform,passlog:p,...r.has?{has:r.has}:{}}),w=e.options,g=l(process.platform);if(g.duration<=0)throw Te(`The cut keeps nothing of ${B(n.path)}: it starts at or after its end.`,`It is ${re(i.duration)} long.`);await Ve(s);let I=process.platform,y=w.media?.cut;if(g.copies.video&&y&&y.start>0){let d=await pt(n.path,y.start,r);d!==void 0&&y.start-d>.05&&(w={...w,media:{...w.media,cut:{...y,start:d}}},g=l(process.platform,w),h.push({code:"media-cut-keyframe",message:`It starts at ${re(d)}, the keyframe just before ${re(y.start)}.`}))}let x=0,_=async d=>{let b=x,F="",v="";for(let P of d.steps){let E=P.args.map(L=>L.replace(be,F).replace(we,v)),D=await dt(E,{tools:r,signal:o,report:P.measures!==void 0,onTime:L=>t({phase:"time",done:Math.min(L,d.duration),total:d.duration,...P.pass?{pass:{at:b+P.pass.at,of:b+P.pass.of}}:{}})});P.measures==="loudness"&&(F=So(D)),P.measures==="noise"&&(v=String(vt(D)))}x=b+Math.max(0,...d.steps.map(P=>P.pass?.of??0))};try{try{await _(g)}catch(F){if(o?.aborted||!g.steps.some(v=>v.args.some(P=>P.endsWith("_videotoolbox"))))throw F;I="linux",g=l(I,w),x=0,await _(g)}let d=w.media?.targetBytes;for(let F of[.95,.9]){if(d===void 0||(await ie(f)).size<=d)break;w={...w,media:{...w.media,targetBytes:Math.floor(d*F)}},g=l(I,w),await _(g)}let b=(await ie(f)).size;if(d!==void 0&&b>d)throw Be(n,e.options.media?.targetBytes??d,b);if(e.options.compress!==void 0&&b>=n.bytes)throw oe(n.path,n.bytes,b);await Ke(f,s)}catch(d){throw await xt(u),o?.aborted||T(d)?d:C(n.path,d)}await xt(u.slice(1));let R=i.video;if(g.fitted&&R&&(g.fitted.width<R.width-2||g.fitted.fps<R.fps)){let d=Ae(e.options.media?.targetBytes??0);h.push({code:"media-fitted",message:`To fit ${d} it is now ${g.fitted.width}\xD7${g.fitted.height} at ${g.fitted.fps} fps.`})}return{job:e,outputBytes:(await ie(s)).size,warnings:h}}function Zn(e,t){if(e.kind!=="media"||!e.facts)return;let o=ft()?.has;if(o)try{ve({input:e.path,output:e.path,target:t,facts:e.facts,options:{background:"#ffffff",keepMetadata:!1},platform:process.platform,passlog:"",has:o});return}catch(n){return T(n)&&n.code==="encoder-missing"?n:void 0}}var Q=e=>new Set(e);function Io(e){let t=e.kind==="media"?e.facts:void 0,o=e.kind==="image"||t!==void 0&&t.audio===void 0;return Q(Pt.filter(n=>!(o&&S[n].media==="sound"||n==="hevc"&&t?.video?.codec==="hevc")))}var It={id:"video",reads:Q(wo),writes:Q(Pt),ops:new Set(["convert"]),probe:e=>Et(e,"video"),alone:!0,run:St,sizeTo:Ft,writesFor:Io},Rt={id:"sound",reads:Q(bo),writes:Q(vo),ops:new Set(["convert"]),probe:e=>Et(e,"sound"),alone:!0,run:St,sizeTo:Ft};import{readFile as ae,rm as kt,stat as Ro}from"node:fs/promises";function jn(e,t){let o=e.split(",").map(r=>r.trim()).filter(r=>r!=="");if(o.length===0)throw Y(e,"That selects no pages.",t);let n=new Set,s=(r,i)=>{if(!Number.isInteger(r)||r<1||r>t)throw Y(i,`"${i}" is outside 1 and ${t}.`,t);return r};for(let r of o){let i=r.match(/^(\d+)\s*-\s*(\d*)$/);if(i?.[1]!==void 0){let a=s(Number(i[1]),r),f=i[2]===""?t:s(Number(i[2]),r);if(f<a)throw Y(r,`"${r}" ends before it starts.`,t);for(let p=a;p<=f;p++)n.add(p-1);continue}if(!/^\d+$/.test(r))throw Y(r,`"${r}" is not a page number.`,t);n.add(s(Number(r),r)-1)}return[...n].sort((r,i)=>r-i)}function $t(e){return[...new Set(e)].sort((t,o)=>t-o)}function er(e){if(e.length===0)return"";let t=[...new Set(e)].sort((r,i)=>r-i),o=[],n=t[0],s=n;for(let r of t.slice(1)){if(r===s+1){s=r;continue}o.push(n===s?`${n+1}`:`${n+1}-${s+1}`),n=r,s=r}return o.push(n===s?`${n+1}`:`${n+1}-${s+1}`),o.join(", ")}function _t(e,t){let o=[...new Set(e)].sort((r,i)=>r-i).filter(r=>r>=0&&r<t-1),n=[],s=0;for(let r of o)n.push({from:s,to:r}),s=r+1;return n.push({from:s,to:t-1}),n}var xe=Ye(()=>import("./pdf-compress-U2E3CNXG.js")),$o=new Set(["pdf","jpeg","png","webp","avif","gif","tiff"]),_o=new Set(["pdf"]);async function q(e){return(await O()).PDFDocument.load(await ae(e),{ignoreEncryption:!0})}var Mo=1024,Mt=Buffer.from("%PDF-","latin1");async function ko(e){return(await U(e,Mo+Mt.length)).indexOf(Mt)!==-1}async function Oo(e){if(!await ko(e))throw new Error(`${e} is not a PDF`);let{surveyDocument:t}=await xe(),o=await q(e),{size:n}=await Ro(e);return{kind:"document",path:e,format:"pdf",bytes:n,pages:o.getPageCount(),encrypted:o.isEncrypted,images:t(o)}}function H(e){for(let t of e)if(t.encrypted)throw te(t.path)}async function Do(e,t,o){let n=await ne(),s=t.format==="jpeg"||t.format==="png",r=s?(await n(o).metadata()).orientation:void 0;if(s&&(r===void 0||r===1))return t.format==="jpeg"?e.embedJpg(o):e.embedPng(o);if(t.format==="jpeg"){let i=await n(o).rotate().jpeg({quality:S.jpeg.defaultQuality,mozjpeg:!0}).toBuffer();return e.embedJpg(i)}return e.embedPng(await n(o).rotate().png().toBuffer())}async function Ao(e,t){let o=e.sources[0];if(o.kind!=="image")throw new Error("the pdf engine cannot embed a document source");let n=[];o.frames>1&&n.push({code:"animation-flattened",message:`${B(o.path)} has ${o.frames} frames, and ${S.pdf.label} cannot animate. Only the first frame was converted.`}),t({phase:"reading"});let s=await ae(o.path);t({phase:"encoding"});let i=await(await O()).PDFDocument.create(),a=await Do(i,o,s);i.addPage([a.width,a.height]).drawImage(a,{x:0,y:0,width:a.width,height:a.height}),t({phase:"writing"});let p=await $(e.outputs[0],await i.save());return{job:e,outputBytes:p,warnings:n}}async function Bo(e,t){H(e.sources.filter(i=>i.kind==="document"));let n=await(await O()).PDFDocument.create();for(let i of e.sources){t({phase:"reading"});let a=await q(i.path),f=await n.copyPages(a,a.getPageIndices());for(let p of f)n.addPage(p)}t({phase:"writing"});let s=await n.save(),r=await $(e.outputs[0],s);return{job:e,outputBytes:r,warnings:[]}}async function To(e,t){let o=e.sources[0];H([o]);let n=await O();t({phase:"reading"});let s=await q(o.path),r=_t(e.cuts,s.getPageCount()),i=[],a=0;try{for(let[f,p]of r.entries()){let u=await n.PDFDocument.create(),h=Array.from({length:p.to-p.from+1},(g,I)=>p.from+I),l=await u.copyPages(s,h);for(let g of l)u.addPage(g);let w=e.outputs[f];if(w===void 0)throw new Error(`split produced ${r.length} parts but was given ${e.outputs.length} outputs`);a+=await $(w,await u.save()),i.push(w),t({phase:"page",done:f+1,total:r.length})}}catch(f){throw await Promise.all(i.map(p=>kt(p,{force:!0}))),f}return{job:e,outputBytes:a,warnings:[]}}async function ye(e,t){let n=await(await O()).PDFDocument.create(),s=await n.copyPages(e,t);for(let r of s)n.addPage(r);return n.save()}async function No(e,t){let o=e.sources[0];if(H([o]),e.pages.length===0)throw le("That extract selects no pages.");t({phase:"reading"});let n=await q(o.path),s=$t(e.pages),r=[],i=0;try{if(e.separate)for(let[a,f]of s.entries()){let p=e.outputs[a];i+=await $(p,await ye(n,[f])),r.push(p),t({phase:"page",done:a+1,total:s.length})}else{t({phase:"writing"});let a=e.outputs[0];i=await $(a,await ye(n,s)),r.push(a)}}catch(a){throw await Promise.all(r.map(f=>kt(f,{force:!0}))),a}return{job:e,outputBytes:i,warnings:[]}}async function Lo(e,t){let o=e.sources[0];H([o]),t({phase:"reading"});let n=await q(o.path),s=new Set(e.pages),r=n.getPageIndices().filter(a=>!s.has(a));if(r.length===0)throw le("That would delete every page.");t({phase:"writing"});let i=await $(e.outputs[0],await ye(n,r));return{job:e,outputBytes:i,warnings:[]}}async function Jo(e,t){let o=e.sources[0];H([o]);let n=await O();t({phase:"reading"});let s=await q(o.path);for(let i of s.getPages()){let f=((i.getRotation().angle+e.turns*90)%360+360)%360;i.setRotation(n.degrees(f))}t({phase:"writing"});let r=await $(e.outputs[0],await s.save());return{job:e,outputBytes:r,warnings:[]}}async function Wo(e,t){let o=e.sources[0];H([o]);let{compressPdf:n}=await xe();t({phase:"reading"});let s=await ae(o.path);t({phase:"encoding"});let{bytes:r,recompressed:i,skipped:a,fromDpi:f,toDpi:p}=await n(s,{quality:e.options.quality??60,dpi:e.options.dpi??150});if(e.options.compress&&r.length>=o.bytes)throw oe(o.path,o.bytes,r.length);t({phase:"writing"});let u=await $(e.outputs[0],r),h=w=>w===1?"":"s",l=[];return i===0&&a===0?l.push({code:"pdf-no-images",message:"This PDF has no images to re-encode, so its size is almost unchanged."}):i===0?l.push({code:"pdf-no-images",message:`None of its ${a} image${h(a)} could be re-encoded \u2014 they are not JPEG data.`}):a>0&&l.push({code:"pdf-images-skipped",message:`${i} image${h(i)} recompressed, ${a} skipped (not JPEG).`}),f!==void 0&&p!==void 0&&l.push({code:"pdf-downsampled",message:`Images reduced from ${f} to ${p} dpi. Pass --dpi ${f} to keep them.`}),{job:e,outputBytes:u,warnings:l}}async function Co(e){if(e.op!=="convert")return;let t=e.sources[0];if(t.kind!=="document")return;let{compressPdf:o}=await xe(),n=await ae(t.path);return{ladder:[e.options.dpi??150,120,96,72].map(s=>({dpi:s})),measure:async s=>(await o(n,{quality:s.quality??60,...s.dpi===void 0?{}:{dpi:s.dpi}})).bytes.byteLength}}var Ot={id:"pdf",measurer:Co,reads:$o,writes:_o,ops:new Set(["convert","merge","split","extract","delete","rotate"]),probe:Oo,async run(e,t){switch(e.op){case"convert":if(e.target!=="pdf")throw new Error("the pdf engine only converts to pdf");return e.sources[0].kind==="document"?Wo(e,t):Ao(e,t);case"merge":return Bo(e,t);case"split":return To(e,t);case"extract":return No(e,t);case"delete":return Lo(e,t);case"rotate":return Jo(e,t);default:throw new Error(`the pdf engine cannot ${e.op}`)}}};import{execFile as Uo}from"node:child_process";import{mkdtemp as zo,readFile as Ie,rm as qo}from"node:fs/promises";import{tmpdir as Ho}from"node:os";import{basename as Go,extname as Vo,join as Dt,win32 as Fe}from"node:path";import{pathToFileURL as Ko}from"node:url";import{promisify as Yo}from"node:util";var Se=Yo(Uo),G=Buffer.from([208,207,17,224,161,177,26,225]);async function Zo(e){if(e.length<G.length||!e.subarray(0,G.length).equals(G))return!1;let t=await je();try{return t.find(t.parse(e),"WordDocument")!==null}catch{return!1}}async function Qo(e){let t=await Xe();try{let o=new t(e);if(!o.getEntry("word/document.xml"))return;let n=0,s=o.getEntry("docProps/app.xml");if(s){let r=/<Pages>(\d+)<\/Pages>/.exec(o.readAsText(s));r?.[1]&&(n=Number(r[1]))}return{pages:n}}catch{return}}var At=Buffer.from([80,75,3,4]);async function Xo(e){let t=await U(e,G.length);return t.subarray(0,At.length).equals(At)||t.subarray(0,G.length).equals(G)}async function jo(e){if(!await Xo(e))throw new Error(`${e} is not a Word document`);let t=await Ie(e),o=await Qo(t);if(o)return{kind:"document",path:e,format:"docx",bytes:t.byteLength,pages:o.pages,encrypted:!1};if(await Zo(t))return{kind:"document",path:e,format:"doc",bytes:t.byteLength,pages:0,encrypted:!1};throw new Error(`${e} is not a Word document`)}function en(e,t){return e==="win32"?[Fe.join(t.ProgramFiles??"C:\\Program Files","LibreOffice","program","soffice.exe"),Fe.join(t["ProgramFiles(x86)"]??"C:\\Program Files (x86)","LibreOffice","program","soffice.exe")]:["/Applications/LibreOffice.app/Contents/MacOS/soffice"]}var tn=0;async function on(){tn++;try{return await Se("soffice",["--version"],{timeout:5e3}),"soffice"}catch{}for(let e of en(process.platform,process.env))try{return await Se(e,["--version"],{timeout:5e3}),e}catch{}}var Bt,nn=!1,rn;async function sn(){return nn?rn:(Bt??=on(),Bt)}var Re="\f";function ce(e){return e.split(/\r?\n/).map(t=>t.trim()).filter(t=>t.length>0)}async function an(e){if(e.format==="docx"){let o=await Ze(),{value:n}=await o.extractRawText({path:e.path});return ce(n)}if(e.format==="doc"){let o=await Qe(),s=await new o().extract(e.path);return ce(s.getBody())}return(await st(await Ie(e.path))).flatMap((o,n)=>n===0?ce(o):[Re,...ce(o)])}var Pe=612,fe=792,N=54,Ee=11,Tt=14;async function cn(e){let{PDFDocument:t,StandardFonts:o}=await O(),n=await t.create(),s=await n.embedFont(o.Helvetica),r=Pe-N*2,i=n.addPage([Pe,fe]),a=fe-N,f=()=>{i=n.addPage([Pe,fe]),a=fe-N};for(let p of e){if(p===Re){f();continue}let u="";for(let h of p.split(/\s+/).filter(Boolean)){let l=u?`${u} ${h}`:h;u&&s.widthOfTextAtSize(l,Ee)>r?(a<N&&f(),i.drawText(u,{x:N,y:a,size:Ee,font:s}),a-=Tt,u=h):u=l}u&&(a<N&&f(),i.drawText(u,{x:N,y:a,size:Ee,font:s}),a-=Tt)}return n.save()}async function fn(e){let{Document:t,Packer:o,PageBreak:n,Paragraph:s}=await et(),r=e.map(a=>a===Re?new s({children:[new n]}):new s(a)),i=new t({sections:[{children:r}]});return o.toBuffer(i)}var pn=new Set(["docx","doc","pdf"]),dn=new Set(["docx","pdf"]),un=new Set(["convert"]),mn={code:"word-basic-fidelity",message:"Converted with basic formatting only \u2014 tables, images, and complex layouts weren't preserved. Install LibreOffice for full-fidelity conversion: brew install --cask libreoffice"};function ln(e=process.platform){return e==="linux"?{code:"word-basic-fidelity",message:"Converted with basic formatting only \u2014 tables, images, and complex layouts weren't preserved. Install LibreOffice for full-fidelity conversion: sudo apt install libreoffice"}:e!=="win32"?mn:{code:"word-basic-fidelity",message:"Converted with basic formatting only \u2014 tables, images, and complex layouts weren't preserved. Install LibreOffice from libreoffice.org for full-fidelity conversion."}}function gn(e,t,o,n=process.platform){return[`-env:UserInstallation=${n==="win32"?Ko(Fe.join(e,"profile"),{windows:!0}).href:`file://${e}/profile`}`,"--headless","--convert-to",o,"--outdir",e,t]}async function hn(e,t,o){let n=await zo(Dt(Ho(),"forge-word-"));try{await Se(e,gn(n,t,o),{timeout:12e4});let s=Go(t,Vo(t));return await Ie(Dt(n,`${s}.${o}`))}finally{await qo(n,{recursive:!0,force:!0})}}async function wn(e,t){if(e.op!=="convert")throw new Error(`the word engine cannot ${e.op}`);let o=e.sources[0];if(o.kind!=="document")throw new Error("the word engine can only convert a document source");if(o.encrypted)throw te(o.path);t({phase:"reading"});let n=await sn();t({phase:"encoding"});let s=[],r;try{if(n!==void 0)r=await hn(n,o.path,e.target);else{let a=await an(o);r=e.target==="pdf"?await cn(a):await fn(a),s.push(ln())}}catch(a){throw C(o.path,a)}t({phase:"writing"});let i=await $(e.outputs[0],r);return{job:e,outputBytes:i,warnings:s}}var Nt={id:"word",reads:pn,writes:dn,ops:un,probe:jo,run:wn};var X=[rt,It,Rt,Ot,Nt,lt,it];function Mr(e){return X.find(t=>t.reads.has(e))}function kr(e){return X.find(t=>t.writes.has(e))}function Or(e){if(e.op==="convert"){let t=e.sources[0].format;return X.find(o=>o.reads.has(t)&&o.writes.has(e.target))}return X.find(t=>t.ops.has(e.op))}async function Dr(e){let t;for(let o of X)try{return await o.probe(e)}catch(n){T(t)||(t=n)}throw t}export{jn as a,$t as b,er as c,_t as d,Zn as e,X as f,Mr as g,kr as h,Or as i,Dr as j};
@@ -0,0 +1,3 @@
1
+ import { createRequire as __forgeCreateRequire } from 'node:module';
2
+ const require = __forgeCreateRequire(import.meta.url);
3
+ import{l as P}from"./chunk-GVVQP3LF.js";import{c as x,e as k,f as F}from"./chunk-I25E2XDH.js";import{K as E,oa as S,qa as l,x as w}from"./chunk-ZBMJTIYR.js";function R(e){if(e.kind!=="media"){if(e.kind==="image"){let{path:t,format:r,bytes:i,width:n,height:s}=e;return{what:"image",path:t,format:r,bytes:i,width:n,height:s}}if(e.format!=="pdf")throw S(e.path);if(e.encrypted)throw w(e.path);return{what:"pdf",path:e.path,bytes:e.bytes,pages:e.pages}}}import{spawn as T}from"node:child_process";import{mkdtemp as A,rm as _}from"node:fs/promises";import{tmpdir as V}from"node:os";import{join as L}from"node:path";import{createInterface as Y}from"node:readline";var $=[[/private video/i,"This video is private."],[/confirm your age/i,"This video is age-restricted."],[/members-only|join this channel/i,"This video is for channel members only."],[/live event will begin|premieres in/i,"This video has not started yet."],[/unavailable|has been removed|does not exist/i,"This video is unavailable."]],f=class extends Error{};function D(e=process.platform,t=process.arch){let r=k("yt-dlp");return r!==void 0&&F(r,e,t)!==void 0?E("yt-dlp"):l(`YouTube links on ${x(e)} need yt-dlp on your PATH.`,void 0,{hint:"Install yt-dlp (https://github.com/yt-dlp/yt-dlp) and put it on your PATH.",shellHint:"Install yt-dlp and put it on your PATH."})}async function z(e,t={}){let r=await P();if(r===void 0)throw D();let i=await A(L(V(),"forge-yt-"));t.onDir?.(i);let n=()=>_(i,{recursive:!0,force:!0});try{let s;try{s=await I(r.entry,e,i,t)}catch(c){if(!(c instanceof f))throw c;if(r.own)throw l(`yt-dlp could not fetch this video: ${c.message}`,c);await H(r.entry,t.signal);try{s=await I(r.entry,e,i,t)}catch(d){throw d instanceof f?l(`yt-dlp could not fetch this video: ${d.message}`,d):d}}return{...s,dispose:n}}catch(s){throw await n(),s}}function I(e,t,r,i){let{signal:n}=i;if(n?.aborted)return Promise.reject(n.reason??new Error("aborted"));let s=["--js-runtimes",`node:${process.execPath}`,"--no-playlist","--no-warnings","--newline","--progress","-f","bestaudio[ext=m4a]/bestaudio","--print","before_dl:forge-facts %(.{title,uploader,duration,is_live})j","--progress-template","download:forge-bytes %(progress.downloaded_bytes)s %(progress.total_bytes,progress.total_bytes_estimate)s","--print","after_move:forge-file %(filepath)s","--no-simulate","-o",L(r,"sound.%(ext)s"),t];return new Promise((c,d)=>{let u=T(e,s,{stdio:["ignore","pipe","pipe"]}),m,h,b="",y=!1,g=o=>{y||(y=!0,n?.removeEventListener("abort",v),o())},v=()=>{u.kill("SIGKILL"),g(()=>d(n?.reason??new Error("aborted")))};n?.addEventListener("abort",v,{once:!0}),Y({input:u.stdout}).on("line",o=>{if(o.startsWith("forge-facts ")){let a=JSON.parse(o.slice(12));if(a.is_live===!0){u.kill("SIGKILL"),g(()=>d(l("Live streams cannot be transcribed.")));return}m={title:String(a.title??""),uploader:String(a.uploader??""),seconds:Number(a.duration??0)},i.onEvent?.({kind:"facts",facts:m})}else if(o.startsWith("forge-bytes ")){let[a,p]=o.slice(12).split(" ").map(Number);Number.isFinite(a)&&Number.isFinite(p)&&(p??0)>0&&i.onEvent?.({kind:"bytes",done:a,total:p})}else o.startsWith("forge-file ")&&(h=o.slice(11))}),u.stderr.on("data",o=>{b+=o.toString()}),u.on("error",o=>g(()=>d(new f(o.message)))),u.on("close",o=>g(()=>{if(o===0&&m!==void 0&&h!==void 0)return c({path:h,facts:m});let a=b.match(/ERROR: (?:\[[^\]]*\] )?(?:[\w-]+: )?(.*)/)?.[1]?.trim()??"",p=$.find(([N])=>N.test(a));d(p?l(p[1]):new f(a||`yt-dlp exited ${o}`))}))})}function H(e,t){return new Promise((r,i)=>{let n=T(e,["--update"],{stdio:"ignore"}),s=()=>n.kill("SIGKILL");t?.addEventListener("abort",s,{once:!0}),n.on("error",()=>r()),n.on("close",()=>{t?.removeEventListener("abort",s),t?.aborted?i(t.reason??new Error("aborted")):r()})})}export{R as a,D as b,z as c};