forge-terminal 0.4.5 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +110 -19
- package/dist/chunks/{about-credits-TJBWWNH6.js → about-credits-FZ35HUFP.js} +2 -2
- package/dist/chunks/args-FSQFXDIX.js +3 -0
- package/dist/chunks/{available-GYIHVSRX.js → available-TNMISSBA.js} +1 -1
- package/dist/chunks/boot-PCZBPNFR.js +3 -0
- package/dist/chunks/catalog-FMHWWMUX.js +3 -0
- package/dist/chunks/check-B6NP7BEM.js +3 -0
- package/dist/chunks/chunk-2CX33C6H.js +3 -0
- package/dist/chunks/chunk-2J2PTA5O.js +3 -0
- package/dist/chunks/chunk-2MLASXG5.js +3 -0
- package/dist/chunks/{chunk-GKECNCKO.js → chunk-3KWAO2N2.js} +1 -1
- package/dist/chunks/{chunk-EHARO6IS.js → chunk-57M4J2BR.js} +1 -1
- package/dist/chunks/chunk-5TEAR5XH.js +3 -0
- package/dist/chunks/{chunk-A6RK5ALT.js → chunk-63BBFKT2.js} +2 -2
- package/dist/chunks/chunk-63XCSYHM.js +3 -0
- package/dist/chunks/{chunk-JFJ3ZJQL.js → chunk-63ZK5SRQ.js} +1 -1
- package/dist/chunks/chunk-655UG277.js +3 -0
- package/dist/chunks/chunk-72TNSFL5.js +36 -0
- package/dist/chunks/chunk-AYB5AJ4E.js +3 -0
- package/dist/chunks/chunk-BD3OLIVT.js +3 -0
- package/dist/chunks/chunk-C32KGH4S.js +3 -0
- package/dist/chunks/chunk-C4UCCBCX.js +3 -0
- package/dist/chunks/chunk-DZOBIUV6.js +3 -0
- package/dist/chunks/chunk-EKTUUKDP.js +80 -0
- package/dist/chunks/chunk-G46QQBT3.js +3 -0
- package/dist/chunks/{chunk-GJ2GZHRI.js → chunk-GLAD7GP2.js} +1 -1
- package/dist/chunks/chunk-H3DIRJFE.js +3 -0
- package/dist/chunks/chunk-HCLEHCAR.js +3 -0
- package/dist/chunks/chunk-I25E2XDH.js +3 -0
- package/dist/chunks/{chunk-YYB3TTGT.js → chunk-JMBEZPYC.js} +1 -1
- package/dist/chunks/chunk-JOIHR724.js +3 -0
- package/dist/chunks/chunk-KH5DHZ2U.js +8 -0
- package/dist/chunks/chunk-KXKQDFHX.js +3 -0
- package/dist/chunks/chunk-LBDSFSYP.js +3 -0
- package/dist/chunks/{chunk-EX7KZBI6.js → chunk-MF3KKEFB.js} +1 -1
- package/dist/chunks/chunk-MTDCDKPU.js +19 -0
- package/dist/chunks/chunk-N6RCLJE6.js +4 -0
- package/dist/chunks/chunk-N72E43Z3.js +3 -0
- package/dist/chunks/{chunk-DERIWZAT.js → chunk-OY4EGSPE.js} +1 -1
- package/dist/chunks/chunk-Q6KQWJ4J.js +3 -0
- package/dist/chunks/chunk-QXNB5DQ2.js +6 -0
- package/dist/chunks/chunk-S2M4XESA.js +6 -0
- package/dist/chunks/chunk-SK2UZ25Y.js +3 -0
- package/dist/chunks/{chunk-IGF6ZFTM.js → chunk-SZRSAL64.js} +1 -1
- package/dist/chunks/chunk-THDAQBQ3.js +3 -0
- package/dist/chunks/chunk-UXRQ4UBQ.js +66 -0
- package/dist/chunks/chunk-WE6KP4FR.js +3 -0
- package/dist/chunks/chunk-WIPP5TWQ.js +3 -0
- package/dist/chunks/chunk-WZWK3PEZ.js +3 -0
- package/dist/chunks/chunk-X26WUHWB.js +6 -0
- package/dist/chunks/chunk-XURW53YK.js +3 -0
- package/dist/chunks/chunk-YINYF6C7.js +3 -0
- package/dist/chunks/chunk-YNZIN42P.js +63 -0
- package/dist/chunks/chunk-ZRHYGR2L.js +134 -0
- package/dist/chunks/clip-command-NZNC46H2.js +3 -0
- package/dist/chunks/clipboard-GICOXMMN.js +3 -0
- package/dist/chunks/colour-GSDOHCFK.js +3 -0
- package/dist/chunks/command-GYCYLUHN.js +3 -0
- package/dist/chunks/config-command-6YUMMZF3.js +3 -0
- package/dist/chunks/continue-editing-QE5RRIMG.js +3 -0
- package/dist/chunks/decoded-NBZ335RZ.js +3 -0
- package/dist/chunks/entry-2XJD7UCY.js +6 -0
- package/dist/chunks/execute-FYEXZ7EY.js +3 -0
- package/dist/chunks/extensions-V5O4NIHI.js +3 -0
- package/dist/chunks/{extensions-command-ABJSGDPK.js → extensions-command-MGPRISPH.js} +1 -1
- package/dist/chunks/ffmpeg-2UZXAB3C.js +3 -0
- package/dist/chunks/image-3CMUB2P4.js +3 -0
- package/dist/chunks/install-IDUHZTTS.js +3 -0
- package/dist/chunks/{install-V62EEK54.js → install-L5C2UT6M.js} +1 -1
- package/dist/chunks/install-size-PZUFEDGI.js +3 -0
- package/dist/chunks/launch-GUHDBMSJ.js +17 -0
- package/dist/chunks/libs-EK64ACG3.js +3 -0
- package/dist/chunks/lock-UQJ66TZ3.js +3 -0
- package/dist/chunks/manager-UKTMRXKE.js +4 -0
- package/dist/chunks/needed-YEXRZMZX.js +3 -0
- package/dist/chunks/own-WOK6H277.js +3 -0
- package/dist/chunks/{paths-5XI5L4KW.js → paths-6OENILJ4.js} +1 -1
- package/dist/chunks/pdfium-LYHOU6WV.js +3 -0
- package/dist/chunks/preferences-3P4V2EDX.js +3 -0
- package/dist/chunks/preset-command-6A2C6VPQ.js +3 -0
- package/dist/chunks/registry-2YU7NW4P.js +3 -0
- package/dist/chunks/{reveal-L6TBFOMV.js → reveal-D5FCZYOA.js} +1 -1
- package/dist/chunks/run-U2CU6VGE.js +5 -0
- package/dist/chunks/{server-TUWDAECT.js → server-QNWPC2CC.js} +16 -16
- package/dist/chunks/text-layer-LHZNDMPZ.js +3 -0
- package/dist/chunks/{theme-7IVYHKTP.js → theme-EHFY7DT6.js} +1 -1
- package/dist/chunks/transcribe-SCL3LFZU.js +3 -0
- package/dist/chunks/transcribe-command-BX2VVUI3.js +3 -0
- package/dist/chunks/{update-command-GMBG7BK6.js → update-command-JCTCRPCS.js} +1 -1
- package/dist/chunks/update-note-GYJWUDFS.js +3 -0
- package/dist/chunks/watch-command-ZLZAWTNJ.js +3 -0
- package/dist/fonts/NotoSans-Bold.ttf.gz +0 -0
- package/dist/fonts/NotoSans-Regular.ttf.gz +0 -0
- package/dist/fonts/OFL.txt +93 -0
- package/dist/helpers/forge-transcribe +0 -0
- package/dist/helpers/forge-transcribe-whisper.mjs +525 -0
- package/dist/index.js +8 -8
- package/dist/third-party-licenses.txt +99 -1
- package/package.json +21 -14
- package/dist/chunks/args-MGXWV4UD.js +0 -3
- package/dist/chunks/boot-AE6XH7Z3.js +0 -3
- package/dist/chunks/catalog-YSMT3PXT.js +0 -3
- package/dist/chunks/check-KAR72Y4X.js +0 -3
- package/dist/chunks/chunk-3UEQ2OX6.js +0 -3
- package/dist/chunks/chunk-5B5XXH22.js +0 -3
- package/dist/chunks/chunk-5IS7O673.js +0 -6
- package/dist/chunks/chunk-6FUVEO3A.js +0 -78
- package/dist/chunks/chunk-6L6C3GJU.js +0 -3
- package/dist/chunks/chunk-7S5DBC3J.js +0 -66
- package/dist/chunks/chunk-AAXBN572.js +0 -4
- package/dist/chunks/chunk-BZXDNDPG.js +0 -3
- package/dist/chunks/chunk-CEULBUUM.js +0 -63
- package/dist/chunks/chunk-DOWMSJ6R.js +0 -3
- package/dist/chunks/chunk-EXLXSKRH.js +0 -3
- package/dist/chunks/chunk-FH3R2YYD.js +0 -19
- package/dist/chunks/chunk-FWIXOYXE.js +0 -3
- package/dist/chunks/chunk-I63TO22X.js +0 -3
- package/dist/chunks/chunk-IWFVEMDN.js +0 -3
- package/dist/chunks/chunk-JSMGNA55.js +0 -3
- package/dist/chunks/chunk-KAHWYWNT.js +0 -3
- package/dist/chunks/chunk-LDKF7KIZ.js +0 -6
- package/dist/chunks/chunk-LNB5D67B.js +0 -3
- package/dist/chunks/chunk-M66BUNYO.js +0 -3
- package/dist/chunks/chunk-PSEIJXGT.js +0 -3
- package/dist/chunks/chunk-QR6QHTC3.js +0 -3
- package/dist/chunks/chunk-QXTXBMTM.js +0 -3
- package/dist/chunks/chunk-SMBK6BTC.js +0 -3
- package/dist/chunks/chunk-TDW6KQH6.js +0 -3
- package/dist/chunks/chunk-TMQDQLY7.js +0 -21
- package/dist/chunks/chunk-XSOCV3F2.js +0 -3
- package/dist/chunks/chunk-YWKMG5WO.js +0 -3
- package/dist/chunks/clip-command-D3DE2WUR.js +0 -3
- package/dist/chunks/clipboard-CPHPA4FH.js +0 -3
- package/dist/chunks/colour-U6QBTJTQ.js +0 -3
- package/dist/chunks/command-I5M275ZV.js +0 -3
- package/dist/chunks/config-command-TYNYVUMP.js +0 -3
- package/dist/chunks/entry-4GMHXHST.js +0 -6
- package/dist/chunks/execute-D4H7QWGR.js +0 -3
- package/dist/chunks/extensions-DOTV7SIR.js +0 -3
- package/dist/chunks/ffmpeg-PF3VLTHK.js +0 -3
- package/dist/chunks/image-J4FT4ACZ.js +0 -3
- package/dist/chunks/install-2A5BGKQU.js +0 -3
- package/dist/chunks/launch-XVWOLOXM.js +0 -15
- package/dist/chunks/lock-KN7CF4YN.js +0 -3
- package/dist/chunks/manager-TVGSLNBE.js +0 -4
- package/dist/chunks/preferences-4VETUGMN.js +0 -3
- package/dist/chunks/preset-command-HORY7KZQ.js +0 -3
- package/dist/chunks/run-6BK4REXK.js +0 -4
- package/dist/chunks/transcribe-command-YUSBCQEQ.js +0 -3
- package/dist/chunks/update-note-A7C2OJKU.js +0 -3
- package/dist/chunks/watch-command-NOMNFJ75.js +0 -3
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { createRequire as __forgeCreateRequire } from 'node:module';
|
|
2
|
+
const require = __forgeCreateRequire(import.meta.url);
|
|
3
|
+
import{b as d}from"./chunk-H3DIRJFE.js";var m=e=>/^[A-Za-z0-9][A-Za-z0-9-]*$/.test(e),u=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),s=e=>typeof e=="number"&&Number.isInteger(e)&&e>0;function h(e){if(!(!u(e)||Object.keys(e).length!==1)){if(s(e.width))return{width:e.width};if(s(e.height))return{height:e.height};if(s(e.percent))return{percent:e.percent}}}function b(e){if(!u(e))return;let t={};if(e.to!==void 0){if(typeof e.to!="string"||!d(e.to))return;t.to=e.to}if(e.quality!==void 0){if(!s(e.quality)||e.quality>100)return;t.quality=e.quality}if(e.maxBytes!==void 0){if(!s(e.maxBytes))return;t.maxBytes=e.maxBytes}if(e.resize!==void 0){let i=h(e.resize);if(!i)return;t.resize=i}for(let i of["trim","sharpen","removeBackground"])if(e[i]!==void 0){if(typeof e[i]!="boolean")return;t[i]=e[i]}if(e.crop!==void 0){if(!u(e.crop)||!s(e.crop.w)||!s(e.crop.h))return;t.crop={w:e.crop.w,h:e.crop.h}}if(e.boost!==void 0){if(e.boost!==2&&e.boost!==3&&e.boost!==4)return;t.boost=e.boost}if(e.compress!==void 0){if(!u(e.compress)||typeof e.compress.dither!="boolean")return;t.compress={dither:e.compress.dither}}if(e.behind!==void 0){if(e.behind!=="white"&&e.behind!=="black")return;t.behind=e.behind}return t}function z(e){if(!u(e)||typeof e.name!="string"||!m(e.name)||typeof e.saveTo!="string"||e.saveTo.trim()==="")return;let t=b(e.steps);if(t)return{name:e.name,steps:t,saveTo:e.saveTo,...e.quickAction===!0?{quickAction:!0}:{}}}var l={white:"#ffffff",black:"#000000"};function x(e,t){let i=[];e.removeBackground&&i.push({kind:"cutout"}),e.boost?i.push({kind:"boost",scale:e.boost}):e.sharpen&&i.push({kind:"boost",scale:1});let o=[];e.trim&&o.push({kind:"cut",trim:!0}),e.crop&&o.push({kind:"cut",crop:e.crop});let c=e.to??t,n={kind:"encode",target:c};if(e.quality!==void 0&&(n.quality=e.quality),e.maxBytes&&(n.maxBytes=e.maxBytes),(e.compress||e.maxBytes)&&(n.compress=e.compress??{dither:!1}),e.resize&&(n.resize=e.resize),i.length===0){let r=o.pop();r?.kind==="cut"&&(r.trim&&(n.trim=!0),r.crop&&(n.crop=r.crop))}if(n.maxBytes&&(n.trim||n.crop||n.resize)){let{trim:r,crop:a,resize:p}=n;o.push({kind:"cut",...r?{trim:r}:{},...a?{crop:a}:{},...p?{resize:p}:{}}),delete n.trim,delete n.crop,delete n.resize}if(e.removeBackground&&!d(c)?.hasAlpha&&(n.background=l[e.behind??"white"]),o.length===0&&i.length===0&&Object.keys(n).length===2&&e.to===void 0)return[];let f=o.filter(r=>r.kind==="cut"&&r.resize);return[...o.filter(r=>!f.includes(r)),...i,...f,n]}export{m as a,z as b,x as c};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { createRequire as __forgeCreateRequire } from 'node:module';
|
|
2
|
+
const require = __forgeCreateRequire(import.meta.url);
|
|
3
|
+
import{a as l}from"./chunk-J7FLFHQJ.js";import{a as s}from"./chunk-H3DIRJFE.js";import{homedir as $}from"node:os";import{posix as f,win32 as m}from"node:path";var x=/[\u0000-\u001f\u007f-\u009f--]/g;function c(e){return e.replace(x,"?")}function g(e,t,n){let i=n.relative(t,e);if(i==="")return"";if(!(i===".."||i.startsWith(`..${n.sep}`)||n.isAbsolute(i)))return i}function I(e,t={}){return c(y(e,t))}function y(e,t){let n=(t.platform??process.platform)==="win32"?m:f;if(t.cwd!==void 0){let a=g(e,t.cwd,n);if(a!==void 0)return a===""?".":a}let i=g(e,t.home??$(),n);return i!==void 0?i===""?"~":`~${n.sep}${i}`:e}function r(e,t=process.platform){return c((t==="win32"?m:f).basename(e))}import{dirname as F}from"node:path";var o=class extends Error{code;title;detail;short;hint;shellHint;constructor(t){super(`${t.title}: ${t.detail}`,t.cause===void 0?void 0:{cause:t.cause}),this.name="ForgeError",this.code=t.code,this.title=t.title,this.detail=t.detail,this.short=t.short,this.hint=t.hint,this.shellHint=t.shellHint}};function E(e){return e instanceof o}function W(e){return new o({code:"file-not-found",title:"File not found",detail:`${r(e)} could not be found.`,short:`${r(e)} could not be found.`,hint:"Check the filename and try again."})}function D(e){return new o({code:"not-a-file",title:"Not a file",detail:`${r(e)} is not a file.`,short:`${r(e)} is not a file.`,hint:"Point Forge at an image, or at a directory of images."})}function J(e){return new o({code:"permission-denied",title:"Permission denied",detail:`${r(e)} could not be read.`,short:`${r(e)} could not be read.`,hint:"Check the file permissions and try again."})}function M(e){return new o({code:"not-a-directory",title:"Invalid path",detail:`${r(e)} could not be found: part of its path is not a directory.`,short:`part of ${r(e)}'s path is not a folder.`,hint:"Check the path and try again."})}function j(e){return new o({code:"symlink-loop",title:"Too many symbolic links",detail:`${r(e)} could not be resolved: its path contains a symbolic-link loop.`,short:`${r(e)}'s path loops back on itself.`,hint:"Check for a circular symlink somewhere in the path."})}function z(e){return new o({code:"path-too-long",title:"Path too long",detail:`${r(e)}'s path is too long for the filesystem to resolve.`,short:`${r(e)}'s path is too long.`,hint:"Use a shorter path and try again."})}function L(e,t){return new o({code:"unreadable-path",title:"Could not read path",detail:`${r(e)} could not be checked.`,short:`${r(e)} could not be checked.`,hint:"Check the path and try again.",cause:t})}function q(e,t){return new o({code:"unsupported-source",title:"Unsupported file type",detail:`${r(e)} is ${t}, which Forge cannot read.`,short:`${r(e)} is ${t}, which Forge cannot read.`,hint:"Forge 0.1 handles images only."})}function Y(e,t){return new o({code:"unsupported-source",title:"Not an image",detail:`${r(e)} is ${t}, not an image.`,hint:"A palette is taken from a photo, a screenshot or artwork."})}function V(e){return new o({code:"unsupported-source",title:"Nothing to take colours from",detail:`${r(e)} has no visible pixels.`})}function _(e,t=process.platform){if(t!=="darwin"){let n=t==="win32"?"Windows":t==="linux"?"Linux":"this system";return new o({code:"heic-decoder-unavailable",title:"Cannot read HEIC here",detail:`${r(e,t)} is a HEIC photo, which needs Forge's free HEIC extension on ${n}.`,short:"HEIC needs the heic extension.",hint:"Install it with: forge extensions add heic",shellHint:"Open /extensions to install it."})}return new o({code:"heic-decoder-unavailable",title:"Cannot read HEIC here",detail:`${r(e)} is a HEIC photo, which Forge decodes with the macOS sips tool.`,short:"HEIC needs sips, which could not be run.",hint:"sips could not be run. It ships with macOS at /usr/bin/sips."})}function X(e,t=process.platform){if(t!=="darwin"){let n=t==="win32"?"Windows":t==="linux"?"Linux":"this system";return new o({code:"raw-decoder-unavailable",title:"Cannot read RAW here",detail:`${r(e,t)} is a camera RAW photo, which needs Forge's free RAW extension on ${n}.`,short:"RAW needs the raw extension.",hint:"Install it with: forge extensions add raw",shellHint:"Open /extensions to install it."})}return new o({code:"raw-decoder-unavailable",title:"Cannot read RAW here",detail:`${r(e,t)} is a camera RAW photo, which Forge reads with macOS's own RAW support.`,short:"RAW needs sips, which could not be run.",hint:"sips could not be run. It ships with macOS at /usr/bin/sips."})}function B(e){return new o({code:"raw-decoder-unavailable",title:"Cannot read this RAW",detail:`${r(e)} is a camera RAW photo that this Mac cannot read.`,short:"macOS cannot read RAW photos from this camera.",hint:"A newer camera usually needs a newer macOS."})}function G(e,t){let n=r(e.path);if(t!==void 0&&t!==e.format){let i=s[t].label;return s[t].lossy?new o({code:"unsupported-compress",title:"Cannot fit that to a size",detail:`Forge cannot search ${n} \u2192 ${i} toward a size yet.`,hint:"Convert it first, then compress the result with --max-size.",shellHint:"Convert it first, then /compress the result to a size."}):new o({code:"unsupported-compress",title:"Cannot fit that to a size",detail:`${i} is lossless \u2014 there is no quality to trade away, so ${n} cannot be made to fit as ${i}.`,hint:"Drop --max-size, or choose a lossy target. forge --formats lists them.",shellHint:"Choose a lossy target to aim for a size."})}if(e.kind==="document"&&e.format==="pdf"){let i=e.images?.skipped??0;return new o({code:"unsupported-compress",title:"Nothing to compress",detail:i>0?`${n}'s images are a kind Forge cannot re-encode, so there is nothing to make smaller.`:`${n} has no images \u2014 it is text and layout, which compression cannot shrink.`,hint:"Try a page operation such as --extract to keep fewer pages, or --to <format> to turn its pages into images.",shellHint:"Try /pdf to keep fewer pages, or /convert to turn its pages into images."})}return e.kind==="document"?new o({code:"unsupported-compress",title:"Nothing to compress",detail:`${n} is ${s[e.format].label}, which has no images Forge can re-encode.`,hint:`Use --to pdf to change it to PDF instead: forge ${n} --to pdf`,shellHint:"Use /convert to change it to PDF instead."}):new o({code:"unsupported-compress",title:"Nothing to compress",detail:`${n} is ${s[e.format].label}, which is lossless \u2014 there is no quality to trade away.`,hint:"Use --to to change it to a smaller format instead. forge --formats lists them.",shellHint:"Use /convert to change it to a smaller format instead."})}function K(e){let t=r(e.path);return new o({code:"unsupported-pdf",title:"/pdf needs a PDF",detail:`${t} is ${s[e.format].label}, not a PDF.`,hint:"Converting it instead."})}function Q(e,t,n){return new o({code:"unsupported-operation",title:`Cannot ${e} these files`,detail:`Not available for these files: ${t}.`,hint:n??"Page operations work on PDFs: --merge takes two or more, the others take one.",shellHint:n??"Use /pdf with a PDF staged \u2014 two or more for merge."})}function Z(e,t,n){let i=e.kind==="media"?`The smallest ${r(e.path)} can get is ${l(n)}, which is still over ${l(t)}.`:`${r(e.path)} is ${l(n)} even at the lowest quality, which is still over ${l(t)}.`;return new o({code:"target-unreachable",title:"Cannot get that small",detail:i,hint:"Try a larger --max-size, or --to a smaller format.",shellHint:"Try a larger target, or /convert to a smaller format."})}function ee(e,t,n){return new o({code:"unsupported-target",title:`Can't convert ${r(e.path)} to ${t}`,detail:`${r(e.path)} is a ${s[e.format].label} ${e.kind==="image"?"image":"document"}.`,hint:`Available: ${n.join(", ")}`})}function te(e,t){return new o({code:"corrupt-source",title:"Damaged file",detail:`${r(e)} could not be read. It may be damaged, or not a format Forge recognises.`,short:`${r(e)} could not be read.`,hint:"The file may be incomplete or corrupted.",cause:t})}function oe(e,t,n){return new o({code:"corrupt-source",title:`Damaged ${s[t].label}`,detail:`${r(e)} is a ${s[t].label} file, but its content could not be read.`,short:`${r(e)} could not be read.`,hint:"The file may be incomplete or corrupted.",cause:n})}function ne(e,t={}){let n=r(e);return new o({code:"encrypted-source",title:"This PDF is password-protected",detail:`${n} is password-protected.`,short:`${n} is password-protected.`,hint:t.attempted?"That password didn't open it. Check it and try again.":`Convert it to images instead: forge ${n} --to jpeg --password-stdin`})}var p=e=>e==="convert"||e==="boost"||e==="remove-background";function re(e,t="convert"){return new o({code:"output-exists",title:"File already exists",detail:`${r(e)} is already there.`,hint:p(t)?"Pass --force to replace it, or choose a different --output.":"Pass --force to replace it, or move the existing file out of the way.",shellHint:"Run it again and Forge will ask before replacing it."})}function ie(e,t){return new o({code:"output-collision",title:"Two files want the same output",detail:`${r(e[0])} and ${r(e[1])} would both become ${r(t)}.`,hint:"Convert them separately, or use --output to send them to different folders.",shellHint:"Convert them one at a time."})}function ae(e,t){return new o({code:"output-collision",title:"One output, written twice",detail:`${r(e)} would write ${r(t)} twice, and only the second would survive.`,hint:"Every output has to be its own file. Check the selection for a repeated page."})}function se(e,t="convert"){return new o({code:"output-is-input",title:"Output would replace the original",detail:`${r(e)} is both the input and the output.`,hint:p(t)?"Choose a different --output, or pass --force to overwrite in place.":"Move or rename that file first, or pass --force to overwrite it in place.",shellHint:p(t)?"Choose a different folder to save it in.":"Move or rename that file first."})}function v(e,t){return new o({code:"permission-denied",title:"Permission denied",detail:`${r(F(e))} is not a folder you can write to.`,hint:"Choose a different --output, or check the folder permissions.",shellHint:"Choose a different folder, or check its permissions.",cause:t})}var k=new Set(["EACCES","EPERM","EROFS"]);function le(e,t){if(E(t))return t;let n=t?.code;return n!==void 0&&k.has(n)?v(e,t):t}function de(e,t){return new o({code:"output-invalid",title:"Cannot write there",detail:`${e} could not be written to.`,hint:"Check that the path is valid and that you have permission to write to it.",cause:t})}function ue(e){return new o({code:"empty-directory",title:"No images found",detail:`${r(e)} contains no images Forge can convert.`,hint:"Try --recursive to look inside subfolders.",shellHint:"Only files directly inside a folder are read \u2014 drop the files themselves, or the folder that holds them."})}function ce(e,t){return new o({code:"invalid-arguments",title:"Invalid arguments",detail:e,hint:t})}function pe(e,t,n){return new o({code:"invalid-page-range",title:"Page range not understood",detail:t,hint:`This document has ${n} pages. Use numbers and spans, like "3-7, 12, 20-".`})}function he(e){return new o({code:"empty-selection",title:"Nothing to write",detail:e,hint:"Select at least one page to keep."})}function ge(e){return new o({code:"invalid-dpi",title:"Invalid resolution",detail:`${String(e)} is not a resolution Forge can use.`,hint:"Give a number between 36 and 600. The default is 150."})}function fe(e){return new o({code:"extension-missing",title:"Extension not installed",detail:`${e} is an optional extension and is not installed.`,hint:`Install it with: forge extensions add ${e}`,shellHint:"Open /extensions to install it."})}function me(e,t,n,i){return new o({code:"extension-outdated",title:"Extension out of date",detail:`${e} ${n} cannot ${t}; that needs ${i} or later.`,hint:`Update it with: forge extensions add ${e}`,shellHint:"Open /extensions to update it."})}function we(e,t){return new o({code:"extension-corrupt",title:"Extension failed verification",detail:`${e}: ${t}`,hint:`Nothing was installed. Try again with: forge extensions add ${e}`,shellHint:"Nothing was installed. Try again from /extensions."})}function be(e,t,n=process.platform){let i=n==="win32"?"PC":n==="darwin"?"Mac":"computer";return new o({code:"extension-unsupported",title:"Extension not available here",detail:`${e} cannot be installed on this ${i}: ${t}`,hint:"See what is available with: forge extensions",shellHint:"See what is available in /extensions."})}function xe(e,t=process.platform){let n=t==="win32"?"Windows":t==="darwin"?"macOS":t==="linux"?"Linux":"this system";return new o({code:"extension-unsupported",title:"Extension not available here",detail:`${e} is not available on ${n}.`,hint:"See what is available with: forge extensions",shellHint:"See what is available in /extensions."})}function $e(e){return new o({code:"update-unavailable",title:"Cannot update this Forge",detail:`This copy of Forge was not installed with npm i -g, so ${e} cannot be installed over it.`,hint:"npm i -g forge-terminal"})}function ye(e,t=process.platform){return t==="win32"?new o({code:"update-denied",title:"Forge is in use",detail:`npm could not replace Forge's files to update it to ${e}. Windows keeps them locked while Forge runs: close every Forge window, then run the command below. If Node is installed for every user, run it in a terminal opened as administrator.`,short:"Windows locks Forge while it runs: close it, then run this",hint:`npm i -g forge-terminal@${e}`}):new o({code:"update-denied",title:"npm needs permission",detail:`npm needs permission to update Forge to ${e}.`,short:"npm needs permission to update Forge",hint:`sudo npm i -g forge-terminal@${e}`})}function Fe(e,t){return new o({code:"update-failed",title:"Update failed",detail:`npm could not install Forge ${e}: ${t}`,short:"npm could not install the update",hint:`npm i -g forge-terminal@${e}`})}function Ee(){return new o({code:"update-unreachable",title:"Could not check for updates",detail:"The npm registry could not be reached.",short:"could not reach npm",hint:"Check your connection (and HTTPS_PROXY if you use a proxy), then run: forge update",shellHint:"Check your connection, then try again."})}function ve(e,t){return new o({code:"extension-download-failed",title:"Download failed",detail:`${e}: ${t}`,hint:`Check your connection (and HTTPS_PROXY if you use a proxy), then run: forge extensions add ${e}`,shellHint:"Check your connection, then try again from /extensions."})}function ke(e,t){return new o({code:"extension-download-failed",title:"Not enough disk space",detail:`${e}: ${t}`,hint:`Free some disk space, then run: forge extensions add ${e}`,shellHint:"Free some disk space, then try again from /extensions."})}function Ce(e,t,n){let i=t?t.what?`${t.what} (forge, pid ${t.pid})`:`another forge (pid ${t.pid}) is using it`:"another forge is using it";return new o({code:"extension-in-use",title:"Extension in use",detail:`${e} is in use: ${i}.`,hint:n==="remove"?`Wait for that job to finish, then run: forge extensions remove ${e}`:"Wait for that job to finish, then try again.",shellHint:n==="remove"?"It can be removed when that job finishes.":"Try again when that job finishes."})}function Se(e){return new o({code:"no-subject",title:"No subject found",detail:`${r(e)} has no clear subject to cut out.`,hint:"Try a photo where the subject stands apart from the background."})}function Te(e,t,n){return n===1?new o({code:"boost-too-large",title:"Too large to sharpen",detail:`${r(e)} is too large to sharpen.`,hint:"Sharpen works on images up to 16,384 px a side and 100 megapixels."}):new o({code:"boost-too-large",title:"Too large to boost",detail:t>=2?`${r(e)} is too large to boost that far; ${t}x is the most it can take.`:`${r(e)} is already too large to boost.`,hint:t>=2?`Try --boost ${t}.`:"Boost works on images up to 100 megapixels.",shellHint:t>=2?`Choose ${t}x instead.`:void 0})}function Ne(e,t,n,i=process.platform){let a=n===1?"sharpen":"boost",d=i==="win32"?"PC":i==="darwin"?"Mac":"computer",u=Math.max(1,Math.round(t/60));return new o({code:"boost-too-slow",title:`Too slow to ${a}`,detail:`${r(e)} would take about ${u} ${u===1?"minute":"minutes"} to ${a} on this ${d}.`,hint:"Try a smaller photo."})}function Pe(e,t){return new o({code:"resize-too-large",title:"Too large to resize to",detail:`${r(e)} would be ${t.width} \xD7 ${t.height}.`,hint:"Resize works up to 16,384 px a side and 100 megapixels."})}var C={darwin:"\u2303\u21E7\u23184",win32:"Win+Shift+S"};function Ie(e,t=process.platform){let n=C[t];return new o({code:"no-clipboard-image",title:"No image",detail:e==="text"?"The clipboard holds text, not a picture.":"The clipboard is empty.",hint:n===void 0?"Copy a picture or a screenshot, then run forge clip again.":`Copy a picture, or take a screenshot with ${n}, then run forge clip again.`})}function He(e=process.platform){return new o({code:"clipboard-unavailable",title:"No clipboard",detail:e==="linux"?"Forge reads the clipboard of a Wayland or X11 desktop, and not over SSH.":"Forge reads the clipboard on macOS, Windows and Linux, and not over SSH."})}function Re(e){return new o({code:"clipboard-tool-missing",title:`Clipboard needs ${e}`,detail:`Forge reaches the clipboard through ${e}, and it is not on this computer.`,short:`${e} is not on this computer`,hint:`Install it with sudo apt install ${e} (or your distribution's package manager), then try again.`})}function Oe(){return new o({code:"nothing-to-undo",title:"Nothing to undo",detail:"No copied image has been changed yet."})}function Ae(e,t,n,i=!1){let a=r(e);if(i)return new o({code:"cannot-compress-more",title:"Cannot compress more",detail:`${a} is no smaller even at the lowest quality, so nothing was written.`,short:"nothing written"});let d=n>t?`would grow from ${l(t)} to ${l(n)}`:`would stay at ${l(t)}`;return new o({code:"cannot-compress-more",title:"Cannot compress more",detail:`${a} ${d}, so nothing was written.`,short:"nothing written",hint:"Try a lower --quality.",shellHint:"Try a lower quality."})}function Ue(e,t,n){return new o({code:"cannot-compress-more",title:"Already small enough",detail:`${r(e)} is ${l(t)}, already under ${l(n)}, so nothing was written.`,short:"already under that size"})}function We(e){return new o({code:"nothing-to-trim",title:"Nothing to trim",detail:`${r(e)} has no empty edges.`,short:"no empty edges"})}function De(e){return new o({code:"animated-trim",title:"Can't trim an animation",detail:`${r(e)} is animated; trimming works on still images.`})}function Je(e,t){return new o({code:"nothing-to-crop",title:"Nothing to crop",detail:`${r(e)} is already ${t}.`,short:`already ${t}`})}function Me(e){return new o({code:"animated-crop",title:"Can't crop an animation",detail:`${r(e)} is animated; cropping works on still images.`})}function je(e){return new o({code:"animated-rotate",title:"Can't rotate an animation",detail:`${r(e)} is animated; rotating works on still images.`})}function ze(e,t=process.platform,n=!1){let i=h(t),a=n?`forge extensions add video (or ${i})`:t==="linux"?`${i} (or your distribution's package manager)`:i;return new o({code:"ffmpeg-missing",title:"Video and audio need ffmpeg",detail:`${r(e)} is a video or audio file, and ffmpeg is not on this computer.`,short:"ffmpeg is not on this computer",hint:`Install it with ${a}, then run Forge again.`})}function Le(e,t,n=process.platform){let i=s[e].label,a=/^[AEFHILMNORSX]/.test(t.codec)?"an":"a",d=t.encoders,u=d.length>1?`${d.slice(0,-1).join(", ")} or ${d.at(-1)}`:d[0]??"",w=d.length>1?"any of them":"it",b=n==="linux"?"Install a full build of ffmpeg, then run Forge again. On Fedora, RPM Fusion's ffmpeg replaces ffmpeg-free.":n==="win32"?`Install a full build of ffmpeg, such as gyan.dev's (${h(n)}), then run Forge again.`:`Install a full build of ffmpeg (${h(n)}), then run Forge again.`;return new o({code:"encoder-missing",title:`Your ffmpeg can't write ${i}`,detail:`${i} needs ${a} ${t.codec} encoder${t.sound?" for its sound":""}: ${u}. Your ffmpeg was built without ${w}.`,short:`Your ffmpeg has no ${t.codec} encoder`,hint:b})}function h(e=process.platform){return e==="win32"?"winget install ffmpeg":e==="linux"?"sudo apt install ffmpeg":"brew install ffmpeg"}function qe(e,t){return new o({code:"conversion-failed",title:"Conversion failed",detail:`${r(e)} could not be converted.`,hint:"Run again with --debug for the underlying error.",shellHint:"Run the same conversion with forge --debug from the command line to see why.",cause:t})}function Ye(e){return new o({code:"no-sound",title:"Nothing to transcribe",detail:`${r(e)} has no sound.`})}function Ve(e,t=process.platform,n=t==="darwin"?"apple":"whisper"){return n==="whisper"?new o({code:"unsupported-source",title:"Cannot transcribe this file",detail:`${r(e,t)} cannot be read by whisper.`,hint:"Video and sound files can be transcribed."}):new o({code:"unsupported-source",title:"Cannot transcribe this file",detail:`${r(e)} cannot be read by Apple's speech recogniser.`,hint:"MP4, MOV, M4A, MP3, WAV and AIFF can be transcribed; with ffmpeg (brew install ffmpeg), any video or sound file."})}function _e(e,t=process.platform,n=t==="darwin"?"apple":"whisper"){let i=n==="apple"?"Apple's speech recogniser":"The whisper extension";return new o({code:"language-unsupported",title:"Language not supported",detail:`${i} does not support ${e}.`,hint:"Pass another with --language, for example --language en-US."})}function Xe(e,t,n={}){return new o({code:"link-unavailable",title:"Cannot transcribe this link",detail:e,...n,...t===void 0?{}:{cause:t}})}function Be(e){return new o({code:"transcribe-unavailable",title:"Transcribe is not available",detail:e})}function Ge(e=!1){return e?new o({code:"read-unavailable",title:"Reading text is not available",detail:"Reading text needs Forge's free read-text extension.",short:"Needs the read-text extension.",hint:"Install it with: forge extensions add read-text",shellHint:"Open /extensions to install it."}):new o({code:"read-unavailable",title:"Reading text is not available",detail:"Reading text needs macOS 26 or later.",short:"Reading text needs macOS 26 or later."})}function Ke(e){let t=r(e);return new o({code:"no-text",title:"No text found",detail:`No text found in ${t}`,short:`No text found in ${t}`})}function Qe(e){return new o({code:"unexpected",title:"Something went wrong",detail:e instanceof Error?e.message:String(e),hint:"This was not expected. Try again \u2014 if it keeps happening, it may be worth reporting.",cause:e})}function Ze(e,t={}){let n=[`\u2715 ${e.title}`,"",` ${e.detail}`];return e.hint&&n.push("",` ${e.hint}`),t.debug&&e.cause instanceof Error&&n.push("",` ${e.cause.stack??e.cause.message}`),n}export{c as a,I as b,r as c,E as d,W as e,D as f,J as g,M as h,j as i,z as j,L as k,q as l,Y as m,V as n,_ as o,X as p,B as q,G as r,K as s,Q as t,Z as u,ee as v,te as w,oe as x,ne as y,re as z,ie as A,ae as B,se as C,v as D,le as E,de as F,ue as G,ce as H,pe as I,he as J,ge as K,fe as L,me as M,we as N,be as O,xe as P,$e as Q,ye as R,Fe as S,Ee as T,ve as U,ke as V,Ce as W,Se as X,Te as Y,Ne as Z,Pe as _,Ie as $,He as aa,Re as ba,Oe as ca,Ae as da,Ue as ea,We as fa,De as ga,Je as ha,Me as ia,je as ja,ze as ka,Le as la,h as ma,qe as na,Ye as oa,Ve as pa,_e as qa,Xe as ra,Be as sa,Ge as ta,Ke as ua,Qe as va,Ze as wa};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { createRequire as __forgeCreateRequire } from 'node:module';
|
|
2
|
+
const require = __forgeCreateRequire(import.meta.url);
|
|
3
|
+
import{c as te,g as st,h as it}from"./chunk-EEQSUBBL.js";import{c as ue,d as at,f as me,g as ct,k as ft}from"./chunk-QXNB5DQ2.js";import{b as nt,c as rt}from"./chunk-XURW53YK.js";import{b as Ce,c as Ue,e as ze,h as je,i as et,j as tt,o as ot}from"./chunk-2J2PTA5O.js";import{n as qe,o as Ve,q as Ge,r as R}from"./chunk-DZOBIUV6.js";import{H as Te,I as V,J as de,L as Ne,P as Be,Y as Le,c as A,d as T,da as j,ka as Je,la as We,na as J,u as Ae,w as Z,y as X}from"./chunk-WIPP5TWQ.js";import{a as De}from"./chunk-J7FLFHQJ.js";import{a as S}from"./chunk-H3DIRJFE.js";import{a as He,b as ee,c as M,e as Ke,f as Ye,g as Qe,h as Ze,i as Xe}from"./chunk-KXKQDFHX.js";import{mkdtemp as Tt,rm as Nt}from"node:fs/promises";import{tmpdir as Bt}from"node:os";import{join as oe}from"node:path";var dt=(e,t,o)=>ze(e,t,o)===void 0;function pt(e,t,o=Number.POSITIVE_INFINITY,n=[2,4]){return[...n].reverse().find(s=>s<o&&dt(e,t,s))??0}async function Lt(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 Be(a(r)?.title??r);let{installed:p,extensionsRoot:d}=await import("./paths-6OENILJ4.js"),w=await p(r);if(!w)throw Ne(r);let l=Ce(w.version);if(e.op==="boost"){let b=a(r),y=Ue(e.scale,w.version,b&&i(b)?.version);if(y)throw y}if(e.op==="boost"&&!dt(n.width,n.height,e.scale))throw Le(n.path,pt(n.width,n.height,Number.POSITIVE_INFINITY,l),e.scale);let{runExtension:h}=await import("./run-U2CU6VGE.js"),g=[];n.frames>1&&g.push({code:"animation-flattened",message:`${A(n.path)} has ${n.frames} frames. Only the first frame was used.`});let I=await Tt(oe(Bt(),"forge-ext-"));try{t({phase:"decoding"});let b=oe(I,"in.png"),y=oe(I,"out.png");await tt(n,b);let $=e.op==="boost"?["--in",b,"--out",y,"--scale",String(e.scale),"--cache",oe(d(),"boost","cache")]:[b,y];await h(w,$,{subject:n.path,what:`${Jt(e)} is running on ${A(n.path)}`,onWait:()=>t({phase:"waiting"}),onStart:()=>t({phase:"encoding"}),onProgress:(v,O)=>t({phase:"tiles",done:v,total:O}),...e.op==="boost"?{maxScale:pt(n.width,n.height,e.scale,l)}:{},...o===void 0?{}:{signal:o}});let x=(await ee())(y);S[e.target].hasAlpha||(x=x.flatten({background:e.options.background}));let P=await je(x,e.target,e.options.quality).toBuffer();t({phase:"writing"});let E=await et(P,s);return{job:e,outputBytes:E,warnings:g}}catch(b){throw T(b)?b:J(n.path,b)}finally{await Nt(I,{recursive:!0,force:!0}).catch(()=>{})}}function Jt(e){return e.op!=="boost"?"Remove background":e.scale===1?"Sharpen":`Boost resolution ${e.scale}\xD7`}var ut={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:Lt};import{randomBytes as ao}from"node:crypto";import{open as co,rm as fo,stat as ne}from"node:fs/promises";import{dirname as po,join as uo}from"node:path";var le="%NOISE_FLOOR%",Wt=["highpass=f=80",`afftdn=nr=12:nf=${le}`],Ct="highpass=f=80,astats=measure_perchannel=none:measure_overall=RMS_trough";function wt(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 ge="%LOUDNORM_MEASURED%",Ut={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"},zt={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"]},qt={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"]},mt=[48e3,24e3,16e3,12e3,8e3];function Vt(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:mt}: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:mt}: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 G=e=>Math.max(2,Math.floor(e/2)*2),Gt=e=>String(Math.round(e*1e3)/1e3),Ht=e=>String(Math.ceil(e*1e3)/1e3),Kt=e=>Math.round(38-(e-1)*20/99),Yt=e=>Math.round(50-(e-1)*30/99),Qt=e=>Math.round(40-(e-1)*18/99),lt=e=>Math.round(20+e*60/100),Zt=e=>Math.round(31-(e-1)*29/99);function Xt(e,t){let o=.15*2**((18-e)/6);return Math.max(64,Math.round(t*o/1e3))}function jt(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 eo="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 gt(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 to=800,oo=15,ht=32;function he(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",d=o.compress!==void 0,w=s==="darwin",l=c=>e.has===void 0||e.has.has(c),h=c=>We(n,c,e.os??s),g=r.cut?.start??0,I=Math.min(r.cut?.end??t.duration,t.duration),b=Math.max(0,I-g),y=r.speed??1,$=b/y,u=i!==void 0&&!f,x=a!==void 0&&!r.mute&&!p,P,E,v,O;if(r.targetBytes!==void 0&&$>0){if(u&&i){let c=st({duration:$,width:i.width,height:i.height,fps:i.fps,hasAudio:x,targetBytes:r.targetBytes});"videoKbps"in c&&(P={width:c.width,height:c.height,fps:c.fps},v=c.videoKbps,E=c.audioKbps)}else if(x){let c=Math.floor(r.targetBytes*8/$/1e3*.98);O=Math.max(ht,Math.min(320,c))}}let F=[];if(u&&i){if(i.hdr&&n!=="hevc"&&l("zscale")&&F.push(eo),o.crop?.box){let c=o.crop.box;F.push(`crop=${G(c.width)}:${G(c.height)}:${c.left}:${c.top}`)}if(P)F.push(`scale=${P.width}:${P.height}`);else if(o.resize){let c=o.resize;"width"in c?F.push(`scale=trunc(min(${G(c.width)}\\,iw)/2)*2:-2`):"height"in c?F.push(`scale=-2:trunc(min(${G(c.height)}\\,ih)/2)*2`):F.push(`scale=trunc(iw*${c.percent/100}/2)*2:-2`)}if(o.rotate&&F.push(o.rotate===90?"transpose=1":o.rotate===270?"transpose=2":"hflip,vflip"),y!==1&&F.push(`setpts=PTS/${y}`),p){let c=Math.min(to,G(i.width));F.push(`fps=${Math.min(oo,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 Y=P?.fps??r.fps,Ie=u&&i!==void 0&&F.length===0&&Y===void 0&&!d&&r.targetBytes===void 0&&(zt[n]??[]).includes(i.codec),m=[],ae=!1;if(!u)m.push("-vn");else if(Ie)m.push("-c:v","copy");else{if(F.length&&m.push("-vf",F.join(",")),p)m.push("-c:v","gif","-loop","0");else if(n==="webm"){if(!l("libvpx-vp9"))throw h({codec:"VP9",encoders:["libvpx-vp9"]});if(ae=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=d?Yt(o.quality??60):33;m.push("-crf",String(c),"-b:v","0")}}else if(n==="hevc"){let c=l("libx265"),k=w&&l("hevc_videotoolbox");if(!c&&!k)throw h({codec:"HEVC",encoders:["libx265",...w?["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&&(!d||!c)){let D=d?lt(o.quality??60):60;m.push("-c:v","hevc_videotoolbox","-q:v",String(D))}else{let D=d?Qt(o.quality??60):26;m.push("-c:v","libx265","-crf",String(D),"-preset","fast")}m.push("-tag:v","hvc1","-pix_fmt",i?.hdr?"p010le":"yuv420p")}else{let c=d?Kt(o.quality??60):21,k=()=>`${v??Xt(c,i?jt(i,o,P,Y,y):0)}k`;if(v===void 0&&!d&&w&&l("h264_videotoolbox"))m.push("-c:v","h264_videotoolbox","-q:v","65");else if(l("libx264"))ae=v!==void 0,v!==void 0?m.push("-c:v","libx264","-preset","medium","-b:v",`${v}k`):d?m.push("-c:v","libx264","-preset","medium","-crf",String(c)):m.push("-c:v","libx264","-preset","veryfast","-crf","21");else if(w&&l("h264_videotoolbox"))v!==void 0?m.push("-c:v","h264_videotoolbox","-b:v",k()):m.push("-c:v","h264_videotoolbox","-q:v",String(lt(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 D=d?Zt(o.quality??60):3;m.push("-c:v","mpeg4","-q:v",String(D))}else throw h({codec:"H.264",encoders:["libx264",...w?["h264_videotoolbox"]:[],"libopenh264",...s==="win32"?["h264_mf"]:[]]});m.push("-pix_fmt","yuv420p")}Y!==void 0?m.push("-r",String(Y)):n==="avi"?m.push("-fps_mode","cfr"):p||m.push("-fps_mode","passthrough")}let Re=r.cleanup?[...Wt]:[],Q=[...Re,...y!==1?gt(y):[]],B=r.loudness;B!==void 0&&Q.push(`loudnorm=I=${B}:TP=-1.5:LRA=11:${ge}:linear=true`);let $e=r.bitrate??E??O,_e=x&&a!==void 0&&Q.length===0&&$e===void 0&&!(d&&f)&&(qt[n]??[]).includes(a.codec),_=[];if(!x)_.push("-an");else if(_e)_.push("-c:a","copy");else{Q.length&&_.push("-af",Q.join(","));let c=Vt(n,s,l);if("codec"in c)throw h(c);_.push("-c:a",c.encoder);let k=$e??c.kbps;if(k!==void 0&&c.kbps!==void 0&&_.push("-b:a",`${k}k`),c.args&&_.push(...c.args),!c.args?.includes("-ac")&&E!==void 0&&E<=ht&&_.push("-ac","1"),B!==void 0&&a){let D=!c.rates||c.rates.includes(a.sampleRate);_.push("-ar",String(D?a.sampleRate:c.rates?.[0]))}}let ce=[];g>0&&ce.push("-ss",Ht(g)),r.cut&&ce.push("-t",Gt(b));let z=[...ce,"-i",e.input],q=[],fe=[...u?["-map","0:v:0"]:[],...x?["-map","0:a:0"]:[]],ke=o.keepMetadata?[]:["-map_metadata","-1"],At=Ut[n]??n,Me=["mp4","hevc","mov","m4a"].includes(n)?["-movflags","+faststart"]:[],Oe=["-f",At,"-y",e.output],pe=s==="win32"?"NUL":"/dev/null",L=[];return r.cleanup&&L.push({args:[...z,...q,"-vn","-af",Ct,"-f","null",pe],measures:"noise"}),B!==void 0&&L.push({args:[...z,...q,"-vn","-af",`${[...Re,...y!==1?gt(y):[]].map(c=>`${c},`).join("")}loudnorm=I=${B}:TP=-1.5:LRA=11:print_format=json`,"-f","null",pe],measures:"loudness",pass:{at:1,of:2}}),ae?(L.push({args:[...z,...q,...fe.slice(0,2),...m,"-pass","1","-passlogfile",e.passlog,"-an","-f","null",pe],pass:{at:1,of:2}}),L.push({args:[...z,...q,...fe,...m,"-pass","2","-passlogfile",e.passlog,..._,...ke,...Me,...Oe],pass:{at:2,of:2}})):L.push({args:[...z,...q,...fe,...m,..._,...ke,...Me,...Oe],...B!==void 0?{pass:{at:2,of:2}}:{}}),{steps:L,duration:$,copies:{video:Ie,audio:_e},...P?{fitted:P}:{}}}var W=(e,t,o)=>e.subarray(t,t+o).toString("latin1"),no=new Set(["heic","heix","hevc","hevx","heim","heis","mif1","msf1","avif","avis","crx "]),ro=new Set(["M4A ","M4B ","M4P ","F4A ","F4B "]);function so(e){let t=W(e,8,4);if(!no.has(t))return t==="qt "?"mov":ro.has(t)?"m4a":"mp4"}function vt(e){if(e.length<4)return;if(W(e,4,4)==="ftyp")return so(e);if(e[0]===26&&e[1]===69&&e[2]===223&&e[3]===163)return e.includes("webm",0,"latin1")?"webm":"mkv";let t=W(e,0,4);if(t==="RIFF"){let o=W(e,8,4);return o==="WAVE"?"wav":o==="AVI "?"avi":void 0}if(t==="FORM"){let o=W(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(W(e,0,3)==="ID3"||e[0]===255&&((e[1]??0)&224)===224&&((e[1]??0)&6)===2)return"mp3"}var mo=["mp4","mov","webm","mkv","avi","gif"],yt=["mp4","mov","hevc","webm","mkv","avi","gif","mp3","m4a","wav"],lo=["mp3","m4a","wav","aiff","flac","opus","ogg"],go=["mp3","m4a","opus","flac","aiff","wav"];async function ho(e){let t=await co(e,"r");try{let o=Buffer.alloc(64),{bytesRead:n}=await t.read(o,0,o.length,0);return o.subarray(0,n)}finally{await t.close()}}function wo(e,t){return t&&!t.video&&(e==="mp4"||e==="mov")?"m4a":e}async function xt(e,t){let o=vt(await ho(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 ne(e)).size,s=await ue(),r;if(s){try{r=await me(e,s)}catch(a){throw Z(e,a)}if(r.duration<=0||!r.video&&!r.audio)throw Z(e,r)}let i=wo(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 vo(){let{assetFor:e,catalogEntry:t}=await import("./catalog-FMHWWMUX.js"),o=t("video");return o!==void 0&&e(o)!==void 0}async function bo(e,t){if(e.kind==="media"&&e.facts)return e.facts;try{return await me(e.path,t)}catch(o){throw Z(e.path,o)}}function yo(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 Pt(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=it({...n,duration:yo(e,n.duration)},{soundOnly:S[e.target].media==="sound",mute:s.mute===!0||e.target==="gif"});return t<r?{floor:r}:void 0}function xo(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 bt(e){await Promise.all(e.map(t=>fo(t,{force:!0}).catch(()=>{})))}async function Ft(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 ue();if(!r)throw Je(n.path,process.platform,await vo());let i=await bo(n,r),a=ao(6).toString("hex"),f=qe(s,a),p=uo(po(s),`.forge-pass-${a}`),d=[f,`${p}-0.log`,`${p}-0.log.temp`,`${p}-0.log.mbtree`,`${p}-0.log.mbtree.temp`],w=[],l=(u,x=e.options)=>he({input:n.path,output:f,target:e.target,facts:i,options:x,platform:u,os:process.platform,passlog:p,...r.has?{has:r.has}:{}}),h=e.options,g=l(process.platform);if(g.duration<=0)throw Te(`The cut keeps nothing of ${A(n.path)}: it starts at or after its end.`,`It is ${te(i.duration)} long.`);await Ve(s);let I=process.platform,b=h.media?.cut;if(g.copies.video&&b&&b.start>0){let u=await ct(n.path,b.start,r);u!==void 0&&b.start-u>.05&&(h={...h,media:{...h.media,cut:{...b,start:u}}},g=l(process.platform,h),w.push({code:"media-cut-keyframe",message:`It starts at ${te(u)}, the keyframe just before ${te(b.start)}.`}))}let y=async u=>{let x="",P="";for(let E of u.steps){let v=E.args.map(F=>F.replace(ge,x).replace(le,P)),O=await ft(v,{tools:r,signal:o,report:E.measures!==void 0,onTime:F=>t({phase:"time",done:Math.min(F,u.duration),total:u.duration,...E.pass?{pass:E.pass}:{}})});E.measures==="loudness"&&(x=xo(O)),E.measures==="noise"&&(P=String(wt(O)))}};try{try{await y(g)}catch(P){if(o?.aborted||!g.steps.some(E=>E.args.some(v=>v.endsWith("_videotoolbox"))))throw P;I="linux",g=l(I,h),await y(g)}let u=h.media?.targetBytes;for(let P of[.95,.9]){if(u===void 0||(await ne(f)).size<=u)break;h={...h,media:{...h.media,targetBytes:Math.floor(u*P)}},g=l(I,h),await y(g)}let x=(await ne(f)).size;if(u!==void 0&&x>u)throw Ae(n,e.options.media?.targetBytes??u,x);if(e.options.compress!==void 0&&x>=n.bytes)throw j(n.path,n.bytes,x);await Ge(f,s)}catch(u){throw await bt(d),o?.aborted||T(u)?u:J(n.path,u)}await bt(d.slice(1));let $=i.video;if(g.fitted&&$&&(g.fitted.width<$.width-2||g.fitted.fps<$.fps)){let u=De(e.options.media?.targetBytes??0);w.push({code:"media-fitted",message:`To fit ${u} it is now ${g.fitted.width}\xD7${g.fitted.height} at ${g.fitted.fps} fps.`})}return{job:e,outputBytes:(await ne(s)).size,warnings:w}}function Wn(e,t){if(e.kind!=="media"||!e.facts)return;let o=at()?.has;if(o)try{he({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 H=e=>new Set(e);function Po(e){let t=e.kind==="media"?e.facts:void 0,o=e.kind==="image"||t!==void 0&&t.audio===void 0;return H(yt.filter(n=>!(o&&S[n].media==="sound"||n==="hevc"&&t?.video?.codec==="hevc")))}var Et={id:"video",reads:H(mo),writes:H(yt),ops:new Set(["convert"]),probe:e=>xt(e,"video"),run:Ft,sizeTo:Pt,writesFor:Po},St={id:"sound",reads:H(lo),writes:H(go),ops:new Set(["convert"]),probe:e=>xt(e,"sound"),run:Ft,sizeTo:Pt};import{readFile as re,rm as $t,stat as Fo}from"node:fs/promises";function zn(e,t){let o=e.split(",").map(r=>r.trim()).filter(r=>r!=="");if(o.length===0)throw V(e,"That selects no pages.",t);let n=new Set,s=(r,i)=>{if(!Number.isInteger(r)||r<1||r>t)throw V(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 V(r,`"${r}" ends before it starts.`,t);for(let p=a;p<=f;p++)n.add(p-1);continue}if(!/^\d+$/.test(r))throw V(r,`"${r}" is not a page number.`,t);n.add(s(Number(r),r)-1)}return[...n].sort((r,i)=>r-i)}function It(e){return[...new Set(e)].sort((t,o)=>t-o)}function qn(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 Rt(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 ve=He(()=>import("./pdf-compress-U2E3CNXG.js")),Eo=new Set(["pdf","jpeg","png","webp","avif","gif","tiff"]),So=new Set(["pdf"]);async function C(e){return(await M()).PDFDocument.load(await re(e),{ignoreEncryption:!0})}async function Io(e){let{surveyDocument:t}=await ve(),o=await C(e),{size:n}=await Fo(e);return{kind:"document",path:e,format:"pdf",bytes:n,pages:o.getPageCount(),encrypted:o.isEncrypted,images:t(o)}}function U(e){for(let t of e)if(t.encrypted)throw X(t.path)}async function Ro(e,t,o){let n=await ee(),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 $o(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:`${A(o.path)} has ${o.frames} frames, and ${S.pdf.label} cannot animate. Only the first frame was converted.`}),t({phase:"reading"});let s=await re(o.path);t({phase:"encoding"});let i=await(await M()).PDFDocument.create(),a=await Ro(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 R(e.outputs[0],await i.save());return{job:e,outputBytes:p,warnings:n}}async function _o(e,t){U(e.sources.filter(i=>i.kind==="document"));let n=await(await M()).PDFDocument.create();for(let i of e.sources){t({phase:"reading"});let a=await C(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 R(e.outputs[0],s);return{job:e,outputBytes:r,warnings:[]}}async function ko(e,t){let o=e.sources[0];U([o]);let n=await M();t({phase:"reading"});let s=await C(o.path),r=Rt(e.cuts,s.getPageCount()),i=[],a=0;try{for(let[f,p]of r.entries()){let d=await n.PDFDocument.create(),w=Array.from({length:p.to-p.from+1},(g,I)=>p.from+I),l=await d.copyPages(s,w);for(let g of l)d.addPage(g);let h=e.outputs[f];if(h===void 0)throw new Error(`split produced ${r.length} parts but was given ${e.outputs.length} outputs`);a+=await R(h,await d.save()),i.push(h),t({phase:"page",done:f+1,total:r.length})}}catch(f){throw await Promise.all(i.map(p=>$t(p,{force:!0}))),f}return{job:e,outputBytes:a,warnings:[]}}async function we(e,t){let n=await(await M()).PDFDocument.create(),s=await n.copyPages(e,t);for(let r of s)n.addPage(r);return n.save()}async function Mo(e,t){let o=e.sources[0];if(U([o]),e.pages.length===0)throw de("That extract selects no pages.");t({phase:"reading"});let n=await C(o.path),s=It(e.pages),r=[],i=0;try{if(e.separate)for(let[a,f]of s.entries()){let p=e.outputs[a];i+=await R(p,await we(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 R(a,await we(n,s)),r.push(a)}}catch(a){throw await Promise.all(r.map(f=>$t(f,{force:!0}))),a}return{job:e,outputBytes:i,warnings:[]}}async function Oo(e,t){let o=e.sources[0];U([o]),t({phase:"reading"});let n=await C(o.path),s=new Set(e.pages),r=n.getPageIndices().filter(a=>!s.has(a));if(r.length===0)throw de("That would delete every page.");t({phase:"writing"});let i=await R(e.outputs[0],await we(n,r));return{job:e,outputBytes:i,warnings:[]}}async function Do(e,t){let o=e.sources[0];U([o]);let n=await M();t({phase:"reading"});let s=await C(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 R(e.outputs[0],await s.save());return{job:e,outputBytes:r,warnings:[]}}async function Ao(e,t){let o=e.sources[0];U([o]);let{compressPdf:n}=await ve();t({phase:"reading"});let s=await re(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 j(o.path,o.bytes,r.length);t({phase:"writing"});let d=await R(e.outputs[0],r),w=h=>h===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${w(a)} could be re-encoded \u2014 they are not JPEG data.`}):a>0&&l.push({code:"pdf-images-skipped",message:`${i} image${w(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:d,warnings:l}}async function To(e){if(e.op!=="convert")return;let t=e.sources[0];if(t.kind!=="document")return;let{compressPdf:o}=await ve(),n=await re(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 _t={id:"pdf",measurer:To,reads:Eo,writes:So,ops:new Set(["convert","merge","split","extract","delete","rotate"]),probe:Io,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"?Ao(e,t):$o(e,t);case"merge":return _o(e,t);case"split":return ko(e,t);case"extract":return Mo(e,t);case"delete":return Oo(e,t);case"rotate":return Do(e,t);default:throw new Error(`the pdf engine cannot ${e.op}`)}}};import{execFile as No}from"node:child_process";import{mkdtemp as Bo,readFile as Ee,rm as Lo}from"node:fs/promises";import{tmpdir as Jo}from"node:os";import{basename as Wo,extname as Co,join as kt,win32 as Pe}from"node:path";import{pathToFileURL as Uo}from"node:url";import{promisify as zo}from"node:util";var Fe=zo(No),be=Buffer.from([208,207,17,224,161,177,26,225]);async function qo(e){if(e.length<be.length||!e.subarray(0,be.length).equals(be))return!1;let t=await Ze();try{return t.find(t.parse(e),"WordDocument")!==null}catch{return!1}}async function Vo(e){let t=await Qe();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}}async function Go(e){let t=await Ee(e),o=await Vo(t);if(o)return{kind:"document",path:e,format:"docx",bytes:t.byteLength,pages:o.pages,encrypted:!1};if(await qo(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 Ho(e,t){return e==="win32"?[Pe.join(t.ProgramFiles??"C:\\Program Files","LibreOffice","program","soffice.exe"),Pe.join(t["ProgramFiles(x86)"]??"C:\\Program Files (x86)","LibreOffice","program","soffice.exe")]:["/Applications/LibreOffice.app/Contents/MacOS/soffice"]}var Ko=0;async function Yo(){Ko++;try{return await Fe("soffice",["--version"],{timeout:5e3}),"soffice"}catch{}for(let e of Ho(process.platform,process.env))try{return await Fe(e,["--version"],{timeout:5e3}),e}catch{}}var Mt,Qo=!1,Zo;async function Xo(){return Qo?Zo:(Mt??=Yo(),Mt)}var Se="\f";function se(e){return e.split(/\r?\n/).map(t=>t.trim()).filter(t=>t.length>0)}async function jo(e){if(e.format==="docx"){let o=await Ke(),{value:n}=await o.extractRawText({path:e.path});return se(n)}if(e.format==="doc"){let o=await Ye(),s=await new o().extract(e.path);return se(s.getBody())}return(await nt(await Ee(e.path))).flatMap((o,n)=>n===0?se(o):[Se,...se(o)])}var ye=612,ie=792,N=54,xe=11,Ot=14;async function en(e){let{PDFDocument:t,StandardFonts:o}=await M(),n=await t.create(),s=await n.embedFont(o.Helvetica),r=ye-N*2,i=n.addPage([ye,ie]),a=ie-N,f=()=>{i=n.addPage([ye,ie]),a=ie-N};for(let p of e){if(p===Se){f();continue}let d="";for(let w of p.split(/\s+/).filter(Boolean)){let l=d?`${d} ${w}`:w;d&&s.widthOfTextAtSize(l,xe)>r?(a<N&&f(),i.drawText(d,{x:N,y:a,size:xe,font:s}),a-=Ot,d=w):d=l}d&&(a<N&&f(),i.drawText(d,{x:N,y:a,size:xe,font:s}),a-=Ot)}return n.save()}async function tn(e){let{Document:t,Packer:o,PageBreak:n,Paragraph:s}=await Xe(),r=e.map(a=>a===Se?new s({children:[new n]}):new s(a)),i=new t({sections:[{children:r}]});return o.toBuffer(i)}var on=new Set(["docx","doc","pdf"]),nn=new Set(["docx","pdf"]),rn=new Set(["convert"]),sn={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 an(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"?sn:{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 cn(e,t,o,n=process.platform){return[`-env:UserInstallation=${n==="win32"?Uo(Pe.join(e,"profile"),{windows:!0}).href:`file://${e}/profile`}`,"--headless","--convert-to",o,"--outdir",e,t]}async function fn(e,t,o){let n=await Bo(kt(Jo(),"forge-word-"));try{await Fe(e,cn(n,t,o),{timeout:12e4});let s=Wo(t,Co(t));return await Ee(kt(n,`${s}.${o}`))}finally{await Lo(n,{recursive:!0,force:!0})}}async function pn(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 X(o.path);t({phase:"reading"});let n=await Xo();t({phase:"encoding"});let s=[],r;try{if(n!==void 0)r=await fn(n,o.path,e.target);else{let a=await jo(o);r=e.target==="pdf"?await en(a):await tn(a),s.push(an())}}catch(a){throw J(o.path,a)}t({phase:"writing"});let i=await R(e.outputs[0],r);return{job:e,outputBytes:i,warnings:s}}var Dt={id:"word",reads:on,writes:nn,ops:rn,probe:Go,run:pn};var K=[ot,Et,St,_t,Dt,ut,rt];function vr(e){return K.find(t=>t.reads.has(e))}function br(e){return K.find(t=>t.writes.has(e))}function yr(e){if(e.op==="convert"){let t=e.sources[0].format;return K.find(o=>o.reads.has(t)&&o.writes.has(e.target))}return K.find(t=>t.ops.has(e.op))}async function xr(e){let t;for(let o of K)try{return await o.probe(e)}catch(n){T(t)||(t=n)}throw t}export{zn as a,It as b,qn as c,Rt as d,Wn as e,K as f,vr as g,br as h,yr as i,xr as j};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { createRequire as __forgeCreateRequire } from 'node:module';
|
|
2
|
+
const require = __forgeCreateRequire(import.meta.url);
|
|
3
|
+
import{a as l,c}from"./chunk-MF3KKEFB.js";import{e as p,f as u}from"./chunk-I25E2XDH.js";import{execFile as P}from"node:child_process";import{access as N,constants as A,mkdir as I,readFile as E,realpath as _,writeFile as F}from"node:fs/promises";import{homedir as B}from"node:os";import{dirname as C,join as f,posix as R,sep as m,win32 as S}from"node:path";import{promisify as T}from"node:util";var w=T(P),H=["yt-dlp","video"],X=e=>H.includes(e),a={"yt-dlp":{binary:"yt-dlp",name:"yt-dlp",formula:"yt-dlp",versionArgs:["--version"],version:e=>e.trim().split(`
|
|
4
|
+
`)[0]?.match(/^\d+(\.\d+)+$/)?.[0]},video:{binary:"ffmpeg",name:"ffmpeg",formula:"ffmpeg",versionArgs:["-hide_banner","-version"],version:e=>e.match(/ffmpeg version (\S+)/)?.[1],beside:["ffprobe"]}},Y=e=>a[e].name,q=e=>a[e].formula;function $(e,n){let r=e.split(".").map(Number),i=n.split(".").map(Number);for(let t=0;t<Math.max(r.length,i.length);t++){let o=r[t]??0,s=i[t]??0;if(Number.isNaN(o)||Number.isNaN(s))return e>n;if(o!==s)return o>s}return!1}function g(e){let n=p(e);return n&&(u(n)?.version??u(n,"darwin","universal")?.version)}function y({platform:e=process.platform,env:n=process.env,deep:r=!1}={}){let t=(n.PATH??n.Path??"").split(e==="win32"?";":":").filter(Boolean);if(e==="darwin"&&t.push("/opt/homebrew/bin","/usr/local/bin"),r){let o=n.HOME??B(),{join:s}=e==="win32"?S:R;t.push(s(o,".local","bin"),s(o,"bin"),"/opt/local/bin","/usr/bin")}return[...new Set(t)]}var O=(e,n=process.platform)=>n==="win32"?`${e}.exe`:e;async function d(e){try{return await N(e,A.X_OK),!0}catch{return!1}}async function b(e,n){let r=a[e];if(await d(n)){for(let i of r.beside??[])if(!await d(f(C(n),O(i))))return;try{let{stdout:i}=await w(n,r.versionArgs,{timeout:5e3}),t=r.version(i);if(t===void 0)return;let o=await _(n).catch(()=>n),s=g(e);return{id:e,path:n,version:t,homebrew:o.includes(`${m}Cellar${m}`),tooOld:e==="yt-dlp"&&s!==void 0&&$(s,t)}}catch{return}}}var h=()=>f(l(),"own.json");async function v(){try{let e=JSON.parse(await E(h(),"utf8"));return typeof e=="object"&&e!==null?e:{}}catch{return{}}}async function j(e){let n=(await v())[e];return typeof n=="string"&&n!==""?n:void 0}async function z(e,n){let r=await v();n===void 0?delete r[e]:r[e]=n,await I(l(),{recursive:!0}),await F(h(),`${JSON.stringify(r,null,2)}
|
|
5
|
+
`)}async function J(e,n={}){let r=await j(e);if(r!==void 0){let o=await b(e,r);if(o)return o}let t=process.env.FORGE_NO_OWN_TOOLS==="1"&&n.dirs===void 0?[]:n.dirs??y({deep:n.deep??!1});for(let o of t){let s=await b(e,f(o,O(a[e].binary)));if(s)return s}}async function k(e){if(await c(e)===void 0)return 0;try{let{removeExtension:n,extensionBytes:r}=await import("./manager-UKTMRXKE.js"),i=await r(e);return await n(e)?i:0}catch{return 0}}async function Q(e={}){let n=await J("yt-dlp",e);if(n&&!n.tooOld)return await k("yt-dlp"),{entry:n.path,own:!0};let r=await c("yt-dlp");return r?{entry:r.entry,own:!1}:void 0}async function x(e){if(e.brew!==void 0)return await d(e.brew)?e.brew:void 0;for(let n of y({env:{PATH:process.env.PATH??""}})){let r=f(n,"brew");if(await d(r))return r}}async function V(e,n={}){if(e.tooOld)return g(e.id);if(!e.homebrew)return;let r=await x(n);if(r!==void 0)try{let{stdout:i}=await w(r,["outdated","--json=v2","--formula",a[e.id].formula],{timeout:15e3,env:{...process.env,HOMEBREW_NO_AUTO_UPDATE:"1"}}),t=JSON.parse(i);if(!Array.isArray(t.formulae))return;let o=t.formulae[0]?.current_version;return typeof o=="string"?o:null}catch{return}}var Z=e=>e.homebrew?"Homebrew":e.id==="yt-dlp"?"yt-dlp":void 0;async function ee(e,n={}){let r,i;if(e.homebrew){let t=await x(n);if(t===void 0)throw new Error("Homebrew was not found");r=t,i=["upgrade",a[e.id].formula]}else if(e.id==="yt-dlp")r=e.path,i=["--update"];else throw new Error(`${a[e.id].name} cannot update itself`);try{await w(r,i,{timeout:10*6e4,maxBuffer:8<<20,...n.signal?{signal:n.signal}:{}})}catch(t){if(n.signal?.aborted)throw n.signal.reason??t;let o=t,s=(o.stderr??"").trim().split(`
|
|
6
|
+
`).filter(Boolean).at(-1)?.replace(/^Error:\s*/,"");throw new Error(s||o.message||"the update failed")}}export{H as a,X as b,Y as c,q as d,$ as e,y as f,b as g,j as h,z as i,J as j,k,Q as l,V as m,Z as n,ee as o};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { createRequire as __forgeCreateRequire } from 'node:module';
|
|
2
|
+
const require = __forgeCreateRequire(import.meta.url);
|
|
3
|
+
import{h as l}from"./chunk-2J2PTA5O.js";import{r as f}from"./chunk-DZOBIUV6.js";import{y as m}from"./chunk-WIPP5TWQ.js";import{b as g,d as w}from"./chunk-KXKQDFHX.js";import{readFile as D,rm as E}from"node:fs/promises";var b=new Set(["pdf"]),x=new Set(["jpeg","png"]),I=new Set(["convert"]),y;function R(){return y??=w().then(t=>t.PDFiumLibrary.init()),y}async function h(t,r){return await(await R()).loadDocument(t,r)}async function J(t){let r=await h(t);try{let e=[];for(let n=0;n<r.getPageCount();n++)e.push(r.getPage(n).getText());return e}finally{r.destroy()}}var T={id:"pdfium",reads:b,writes:x,ops:I,probe(){throw new Error("pdfium does not probe; engines/pdf.ts classifies PDFs")},async run(t,r){if(t.op!=="convert")throw new Error(`pdfium cannot ${t.op}`);let e=t.sources[0];if(e.kind!=="document")throw new Error("the pdfium engine can only rasterise a document source");if(e.encrypted&&t.options.password===void 0)throw m(e.path);let n=t.options.dpi??150,i=t.options.pages??Array.from({length:e.pages},(o,a)=>a);if(i.length!==t.outputs.length)throw new Error(`pdfium was given ${i.length} pages but ${t.outputs.length} outputs`);for(let o of i)if(o<0||o>=e.pages)throw new Error(`pdfium was asked for page ${o}, but ${e.path} has ${e.pages} pages`);let P=await g(),d=await h(await D(e.path),t.options.password);try{let o=[],a=0;try{for(let[s,p]of i.entries()){let u=await d.getPage(p).render({scale:n/72,render:"bitmap",transparent:!0}),F=P(u.data,{raw:{width:u.width,height:u.height,channels:4}}).flatten({background:t.options.background}),S=await l(F,t.target,t.options.quality).toBuffer(),c=t.outputs[s];a+=await f(c,S),o.push(c),r({phase:"page",done:s+1,total:i.length})}}catch(s){throw await Promise.all(o.map(p=>E(p,{force:!0}))),s}return{job:t,outputBytes:a,warnings:[]}}finally{d.destroy()}}};export{h as a,J as b,T as c};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { createRequire as __forgeCreateRequire } from 'node:module';
|
|
2
|
+
const require = __forgeCreateRequire(import.meta.url);
|
|
3
|
+
import{b as g,c as R,d as T,e as E,f as w,g as d}from"./chunk-QVACE4IE.js";import{H as y}from"./chunk-WIPP5TWQ.js";var L={set:"tailwind",start:50,end:950,count:11},D=["tailwind","even","radix"],I=[0,50,100,150,200,250,300,350,400,450],$=[550,600,650,700,750,800,850,900,950,1e3],N=Array.from({length:19},(e,t)=>t+3),P=[20,50,100,150,200,260,330,420,500,560,750,920],_=8;function W({set:e,start:t,end:n,count:r}){if(!D.includes(e))return`The set must be tailwind, even or radix; got ${e}.`;if(e!=="radix"){if(!I.includes(t))return t%50===0?`The start must be from 0 to 450, so the colour (500) stays in the scale; got ${t}.`:`The start must be a multiple of 50; got ${t}.`;if(!$.includes(n))return n%50===0?`The end must be from 550 to 1000, so the colour (500) stays in the scale; got ${n}.`:`The end must be a multiple of 50; got ${n}.`;if(e==="even"&&!N.includes(r))return`An even set has 3 to 21 steps; got ${r}.`}}function x(e){let{set:t,start:n,end:r,count:a}=e;if(t==="radix")return P.map((o,u)=>({step:u+1,at:o}));if(t==="tailwind"){let o=new Set([n,r,500]);for(let u=Math.ceil((n+1)/100)*100;u<r;u+=100)o.add(u);return[...o].sort((u,s)=>u-s).map(u=>({step:u,at:u}))}let i=a-1,l=Math.round(i*(500-n)/(r-n)),f=Math.max(1,Math.min(i-1,l)),h=i-f,c=[];for(let o=0;o<=f;o++)c.push(n+(500-n)*o/f);for(let o=1;o<=h;o++)c.push(500+(r-500)*o/h);for(let o of[10,5,1]){let u=c.map(s=>Math.round(s/o)*o);if(new Set(u).size===u.length)return c.map((s,p)=>({step:u[p],at:s}))}return c.map(o=>({step:o,at:o}))}function F(e){return x(e).map(t=>t.step)}var Y=F(L);function q(e){return e.set==="radix"?_:x(e).findIndex(t=>t.at===500)}var H=[[50,1],[100,.86],[200,.68],[300,.46],[400,.22],[500,0]],U=[[500,0],[600,.2],[700,.4],[800,.6],[900,.8],[950,1]];function M(e,t){for(let n=1;n<e.length;n++){let[r,a]=e[n-1],[i,l]=e[n];if(t<=i)return a+(l-a)*(t-r)/(i-r)}return e[e.length-1][1]}var j=.995,k=.35,B=5e-4;function J(e,t=L){let n=W(t);if(n)throw y(n,"Try: Tailwind, from 50 to 950.");let{L:r,C:a,h:i}=w(R(e)),l=a<B,f=Math.max(.975,r),h=r<.16?.42*r:Math.max(.16,.42*r),c=x(t),o=c[c.length-1]?.at===1e3;return c.map(({step:u,at:s})=>{if(s===500)return{step:u,at:s,rgb:{...e},hex:g(e),reference:!0};let p,b;if(s>=50&&s<500){let m=M(H,s);p=r+(f-r)*m,b=a*(1-.88*m)}else if(s<50){let m=(50-s)/50;p=f+(Math.max(j,f)-f)*m,b=a*.12*(1-m)}else if(s<=950||o){let m=o?(s-500)/500:M(U,s);p=r-(r-h)*m,b=a*(1-.45*m)}else{let m=(s-950)/50;p=h*(1-k*m),b=a*.55*(1-.4*m)}for(l&&(b=0);b>0&&!E(d({L:p,C:b,h:i}));)b-=.002;let A=T(d({L:p,C:Math.max(0,b),h:i}));return{step:u,at:s,rgb:A,hex:g(A),reference:!1}})}var S=e=>{let t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4},C=({r:e,g:t,b:n})=>.2126*S(e)+.7152*S(t)+.0722*S(n);function O(e,t){let[n,r]=[C(e),C(t)].sort((a,i)=>i-a);return(n+.05)/(r+.05)}function V(e){return e>=7?"AAA":e>=4.5?"AA":e>=3?"large":"fails"}var G={r:255,g:255,b:255},X={r:0,g:0,b:0},v=e=>Math.floor(e*10)/10;function Z(e){return{white:v(O(e,G)),black:v(O(e,X))}}export{L as a,D as b,I as c,$ as d,N as e,x as f,F as g,q as h,J as i,O as j,V as k,Z as l};
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { createRequire as __forgeCreateRequire } from 'node:module';
|
|
2
|
+
const require = __forgeCreateRequire(import.meta.url);
|
|
3
|
+
import{a as M}from"./chunk-U5TEGDGH.js";import{a as X,b as Q}from"./chunk-HZDYZ5RD.js";import{a as D}from"./chunk-JMBEZPYC.js";import{b as W}from"./chunk-HCLEHCAR.js";import{a as K}from"./chunk-3KWAO2N2.js";import{b as J}from"./chunk-EEQSUBBL.js";import{a as Y}from"./chunk-KH5DHZ2U.js";import{a as U}from"./chunk-2J2PTA5O.js";import{m as R}from"./chunk-THDAQBQ3.js";import{H as d,K as H}from"./chunk-WIPP5TWQ.js";import{d as L}from"./chunk-J7FLFHQJ.js";import{b as z}from"./chunk-H3DIRJFE.js";var x=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},v=class extends x{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};var E=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new v(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(t,n):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function N(s){let e=s.name()+(s.variadic===!0?"...":"");return s.required?"<"+e+">":"["+e+"]"}import{EventEmitter as le}from"node:events";import G from"node:child_process";import C from"node:path";import F from"node:fs";import m from"node:process";import{stripVTControlCharacters as he}from"node:util";import{stripVTControlCharacters as se}from"node:util";var T=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(i=>!i._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((i,o)=>i.name().localeCompare(o.name())),t}compareOptions(e,t){let n=i=>i.short?i.short.replace(/^-/,""):i.long.replace(/^--/,"");return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(i=>!i.hidden),n=e._getHelpOption();if(n&&!n.hidden){let i=n.short&&e._findOption(n.short),o=n.long&&e._findOption(n.long);!i&&!o?t.push(n):n.long&&!o?t.push(e.createOption(n.long,n.description)):n.short&&!i&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let i=n.options.filter(o=>!o.hidden);t.push(...i)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(n=>N(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((n,i)=>Math.max(n,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(i)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,i)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(i)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,i)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(i)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,i)=>Math.max(n,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(i)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let n="";for(let i=e.parent;i;i=i.parent)n=i.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0){let n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatItemList(e,t,n){return t.length===0?[]:[n.styleTitle(e),...t,""]}groupItems(e,t,n){let i=new Map;return e.forEach(o=>{let r=n(o);i.has(r)||i.set(r,[])}),t.forEach(o=>{let r=n(o);i.has(r)||i.set(r,[]),i.get(r).push(o)}),i}formatHelp(e,t){let n=t.padWidth(e,t),i=t.helpWidth??80;function o(c,p){return t.formatItem(c,n,p,t)}let r=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],u=t.commandDescription(e);u.length>0&&(r=r.concat([t.boxWrap(t.styleCommandDescription(u),i),""]));let l=t.visibleArguments(e).map(c=>o(t.styleArgumentTerm(t.argumentTerm(c)),t.styleArgumentDescription(t.argumentDescription(c))));if(r=r.concat(this.formatItemList("Arguments:",l,t)),this.groupItems(e.options,t.visibleOptions(e),c=>c.helpGroupHeading??"Options:").forEach((c,p)=>{let O=c.map(_=>o(t.styleOptionTerm(t.optionTerm(_)),t.styleOptionDescription(t.optionDescription(_))));r=r.concat(this.formatItemList(p,O,t))}),t.showGlobalOptions){let c=t.visibleGlobalOptions(e).map(p=>o(t.styleOptionTerm(t.optionTerm(p)),t.styleOptionDescription(t.optionDescription(p))));r=r.concat(this.formatItemList("Global Options:",c,t))}return this.groupItems(e.commands,t.visibleCommands(e),c=>c.helpGroup()||"Commands:").forEach((c,p)=>{let O=c.map(_=>o(t.styleSubcommandTerm(t.subcommandTerm(_)),t.styleSubcommandDescription(t.subcommandDescription(_))));r=r.concat(this.formatItemList(p,O,t))}),r.join(`
|
|
4
|
+
`)}displayWidth(e){return se(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t==="[command]"?this.styleSubcommandText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleCommandText(t)).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleSubcommandText(t)).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,i){let r=" ".repeat(2);if(!n)return r+e;let u=e.padEnd(t+e.length-i.displayWidth(e)),l=2,a=(this.helpWidth??80)-t-l-2,c;return a<this.minWidthToWrap||i.preformatted(n)?c=n:c=i.boxWrap(n,a).replace(/\n/g,`
|
|
5
|
+
`+" ".repeat(t+l)),r+u+" ".repeat(l)+c.replace(/\n/g,`
|
|
6
|
+
${r}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),i=/[\s]*[^\s]+/g,o=[];return n.forEach(r=>{let u=r.match(i);if(u===null){o.push("");return}let l=[u.shift()],h=this.displayWidth(l[0]);u.forEach(a=>{let c=this.displayWidth(a);if(h+c<=t){l.push(a),h+=c;return}o.push(l.join(""));let p=a.trimStart();l=[p],h=this.displayWidth(p)}),o.push(l.join(""))}),o.join(`
|
|
7
|
+
`)}};var A=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=ae(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new v(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(t,n):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?Z(this.name().replace(/^no-/,"")):Z(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},V=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let i=this.negativeOptions.get(n).presetArg,o=i!==void 0?i:!1;return t.negate===(o===e)}};function Z(s){return s.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function ae(s){let e,t,n=/^-[^-]$/,i=/^--[^-]/,o=s.split(/[ |,]+/).concat("guard");if(n.test(o[0])&&(e=o.shift()),i.test(o[0])&&(t=o.shift()),!e&&n.test(o[0])&&(e=o.shift()),!e&&i.test(o[0])&&(e=t,t=o.shift()),o[0].startsWith("-")){let r=o[0],u=`option creation failed due to '${r}' in option flags '${s}'`;throw/^-[^-][^-]/.test(r)?new Error(`${u}
|
|
8
|
+
- a short flag is a single dash and a single character
|
|
9
|
+
- either use a single dash and a single character (for a short flag)
|
|
10
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`):n.test(r)?new Error(`${u}
|
|
11
|
+
- too many short flags`):i.test(r)?new Error(`${u}
|
|
12
|
+
- too many long flags`):new Error(`${u}
|
|
13
|
+
- unrecognised flag format`)}if(e===void 0&&t===void 0)throw new Error(`option creation failed due to no flags found in '${s}'.`);return{shortFlag:e,longFlag:t}}function ue(s,e){if(Math.abs(s.length-e.length)>3)return Math.max(s.length,e.length);let t=[];for(let n=0;n<=s.length;n++)t[n]=[n];for(let n=0;n<=e.length;n++)t[0][n]=n;for(let n=1;n<=e.length;n++)for(let i=1;i<=s.length;i++){let o;s[i-1]===e[n-1]?o=0:o=1,t[i][n]=Math.min(t[i-1][n]+1,t[i][n-1]+1,t[i-1][n-1]+o),i>1&&n>1&&s[i-1]===e[n-2]&&s[i-2]===e[n-1]&&(t[i][n]=Math.min(t[i][n],t[i-2][n-2]+1))}return t[s.length][e.length]}function q(s,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=s.startsWith("--");t&&(s=s.slice(2),e=e.map(r=>r.slice(2)));let n=[],i=3,o=.4;return e.forEach(r=>{if(r.length<=1)return;let u=ue(s,r),l=Math.max(s.length,r.length);(l-u)/l>o&&(u<i?(i=u,n=[r]):u===i&&n.push(r))}),n.sort((r,u)=>r.localeCompare(u)),t&&(n=n.map(r=>`--${r}`)),n.length>1?`
|
|
14
|
+
(Did you mean one of ${n.join(", ")}?)`:n.length===1?`
|
|
15
|
+
(Did you mean ${n[0]}?)`:""}var $=class s extends le{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:t=>m.stdout.write(t),writeErr:t=>m.stderr.write(t),outputError:(t,n)=>n(t),getOutHelpWidth:()=>m.stdout.isTTY?m.stdout.columns:void 0,getErrHelpWidth:()=>m.stderr.isTTY?m.stderr.columns:void 0,getOutHasColors:()=>te()??(m.stdout.isTTY&&m.stdout.hasColors?.()),getErrHasColors:()=>te()??(m.stderr.isTTY&&m.stderr.hasColors?.()),stripColor:t=>he(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let i=t,o=n;typeof i=="object"&&i!==null&&(o=i,i=null),o=o||{};let[,r,u]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(r);return i&&(l.description(i),l._executableHandler=!0),o.isDefault&&(this._defaultCommandName=l._name),l._hidden=!!(o.noHelp||o.hidden),l._executableFile=o.executableFile||null,u&&l.arguments(u),this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),i?this:l}createCommand(e){return new s(e)}createHelp(){return Object.assign(new T,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...e},this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
16
|
+
- specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new E(e,t)}argument(e,t,n,i){let o=this.createArgument(e,t);return typeof n=="function"?o.default(i).argParser(n):o.default(n),this.addArgument(o),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t?.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let n=e??"help [command]",[,i,o]=n.match(/([^ ]+) *(.*)/),r=t??"display help for command",u=this.createCommand(i);return u.helpOption(!1),o&&u.arguments(o),r&&u.description(r),this._addImplicitHelpCommand=!0,this._helpCommand=u,(e||t)&&this._initCommandGroup(u),this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
17
|
+
Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new x(e,t,n)),m.exit(e)}action(e){let t=n=>{let i=this.registeredArguments.length,o=n.slice(0,i);return this._storeOptionsAsProperties?o[i]=this:o[i]=this.opts(),o.push(this),e.apply(this,o)};return this._actionHandler=t,this}createOption(e,t){return new A(e,t)}_callParseArg(e,t,n,i){try{return e.parseArg(t,n)}catch(o){if(o.code==="commander.invalidArgument"){let r=`${i} ${o.message}`;this.error(r,{exitCode:o.exitCode,code:o.code})}throw o}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
|
|
18
|
+
- already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=i=>[i.name()].concat(i.aliases()),n=t(e).find(i=>this._findCommand(i));if(n){let i=t(this._findCommand(n)).join("|"),o=t(e).join("|");throw new Error(`cannot add command '${o}' as already have command '${i}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let i=(o,r,u)=>{o==null&&e.presetArg!==void 0&&(o=e.presetArg);let l=this.getOptionValue(n);o!==null&&e.parseArg?o=this._callParseArg(e,o,l,r):o!==null&&e.variadic&&(o=e._collectValue(o,l)),o==null&&(e.negate?o=!1:e.isBoolean()||e.optional?o=!0:o=""),this.setOptionValueWithSource(n,o,u)};return this.on("option:"+t,o=>{let r=`error: option '${e.flags}' argument '${o}' is invalid.`;i(o,r,"cli")}),e.envVar&&this.on("optionEnv:"+t,o=>{let r=`error: option '${e.flags}' value '${o}' from env '${e.envVar}' is invalid.`;i(o,r,"env")}),this}_optionEx(e,t,n,i,o){if(typeof t=="object"&&t instanceof A)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let r=this.createOption(t,n);if(r.makeOptionMandatory(!!e.mandatory),typeof i=="function")r.default(o).argParser(i);else if(i instanceof RegExp){let u=i;i=(l,h)=>{let a=u.exec(l);return a?a[0]:h},r.default(o).argParser(i)}else r.default(i);return this.addOption(r)}option(e,t,n,i){return this._optionEx({},e,t,n,i)}requiredOption(e,t,n,i){return this._optionEx({mandatory:!0},e,t,n,i)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){m.versions?.electron&&(t.from="electron");let i=m.execArgv??[];(i.includes("-e")||i.includes("--eval")||i.includes("-p")||i.includes("--print"))&&(t.from="eval")}e===void 0&&(e=m.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":m.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_prepareForParse(){this._savedState===null?(this.options.filter(e=>e.negate&&e.defaultValue===void 0&&this.getOptionValue(e.attributeName())===void 0).forEach(e=>{let t=e.long.replace(/^--no-/,"--");this._findOption(t)||this.setOptionValueWithSource(e.attributeName(),!0,"default")}),this.saveStateBeforeParse()):this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
19
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,n){if(F.existsSync(e))return;let i=t?`searched for local subcommand relative to directory '${t}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",o=`'${e}' does not exist
|
|
20
|
+
- if '${n}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
21
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
22
|
+
- ${i}`;throw new Error(o)}_executeSubCommand(e,t){t=t.slice();let n=[".js",".ts",".tsx",".mjs",".cjs"];function i(a,c){let p=C.resolve(a,c);if(F.existsSync(p))return p;if(n.includes(C.extname(c)))return;let O=n.find(_=>F.existsSync(`${p}${_}`));if(O)return`${p}${O}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,r=this._executableDir||"";if(this._scriptPath){let a;try{a=F.realpathSync(this._scriptPath)}catch{a=this._scriptPath}r=C.resolve(C.dirname(a),r)}if(r){let a=i(r,o);if(!a&&!e._executableFile&&this._scriptPath){let c=C.basename(this._scriptPath,C.extname(this._scriptPath));c!==this._name&&(a=i(r,`${c}-${e._name}`))}o=a||o}let u=n.includes(C.extname(o)),l;m.platform!=="win32"?u?(t.unshift(o),t=ee(m.execArgv).concat(t),l=G.spawn(m.argv[0],t,{stdio:"inherit"})):l=G.spawn(o,t,{stdio:"inherit"}):(this._checkForMissingExecutable(o,r,e._name),t.unshift(o),t=ee(m.execArgv).concat(t),l=G.spawn(m.execPath,t,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(c=>{m.on(c,()=>{l.killed===!1&&l.exitCode===null&&l.kill(c)})});let h=this._exitCallback;l.on("close",a=>{a=a??1,h?h(new x(a,"commander.executeSubCommandAsync","(close)")):m.exit(a)}),l.on("error",a=>{if(a.code==="ENOENT")this._checkForMissingExecutable(o,r,e._name);else if(a.code==="EACCES")throw new Error(`'${o}' not executable`);if(!h)m.exit(1);else{let c=new x(1,"commander.executeSubCommandAsync","(error)");c.nestedError=a,h(c)}}),this.runningCommand=l}_dispatchSubcommand(e,t,n){let i=this._findCommand(e);i||this.help({error:!0}),i._prepareForParse();let o;return o=this._chainOrCallSubCommandHook(o,i,"preSubcommand"),o=this._chainOrCall(o,()=>{if(i._executableHandler)this._executeSubCommand(i,t.concat(n));else return i._parseCommand(t,n)}),o}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(n,i,o)=>{let r=i;if(i!==null&&n.parseArg){let u=`error: command-argument value '${i}' is invalid for argument '${n.name()}'.`;r=this._callParseArg(n,i,o,u)}return r};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,i)=>{let o=n.defaultValue;n.variadic?i<this.args.length?(o=this.args.slice(i),n.parseArg&&(o=o.reduce((r,u)=>e(n,u,r),n.defaultValue))):o===void 0&&(o=[]):i<this.args.length&&(o=this.args[i],n.parseArg&&(o=e(n,o,n.defaultValue))),t[i]=o}),this.processedArgs=t}_chainOrCall(e,t){return e?.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,i=[];return this._getCommandAndAncestors().reverse().filter(o=>o._lifeCycleHooks[t]!==void 0).forEach(o=>{o._lifeCycleHooks[t].forEach(r=>{i.push({hookedCommand:o,callback:r})})}),t==="postAction"&&i.reverse(),i.forEach(o=>{n=this._chainOrCall(n,()=>o.callback(o.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let i=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(o=>{i=this._chainOrCall(i,()=>o(this,t))}),i}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},o=`command:${this.name()}`;if(this._actionHandler){i(),this._processArguments();let r;return r=this._chainOrCallHooks(r,"preAction"),r=this._chainOrCall(r,()=>this._actionHandler(this.processedArgs)),this.parent&&(r=this._chainOrCall(r,()=>{this.parent.emit(o,e,t)})),r=this._chainOrCallHooks(r,"postAction"),r}if(this.parent?.listenerCount(o))i(),this._processArguments(),this.parent.emit(o,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(i(),this._processArguments())}else this.commands.length?(i(),this.help({error:!0})):(i(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let i=n.attributeName();return this.getOptionValue(i)===void 0?!1:this.getOptionValueSource(i)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let i=e.find(o=>n.conflictsWith.includes(o.attributeName()));i&&this._conflictingOption(n,i)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],i=t;function o(a){return a.length>1&&a[0]==="-"}let r=a=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(a)?!this._getCommandAndAncestors().some(c=>c.options.map(p=>p.short).some(p=>/^-\d$/.test(p))):!1,u=null,l=null,h=0;for(;h<e.length||l;){let a=l??e[h++];if(l=null,a==="--"){i===n&&i.push(a),i.push(...e.slice(h));break}if(u&&(!o(a)||r(a))){this.emit(`option:${u.name()}`,a);continue}if(u=null,o(a)){let c=this._findOption(a);if(c){if(c.required){let p=e[h++];p===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,p)}else if(c.optional){let p=null;h<e.length&&(!o(e[h])||r(e[h]))&&(p=e[h++]),this.emit(`option:${c.name()}`,p)}else this.emit(`option:${c.name()}`);u=c.variadic?c:null;continue}}if(a.length>2&&a[0]==="-"&&a[1]!=="-"){let c=this._findOption(`-${a[1]}`);if(c){c.required||c.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${c.name()}`,a.slice(2)):(this.emit(`option:${c.name()}`),l=`-${a.slice(2)}`);continue}}if(/^--[^=]+=/.test(a)){let c=a.indexOf("="),p=this._findOption(a.slice(0,c));if(p&&(p.required||p.optional)){this.emit(`option:${p.name()}`,a.slice(c+1));continue}}if(i===t&&o(a)&&!(this.commands.length===0&&r(a))&&(i=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(a)){t.push(a),n.push(...e.slice(h));break}else if(this._getHelpCommand()&&a===this._getHelpCommand().name()){t.push(a,...e.slice(h));break}else if(this._defaultCommandName){n.push(a,...e.slice(h));break}}if(this._passThroughOptions){i.push(a,...e.slice(h));break}i.push(a)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let i=this.options[n].attributeName();e[i]=i===this._versionOptionName?this._version:this[i]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
|
|
23
|
+
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
24
|
+
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
25
|
+
`),this.outputHelp({error:!0}));let n=t||{},i=n.exitCode||1,o=n.code||"commander.error";this._exit(i,o,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in m.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,m.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new V(this.options),t=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(i=>!t(i)).forEach(i=>{this.setOptionValueWithSource(i,n.implied[i],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let n=r=>{let u=r.attributeName(),l=this.getOptionValue(u),h=this.options.find(c=>c.negate&&u===c.attributeName()),a=this.options.find(c=>!c.negate&&u===c.attributeName());return h&&(h.presetArg===void 0&&l===!1||h.presetArg!==void 0&&l===h.presetArg)?h:a||r},i=r=>{let u=n(r),l=u.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${u.envVar}'`:`option '${u.flags}'`},o=`error: ${i(e)} cannot be used with ${i(t)}`;this.error(o,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let i=[],o=this;do{let r=o.createHelp().visibleOptions(o).filter(u=>u.long).map(u=>u.long);i=i.concat(r),o=o.parent}while(o&&!o._enablePositionalOptions);t=q(e,i)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?"":"s",i=e.length,o=this.parent?` for '${this.name()}'`:"",r=e.join(", "),u=`error: too many arguments${o}. Expected ${t} argument${n} but got ${i}: ${r}.`;this.error(u,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let i=[];this.createHelp().visibleCommands(this).forEach(o=>{i.push(o.name()),o.alias()&&i.push(o.alias())}),t=q(e,i)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";let i=this.createOption(t,n);return this._versionOptionName=i.attributeName(),this._registerOption(i),this.on("option:"+i.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
26
|
+
`),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let i=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${i}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(n=>N(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}helpGroup(e){return e===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=e,this)}commandsGroup(e){return e===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=e,this)}optionsGroup(e){return e===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=C.basename(e,C.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let i=t.formatHelp(this,t);return n.hasColors?i:this._outputConfiguration.stripColor(i)}_getOutputContext(e){e=e||{};let t=!!e.error,n,i,o;return t?(n=u=>this._outputConfiguration.writeErr(u),i=this._outputConfiguration.getErrHasColors(),o=this._outputConfiguration.getErrHelpWidth()):(n=u=>this._outputConfiguration.writeOut(u),i=this._outputConfiguration.getOutHasColors(),o=this._outputConfiguration.getOutHelpWidth()),{error:t,write:u=>(i||(u=this._outputConfiguration.stripColor(u)),n(u)),hasColors:i,helpWidth:o}}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let n=this._getOutputContext(e),i={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(r=>r.emit("beforeAllHelp",i)),this.emit("beforeHelp",i);let o=this.helpInformation({error:n.error});if(t&&(o=t(o),typeof o!="string"&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(o),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",i),this._getCommandAndAncestors().forEach(r=>r.emit("afterAllHelp",i))}helpOption(e,t){return typeof e=="boolean"?(e?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(e??"-h, --help",t??"display help for command"),(e||t)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(m.exitCode??0);t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
27
|
+
Expecting one of '${n.join("', '")}'`);let i=`${e}Help`;return this.on(i,o=>{let r;typeof t=="function"?r=t({error:o.error,command:o.command}):r=t,r&&o.write(`${r}
|
|
28
|
+
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(i=>t.is(i))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function ee(s){return s.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",i="9229",o;return(o=e.match(/^(--inspect(-brk)?)$/))!==null?t=o[1]:(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=o[1],/^\d+$/.test(o[3])?i=o[3]:n=o[3]):(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=o[1],n=o[3],i=o[4]),t&&i!=="0"?`${t}=${n}:${parseInt(i)+1}`:e})}function te(){if(m.env.NO_COLOR||m.env.FORCE_COLOR==="0"||m.env.FORCE_COLOR==="false")return!1;if(m.env.FORCE_COLOR||m.env.CLICOLOR_FORCE!==void 0)return!0}var Ze=new $;function ce(s){let[,e,t,...n]=s;if(e===void 0||e==="list")return{kind:"config",action:"list"};if(e==="path")return{kind:"config",action:"path"};if(e==="set"){if(t===void 0||!D.includes(t))throw d(`Unknown config setting ${t??"(none)"}.`,`Try one of: ${D.join(", ")}.`);let i=n.join(" ");if(i.length===0)throw d(`forge config set ${t} needs a value.`);return{kind:"config",action:"set",key:t,value:i}}throw d(`Unknown config action ${e}.`,"Try: forge config list, forge config set <setting> <value>, or forge config path.")}var de={jpg:"jpeg",tif:"tiff",heif:"heic"};function I(s){let e=s.toLowerCase().replace(/^\./,""),t=z(de[e]??e);if(!t)throw d(`${s} is not a format Forge knows.`,"Run forge --formats to see what is available.");return t.id}function P(s,e,t,n,i){let o=Number(String(e).replace(/k$/i,""));if(!Number.isFinite(o)||o<t||o>n)throw d(`${s} takes ${t} to ${n}, not ${e}.`,`For example ${s} ${i}.`);return o}function pe(s){let e={};if(s.cut!==void 0){let t=J(String(s.cut));if(!t)throw d(`--cut takes a start and an end, the end after the start, not ${s.cut}.`,"For example --cut 0:03.2-0:41, or --cut 0:10- to keep from 0:10 to the end.");e.cut=t.end===void 0?{start:t.start}:{start:t.start,end:t.end}}return s.mute&&(e.mute=!0),s.speed!==void 0&&(e.speed=P("--speed",s.speed,.25,4,"2")),s.fps!==void 0&&(e.fps=P("--fps",s.fps,1,120,"30")),s.bitrate!==void 0&&(e.bitrate=Math.round(P("--bitrate",s.bitrate,32,320,"128k"))),s.loudness!==void 0&&(e.loudness=P("--loudness",s.loudness,-70,-5,"-16")),s.cleanAudio&&(e.cleanup=!0,e.loudness??=-16),Object.keys(e).length?e:void 0}function S(s){let e=Number(s);if(!Number.isInteger(e)||e<1||e>100)throw d(`Quality must be a whole number between 1 and 100, not ${s}.`);return e}function ne(s,e){let t=/^\d+$/.test(String(e))?Number(e):Number.NaN;if(!Number.isInteger(t)||t<1)throw d(`${s} takes a whole number of pixels, at least 1, not ${e}.`);return t}function fe(s){let e=String(s),t=/^\d+(\.\d+)?%?$/.test(e)?Number.parseFloat(e):Number.NaN;if(!(t>=1&&t<=W))throw d(`--resize takes a percent from 1 to ${W}, not ${s}.`,"Try --resize 50% to halve, or --width 1200 for an exact width.");return t}function j(s){let e=Number(s);if(!Number.isInteger(e)||e<1)throw d(`Concurrency must be a positive whole number, not ${s}.`);return e}var me=`
|
|
29
|
+
Exit codes:
|
|
30
|
+
0 every input succeeded
|
|
31
|
+
1 the command was understood, and at least one input failed or was refused
|
|
32
|
+
2 the command itself was invalid: an unknown flag, a missing argument, contradictory flags`,ie=`
|
|
33
|
+
Other commands:
|
|
34
|
+
forge probe <files...> what each file is and what Forge can do with it
|
|
35
|
+
forge palette <image> an image's main colours (--json, --svg, --inside <hex>)
|
|
36
|
+
forge scale <colour> 50\u2013950 from one colour, with it at 500 (--json, --svg)
|
|
37
|
+
forge clip compress the copied image and put it back (--to, --quality,
|
|
38
|
+
--max-size, --save [folder], --undo)
|
|
39
|
+
forge transcribe <file | link>
|
|
40
|
+
a video or audio file, or a YouTube link, into notes
|
|
41
|
+
(--to all | notes | transcript, --detail brief | standard | detailed,
|
|
42
|
+
--format md | docx | pdf | txt, --language <id>, -o <path>, --force)
|
|
43
|
+
forge watch <folder> --to <format>
|
|
44
|
+
convert the folder, then every file added to it, until ctrl-c
|
|
45
|
+
(--quality, --dpi, -o <folder>, --new-only, --json)
|
|
46
|
+
forge config [list | path | set <setting> <value>]
|
|
47
|
+
forge extensions [add | remove <id>] optional extras, such as boost and remove-background
|
|
48
|
+
forge update install a newer Forge, if there is one
|
|
49
|
+
forge uninstall take Forge out of the right-click menu, then remove it
|
|
50
|
+
forge mcp run as a local MCP server over stdio, for AI agents`;function ge(s=process.platform){if(s==="darwin")return ie;let e=s==="win32"?"boost and whisper":"whisper and heic";return ie.replace("a video or audio file, or a YouTube link, into notes","a video or audio file, or a YouTube link, into a transcript").replace("optional extras, such as boost and remove-background",`optional extras, such as ${e}`)}function B(s){let e=L(String(s));if(e===void 0)throw d(`${s} is not a size.`,"Try a number with a unit, for example 500kb, 2mb or 1.5mb.");return e}function be(s){let e=s.slice(1).filter(n=>n!=="--json"),t=e.find(n=>n.startsWith("-"));if(t!==void 0)throw d(`forge probe takes files, not ${t}.`,"Try: forge probe photo.jpg --json");if(e.length===0)throw d("No files given.","Name a file, for example: forge probe scan.pdf --json");return{kind:"probe",inputs:e}}function _e(s){let e={kind:"clip",undo:!1,debug:!1},t=s.slice(1),n=(i,o)=>{let r=t[o+1];if(r===void 0||r.startsWith("-"))throw d(`${i} needs a value.`);return r};for(let i=0;i<t.length;i++){let o=t[i];if(o!=="--json")if(o==="--debug")e.debug=!0;else if(o==="--undo")e.undo=!0;else if(o==="--to"||o==="-t")e.target=I(n(o,i++));else if(o==="--quality"||o==="-q")e.quality=S(n(o,i++));else if(o==="--max-size")e.maxBytes=B(n(o,i++));else if(o==="--save"){let r=t[i+1];e.save=r===void 0||r.startsWith("-")?!0:t[++i]}else throw o.startsWith("-")?d(`forge clip does not take ${o}.`,"Try: forge --help"):d(`forge clip takes no files: it reads the clipboard, not ${o}.`,`To compress a file, try: forge ${o} --quality 80`)}if(e.undo&&Object.keys(e).some(i=>!["kind","undo","debug"].includes(i)))throw d("--undo takes no other flag.","Try: forge clip --undo");if(e.quality!==void 0&&e.maxBytes!==void 0)throw d("Use either --quality or --max-size, not both.","They are two ways of asking for the same thing, and Forge will not guess which wins.");return e}function we(s){let e=s.slice(1),t=[],n={kind:"transcribe",input:"",notes:!0,transcript:!0,detail:Q,force:!1,debug:!1},i=(l,h)=>{let a=e[h+1];if(a===void 0||a.startsWith("-"))throw d(`${l} needs a value.`);return a},o="Try: forge transcribe talk.mp4";for(let l=0;l<e.length;l++){let h=e[l];if(h==="--debug")n.debug=!0;else if(h==="--force"||h==="-f")n.force=!0;else if(h==="--language"||h==="-l")n.language=i(h,l++);else if(h==="--output"||h==="-o")n.output=i(h,l++);else if(h==="--detail"){let a=i(h,l++).toLowerCase();if(!X.includes(a))throw d(`forge transcribe writes notes in brief, standard or detailed, not ${a}.`,"Try: forge transcribe talk.mp4 --detail brief");n.detail=a}else if(h==="--format"){let a=i(h,l++).toLowerCase(),c=Y.find(p=>p.id===a||p.label.toLowerCase()===a);if(c===void 0)throw d(`forge transcribe writes md, docx, pdf or txt, not ${a}.`,"Try: forge transcribe talk.mp4 --format pdf");n.format=c.id}else if(h==="--to"||h==="-t"){let a=i(h,l++).toLowerCase();if(a!=="all"&&a!=="notes"&&a!=="transcript")throw d(`forge transcribe makes all, notes or a transcript, not ${a}.`,"Try: forge transcribe talk.mp4 --to transcript");n.to=a,n.notes=a!=="transcript",n.transcript=a!=="notes"}else{if(h.startsWith("-"))throw d(`forge transcribe does not take ${h}.`,o);t.push(h)}}let[r,...u]=t;if(r===void 0)throw d("forge transcribe needs a file or a link.",o);if(u.length>0)throw d("forge transcribe takes one file or link at a time.",o);return{...n,input:r}}function ye(s){let e=s.slice(1),t=[],n,i={kind:"watch",newOnly:!1,debug:!1},o={},r=(h,a)=>{let c=e[a+1];if(c===void 0||c.startsWith("-"))throw d(`${h} needs a value.`);return c};for(let h=0;h<e.length;h++){let a=e[h];if(a!=="--json")if(a==="--debug")i.debug=!0;else if(a==="--new-only")i.newOnly=!0;else if(a==="--to"||a==="-t")n=I(r(a,h++));else if(a==="--quality"||a==="-q")o.quality=S(r(a,h++));else if(a==="--output"||a==="-o")o.output=r(a,h++);else if(a==="--dpi"){let c=r(a,h++),p=Number(c);if(!Number.isInteger(p)||p<36||p>600)throw H(c);o.dpi=p}else{if(a.startsWith("-"))throw d(`forge watch does not take ${a}.`,"Try: forge watch ./images --to webp");t.push(a)}}let[u,...l]=t;if(u===void 0)throw d("forge watch needs a folder.","Try: forge watch ./images --to webp");if(l.length>0)throw d("forge watch watches one folder at a time.",`Try: forge watch ${u} --to webp`);if(n===void 0)throw d("forge watch needs a format to convert to.",`Try: forge watch ${u} --to webp`);return{kind:"watch",folder:u,target:n,...o.quality===void 0?{}:{quality:o.quality},...o.dpi===void 0?{}:{dpi:o.dpi},...o.output===void 0?{}:{output:o.output},newOnly:i.newOnly,debug:i.debug}}function Oe(s){let e=s.slice(1).filter(r=>r!=="--json"),t=e.find(r=>r.startsWith("-"));if(t!==void 0)throw d(`forge extensions does not take ${t}.`,"Try: forge extensions, forge extensions add <id>, or forge extensions remove <id>.");let[n,i,...o]=e;if(n===void 0)return{kind:"extensions",action:"list"};if(n!=="add"&&n!=="remove")throw d(`Unknown extensions action ${n}.`,"Try: forge extensions, forge extensions add <id>, or forge extensions remove <id>.");if(i===void 0||o.length>0)throw d(`forge extensions ${n} takes exactly one extension.`,`Try: forge extensions ${n} boost`);return{kind:"extensions",action:n,id:i}}function oe(s){if(s===void 0)throw d("No colour given.","Try: forge scale 6579FD \u2014 or quote it, '#6579FD', because an unquoted # starts a comment in the shell.");let e=M(s)?.rgb;if(!e)throw d(`${s} is not a colour.`,"Try a hex code (6579FD), rgb(), hsl(), oklch() or a colour name, quoted: 'rgb(101 121 253)'.");return e}function xe(s,e=process.platform,t=process.env){let o=e==="linux"&&!t.WAYLAND_DISPLAY&&!!t.DISPLAY?" --svg a card of swatches; pipe to xclip -sel c, paste into Figma":` --svg a card of swatches; pipe to ${e==="win32"?"clip":e==="linux"?"wl-copy":"pbcopy"} and paste into Figma`;return s==="scale"?`Usage: forge scale <colour> [--json] [--svg]
|
|
51
|
+
|
|
52
|
+
50\u2013950 built in OKLCH, with <colour> at 500. Pass the hex without #, or quote it.
|
|
53
|
+
--json one JSON document: scale.steps[] with hex, oklch, white, black
|
|
54
|
+
${o}
|
|
55
|
+
`:`Usage: forge palette <image> [--json] [--svg] [--inside <hex>]
|
|
56
|
+
|
|
57
|
+
An image's main colours, most of the image first.
|
|
58
|
+
--json one JSON document: palette.colours[] with hex, rgb, oklch, share
|
|
59
|
+
${o}
|
|
60
|
+
--inside <hex> the shades of the palette colour nearest <hex>
|
|
61
|
+
`}function Ce(s){let[e,...t]=s;if(t.includes("--help")||t.includes("-h"))throw process.stdout.write(xe(e==="scale"?"scale":"palette")),new x(0,"commander.helpDisplayed","(outputHelp)");let n=t.filter(l=>l!=="--json"&&l!=="--svg"),i=t.includes("--svg"),o=n.indexOf("--inside"),r=o===-1?void 0:n[o+1];o!==-1&&n.splice(o,2);let u=n.find(l=>l.startsWith("-"));if(u!==void 0)throw d(`forge ${e} does not take ${u}.`,`Try: forge ${e} --help`);if(e==="scale"){if(o!==-1)throw d("--inside is for forge palette.","Try: forge palette photo.jpg --inside F26E69");if(n.length>1)throw d("forge scale takes one colour.","Try: forge scale 6579FD");return{kind:"scale",colour:oe(n[0]),svg:i}}if(n.length!==1)throw d(n.length===0?"No image given.":"forge palette takes one image.","Try: forge palette photo.jpg");return{kind:"palette",input:n[0],svg:i,...o===-1?{}:{inside:oe(r)}}}function ft(s){let e=s.indexOf("--");return(e===-1?s:s.slice(0,e)).includes("--json")}function ke(s){let e=s.indexOf("--"),t=e===-1?s:s.slice(0,e),n=e===-1?[]:s.slice(e),i=[],o;for(let r=0;r<t.length;r++){let u=t[r],l=u.startsWith("--boost=")?u.slice(8):void 0;if(u!=="--boost"&&l===void 0){i.push(u);continue}let h=l;if(h===void 0&&/^\d+$/.test(t[r+1]??"")&&(h=t[++r]),h!==void 0&&h!=="2"&&h!=="3"&&h!=="4")throw d(`--boost takes 2, 3 or 4, not ${h}.`,"Try --boost, --boost 2, --boost 3 or --boost 4.");o=h==="4"?4:h==="3"?3:2}return{rest:[...i,...n],...o===void 0?{}:{scale:o}}}function mt(s){let e=s;if(e[0]==="clip"||e[0]==="watch"||e[0]==="transcribe"||e[0]==="config"||e[0]==="probe"||e[0]==="extensions"||e[0]==="palette"||e[0]==="scale"||e[0]==="update"||e[0]==="uninstall")return ve(e);let t=ke(e);return Ae(t.rest,t.scale)}function ve(s){if(s[0]==="update"){let e=s.slice(1).filter(t=>t!=="--json");if(e.length>0)throw d(`forge update takes nothing else, got: ${e.join(" ")}.`,"Try: forge update");return{kind:"update"}}if(s[0]==="uninstall"){let e=s.slice(1);if(e.length>0)throw d(`forge uninstall takes nothing else, got: ${e.join(" ")}.`,"Try: forge uninstall");return{kind:"uninstall"}}return s[0]==="clip"?_e(s):s[0]==="watch"?ye(s):s[0]==="transcribe"?we(s):s[0]==="config"?ce(s.filter(e=>e!=="--json")):s[0]==="probe"?be(s):s[0]==="palette"||s[0]==="scale"?Ce(s):Oe(s)}function Ae(s,e){let t=new $().name("forge").description("Convert \u2014 transform your files from the terminal").argument("[inputs...]","files, folders or globs").option("-t, --to <format>","target format").option("-o, --output <path>","output file or directory").option("-q, --quality <n>","quality for lossy formats, 1-100").option("--background <colour>","fill colour when flattening transparency","#ffffff").option("--keep-metadata","preserve EXIF and GPS data",!1).option("--recursive","descend into subfolders",!1).option("--force","allow overwriting existing files",!1).option("--max-size <size>","compress until the file fits, e.g. 500kb").option("--concurrency <n>","how many files to convert at once").option("--debug","show underlying errors",!1).option("--formats","list supported formats",!1).option("--merge","combine several PDFs into one").option("--split <mode>","every-page | every=N | at=N,N").option("--extract <pages>","keep only these pages, e.g. 3-7,12").option("--delete <pages>","drop these pages").option("--rotate <degrees>","90, 180 or 270").option("--separate","with --extract, write one file per page").option("--sharpen","sharpen at the same size; needs the boost extension").option("--boost [2|3|4]","sharpen and enlarge 2x (default), 3x or 4x; needs the boost extension").option("--trim","cut transparent or solid-colour edges; keeps the format").option("--crop <W:H>","cut to a shape, e.g. 1:1, 4:5, 16:9; keeps the subject").option("--resize <percent>","resize to a percent of the size, 1-200, e.g. 50%").option("--width <px>","resize to this width; the height follows").option("--height <px>","resize to this height; the width follows").option("--remove-bg","cut out the subject; needs the remove-background extension").option("--cut <start-end>","video or audio: keep from start to end, e.g. 0:03.2-0:41").option("--mute","video: take the sound out").option("--speed <x>","video or audio: play faster or slower, 0.25-4").option("--fps <n>","video: frames per second").option("--bitrate <kbps>","audio: bitrate, e.g. 128k").option("--loudness <LUFS>","audio: even out loudness to this level, e.g. -16").option("--clean-audio","video or audio: take out rumble and hiss, then even the level").option("--preset <name>","run a preset saved from Done, e.g. --preset blog").option("--pages <ranges>","with --to, which pages to render, e.g. 3-7,12").option("--dpi <n>","rasterisation resolution, 36-600","150").option("--password-stdin","read an encrypted PDF's password from stdin").option("--json","print one JSON document on stdout instead of text").helpOption("-h, --help","show this help").version(K,"-V, --version","show the version").addHelpText("after",`${ge()}
|
|
62
|
+
${me}`).configureOutput({outputError:()=>{}}).exitOverride().allowExcessArguments(!1);try{t.parse(s,{from:"user"})}catch(f){if(f instanceof x&&f.code!=="commander.helpDisplayed"&&f.code!=="commander.version"){let[g="",...b]=f.message.replace(/^error: /,"").split(`
|
|
63
|
+
`),w=b.join(" ").trim().replace(/^\((.*)\)\.?$/,"$1");throw d(`${g.charAt(0).toUpperCase()}${g.slice(1).replace(/\.$/,"")}.`,w||"Run forge --help to see what Forge accepts.")}throw f}let n=t.opts(),i=t.args;if(n.formats)return{kind:"formats"};let o=pe(n);if(o!==void 0&&n.trim)throw d("--trim cuts the empty edges of an image.","To keep part of a video or audio file, use --cut, for example --cut 0:03-0:41.");if(n.preset!==void 0){let f=[["to","--to"],["quality","--quality"],["maxSize","--max-size"],["merge","--merge"],["split","--split"],["extract","--extract"],["delete","--delete"],["rotate","--rotate"],["sharpen","--sharpen"],["trim","--trim"],["crop","--crop"],["resize","--resize"],["width","--width"],["height","--height"],["removeBg","--remove-bg"],["pages","--pages"]].filter(([g])=>n[g]!==void 0&&n[g]!==!1).map(([,g])=>g);if(e!==void 0&&f.push("--boost"),f.length>0)throw d(`--preset already says what to do \u2014 leave out ${f.join(" and ")}.`,"Run the preset alone, or change it from Done with \u2192 continue editing.");return{kind:"preset",inputs:i,name:String(n.preset),...n.output===void 0?{}:{output:String(n.output)},force:n.force===!0,recursive:n.recursive===!0,debug:n.debug===!0}}if(n.pages!==void 0&&n.to===void 0)throw d("--pages needs --to: it chooses which pages to render.");let r=["merge","split","extract","delete","rotate"].filter(f=>n[f]!==void 0);if(r.length>1)throw d(`Use one operation at a time \u2014 got ${r.map(f=>`--${f}`).join(" and ")}.`);let u=[...n.sharpen?["--sharpen"]:[],...e!==void 0?["--boost"]:[],...n.removeBg?["--remove-bg"]:[]],l=[...n.resize!==void 0?["--resize"]:[],...n.width!==void 0?["--width"]:[],...n.height!==void 0?["--height"]:[]],h=o!==void 0&&!n.to&&n.quality===void 0&&n.maxSize===void 0;if(n.trim||n.crop!==void 0||l.length>0||h){if(l.length>1)throw d(`Use one of --resize, --width and --height \u2014 got ${l.join(" and ")}.`);let f=n.crop!==void 0?"--crop":l[0]??(n.trim?"--trim":"--cut"),g=[...n.crop!==void 0&&n.trim?["--trim"]:[],...u,...n.maxSize!==void 0?["--max-size"]:[],...n.pages!==void 0?["--pages"]:[],...r.map(re=>`--${re}`)][0];if(g!==void 0)throw d(`${f} cannot be combined with ${g}.`,g!=="--max-size"?"Run them one after the other.":f==="--crop"?"Crop first, then compress the result: forge photo-cropped-1x1.jpg --max-size 500kb":"Resize first, then compress the result: forge photo-1200x900.jpg --max-size 500kb");let b=n.crop!==void 0?{aspect:R(String(n.crop))}:void 0,w=n.resize!==void 0?{percent:fe(n.resize)}:n.width!==void 0?{width:ne("--width",n.width)}:n.height!==void 0?{height:ne("--height",n.height)}:void 0;if(i.length===0)throw d("No files given.","Name an image, for example: forge photo.jpg --resize 50%");let k={background:String(n.background),keepMetadata:!!n.keepMetadata};n.quality!==void 0&&(k.quality=S(String(n.quality)));let y={kind:"edit",inputs:i,trim:!!n.trim,options:k,force:!!n.force,recursive:!!n.recursive,debug:!!n.debug};return b!==void 0&&(y.crop=b),w!==void 0&&(y.resize=w),o!==void 0&&(y.media=o),n.to&&(y.target=I(String(n.to))),n.output!==void 0&&(y.output=String(n.output)),n.concurrency!==void 0&&(y.concurrency=j(String(n.concurrency))),y}let a=n.sharpen?1:e,c=a!==void 0?"boost":n.removeBg?"remove-background":null;if(c!==null){if(u.length>1)throw d(`Use one operation at a time \u2014 got ${u.join(" and ")}.`);let f=u[0];if(r.length>0)throw d(`${f} cannot be combined with --${r[0]}.`);if(n.maxSize!==void 0||n.pages!==void 0)throw d(`${f} cannot be combined with ${n.maxSize!==void 0?"--max-size":"--pages"}.`);if(i.length===0)throw d("No files given.",`Name an image, for example: forge photo.jpg ${f}`);let g=n.to?I(String(n.to)):"png";if(c==="remove-background"){let k=U(g);if(k)throw k}let b={background:String(n.background),keepMetadata:!!n.keepMetadata};n.quality!==void 0&&(b.quality=S(String(n.quality)));let w={kind:"extension-op",op:c,inputs:i,target:g,options:b,force:!!n.force,recursive:!!n.recursive,debug:!!n.debug};return a!==void 0&&(w.scale=a),n.output!==void 0&&(w.output=String(n.output)),n.concurrency!==void 0&&(w.concurrency=j(String(n.concurrency))),w}if(r.length===1){let f=r[0];if(i.length===0)throw d("No files given.",`Name a PDF, for example: forge doc.pdf --${f}`);if(n.separate&&f!=="extract")throw d(`--separate only applies to --extract, not --${f}.`);if(n.output!==void 0)throw d(`--output does not apply to --${f}.`,"Page operations name their own outputs, beside the source. Rename the result afterwards.");let g={kind:"pageop",action:f,inputs:i,force:!!n.force,debug:!!n.debug};if(f==="rotate"){let b=Number(n.rotate);if(!Number.isInteger(b)||b%90!==0||b===0||b>=360)throw d(`--rotate takes a multiple of 90 below 360, not "${n.rotate}".`);g.rotate=b}if((f==="extract"||f==="delete")&&(g.pages=String(n[f]),f==="extract"&&n.separate&&(g.separate=!0)),f==="split"){let b=String(n.split),w=b.match(/^every=(\d+)$/),k=b.match(/^at=([\d,\s]+)$/);if(b==="every-page")g.split={mode:"every-page"};else if(w?.[1]!==void 0){let y=Number(w[1]);if(!Number.isInteger(y)||y<1)throw d(`--split every=N takes a whole number of pages, at least 1, not "${w[1]}".`);g.split={mode:"every-n",n:y}}else if(k?.[1])g.split={mode:"points",after:k[1].split(",").map(y=>Number(y.trim()))};else throw d(`--split takes every-page, every=N or at=N,N \u2014 not "${b}".`)}return g}if(i.length===0&&!n.to&&n.quality===void 0&&n.maxSize===void 0)return{kind:"shell"};if(n.quality!==void 0&&n.maxSize!==void 0)throw d("Use either --quality or --max-size, not both.","They are two ways of asking for the same thing, and Forge will not guess which wins.");if(!n.to&&(n.quality!==void 0||n.maxSize!==void 0)){if(i.length===0)throw d("No files given.","Name a file, for example: forge photo.jpg --max-size 500kb");let f={background:String(n.background),keepMetadata:!!n.keepMetadata};o!==void 0&&(f.media=o);let g={kind:"compress",inputs:i,options:f,force:!!n.force,recursive:!!n.recursive,debug:!!n.debug};if(n.quality!==void 0&&(g.quality=S(String(n.quality))),n.maxSize!==void 0&&(g.maxBytes=B(n.maxSize)),n.output!==void 0&&(g.output=String(n.output)),t.getOptionValueSource("dpi")==="cli"){let b=Number(n.dpi);if(!Number.isInteger(b)||b<36||b>600)throw H(n.dpi);g.dpi=b}return n.concurrency!==void 0&&(g.concurrency=j(String(n.concurrency))),g}if(!n.to)throw d("No target format given.","Add --to <format>, for example: forge photo.jpg --to webp");if(i.length===0)throw d("No files given.","Name a file, a folder or a glob, for example: forge photo.jpg --to webp");let p={background:String(n.background),keepMetadata:!!n.keepMetadata};n.quality!==void 0&&(p.quality=S(String(n.quality))),o!==void 0&&(p.media=o);let O=Number(n.dpi);if(!Number.isInteger(O)||O<36||O>600)throw H(n.dpi);let _={kind:"convert",inputs:i,target:I(String(n.to)),options:p,force:!!n.force,recursive:!!n.recursive,debug:!!n.debug,dpi:O,passwordStdin:!!n.passwordStdin};return n.output!==void 0&&(_.output=String(n.output)),n.pages!==void 0&&(_.pages=String(n.pages)),n.maxSize!==void 0&&(_.maxBytes=B(n.maxSize)),n.concurrency!==void 0&&(_.concurrency=j(String(n.concurrency))),_}export{me as a,ie as b,ge as c,xe as d,ft as e,mt as f};
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { createRequire as __forgeCreateRequire } from 'node:module';
|
|
2
|
+
const require = __forgeCreateRequire(import.meta.url);
|
|
3
|
+
import{r as F}from"./chunk-DZOBIUV6.js";import{execFile as vn}from"node:child_process";import{chmodSync as le,existsSync as Ke,mkdirSync as pe,readdirSync as Ge,readFileSync as H,rmdirSync as Mn,rmSync as $,writeFileSync as In}from"node:fs";import{dirname as U,join as u}from"node:path";var tn={convert:"#55c7d9",compress:"#79c98b",edit:"#b39ae8",pdf:"#ff6b4a"},rn="#55c7d9",on="#a68ce0",sn=4/5,an=(e,n,t,r)=>`<path fill="${r}" d="M${e} ${n}h${4*t}v${t}h${-3*t}v${t}h${2*t}v${t}h${-2*t}v${2*t}h${-t}z"/>`;function cn(e,n){let t=n<=20,r=t?3:4,i=t?6:4.6,o=t?51:51.5,c=Array.from({length:r},(g,w)=>o-(r-1-w)*i).map(g=>`<line x1="${g}" y1="66" x2="${g+66*sn}" y2="0"/>`).join(""),f=e==="forge"?"url(#w)":tn[e];return`<svg width="${n}" height="${n}" viewBox="0 0 64 64" xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="w" gradientUnits="userSpaceOnUse" x1="34" y1="0" x2="62" y2="0"><stop offset="0" stop-color="${rn}"/><stop offset="1" stop-color="${on}"/></linearGradient><clipPath id="c"><rect width="64" height="64" rx="14"/></clipPath><clipPath id="i"><rect x="1.5" y="1.5" width="61" height="61" rx="12.5"/></clipPath></defs><g clip-path="url(#c)"><rect width="64" height="64" fill="#1e1e1e"/><g clip-path="url(#i)" stroke="${f}" stroke-width="${t?3.6:2.4}">${c}</g>${an(16,12,8,"#e7e7e7")}</g><rect x=".75" y=".75" width="62.5" height="62.5" rx="13.5" fill="none" stroke="#3a3a3a" stroke-width="1.5"/></svg>`}async function S(e,n){let{default:t}=await import("sharp");return t(Buffer.from(cn(e,n))).png().toBuffer()}function he(e){let n=Buffer.alloc(6);n.writeUInt16LE(0,0),n.writeUInt16LE(1,2),n.writeUInt16LE(e.length,4);let t=6+16*e.length,r=e.map(({size:i,png:o})=>{let s=Buffer.alloc(16);return s[0]=i>=256?0:i,s[1]=i>=256?0:i,s.writeUInt16LE(1,4),s.writeUInt16LE(32,6),s.writeUInt32LE(o.length,8),s.writeUInt32LE(t,12),t+=o.length,s});return Buffer.concat([n,...r,...e.map(i=>i.png)])}function y(e){let n=[{action:"open",label:"Open Forge",kinds:["image","folder"],window:!0,paint:"forge"},{action:"convert",label:"Convert in Forge",kinds:["image","folder"],window:!0,paint:"convert"},{action:"compress",label:"Compress in Forge",kinds:["image","folder"],window:!0,paint:"compress"},{action:"sharpen",label:"Sharpen in Forge",kinds:["image"],window:!1,paint:"edit"},{action:"open-pdf",label:"Open in Forge",kinds:["pdf"],window:!0,paint:"pdf"}],t=(e.presets??[]).map(r=>({action:"preset",preset:r,label:`${r} in Forge`,kinds:["image"],window:!1,paint:"forge"}));return[...e.sharpen?n:n.filter(r=>r.action!=="sharpen"),...t]}var $e=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");function B(e,n){if(typeof e=="string")return`${n}<string>${$e(e)}</string>`;if(typeof e=="number")return`${n}<integer>${e}</integer>`;if(typeof e=="boolean")return`${n}<${e}/>`;if(Array.isArray(e))return`${n}<array>
|
|
4
|
+
${e.map(r=>B(r,`${n} `)).join(`
|
|
5
|
+
`)}
|
|
6
|
+
${n}</array>`;let t=Object.entries(e).map(([r,i])=>`${n} <key>${$e(r)}</key>
|
|
7
|
+
${B(i,`${n} `)}`);return t.length===0?`${n}<dict/>`:`${n}<dict>
|
|
8
|
+
${t.join(`
|
|
9
|
+
`)}
|
|
10
|
+
${n}</dict>`}var ye=e=>`<?xml version="1.0" encoding="UTF-8"?>
|
|
11
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
12
|
+
<plist version="1.0">
|
|
13
|
+
${B(e,"")}
|
|
14
|
+
</plist>
|
|
15
|
+
`,un={image:"public.image",folder:"public.folder",pdf:"com.adobe.pdf"};function fn(e){return e.length===1&&e[0]==="image"?"com.apple.Automator.fileSystemObject.image":e.length===1&&e[0]==="pdf"?"com.apple.Automator.fileSystemObject.PDF":e.length===1&&e[0]==="folder"?"com.apple.Automator.fileSystemObject.folder":"com.apple.Automator.fileSystemObject"}var a=e=>`'${e.replace(/'/g,"'\\''")}'`,j="forge",xe=e=>e.preset===void 0?`com.forge-terminal.menu.${e.action}`:`com.forge-terminal.menu.preset.${e.preset}`,we="com.forge-terminal.menu.",Se="runWorkflowAsService",E=e=>`${xe(e)} - ${e.label} - ${Se}`,ln=`ObjC.import('Foundation')
|
|
16
|
+
function run(argv) {
|
|
17
|
+
const domain = argv[0]
|
|
18
|
+
const defaults = $.NSUserDefaults.standardUserDefaults
|
|
19
|
+
const or = (v) => (v.isNil() ? $.NSDictionary.dictionary : v)
|
|
20
|
+
const all = $.NSMutableDictionary.dictionaryWithDictionary(or(defaults.persistentDomainForName(domain)))
|
|
21
|
+
const status = $.NSMutableDictionary.dictionaryWithDictionary(or(all.objectForKey('NSServicesStatus')))
|
|
22
|
+
const on = { presentation_modes: { ContextMenu: true, FinderPreview: true, ServicesMenu: true, TouchBar: true } }
|
|
23
|
+
for (const arg of argv.slice(1)) {
|
|
24
|
+
const key = arg.slice(1)
|
|
25
|
+
if (arg[0] === '+') status.setObjectForKey($(on), key)
|
|
26
|
+
else status.removeObjectForKey(key)
|
|
27
|
+
}
|
|
28
|
+
all.setObjectForKey(status, 'NSServicesStatus')
|
|
29
|
+
defaults.setPersistentDomainForName(all, domain)
|
|
30
|
+
}`;function D(e){return[e.osascript??"/usr/bin/osascript",["-l","JavaScript","-e",ln,e.domain??"pbs",...e.on.map(n=>`+${n}`),...e.off.map(n=>`-${n}`)]]}function _(e,n){let t=ye({CFBundleDevelopmentRegion:"English",CFBundleIdentifier:xe(e),CFBundleInfoDictionaryVersion:"6.0",CFBundleName:e.label,CFBundlePackageType:"BNDL",CFBundleShortVersionString:"1.0",CFBundleVersion:"1",NSServices:[{NSIconName:j,NSMenuItem:{default:e.label},NSMessage:Se,NSRequiredContext:{NSApplicationIdentifier:"com.apple.finder"},NSSendFileTypes:e.kinds.map(s=>un[s])}]}),r=e.preset===void 0?"":` ${a(e.preset)}`,i=`${a(n)} ${e.action}${r} "$@"`,o=ye({AMApplicationBuild:"521",AMApplicationVersion:"2.10",AMDocumentVersion:"2",actions:[{action:{AMAccepts:{Container:"List",Optional:!0,Types:["com.apple.cocoa.path"]},AMActionVersion:"2.0.3",AMApplication:["Automator"],AMParameterProperties:{COMMAND_STRING:{},CheckedForUserDefaultShell:{},inputMethod:{},shell:{},source:{}},AMProvides:{Container:"List",Types:["com.apple.cocoa.string"]},ActionBundlePath:"/System/Library/Automator/Run Shell Script.action",ActionName:"Run Shell Script",ActionParameters:{COMMAND_STRING:i,CheckedForUserDefaultShell:!0,inputMethod:1,shell:"/bin/zsh",source:""},BundleIdentifier:"com.apple.RunShellScript",CFBundleVersion:"2.0.3",CanShowSelectedItemsWhenRun:!1,CanShowWhenRun:!0,Category:["AMCategoryUtilities"],"Class Name":"RunShellScriptAction",InputUUID:"7A1F3C2E-0F4B-4E8A-9C61-5B2D8E4F1A01",OutputUUID:"7A1F3C2E-0F4B-4E8A-9C61-5B2D8E4F1A02",UUID:"7A1F3C2E-0F4B-4E8A-9C61-5B2D8E4F1A03",UnlocalizedApplications:["Automator"]},isViewVisible:!0}],connectors:{},workflowMetaData:{serviceApplicationBundleID:"com.apple.finder",serviceApplicationPath:"/System/Library/CoreServices/Finder.app",serviceInputTypeIdentifier:fn(e.kinds),serviceOutputTypeIdentifier:"com.apple.Automator.nothing",serviceProcessesInput:!1,workflowTypeIdentifier:"com.apple.Automator.servicesMenu"}});return{name:`${e.label}.workflow`,files:{"Contents/Info.plist":t,"Contents/document.wflow":o,"Contents/Resources/document.wflow":o}}}import{execFile as xn}from"node:child_process";import{accessSync as pn,constants as mn}from"node:fs";import{isAbsolute as De,join as p}from"node:path";var d="forge-terminal-menu";function ve(e){let n=r=>r&&De(r)?r:void 0,t=(e.xdgConfigDirs??"").split(":").filter(r=>De(r));return{dataHome:n(e.xdgDataHome)??p(e.home,".local","share"),configHome:n(e.xdgConfigHome)??p(e.home,".config"),configDirs:t.length>0?t:["/etc/xdg"]}}function K(e,n=process.env.PATH){for(let t of(n??"").split(":"))if(t!=="")try{return pn(p(t,e),mn.X_OK),!0}catch{}return!1}var Me={image:"image/*",folder:"inode/directory",pdf:"application/pdf"},gn=e=>e.map(n=>`${Me[n]};`).join(""),P=e=>`${e.paint}.png`,h=e=>p(e.dataHome,"nautilus","scripts","Forge"),b=e=>e.preset===void 0?e.action:`preset-${e.preset}`,k=e=>e.preset===void 0?e.action:`preset ${e.preset}`,G=e=>e.label;function Ie(e,n){return`#!/bin/sh
|
|
31
|
+
# ${d}: Forge's right-click menu, written by Forge. \`forge menu remove\` takes it out.
|
|
32
|
+
if [ -n "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS" ]; then
|
|
33
|
+
IFS='
|
|
34
|
+
'
|
|
35
|
+
set -f
|
|
36
|
+
set -- $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS
|
|
37
|
+
fi
|
|
38
|
+
exec ${a(n)} ${k(e)} "$@"
|
|
39
|
+
`}var I=e=>p(e.dataHome,"nemo","actions"),W=(e,n)=>`forge-${e.preset===void 0?n.indexOf(e.action)+1:n.length+1}-${b(e)}.nemo_action`,M=e=>e.replace(/%/g,"%%");function Ne(e,n){return`[Nemo Action]
|
|
40
|
+
# ${d}: Forge's right-click menu, written by Forge. \`forge menu remove\` takes it out.
|
|
41
|
+
Name=${M(e.label)}
|
|
42
|
+
Comment=${M(e.label)}
|
|
43
|
+
Exec=${M(a(n))} ${k(e)} %F
|
|
44
|
+
Selection=notnone
|
|
45
|
+
Mimetypes=${gn(e.kinds)}
|
|
46
|
+
`}var A=e=>p(e.dataHome,"kio","servicemenus"),V=e=>`forge-${e}.desktop`,X=["image","folder","pdf"],dn=e=>M(`"${e.replace(/[\\"`$]/g,"\\$&")}"`).replace(/\\/g,"\\\\");function Fe(e,n,t){let r=n.filter(c=>c.kinds.includes(e));if(r.length===0)return;let i=r.length>1,o=["[Desktop Entry]",`# ${d}: Forge's right-click menu, written by Forge. \`forge menu remove\` takes it out.`,"Type=Service","ServiceTypes=KonqPopupMenu/Plugin","X-KDE-ServiceTypes=KonqPopupMenu/Plugin",`MimeType=${Me[e]};`,`Actions=${r.map(c=>`${b(c)};`).join("")}`,"X-KDE-Priority=TopLevel",...i?["X-KDE-Submenu=Forge",`Icon=${p(t.menuDir,"forge.png")}`]:[]],s=r.map(c=>["",`[Desktop Action ${b(c)}]`,`Name=${c.label}`,`Icon=${p(t.menuDir,P(c))}`,`Exec=${dn(t.launcher)} ${k(c)} %F`].join(`
|
|
47
|
+
`));return`${[...o,...s].join(`
|
|
48
|
+
`)}
|
|
49
|
+
`}var C=e=>p(e.configHome,"Thunar","uca.xml"),Ee=e=>e.configDirs.map(n=>p(n,"Thunar","uca.xml")),be=`<?xml version="1.0" encoding="UTF-8"?>
|
|
50
|
+
<actions>
|
|
51
|
+
</actions>
|
|
52
|
+
`,hn=e=>`${d}-${b(e)}`,v=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),$n={image:{patterns:["*"],type:"image-files"},folder:{patterns:["*"],type:"directories"},pdf:{patterns:["*.pdf","*.PDF"],type:"other-files"}};function Pe(e,n){return e.map(t=>{let r=t.kinds.map(s=>$n[s]),i=[...new Set(r.flatMap(s=>s.patterns))],o=i.includes("*")?["*"]:i;return["<action>",` <icon>${v(p(n.menuDir,P(t)))}</icon>`,` <name>${v(t.label)}</name>`,` <submenu>${t.kinds.includes("pdf")?"":"Forge"}</submenu>`,` <unique-id>${hn(t)}</unique-id>`,` <command>${v(M(a(n.launcher)))} ${k(t)} %F</command>`,` <description>${v(t.label)}</description>`," <range></range>",` <patterns>${v(o.join(";"))}</patterns>`,...r.map(s=>` <${s.type}/>`),"</action>"].join(`
|
|
53
|
+
`)}).map(t=>`${t}
|
|
54
|
+
`).join("")}var yn=/[ \t]*<action>[\s\S]*?<\/action>[ \t]*\r?\n?/g;function J(e){return e.replace(yn,n=>n.includes(`<unique-id>${d}-`)?"":n)}function q(e,n){let t=J(e),r=t.lastIndexOf("</actions>");if(r===-1||!/<actions>/.test(t))return;let i=t.lastIndexOf(`
|
|
55
|
+
`,r)+1;return/^[ \t]*$/.test(t.slice(i,r))&&(r=i),`${t.slice(0,r)}${n}${t.slice(r)}`}var ke=(e,n,t)=>K("thunar",n)||t(p(e.configHome,"Thunar"));var Y="ForgeTerminal.Forge",Ae=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),Q=e=>e.replace(/['‘’‚‛]/g,"$&$&"),Ce=Q;function Z(e,n){return["[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] > $null","[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] > $null","$x = New-Object Windows.Data.Xml.Dom.XmlDocument",`$x.LoadXml('<toast><visual><binding template="ToastText02"><text id="1">${Ce(Ae(e))}</text><text id="2">${Ce(Ae(n))}</text></binding></visual></toast>')`,`[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('${Y}').Show([Windows.UI.Notifications.ToastNotification]::new($x))`].join("; ")}function wn(e,n,t=process.platform){return t==="win32"?["powershell.exe",["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",Z(e,n)]]:["/usr/bin/osascript",["-e","on run argv","-e","display notification (item 2 of argv) with title (item 1 of argv)","-e","end run",e,n]]}var T=e=>`"${e.replace(/[\\"]/g,"\\$&").replace(/\n/g,"\\n")}"`;function Sn(e,n,t={}){let r=t.has??(i=>K(i));if(r("notify-send"))return["notify-send",["--app-name=Forge",...t.icon?[`--icon=${t.icon}`]:[],"--",e,n]];if(r("gdbus"))return["gdbus",["call","--session","--dest","org.freedesktop.Notifications","--object-path","/org/freedesktop/Notifications","--method","org.freedesktop.Notifications.Notify",T("Forge"),"0",T(t.icon??""),T(e),T(n),"[]","{}","-1"]]}function _n(e,n,t=process.platform,r={}){let i=t==="linux"?Sn(e,n,r):wn(e,n,t);return new Promise(o=>{if(i===void 0)return o();try{xn(i[0],i[1],{timeout:1e4,windowsHide:!0},()=>o())}catch{o()}})}var z="Forge was uninstalled",ee="Its menu items are removed.",Te="Forge could not start",Oe="Run forge in a terminal once to set its menu up again.";function Le(e){let{osascript:n,pbs:t}=e.tools??{osascript:"/usr/bin/osascript",pbs:"/System/Library/CoreServices/pbs"},r=[e.node,...e.execArgv,e.forge].map(a).join(" "),[i,o]=D({on:[],off:e.services,osascript:n}),s=[i,...o].map(a).join(" "),c=(f,g)=>`${a(n)} -e 'display notification "${g}" with title "${f}"'`;return`#!/bin/sh
|
|
56
|
+
# Forge's right-click menu. Rewritten by Forge whenever it sets the menu up.
|
|
57
|
+
if [ ! -f ${a(e.forge)} ]; then
|
|
58
|
+
# Forge is gone: take its menu with it, and say so once.
|
|
59
|
+
${e.bundles.map(f=>` rm -rf ${a(f)}`).join(`
|
|
60
|
+
`)}
|
|
61
|
+
rm -rf ${a(e.menuDir)}
|
|
62
|
+
${s}
|
|
63
|
+
${a(t)} -update
|
|
64
|
+
${c(z,ee)}
|
|
65
|
+
exit 0
|
|
66
|
+
fi
|
|
67
|
+
if [ ! -x ${a(e.node)} ]; then
|
|
68
|
+
${c(Te,Oe)}
|
|
69
|
+
exit 1
|
|
70
|
+
fi
|
|
71
|
+
${e.xdgConfigHome===void 0?"":`export XDG_CONFIG_HOME=${a(e.xdgConfigHome)}
|
|
72
|
+
`}exec ${r} menu run "$@"
|
|
73
|
+
`}function Ue(e){let n=e.xdgConfigHome===void 0?{}:{XDG_CONFIG_HOME:e.xdgConfigHome};return`// Forge's right-click menu. Rewritten by Forge whenever it sets the menu up.
|
|
74
|
+
import { execFileSync, spawn } from 'node:child_process'
|
|
75
|
+
import { existsSync, rmSync } from 'node:fs'
|
|
76
|
+
|
|
77
|
+
const FORGE = ${JSON.stringify(e.forge)}
|
|
78
|
+
const ARGS = ${JSON.stringify(e.execArgv)}
|
|
79
|
+
const MENU = ${JSON.stringify(e.menuDir)}
|
|
80
|
+
const KEYS = ${JSON.stringify(e.keys)}
|
|
81
|
+
const ENV = ${JSON.stringify(n)}
|
|
82
|
+
|
|
83
|
+
if (existsSync(FORGE)) {
|
|
84
|
+
const child = spawn(process.execPath, [...ARGS, FORGE, 'menu', 'run', ...process.argv.slice(2)], {
|
|
85
|
+
stdio: 'inherit',
|
|
86
|
+
windowsHide: true,
|
|
87
|
+
env: { ...process.env, ...ENV },
|
|
88
|
+
})
|
|
89
|
+
child.on('exit', (code) => process.exit(code ?? 0))
|
|
90
|
+
} else {
|
|
91
|
+
// Forge is gone: say so while its app ID still exists, then take the menu with it.
|
|
92
|
+
try {
|
|
93
|
+
execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', ${JSON.stringify(Z(z,ee))}], { windowsHide: true })
|
|
94
|
+
} catch {}
|
|
95
|
+
for (const key of KEYS) {
|
|
96
|
+
try {
|
|
97
|
+
execFileSync('reg.exe', ['delete', key, '/f'], { windowsHide: true, stdio: 'ignore' })
|
|
98
|
+
} catch {}
|
|
99
|
+
}
|
|
100
|
+
rmSync(MENU, { recursive: true, force: true })
|
|
101
|
+
}
|
|
102
|
+
`}function Dn(){return`say() {
|
|
103
|
+
if command -v notify-send >/dev/null 2>&1; then
|
|
104
|
+
notify-send --app-name=Forge -- "$1" "$2" >/dev/null 2>&1
|
|
105
|
+
elif command -v gdbus >/dev/null 2>&1; then
|
|
106
|
+
${["gdbus call --session --dest org.freedesktop.Notifications","--object-path /org/freedesktop/Notifications","--method org.freedesktop.Notifications.Notify",`Forge 0 "''" "\\"$1\\"" "\\"$2\\"" '[]' '{}' -1`].join(" ")} >/dev/null 2>&1
|
|
107
|
+
fi
|
|
108
|
+
}`}function He(e){let n=[e.node,...e.execArgv,e.forge].map(a).join(" "),t=e.files.map(a).join(` \\
|
|
109
|
+
`),r="";if(e.thunar!==void 0){let i=a(e.thunar.file),o=a(`${e.thunar.file}.forge-tmp`),s=a(e.thunar.seed),c=['/<action>/ { held = ""; holding = 1 }',`holding { held = held $0 "\\n"; if (/<\\/action>/) { holding = 0; if (held !~ /<unique-id>${e.marker}-/) printf "%s", held }; next }`,"{ print }"].join(`
|
|
110
|
+
`);r=` if [ -f ${i} ] && grep -qF '<unique-id>${e.marker}-' ${i}; then
|
|
111
|
+
awk ${a(c)} ${i} > ${o} && mv -f ${o} ${i}
|
|
112
|
+
if [ -f ${s} ] && cmp -s ${s} ${i}; then rm -f ${i}; fi
|
|
113
|
+
fi
|
|
114
|
+
`}return`#!/bin/sh
|
|
115
|
+
# Forge's right-click menu. Rewritten by Forge whenever it sets the menu up.
|
|
116
|
+
${Dn()}
|
|
117
|
+
if [ ! -f ${a(e.forge)} ]; then
|
|
118
|
+
# Forge is gone: take its menu with it, and say so once.
|
|
119
|
+
for f in ${t}; do
|
|
120
|
+
if [ -f "$f" ] && grep -qF ${a(e.marker)} "$f"; then rm -f "$f"; fi
|
|
121
|
+
done
|
|
122
|
+
${r}${e.folders.map(i=>` rmdir ${a(i)} 2>/dev/null
|
|
123
|
+
`).join("")} rm -rf ${a(e.menuDir)}
|
|
124
|
+
say ${a(z)} ${a(ee)}
|
|
125
|
+
exit 0
|
|
126
|
+
fi
|
|
127
|
+
if [ ! -x ${a(e.node)} ]; then
|
|
128
|
+
say ${a(Te)} ${a(Oe)}
|
|
129
|
+
exit 1
|
|
130
|
+
fi
|
|
131
|
+
${e.xdgConfigHome===void 0?"":`export XDG_CONFIG_HOME=${a(e.xdgConfigHome)}
|
|
132
|
+
`}exec ${n} menu run "$@"
|
|
133
|
+
`}var O="HKCU\\Software\\Classes",Re=`${O}\\SystemFileAssociations\\image\\shell\\Forge`,Be=`${O}\\Directory\\shell\\Forge`,te=`${O}\\SystemFileAssociations\\.pdf\\shell\\ForgeOpen`,je=`${O}\\AppUserModelId\\${Y}`,ie=()=>[Re,Be,te,je],oe=e=>`${e.paint}.ico`;function _e(e){let n=o=>`conhost.exe --headless "${e.node}" "${e.menuDir}\\run.mjs" ${o.action}${o.preset===void 0?"":` ${o.preset}`} "%1"`,t=o=>`${e.menuDir}\\${oe(o)}`,r=(o,s)=>{let c=e.items.filter(f=>f.kinds.includes(s));return c.length===0?[]:[{key:o,values:{MUIVerb:"Forge",Icon:t({paint:"forge"}),SubCommands:""}},...c.flatMap((f,g)=>{let w=f.preset===void 0?f.action:`preset-${f.preset}`,l=`${o}\\shell\\${g+1}${w}`;return[{key:l,values:{MUIVerb:f.label,Icon:t(f)}},{key:`${l}\\command`,values:{"":n(f)}}]})]},i=e.items.find(o=>o.kinds.includes("pdf"));return[...r(Re,"image"),...r(Be,"folder"),...i?[{key:te,values:{MUIVerb:i.label,Icon:t(i)}},{key:`${te}\\command`,values:{"":n(i)}}]:[],{key:je,values:{DisplayName:"Forge",IconUri:`${e.menuDir}\\forge.png`}}]}var re=e=>`'${Q(e)}'`,ne=e=>re(`Registry::${e.replace(/^HKCU\\/,"HKEY_CURRENT_USER\\")}`);function se(e){return["$ErrorActionPreference = 'Stop'",...ie().map(t=>`Remove-Item -Path ${ne(t)} -Recurse -Force -ErrorAction SilentlyContinue`),...e.flatMap(({key:t,values:r})=>[`New-Item -Path ${ne(t)} -Force | Out-Null`,...Object.entries(r).map(([i,o])=>`Set-ItemProperty -LiteralPath ${ne(t)} -Name ${re(i===""?"(default)":i)} -Value ${re(o)}`)])].join(`
|
|
134
|
+
`)}var ot=(e,n)=>e.version===n.version&&e.forge===n.forge&&e.node===n.node&&e.execArgv.join("\0")===n.execArgv.join("\0")&&e.xdgConfigHome===n.xdgConfigHome&&(e.presets??[]).join("\0")===(n.presets??[]).join("\0"),We="/System/Library/CoreServices/pbs",Ve=e=>u(e.menuDir,"state.json"),N=e=>u(e.home,"Library","Services"),ce=e=>y({sharpen:!0}).map(n=>u(N(e),`${n.label}.workflow`)),ue=()=>y({sharpen:!0}).map(E);function Xe(e){let n;try{n=Ge(N(e)).filter(t=>t.endsWith(".workflow"))}catch{return[]}return n.flatMap(t=>{let r=u(N(e),t);try{let i=H(u(r,"Contents","Info.plist"),"utf8"),o=/<key>CFBundleIdentifier<\/key>\s*<string>([^<]*)<\/string>/.exec(i)?.[1],s=/<key>CFBundleName<\/key>\s*<string>([^<]*)<\/string>/.exec(i)?.[1];return!o?.startsWith(we)||s===void 0?[]:[{path:r,key:`${o} - ${(f=>f.replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&"))(s)} - runWorkflowAsService`}]}catch{return[]}})}function Nn(e){try{return JSON.parse(H(Ve(e),"utf8"))}catch{return}}var st=e=>Nn(e)!==void 0,m=(e,n)=>{pe(U(e),{recursive:!0}),In(e,n)};async function at(e){if(!Fn(e.platform))return;let n=y({sharpen:e.sharpen,presets:e.presets??[]});if(pe(e.menuDir,{recursive:!0}),e.platform==="linux")await kn(e,n);else if(e.platform==="darwin"){let r=u(e.menuDir,"run"),i=n.filter(l=>l.preset!==void 0),o=i.map(l=>u(N(e),_(l,r).name));m(r,Le({...e,bundles:[...ce(e),...o],services:[...ue(),...i.map(E)]})),le(r,493);let s=Xe(e);for(let l of[...ce(e),...s.map(R=>R.path)])$(l,{recursive:!0,force:!0});let c=new Map,{default:f}=await import("sharp");for(let l of n){c.has(l.paint)||c.set(l.paint,await f(await S(l.paint,64)).tiff().toBuffer());let{name:R,files:ze}=_(l,r),de=u(N(e),R);for(let[en,nn]of Object.entries(ze))m(u(de,en),nn);m(u(de,"Contents","Resources",`${j}.tiff`),c.get(l.paint))}let g=n.map(E),w=new Set([...ue(),...s.map(l=>l.key)]);await e.run(...D({on:g,off:[...w].filter(l=>!g.includes(l))})),await e.run(We,["-update"])}else{m(u(e.menuDir,"run.mjs"),Ue({...e,keys:ie()}));for(let r of Je){let i=await Promise.all([16,24,32,48,256].map(async o=>({size:o,png:await S(r,o)})));m(u(e.menuDir,oe({paint:r})),he(i))}m(u(e.menuDir,"forge.png"),await S("forge",256)),await e.run("powershell.exe",Ze(se(_e({...e,items:n}))))}let t={version:e.version,forge:e.forge,node:e.node,execArgv:e.execArgv,...e.xdgConfigHome===void 0?{}:{xdgConfigHome:e.xdgConfigHome},...e.presets&&e.presets.length>0?{presets:[...e.presets]}:{}};m(Ve(e),JSON.stringify(t))}var Fn=e=>e==="darwin"||e==="win32"||e==="linux",Je=["forge","convert","compress","edit","pdf"],qe=e=>ve({home:e.home,...e.xdgDataHome===void 0?{}:{xdgDataHome:e.xdgDataHome},...e.xdgConfigHome===void 0?{}:{xdgConfigHome:e.xdgConfigHome},...e.xdgConfigDirs===void 0?{}:{xdgConfigDirs:e.xdgConfigDirs}});function fe(e){let n=y({sharpen:!0}),t=n.map(i=>i.action),r=(i,o)=>{try{return Ge(i).filter(o).map(s=>u(i,s))}catch{return[]}};return[...new Set([...n.map(i=>u(h(e),G(i))),...r(h(e),()=>!0),...n.map(i=>u(I(e),W(i,t))),...r(I(e),i=>i.startsWith("forge-")&&i.endsWith(".nemo_action")),...X.map(i=>u(A(e),V(i)))])]}var x=e=>{try{return H(e,"utf8")}catch{return}};function Ye(e){for(let n of e)x(n)?.includes(d)&&$(n,{force:!0})}var Qe=e=>u(e.menuDir,"made.json"),me=e=>{try{return JSON.parse(H(Qe(e),"utf8"))}catch{return[]}};function L(e,n){let t=[];for(let r=n;!Ke(r)&&U(r)!==r;r=U(r))t.push(r);t.length!==0&&(pe(n,{recursive:!0}),m(Qe(e),JSON.stringify([...new Set([...me(e),...t])])))}function En(e){for(let n of[...e].sort((t,r)=>r.length-t.length))try{Mn(n)}catch{}}var ge=e=>u(e.menuDir,"thunar-seed.xml");async function bn(e,n,t,r){let i=C(n),o=x(i);if(o===void 0){if(!ke(n,e.path,Ke))return;o=Ee(n).map(x).find(c=>c!==void 0&&q(c,"")!==void 0)??be,m(ge(e),o),L(e,U(i))}let s=q(o,Pe(t,{launcher:r,menuDir:e.menuDir}));s!==void 0&&s!==x(i)&&await F(i,Buffer.from(s))}async function Pn(e,n){let t=C(n),r=x(t);if(r===void 0||!r.includes(`<unique-id>${d}-`))return;let i=J(r);i===x(ge(e))?$(t,{force:!0}):await F(t,Buffer.from(i))}async function ae(e,n,t=!1){await F(e,Buffer.from(n)),t&&le(e,493)}async function kn(e,n){let t=qe(e),r=u(e.menuDir,"run");for(let o of Je)m(u(e.menuDir,P({paint:o})),await S(o,128));Ye(fe(t));let i=y({sharpen:!0}).map(o=>o.action);L(e,h(t));for(let o of n)await ae(u(h(t),G(o)),Ie(o,r),!0);L(e,I(t));for(let o of n)await ae(u(I(t),W(o,i)),Ne(o,r));L(e,A(t));for(let o of X){let s=Fe(o,n,{launcher:r,menuDir:e.menuDir});s!==void 0&&await ae(u(A(t),V(o)),s,!0)}await bn(e,t,n,r),m(r,He({...e,files:fe(t),folders:[...new Set([h(t),...me(e)])].sort((o,s)=>s.length-o.length),marker:d,thunar:{file:C(t),seed:ge(e)}})),le(r,493)}async function An(e){let n=qe(e);Ye(fe(n)),await Pn(e,n),En([h(n),...me(e)]),$(e.menuDir,{recursive:!0,force:!0})}async function ct(e){if(e.platform==="linux")await An(e);else if(e.platform==="darwin"){let n=Xe(e);for(let r of[...ce(e),...n.map(i=>i.path)])$(r,{recursive:!0,force:!0});$(e.menuDir,{recursive:!0,force:!0});let t=new Set([...ue(),...n.map(r=>r.key)]);await e.run(...D({on:[],off:[...t]})),await e.run(We,["-update"])}else e.platform==="win32"&&($(e.menuDir,{recursive:!0,force:!0}),await e.run("powershell.exe",Ze(se([]))))}var Ze=e=>["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",e],ut=(e,n)=>new Promise((t,r)=>{vn(e,n,{timeout:6e4,windowsHide:!0},i=>i?r(i):t())});export{a,K as b,P as c,_n as d,ot as e,Nn as f,st as g,at as h,Fn as i,ct as j,ut as k};
|