UNPKG

ts-shasum

Version:

Compute and check SHA256 message digest.

18 lines (14 loc) 11.7 kB
/** * Version: 1.2.0 * * Copyright (c) 2024 kjxbyz. All rights reserved. */ import{EventEmitter as V}from"events";function O(n){return n==null?[]:Array.isArray(n)?n:[n]}function N(n,e,s,t){var i,o=n[e],r=~t.string.indexOf(e)?s==null||s===!0?"":String(s):typeof s=="boolean"?s:~t.boolean.indexOf(e)?s==="false"?!1:s==="true"||(n._.push((i=+s,i*0===0?i:s)),!!s):(i=+s,i*0===0?i:s);n[e]=o==null?r:Array.isArray(o)?o.concat(r):[o,r]}function _(n,e){n=n||[],e=e||{};var s,t,i,o,r,h={_:[]},a=0,l=0,c=0,p=n.length;let m=e.alias!==void 0,u=e.unknown!==void 0,k=e.default!==void 0;if(e.alias=e.alias||{},e.string=O(e.string),e.boolean=O(e.boolean),m)for(s in e.alias)for(t=e.alias[s]=O(e.alias[s]),a=0;a<t.length;a++)(e.alias[t[a]]=t.concat(s)).splice(a,1);for(a=e.boolean.length;a-- >0;)for(t=e.alias[e.boolean[a]]||[],l=t.length;l-- >0;)e.boolean.push(t[l]);for(a=e.string.length;a-- >0;)for(t=e.alias[e.string[a]]||[],l=t.length;l-- >0;)e.string.push(t[l]);if(k){for(s in e.default)if(o=typeof e.default[s],t=e.alias[s]=e.alias[s]||[],e[o]!==void 0)for(e[o].push(s),a=0;a<t.length;a++)e[o].push(t[a])}let v=u?Object.keys(e.alias):[];for(a=0;a<p;a++){if(i=n[a],i==="--"){h._=h._.concat(n.slice(++a));break}for(l=0;l<i.length&&i.charCodeAt(l)===45;l++);if(l===0)h._.push(i);else if(i.substring(l,l+3)==="no-"){if(o=i.substring(l+3),u&&!~v.indexOf(o))return e.unknown(i);h[o]=!1}else{for(c=l+1;c<i.length&&i.charCodeAt(c)!==61;c++);for(o=i.substring(l,c),r=i.substring(++c)||a+1===p||(""+n[a+1]).charCodeAt(0)===45||n[++a],t=l===2?[o]:o,c=0;c<t.length;c++){if(o=t[c],u&&!~v.indexOf(o))return e.unknown("-".repeat(l)+o);N(h,o,c+1<t.length||r,e)}}}if(k)for(s in e.default)h[s]===void 0&&(h[s]=e.default[s]);if(m)for(s in h)for(t=e.alias[s]||[];t.length>0;)h[t.shift()]=h[s];return h}var j=n=>n.replace(/[<[].+/,"").trim(),B=n=>{let e=/<([^>]+)>/g,s=/\[([^\]]+)\]/g,t=[],i=h=>{let a=!1,l=h[1];return l.startsWith("...")&&(l=l.slice(3),a=!0),{required:h[0].startsWith("<"),value:l,variadic:a}},o;for(;o=e.exec(n);)t.push(i(o));let r;for(;r=s.exec(n);)t.push(i(r));return t},P=n=>{let e={alias:{},boolean:[]};for(let[s,t]of n.entries())t.names.length>1&&(e.alias[t.names[0]]=t.names.slice(1)),t.isBoolean&&(t.negated&&n.some((o,r)=>r!==s&&o.names.some(h=>t.names.includes(h))&&typeof o.required=="boolean")||e.boolean.push(t.names[0]));return e},$=n=>n.sort((e,s)=>e.length>s.length?-1:1)[0],F=(n,e)=>n.length>=e?n:`${n}${" ".repeat(e-n.length)}`,I=n=>n.replace(/([a-z])-([a-z])/g,(e,s,t)=>s+t.toUpperCase()),L=(n,e,s)=>{let t=0,i=e.length,o=n,r;for(;t<i;++t)r=o[e[t]],o=o[e[t]]=t===i-1?s:r??(~e[t+1].indexOf(".")||!(+e[t+1]>-1)?{}:[])},q=(n,e)=>{for(let s of Object.keys(e)){let t=e[s];t.shouldTransform&&(n[s]=Array.prototype.concat.call([],n[s]),typeof t.transformFunction=="function"&&(n[s]=n[s].map(t.transformFunction)))}},M=n=>{let e=/([^\\\/]+)$/.exec(n);return e?e[1]:""},A=n=>n.split(".").map((e,s)=>s===0?I(e):e).join("."),d=class extends Error{constructor(e){super(e),this.name=this.constructor.name,typeof Error.captureStackTrace=="function"?Error.captureStackTrace(this,this.constructor):this.stack=new Error(e).stack}},w=class{constructor(e,s,t){this.rawName=e,this.description=s,this.config=Object.assign({},t),e=e.replace(/\.\*/g,""),this.negated=!1,this.names=j(e).split(",").map(i=>{let o=i.trim().replace(/^-{1,2}/,"");return o.startsWith("no-")&&(this.negated=!0,o=o.replace(/^no-/,"")),A(o)}).sort((i,o)=>i.length>o.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null&&(this.config.default=!0),e.includes("<")?this.required=!0:e.includes("[")?this.required=!1:this.isBoolean=!0}},G=process.argv,R=`${process.platform}-${process.arch} node-${process.version}`,b=class{constructor(e,s,t={},i){this.rawName=e,this.description=s,this.config=t,this.cli=i,this.options=[],this.aliasNames=[],this.name=j(e),this.args=B(e),this.examples=[]}usage(e){return this.usageText=e,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(e,s="-v, --version"){return this.versionNumber=e,this.option(s,"Display version number"),this}example(e){return this.examples.push(e),this}option(e,s,t){let i=new w(e,s,t);return this.options.push(i),this}alias(e){return this.aliasNames.push(e),this}action(e){return this.commandAction=e,this}isMatched(e){return this.name===e||this.aliasNames.includes(e)}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof y}hasOption(e){return e=e.split(".")[0],this.options.find(s=>s.names.includes(e))}outputHelp(){let{name:e,commands:s}=this.cli,{versionNumber:t,options:i,helpCallback:o}=this.cli.globalCommand,r=[{body:`${e}${t?`/${t}`:""}`}];if(r.push({title:"Usage",body:` $ ${e} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&s.length>0){let l=$(s.map(c=>c.rawName));r.push({title:"Commands",body:s.map(c=>` ${F(c.rawName,l.length)} ${c.description}`).join(` `)}),r.push({title:"For more info, run any command with the `--help` flag",body:s.map(c=>` $ ${e}${c.name===""?"":` ${c.name}`} --help`).join(` `)})}let a=this.isGlobalCommand?i:[...this.options,...i||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand&&(a=a.filter(l=>l.name!=="version")),a.length>0){let l=$(a.map(c=>c.rawName));r.push({title:"Options",body:a.map(c=>` ${F(c.rawName,l.length)} ${c.description} ${c.config.default===void 0?"":`(default: ${c.config.default})`}`).join(` `)})}this.examples.length>0&&r.push({title:"Examples",body:this.examples.map(l=>typeof l=="function"?l(e):l).join(` `)}),o&&(r=o(r)||r),console.log(r.map(l=>l.title?`${l.title}: ${l.body}`:l.body).join(` `))}outputVersion(){let{name:e}=this.cli,{versionNumber:s}=this.cli.globalCommand;s&&console.log(`${e}/${s} ${R}`)}checkRequiredArgs(){let e=this.args.filter(s=>s.required).length;if(this.cli.args.length<e)throw new d(`missing required args for command \`${this.rawName}\``)}checkUnknownOptions(){let{options:e,globalCommand:s}=this.cli;if(!this.config.allowUnknownOptions){for(let t of Object.keys(e))if(t!=="--"&&!this.hasOption(t)&&!s.hasOption(t))throw new d(`Unknown option \`${t.length>1?`--${t}`:`-${t}`}\``)}}checkOptionValue(){let{options:e,globalCommand:s}=this.cli,t=[...s.options,...this.options];for(let i of t){let o=e[i.name.split(".")[0]];if(i.required){let r=t.some(h=>h.negated&&h.names.includes(i.name));if(o===!0||o===!1&&!r)throw new d(`option \`${i.rawName}\` value is missing`)}}}},y=class extends b{constructor(e){super("@@global@@","",{},e)}},g=Object.assign,C=class extends V{constructor(e=""){super(),this.name=e,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new y(this),this.globalCommand.usage("<command> [options]")}usage(e){return this.globalCommand.usage(e),this}command(e,s,t){let i=new b(e,s||"",t,this);return i.globalCommand=this.globalCommand,this.commands.push(i),i}option(e,s,t){return this.globalCommand.option(e,s,t),this}help(e){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=e,this.showHelpOnExit=!0,this}version(e,s="-v, --version"){return this.globalCommand.version(e,s),this.showVersionOnExit=!0,this}example(e){return this.globalCommand.example(e),this}outputHelp(){this.matchedCommand?this.matchedCommand.outputHelp():this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:e,options:s},t,i){return this.args=e,this.options=s,t&&(this.matchedCommand=t),i&&(this.matchedCommandName=i),this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}parse(e=G,{run:s=!0}={}){this.rawArgs=e,this.name||(this.name=e[1]?M(e[1]):"cli");let t=!0;for(let o of this.commands){let r=this.mri(e.slice(2),o),h=r.args[0];if(o.isMatched(h)){t=!1;let a=g(g({},r),{args:r.args.slice(1)});this.setParsedInfo(a,o,h),this.emit(`command:${h}`,o)}}if(t){for(let o of this.commands)if(o.name===""){t=!1;let r=this.mri(e.slice(2),o);this.setParsedInfo(r,o),this.emit("command:!",o)}}if(t){let o=this.mri(e.slice(2));this.setParsedInfo(o)}this.options.help&&this.showHelpOnExit&&(this.outputHelp(),s=!1,this.unsetMatchedCommand()),this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null&&(this.outputVersion(),s=!1,this.unsetMatchedCommand());let i={args:this.args,options:this.options};return s&&this.runMatchedCommand(),!this.matchedCommand&&this.args[0]&&this.emit("command:*"),i}mri(e,s){let t=[...this.globalCommand.options,...s?s.options:[]],i=P(t),o=[],r=e.indexOf("--");r>-1&&(o=e.slice(r+1),e=e.slice(0,r));let h=_(e,i);h=Object.keys(h).reduce((m,u)=>g(g({},m),{[A(u)]:h[u]}),{_:[]});let a=h._,l={"--":o},c=s&&s.config.ignoreOptionDefaultValue?s.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,p=Object.create(null);for(let m of t){if(!c&&m.config.default!==void 0)for(let u of m.names)l[u]=m.config.default;Array.isArray(m.config.type)&&p[m.name]===void 0&&(p[m.name]=Object.create(null),p[m.name].shouldTransform=!0,p[m.name].transformFunction=m.config.type[0])}for(let m of Object.keys(h))if(m!=="_"){let u=m.split(".");L(l,u,h[m]),q(l,p)}return{args:a,options:l}}runMatchedCommand(){let{args:e,options:s,matchedCommand:t}=this;if(!t||!t.commandAction)return;t.checkUnknownOptions(),t.checkOptionValue(),t.checkRequiredArgs();let i=[];return t.args.forEach((o,r)=>{o.variadic?i.push(e.slice(r)):i.push(e[r])}),i.push(s),t.commandAction.apply(this,i)}},T=(n="")=>new C(n);import{globSync as U}from"glob";import{createHash as z}from"node:crypto";import{createReadStream as W,writeFileSync as K,readFileSync as Q}from"node:fs";async function H(n,e,s="sha256",t,i){let o=Object.fromEntries((await x(n,s,t,i)).map(([r,h])=>[h,r]));return e.reduce((r,[h,a])=>(r.push([a,h==o[a]]),r),[])}async function x(n,e="sha256",s,t){return await Promise.all((await X(n)).map(async i=>[await J(i,e,s,t),i]))}function E(n,e,s){let t=e.map(([i,o])=>`${i} ${o}`);K(n,t.join(` `),s)}function S(n,e,s){let t=Q(n,e);return Buffer.isBuffer(t)&&(t=t.toString(s)),t?.split(` `)?.reduce((i,o)=>(i.push(o.split(" ")),i),[])||[]}function J(n,e,s,t){return new Promise(function(i,o){let r=z(e,s),h=W(n,t);h.on("readable",()=>{let a=h.read();a?r.update(a):i(r.digest("hex"))}),h.on("error",a=>{o(a)})})}function X(n){return new Promise(function(e,s){try{let t=U(n,{});e(t)}catch(t){s(t)}})}var D="1.2.0";var f=T("shasum");f.command("create <entry> [...files]","Compute SHA256 message digest.").option("--algorithm <algorithm>","The `algorithm` is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. On recent releases of OpenSSL, `openssl list -digest-algorithms` will display the available digest algorithms. (default: sha256) ",{default:"sha256"}).action(async(n,e,s)=>{console.debug(e,s);try{let t=await x(e,s.algorithm);console.warn(t),E(n,t),console.log("Saved successfully")}catch(t){console.error(t),process.exit(1)}});f.command("verify <entry> [...files]","Check SHA256 message digest.").option("--algorithm <algorithm>","The `algorithm` is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. On recent releases of OpenSSL, `openssl list -digest-algorithms` will display the available digest algorithms. (default: sha256) ",{default:"sha256"}).action(async(n,e,s)=>{console.debug(n,e,s);try{let t=S(n),i=await H(e,t,s.algorithm);console.warn(i)}catch(t){console.error(t),process.exit(1)}});f.help();f.version(D);f.parse();