piconvert
Version:
Convert pictures to other formats. Supports ai, cdr, vsd, pdf, and more formats. GitHub Actions & CLI Tool.
5 lines (4 loc) • 9.18 kB
JavaScript
;var H=Object.create;var z=Object.defineProperty;var K=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var Q=Object.getPrototypeOf,R=Object.prototype.hasOwnProperty;var W=(s,p,t,o)=>{if(p&&typeof p=="object"||typeof p=="function")for(let n of M(p))!R.call(s,n)&&n!==t&&z(s,n,{get:()=>p[n],enumerable:!(o=K(p,n))||o.enumerable});return s};var C=(s,p,t)=>(t=s!=null?H(Q(s)):{},W(p||!s||!s.__esModule?z(t,"default",{value:s,enumerable:!0}):t,s));var F=require("fs"),b=require("path"),h=require("commander");var r=require("chalk");var c=require("fs"),m=require("path"),D=C(require("events")),E=C(require("js-yaml"));var P=require("child_process"),L=C(require("sharp"));function _(s){var t;return s=(((t=s.split("."))==null?void 0:t.pop())||"").toLowerCase().trim(),{jpg:"jpeg"}[s]||s}var X=["jpeg","png","webp","gif","avif","tiff"],Y=["svg","png","ps","eps","pdf","emf","wmf","xaml"];async function I(s,p,t,o,n=!1){p=_(p);let e=`svg -> ${p} ${t||""}x${o||""}`;n&&(console.log(`Normalized Type: ${p}`),console.time(e));let l;if(["svg"].includes(p))l=Buffer.from(s);else if(X.includes(p)){n&&console.log("Use: sharp");let i=(0,L.default)(Buffer.from(s));(t===null||t<=0)&&(t=null),(o===null||o<=0)&&(o=null),(t||o)&&i.resize(t,o),l=await i[p]().toBuffer()}else if(Y.includes(p)){n&&console.log("Use: inkscape");let i=["--export-area-page",`--export-type ${p}`];t!==null&&t>0&&i.push(`--export-width ${t}`),o!==null&&o>0&&i.push(`--export-height ${o}`),l=(0,P.execSync)(`inkscape --pipe ${i.join(" ")} --export-filename -`,{input:s,stdio:"pipe"})}else throw new Error(`Unsupported file type: ${p}`);return n&&console.timeEnd(e),l}var U=require("child_process"),N=require("svgo");var Z=["ai","cdr","vsd","pdf","jpg","jpeg","png","gif","bmp"];async function S(s,p=!1){let t=_(s),o=`${t} -> svg`;p&&(console.log(`Normalized Type: ${t}`),console.time(o));let n="";if(Z.includes(t)){let l=(0,U.spawn)("inkscape",["--pipe","--export-plain-svg","--pdf-poppler","--export-type","svg","--export-filename","-",s]);l.stdout.on("data",i=>n+=i.toString()),await new Promise(i=>l.on("close",()=>i(n)))}else throw new Error(`Unsupported file type: ${t}`);let e=(0,N.optimize)(n,{multipass:!0});return p&&console.timeEnd(o),e.data}var $=class extends D.default{constructor(){super(...arguments);this.imports=[];this.exports={}}emit(t,...o){return super.emit(t,...o)}on(t,o){return super.on(t,o)}async convert(t,o,n,e,l=!1){this.emit("task-start",o,n,e);try{let i=(0,m.resolve)(n,`${(0,m.basename)(o.split(".").slice(0,-1).join("."))}${e.width||e.height?`.${e.width||""}x${e.height||""}`:""}.${e.format}`);if(e.force||!(0,c.existsSync)(i)){(0,c.existsSync)(n)||(0,c.mkdirSync)(n,{recursive:!0});let a=await I(t,e.format,e.width,e.height,l);(0,c.writeFileSync)(i,a),this.emit("task-succeeded",o,n,e)}else this.emit("task-skipped",o,n,e)}catch(i){l&&console.error(i),this.emit("task-failed",o,n,e)}}async convert_file(t,o,n,e=!1,l=!1){this.emit("file-start",t,o,n,e,l);let i=(0,m.resolve)((0,m.dirname)(t),t.split(".").slice(0,-1).join(".")),a=(0,c.existsSync)(i+".yml")?i+".yml":(0,c.existsSync)(i+".yaml")?i+".yaml":null,u=n;a&&(u=E.default.load((0,c.readFileSync)(a,"utf8")));let f=Object.keys(u),x=[];for(let v of f){let g=u[v];if(g)for(let d of g){let A=typeof d=="number"?d:parseInt(d.split("x")[0])||0,G=typeof d=="number"?d:parseInt(d.split("x")[1])||0;x.push({format:v,width:A,height:G,force:e})}else x.push({format:v,width:0,height:0,force:e})}let w=await S(t,l);for(let v of x)await this.convert(w,t,o,v,l);this.emit("file-finish",t,o,n,e,l)}async convert_directory(t,o,n,e,l=!1,i=!1,a=!0){this.emit("directory-start",t,o,n,e,l,i,a);let u=(0,c.readdirSync)(t),f=u.filter(g=>(0,c.statSync)((0,m.resolve)(t,g)).isFile()).filter(g=>{var d;return n.includes((d=g.split(".").pop())==null?void 0:d.toLowerCase())}),x=u.filter(g=>(0,c.statSync)((0,m.resolve)(t,g)).isDirectory()),w=(0,c.existsSync)((0,m.resolve)(t,"piconvert.yml"))?(0,m.resolve)(t,"piconvert.yml"):(0,c.existsSync)((0,m.resolve)(t,"piconvert.yaml"))?(0,m.resolve)(t,"piconvert.yaml"):(0,c.existsSync)((0,m.resolve)(t,".piconvert.yml"))?(0,m.resolve)(t,".piconvert.yml"):(0,c.existsSync)((0,m.resolve)(t,".piconvert.yaml"))?(0,m.resolve)(t,".piconvert.yaml"):null,v=e;w&&(v=E.default.load((0,c.readFileSync)(w,"utf8")));for(let g of f)await this.convert_file((0,m.resolve)(t,g),o,v,l,i);if(this.emit("directory-finish",t,o,n,e,l,i,a),a){let g=x.filter(d=>d[0]&&d[0]!==".").map(d=>(0,m.resolve)(t,d));for(let d of g)await this.convert_directory(d,(0,m.resolve)(o,(0,m.basename)(d)),n,v,l,i,a)}}export(t,o=null){return this.exports[t]=o,this}clear_exports(){return this.exports={},this}import(t){return this.imports.push(t),this}clear_imports(){return this.imports=[],this}async run(t,o,n=!0,e=!1,l=!1){t=(0,m.resolve)(t),o=(0,m.resolve)(o),this.emit("conversion-start",t,o),(0,c.existsSync)(t)&&((0,c.statSync)(t).isDirectory()?await this.convert_directory(t,o,this.imports,this.exports,e,l,n):await this.convert_file(t,o,this.exports,e,l)),this.emit("conversion-finish",t,o)}},T=$;var J=require("child_process");var V=require("child_process"),O=["ai","cdr","vsd","pdf","jpg","jpeg","png","gif","bmp"],j=["svg","png","ps","eps","pdf","emf","wmf","xaml"];function k(){try{return(0,V.execSync)("inkscape --version",{stdio:"pipe"}).toString().match(/\d+\.\d+\.\d+/)!==null}catch{return!1}}async function q(s=!1){if(k())return!0;{let p=process.getuid&&process.getuid()===0?"sudo ":"",t="";process.platform==="linux"?t=`${p}add-apt-repository -y ppa:inkscape.dev/stable && ${p}apt update && ${p}apt install -y inkscape`:process.platform==="darwin"?t="brew install --cask inkscape":process.platform==="win32"?t="choco install inkscape":t="echo 'Please download from https://inkscape.org/release/ and install manually.'",(0,J.execSync)(t,{stdio:s?"inherit":"ignore"})}return k()}var B=JSON.parse((0,F.readFileSync)((0,b.resolve)(__dirname,"../package.json"),"utf8"));h.program.version((0,r.cyanBright)("piconvert")+" "+(0,r.yellowBright)("v"+B.version)+`
`+B.description);h.program.argument("[path]","Source path. If it's a directory, all files matched selected import types in it and its subdirectories will be converted.","pictures").option("-d, --dir <directory>","Output directory","piconvert").option("-i, --inputs <formats>","Import (input) formats. Supports: "+O.map(s=>(0,r.yellowBright)(s)).join(","),"ai").option("-o, --outputs <formats>","Export (output) formats. Supports: "+j.map(s=>(0,r.yellowBright)(s)).join(","),"svg,png").option("-f, --force","Overwrite existing files",!1).option("-s, --silent","Silent mode, no output",!1).option("-v, --verbose","Verbose mode, print all Inkscape output",!1).action(async s=>{console.log((0,r.cyanBright)("piconvert")+" "+(0,r.yellowBright)("v"+B.version)),s=(0,b.resolve)(s);let p=(0,b.resolve)(h.program.opts().dir),t=h.program.opts().inputs.split(",").map(a=>{let u=a.trim().toLowerCase();return O.includes(u)?u:null}).filter(a=>a!==null),o=h.program.opts().outputs.split(",").map(a=>{let u=a.trim().toLowerCase();return j.includes(u)?u:null}).filter(a=>a!==null),n=h.program.opts().force,e=h.program.opts().silent,l=h.program.opts().verbose;k()===!1&&(console.error((0,r.redBright)("Inkscape is not installed.")),process.platform==="linux"?console.log("Install via: "+(0,r.yellowBright)("add-apt-repository -y ppa:inkscape.dev/stable && apt update && apt install -y inkscape")):process.platform==="darwin"?console.log("Install via: "+(0,r.yellowBright)("brew install --cask inkscape")):console.log("Install from: "+(0,r.yellowBright)("https://www.inkscape.org/release/")),process.exit(1)),(0,F.existsSync)(s)||(console.error((0,r.redBright)(`Input path does not exist.
Path: ${s}`)),process.exit(1));let i=new T;for(let a of t)i.import(a);for(let a of o)i.export(a);i.on("conversion-start",(a,u)=>{e||console.log((0,r.magentaBright)("[Conversion started] ")+(0,r.yellowBright)(a)+" -> "+(0,r.yellowBright)(u))}),i.on("conversion-finish",(a,u)=>{e||console.log((0,r.magentaBright)("[Conversion finished] ")+(0,r.yellowBright)(a)+" -> "+(0,r.yellowBright)(u))}),i.on("directory-start",()=>{e||console.group()}),i.on("directory-finish",()=>{e||console.groupEnd()}),i.on("file-start",a=>{e||console.log((0,r.magentaBright)("[File]"),(0,r.blueBright)(a.replace(s,"").substring(1))),e||console.group()}),i.on("file-finish",()=>{e||console.groupEnd()}),i.on("task-succeeded",(a,u,f)=>{e||console.log((0,r.greenBright)("[Succeeded]"),(0,r.cyanBright)(f.format+" "+(f.width||"")+(f.width||f.height?"x":"")+(f.height||"")))}),i.on("task-failed",(a,u,f)=>{e||console.log((0,r.redBright)("[Failed]"),(0,r.cyanBright)(f.format+" "+(f.width||"")+(f.width||f.height?"x":"")+(f.height||"")))}),i.on("task-skipped",(a,u,f)=>{e||console.log((0,r.yellowBright)("[Skipped]"),(0,r.cyanBright)(f.format+" "+(f.width||"")+(f.width||f.height?"x":"")+(f.height||"")))}),i.run(s,p,!0,n,l)});h.program.command("install").option("-v, --verbose","Verbose mode, print execution output",!1).action(async()=>{let s=await q(h.program.opts().verbose);console.log(s?(0,r.greenBright)("Inkscape installed."):(0,r.redBright)("Cannot install Inkscape."))});h.program.parse();