@clerc/core 0.40.0 → 0.42.0
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 +9 -0
- package/dist/index.d.ts +175 -375
- package/dist/index.js +795 -1
- package/package.json +13 -13
package/dist/index.js
CHANGED
|
@@ -1 +1,795 @@
|
|
|
1
|
-
import{format as ie}from"node:util";import"@clerc/core";const ce=e=>Array.isArray(e)?e:[e],xe=e=>e.replace(/[\W_]([a-z\d])?/gi,(t,s)=>s?s.toUpperCase():""),Re=(e,t)=>t.length!==e.length?!1:e.every((s,r)=>s===t[r]),$e=(e,t)=>t.length>e.length?!1:Re(e.slice(0,t.length),t);function U(e){return e!==null&&typeof e=="object"}function V(e,t,s=".",r){if(!U(t))return V(e,{},s,r);const o=Object.assign({},t);for(const n in e){if(n==="__proto__"||n==="constructor")continue;const a=e[n];a!=null&&(r&&r(o,n,a,s)||(Array.isArray(a)&&Array.isArray(o[n])?o[n]=[...a,...o[n]]:U(a)&&U(o[n])?o[n]=V(a,o[n],(s?`${s}.`:"")+n.toString(),r):o[n]=a))}return o}function je(e){return(...t)=>t.reduce((s,r)=>V(s,r,"",e),{})}const qe=je();class Te{constructor(){this.listenerMap={},this.wildcardListeners=new Set}on(t,s){return t==="*"?(this.wildcardListeners.add(s),this):(this.listenerMap[t]||(this.listenerMap[t]=new Set),this.listenerMap[t].add(s),this)}emit(t,...s){return this.listenerMap[t]&&(this.wildcardListeners.forEach(r=>r.apply(null,[t,...s])),this.listenerMap[t].forEach(r=>r(...s))),this}off(t,s){var r,o;return t===void 0?(this.listenerMap={},this.wildcardListeners.clear(),this):t==="*"?(s?this.wildcardListeners.delete(s):this.wildcardListeners.clear(),this):(s?(r=this.listenerMap[t])==null||r.delete(s):(o=this.listenerMap[t])==null||o.clear(),this)}}const Ge="known-flag",He="unknown-flag",Ue="argument",{stringify:A}=JSON,Ve=/\B([A-Z])/g,Je=e=>e.replace(Ve,"-$1").toLowerCase(),{hasOwnProperty:ze}=Object.prototype,W=(e,t)=>ze.call(e,t),Ke=e=>Array.isArray(e),ue=e=>typeof e=="function"?[e,!1]:Ke(e)?[e[0],!0]:ue(e.type),Ze=(e,t)=>e===Boolean?t!=="false":t,Qe=(e,t)=>typeof t=="boolean"?t:e===Number&&t===""?Number.NaN:e(t),Xe=/[\s.:=]/,Ye=e=>{const t=`Flag name ${A(e)}`;if(e.length===0)throw new Error(`${t} cannot be empty`);if(e.length===1)throw new Error(`${t} must be longer than a character`);const s=e.match(Xe);if(s)throw new Error(`${t} cannot contain ${A(s==null?void 0:s[0])}`)},et=e=>{const t={},s=(r,o)=>{if(W(t,r))throw new Error(`Duplicate flags named ${A(r)}`);t[r]=o};for(const r in e){if(!W(e,r))continue;Ye(r);const o=e[r],n=[[],...ue(o),o];s(r,n);const a=Je(r);if(r!==a&&s(a,n),"alias"in o&&typeof o.alias=="string"){const{alias:u}=o,c=`Flag alias ${A(u)} for flag ${A(r)}`;if(u.length===0)throw new Error(`${c} cannot be empty`);if(u.length>1)throw new Error(`${c} must be a single character`);s(u,n)}}return t},tt=(e,t)=>{const s={};for(const r in e){if(!W(e,r))continue;const[o,,n,a]=t[r];if(o.length===0&&"default"in a){let{default:u}=a;typeof u=="function"&&(u=u()),s[r]=u}else s[r]=n?o:o.pop()}return s},q="--",st=/[.:=]/,rt=/^-{1,2}\w/,nt=e=>{if(!rt.test(e))return;const t=!e.startsWith(q);let s=e.slice(t?1:2),r;const o=s.match(st);if(o){const{index:n}=o;r=s.slice(n+1),s=s.slice(0,n)}return[s,r,t]},ot=(e,{onFlag:t,onArgument:s})=>{let r;const o=(n,a)=>{if(typeof r!="function")return!0;r(n,a),r=void 0};for(let n=0;n<e.length;n+=1){const a=e[n];if(a===q){o();const c=e.slice(n+1);s==null||s(c,[n],!0);break}const u=nt(a);if(u){if(o(),!t)continue;const[c,l,m]=u;if(m)for(let d=0;d<c.length;d+=1){o();const w=d===c.length-1;r=t(c[d],w?l:void 0,[n,d+1,w])}else r=t(c,l,[n])}else o(a,[n])&&(s==null||s([a],[n]))}o()},at=(e,t)=>{for(const[s,r,o]of t.reverse()){if(r){const n=e[s];let a=n.slice(0,r);if(o||(a+=n.slice(r+1)),a!=="-"){e[s]=a;continue}}e.splice(s,1)}},le=(e,t=process.argv.slice(2),{ignore:s}={})=>{const r=[],o=et(e),n={},a=[];return a[q]=[],ot(t,{onFlag(u,c,l){const m=W(o,u);if(!(s!=null&&s(m?Ge:He,u,c))){if(m){const[d,w]=o[u],_=Ze(w,c),B=(j,M)=>{r.push(l),M&&r.push(M),d.push(Qe(w,j||""))};return _===void 0?B:B(_)}W(n,u)||(n[u]=[]),n[u].push(c===void 0?!0:c),r.push(l)}},onArgument(u,c,l){s!=null&&s(Ue,t[c[0]])||(a.push(...u),l?(a[q]=u,t.splice(c[0])):r.push(c))}}),at(t,r),{flags:tt(e,o),unknownFlags:n,_:a}},L=JSON.stringify;class he extends Error{constructor(t,s){super(s("core.commandExists",L(t))),this.commandName=t}}class de extends Error{constructor(t,s){super(s("core.noSuchCommand",L(t))),this.commandName=t}}class fe extends Error{constructor(t){super(t("core.noCommandGiven"))}}class pe extends Error{constructor(t,s,r){super(r("core.commandNameConflict",L(t),L(s))),this.n1=t,this.n2=s}}class me extends Error{constructor(t){super(t("core.scriptNameNotSet"))}}class Ce extends Error{constructor(t){super(t("core.descriptionNotSet"))}}class we extends Error{constructor(t){super(t("core.versionNotSet"))}}class ge extends Error{constructor(t,s){super(s("core.badNameFormat",L(t))),this.commandName=t}}class J extends Error{constructor(t){super(t("core.localeMustBeCalledFirst"))}}const it={en:{"core.commandExists":'Command "%s" exists.',"core.noSuchCommand":"No such command: %s.","core.noCommandGiven":"No command given.","core.commandNameConflict":"Command name %s conflicts with %s. Maybe caused by alias.","core.scriptNameNotSet":"Name not set.","core.descriptionNotSet":"Description not set.","core.versionNotSet":"Version not set.","core.badNameFormat":"Bad name format: %s.","core.localeMustBeCalledFirst":"locale() or fallbackLocale() must be called at first.","core.cliParseMustBeCalled":"cli.parse() must be called.","core.spreadParameterMustBeLast":"Invalid Parameter: Spread parameter %s must be last.","core.requiredParameterCannotComeAfterOptionalParameter":"Invalid Parameter: Required parameter %s cannot come after optional parameter %s.","core.parameterMustBeWrappedInBrackets":"Invalid Parameter: Parameter %s must be wrapped in <> (required parameter) or [] (optional parameter).","core.parameterIsUsedMoreThanOnce":"Invalid Parameter: Parameter %s is used more than once.","core.missingRequiredParameter":"Missing required parameter %s."},"zh-CN":{"core.commandExists":'\u547D\u4EE4 "%s" \u5DF2\u5B58\u5728\u3002',"core.noSuchCommand":"\u627E\u4E0D\u5230\u547D\u4EE4: %s\u3002","core.noCommandGiven":"\u6CA1\u6709\u8F93\u5165\u547D\u4EE4\u3002","core.commandNameConflict":"\u547D\u4EE4\u540D\u79F0 %s \u548C %s \u51B2\u7A81\u3002 \u53EF\u80FD\u662F\u7531\u4E8E\u522B\u540D\u5BFC\u81F4\u7684\u3002","core.scriptNameNotSet":"\u672A\u8BBE\u7F6E CLI Script \u540D\u79F0\u3002","core.descriptionNotSet":"\u672A\u8BBE\u7F6E CLI \u63CF\u8FF0\u3002","core.versionNotSet":"\u672A\u8BBE\u7F6E CLI \u7248\u672C\u3002","core.badNameFormat":"\u9519\u8BEF\u7684\u547D\u4EE4\u540D\u5B57\u683C\u5F0F: %s\u3002","core.localeMustBeCalledFirst":"locale() \u6216 fallbackLocale() \u5FC5\u987B\u5728\u6700\u5F00\u59CB\u8C03\u7528\u3002","core.cliParseMustBeCalled":"cli.parse() \u5FC5\u987B\u88AB\u8C03\u7528\u3002","core.spreadParameterMustBeLast":"\u4E0D\u5408\u6CD5\u7684\u53C2\u6570: \u5C55\u5F00\u53C2\u6570 %s \u5FC5\u987B\u5728\u6700\u540E\u3002","core.requiredParameterCannotComeAfterOptionalParameter":"\u4E0D\u5408\u6CD5\u7684\u53C2\u6570: \u5FC5\u586B\u53C2\u6570 %s \u4E0D\u80FD\u5728\u53EF\u9009\u53C2\u6570 %s \u4E4B\u540E\u3002","core.parameterMustBeWrappedInBrackets":"\u4E0D\u5408\u6CD5\u7684\u53C2\u6570: \u53C2\u6570 %s \u5FC5\u987B\u88AB <> (\u5FC5\u586B\u53C2\u6570) \u6216 [] (\u53EF\u9009\u53C2\u6570) \u5305\u88F9\u3002","core.parameterIsUsedMoreThanOnce":"\u4E0D\u5408\u6CD5\u7684\u53C2\u6570: \u53C2\u6570 %s \u88AB\u4F7F\u7528\u4E86\u591A\u6B21\u3002","core.missingRequiredParameter":"\u7F3A\u5C11\u5FC5\u586B\u53C2\u6570 %s\u3002"}},{stringify:k}=JSON;function z(e,t){const s=[];let r,o;for(const n of e){if(o)throw new Error(t("core.spreadParameterMustBeLast",k(o)));const a=n[0],u=n[n.length-1];let c;if(a==="<"&&u===">"&&(c=!0,r))throw new Error(t("core.requiredParameterMustBeBeforeOptional",k(n),k(r)));if(a==="["&&u==="]"&&(c=!1,r=n),c===void 0)throw new Error(t("core.parameterMustBeWrappedInBrackets",k(n)));let l=n.slice(1,-1);const m=l.slice(-3)==="...";m&&(o=n,l=l.slice(0,-3)),s.push({name:l,required:c,spread:m})}return s}function K(e,t,s,r){for(let o=0;o<t.length;o+=1){const{name:n,required:a,spread:u}=t[o],c=xe(n);if(c in e)throw new Error(r("core.parameterIsUsedMoreThanOnce",k(n)));const l=u?s.slice(o):s[o];if(u&&(o=t.length),a&&(!l||u&&l.length===0))throw new Error(r("core.missingRequiredParameter",k(n)));e[c]=l}}const Ee=typeof Deno!="undefined",ct=typeof process!="undefined"&&!Ee,ut=process.versions.electron&&!process.defaultApp;function _e(e,t,s,r){if(s.alias){const o=ce(s.alias);for(const n of o){if(n in t)throw new pe(t[n].name,s.name,r);e.set(typeof n=="symbol"?n:n.split(" "),{...s,__isAlias:!0})}}}function ve(e,t){const s=new Map;e[p]&&(s.set(p,e[p]),_e(s,e,e[p],t));for(const r of Object.values(e))_e(s,e,r,t),s.set(r.name.split(" "),r);return s}function Me(e,t,s){var r;const o=ve(e,s);for(const[n,a]of o.entries()){const u=le((r=a==null?void 0:a.flags)!=null?r:Object.create(null),[...t]),{_:c}=u;if(n!==p&&$e(c,n))return[a,n]}return o.has(p)?[o.get(p),p]:[void 0,void 0]}const Z=()=>ct?process.argv.slice(ut?1:2):Ee?Deno.args:[];function Fe(e){const t={pre:[],normal:[],post:[]};for(const r of e){const o=typeof r=="object"?r:{fn:r},{enforce:n,fn:a}=o;n==="post"||n==="pre"?t[n].push(a):t.normal.push(a)}const s=[...t.pre,...t.normal,...t.post];return r=>{return o(0);function o(n){const a=s[n];return a(r,o.bind(null,n+1))}}}const lt=/\s\s+/,Ne=e=>e===p?!0:!(e.startsWith(" ")||e.endsWith(" "))&&!lt.test(e),ht=(e,t)=>t?`[${e}]`:`<${e}>`,dt="<Root>",ye=e=>Array.isArray(e)?e.join(" "):typeof e=="string"?e:dt,Be=()=>process.env.CLERC_LOCALE?process.env.CLERC_LOCALE:Intl.DateTimeFormat().resolvedOptions().locale,ke=e=>e.filter(t=>!t.startsWith("-"));var Q=(e,t,s)=>{if(!t.has(e))throw TypeError("Cannot "+s)},i=(e,t,s)=>(Q(e,t,"read from private field"),s?s.call(e):t.get(e)),h=(e,t,s)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,s)},C=(e,t,s,r)=>(Q(e,t,"write to private field"),r?r.call(e,s):t.set(e,s),s),f=(e,t,s)=>(Q(e,t,"access private method"),s),T,v,F,N,D,O,G,b,S,P,I,x,R,$,y,X,Se,Y,Ae,ee,We,g,E,te,Le,se,De,re,Oe,H,ne,oe,be;const p=Symbol.for("Clerc.Root"),Pe=class{constructor(e,t,s){h(this,X),h(this,Y),h(this,ee),h(this,g),h(this,te),h(this,se),h(this,re),h(this,H),h(this,oe),h(this,T,""),h(this,v,""),h(this,F,""),h(this,N,""),h(this,D,[]),h(this,O,Object.create(null)),h(this,G,new Te),h(this,b,Object.create(null)),h(this,S,new Set),h(this,P,void 0),h(this,I,[]),h(this,x,!1),h(this,R,"en"),h(this,$,"en"),h(this,y,Object.create(null)),this.i18n={add:r=>{C(this,y,qe(i(this,y),r))},t:(r,...o)=>{const n=i(this,y)[i(this,$)]||i(this,y)[i(this,R)],a=i(this,y)[i(this,R)];return n[r]?ie(n[r],...o):a[r]?ie(a[r],...o):void 0}},C(this,v,e!=null?e:i(this,v)),C(this,F,t!=null?t:i(this,F)),C(this,N,s!=null?s:i(this,N)),C(this,$,Be()),f(this,ee,We).call(this)}get _name(){return i(this,T)||i(this,v)}get _scriptName(){return i(this,v)}get _description(){return i(this,F)}get _version(){return i(this,N)}get _inspectors(){return i(this,D)}get _commands(){return i(this,O)}get _flags(){return i(this,b)}static create(e,t,s){return new Pe(e,t,s)}name(e){return f(this,g,E).call(this),C(this,T,e),this}scriptName(e){return f(this,g,E).call(this),C(this,v,e),this}description(e){return f(this,g,E).call(this),C(this,F,e),this}version(e){return f(this,g,E).call(this),C(this,N,e),this}locale(e){if(i(this,x))throw new J(this.i18n.t);return C(this,$,e),this}fallbackLocale(e){if(i(this,x))throw new J(this.i18n.t);return C(this,R,e),this}errorHandler(e){return i(this,I).push(e),this}command(e,t,s={}){return f(this,H,ne).call(this,()=>f(this,te,Le).call(this,e,t,s)),this}flag(e,t,s){return i(this,b)[e]={description:t,...s},this}on(e,t){return i(this,G).on(e,t),this}use(e){return f(this,g,E).call(this),e.setup(this)}inspector(e){return f(this,g,E).call(this),i(this,D).push(e),this}parse(e=Z()){f(this,g,E).call(this);const{argv:t,run:s}=Array.isArray(e)?{argv:e,run:!0}:{argv:Z(),...e};return C(this,P,[...t]),f(this,se,De).call(this),s&&this.runMatchedCommand(),this}runMatchedCommand(){return f(this,H,ne).call(this,()=>f(this,oe,be).call(this)),process.title=i(this,v),this}};let ft=Pe;T=new WeakMap,v=new WeakMap,F=new WeakMap,N=new WeakMap,D=new WeakMap,O=new WeakMap,G=new WeakMap,b=new WeakMap,S=new WeakMap,P=new WeakMap,I=new WeakMap,x=new WeakMap,R=new WeakMap,$=new WeakMap,y=new WeakMap,X=new WeakSet,Se=function(){return i(this,S).has(p)},Y=new WeakSet,Ae=function(){return Object.prototype.hasOwnProperty.call(this._commands,p)},ee=new WeakSet,We=function(){this.i18n.add(it)},g=new WeakSet,E=function(){C(this,x,!0)},te=new WeakSet,Le=function(e,t,s={}){f(this,g,E).call(this);const{t:r}=this.i18n,n=(d=>!(typeof d=="string"||d===p))(e),a=n?e.name:e;if(!Ne(a))throw new ge(a,r);const{handler:u=void 0,...c}=n?e:{name:a,description:t,...s},l=[c.name],m=c.alias?ce(c.alias):[];c.alias&&l.push(...m);for(const d of l)if(i(this,S).has(d))throw new he(ye(d),r);return i(this,O)[a]=c,i(this,S).add(c.name),m.forEach(d=>i(this,S).add(d)),n&&u&&this.on(e.name,u),this},se=new WeakSet,De=function(){const{t:e}=this.i18n;if(!i(this,v))throw new me(e);if(!i(this,F))throw new Ce(e);if(!i(this,N))throw new we(e)},re=new WeakSet,Oe=function(e){var t;const s=i(this,P),{t:r}=this.i18n,[o,n]=e(),a=!!o,u={...i(this,b),...o==null?void 0:o.flags},c=le(u,[...s]),{_:l,flags:m,unknownFlags:d}=c;let w=!a||o.name===p?l:l.slice(o.name.split(" ").length),_=(t=o==null?void 0:o.parameters)!=null?t:[];const B=_.indexOf("--"),j=_.slice(B+1)||[],M=Object.create(null);if(B>-1&&j.length>0){_=_.slice(0,B);const ae=l["--"];w=w.slice(0,-ae.length||void 0),K(M,z(_,r),w,r),K(M,z(j,r),ae,r)}else K(M,z(_,r),w,r);const Ie={...m,...d};return{name:o==null?void 0:o.name,called:Array.isArray(n)?n.join(" "):n,resolved:a,hasRootOrAlias:i(this,X,Se),hasRoot:i(this,Y,Ae),raw:{...c,parameters:w,mergedFlags:Ie},parameters:M,flags:m,unknownFlags:d,cli:this}},H=new WeakSet,ne=function(e){try{e()}catch(t){if(i(this,I).length>0)i(this,I).forEach(s=>s(t));else throw t}},oe=new WeakSet,be=function(){f(this,g,E).call(this);const{t:e}=this.i18n,t=i(this,P);if(!t)throw new Error(e("core.cliParseMustBeCalled"));const s=()=>Me(i(this,O),t,e),r=()=>f(this,re,Oe).call(this,s),o={enforce:"post",fn:u=>{const[c]=s(),l=ke(t).join(" ");if(!c)throw l?new de(l,e):new fe(e);i(this,G).emit(c.name,u)}},n=[...i(this,D),o];Fe(n)(r())};const pt=e=>e,mt=(e,t,s)=>s,Ct=(e,t)=>t,wt=(e,t)=>({...e,handler:t});export{ft as Clerc,he as CommandExistsError,pe as CommandNameConflictError,Ce as DescriptionNotSetError,ge as InvalidCommandNameError,J as LocaleNotCalledFirstError,fe as NoCommandGivenError,de as NoSuchCommandError,p as Root,me as ScriptNameNotSetError,we as VersionNotSetError,Fe as compose,wt as defineCommand,mt as defineHandler,Ct as defineInspector,pt as definePlugin,Be as detectLocale,ye as formatCommandName,Ne as isValidName,Z as resolveArgv,Me as resolveCommand,ve as resolveFlattenCommands,ke as stripFlags,ht as withBrackets};
|
|
1
|
+
import { format } from 'node:util';
|
|
2
|
+
import { camelCase, arrayStartsWith, toArray } from '@clerc/utils';
|
|
3
|
+
import defu from 'defu';
|
|
4
|
+
import { LiteEmit } from 'lite-emit';
|
|
5
|
+
import { typeFlag } from 'type-flag';
|
|
6
|
+
import { IS_NODE, IS_ELECTRON, IS_DENO } from 'is-platform';
|
|
7
|
+
|
|
8
|
+
const s = JSON.stringify;
|
|
9
|
+
class CommandExistsError extends Error {
|
|
10
|
+
constructor(commandName, t) {
|
|
11
|
+
super(t("core.commandExists", s(commandName)));
|
|
12
|
+
this.commandName = commandName;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
class NoSuchCommandError extends Error {
|
|
16
|
+
constructor(commandName, t) {
|
|
17
|
+
super(t("core.noSuchCommand", s(commandName)));
|
|
18
|
+
this.commandName = commandName;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
class NoCommandGivenError extends Error {
|
|
22
|
+
constructor(t) {
|
|
23
|
+
super(t("core.noCommandGiven"));
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
class CommandNameConflictError extends Error {
|
|
27
|
+
constructor(n1, n2, t) {
|
|
28
|
+
super(t("core.commandNameConflict", s(n1), s(n2)));
|
|
29
|
+
this.n1 = n1;
|
|
30
|
+
this.n2 = n2;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
class ScriptNameNotSetError extends Error {
|
|
34
|
+
constructor(t) {
|
|
35
|
+
super(t("core.scriptNameNotSet"));
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
class DescriptionNotSetError extends Error {
|
|
39
|
+
constructor(t) {
|
|
40
|
+
super(t("core.descriptionNotSet"));
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
class VersionNotSetError extends Error {
|
|
44
|
+
constructor(t) {
|
|
45
|
+
super(t("core.versionNotSet"));
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
class InvalidCommandNameError extends Error {
|
|
49
|
+
constructor(commandName, t) {
|
|
50
|
+
super(t("core.badNameFormat", s(commandName)));
|
|
51
|
+
this.commandName = commandName;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
class LocaleNotCalledFirstError extends Error {
|
|
55
|
+
constructor(t) {
|
|
56
|
+
super(t("core.localeMustBeCalledFirst"));
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const locales = {
|
|
61
|
+
"en": {
|
|
62
|
+
"core.commandExists": 'Command "%s" exists.',
|
|
63
|
+
"core.noSuchCommand": "No such command: %s.",
|
|
64
|
+
"core.noCommandGiven": "No command given.",
|
|
65
|
+
"core.commandNameConflict": "Command name %s conflicts with %s. Maybe caused by alias.",
|
|
66
|
+
"core.scriptNameNotSet": "Name not set.",
|
|
67
|
+
"core.descriptionNotSet": "Description not set.",
|
|
68
|
+
"core.versionNotSet": "Version not set.",
|
|
69
|
+
"core.badNameFormat": "Bad name format: %s.",
|
|
70
|
+
"core.localeMustBeCalledFirst": "locale() or fallbackLocale() must be called at first.",
|
|
71
|
+
"core.cliParseMustBeCalled": "cli.parse() must be called.",
|
|
72
|
+
"core.spreadParameterMustBeLast": "Invalid Parameter: Spread parameter %s must be last.",
|
|
73
|
+
"core.requiredParameterCannotComeAfterOptionalParameter": "Invalid Parameter: Required parameter %s cannot come after optional parameter %s.",
|
|
74
|
+
"core.parameterMustBeWrappedInBrackets": "Invalid Parameter: Parameter %s must be wrapped in <> (required parameter) or [] (optional parameter).",
|
|
75
|
+
"core.parameterIsUsedMoreThanOnce": "Invalid Parameter: Parameter %s is used more than once.",
|
|
76
|
+
"core.missingRequiredParameter": "Missing required parameter %s."
|
|
77
|
+
},
|
|
78
|
+
"zh-CN": {
|
|
79
|
+
"core.commandExists": '\u547D\u4EE4 "%s" \u5DF2\u5B58\u5728\u3002',
|
|
80
|
+
"core.noSuchCommand": "\u627E\u4E0D\u5230\u547D\u4EE4: %s\u3002",
|
|
81
|
+
"core.noCommandGiven": "\u6CA1\u6709\u8F93\u5165\u547D\u4EE4\u3002",
|
|
82
|
+
"core.commandNameConflict": "\u547D\u4EE4\u540D\u79F0 %s \u548C %s \u51B2\u7A81\u3002 \u53EF\u80FD\u662F\u7531\u4E8E\u522B\u540D\u5BFC\u81F4\u7684\u3002",
|
|
83
|
+
"core.scriptNameNotSet": "\u672A\u8BBE\u7F6E CLI Script \u540D\u79F0\u3002",
|
|
84
|
+
"core.descriptionNotSet": "\u672A\u8BBE\u7F6E CLI \u63CF\u8FF0\u3002",
|
|
85
|
+
"core.versionNotSet": "\u672A\u8BBE\u7F6E CLI \u7248\u672C\u3002",
|
|
86
|
+
"core.badNameFormat": "\u9519\u8BEF\u7684\u547D\u4EE4\u540D\u5B57\u683C\u5F0F: %s\u3002",
|
|
87
|
+
"core.localeMustBeCalledFirst": "locale() \u6216 fallbackLocale() \u5FC5\u987B\u5728\u6700\u5F00\u59CB\u8C03\u7528\u3002",
|
|
88
|
+
"core.cliParseMustBeCalled": "cli.parse() \u5FC5\u987B\u88AB\u8C03\u7528\u3002",
|
|
89
|
+
"core.spreadParameterMustBeLast": "\u4E0D\u5408\u6CD5\u7684\u53C2\u6570: \u5C55\u5F00\u53C2\u6570 %s \u5FC5\u987B\u5728\u6700\u540E\u3002",
|
|
90
|
+
"core.requiredParameterCannotComeAfterOptionalParameter": "\u4E0D\u5408\u6CD5\u7684\u53C2\u6570: \u5FC5\u586B\u53C2\u6570 %s \u4E0D\u80FD\u5728\u53EF\u9009\u53C2\u6570 %s \u4E4B\u540E\u3002",
|
|
91
|
+
"core.parameterMustBeWrappedInBrackets": "\u4E0D\u5408\u6CD5\u7684\u53C2\u6570: \u53C2\u6570 %s \u5FC5\u987B\u88AB <> (\u5FC5\u586B\u53C2\u6570) \u6216 [] (\u53EF\u9009\u53C2\u6570) \u5305\u88F9\u3002",
|
|
92
|
+
"core.parameterIsUsedMoreThanOnce": "\u4E0D\u5408\u6CD5\u7684\u53C2\u6570: \u53C2\u6570 %s \u88AB\u4F7F\u7528\u4E86\u591A\u6B21\u3002",
|
|
93
|
+
"core.missingRequiredParameter": "\u7F3A\u5C11\u5FC5\u586B\u53C2\u6570 %s\u3002"
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
const { stringify } = JSON;
|
|
98
|
+
function parseParameters(parameters, t) {
|
|
99
|
+
const parsedParameters = [];
|
|
100
|
+
let hasOptional;
|
|
101
|
+
let hasSpread;
|
|
102
|
+
for (const parameter of parameters) {
|
|
103
|
+
if (hasSpread) {
|
|
104
|
+
throw new Error(
|
|
105
|
+
t("core.spreadParameterMustBeLast", stringify(hasSpread))
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
const firstCharacter = parameter[0];
|
|
109
|
+
const lastCharacter = parameter[parameter.length - 1];
|
|
110
|
+
let required;
|
|
111
|
+
if (firstCharacter === "<" && lastCharacter === ">") {
|
|
112
|
+
required = true;
|
|
113
|
+
if (hasOptional) {
|
|
114
|
+
throw new Error(
|
|
115
|
+
t(
|
|
116
|
+
"core.requiredParameterMustBeBeforeOptional",
|
|
117
|
+
stringify(parameter),
|
|
118
|
+
stringify(hasOptional)
|
|
119
|
+
)
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
if (firstCharacter === "[" && lastCharacter === "]") {
|
|
124
|
+
required = false;
|
|
125
|
+
hasOptional = parameter;
|
|
126
|
+
}
|
|
127
|
+
if (required === void 0) {
|
|
128
|
+
throw new Error(
|
|
129
|
+
t("core.parameterMustBeWrappedInBrackets", stringify(parameter))
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
let name = parameter.slice(1, -1);
|
|
133
|
+
const spread = name.slice(-3) === "...";
|
|
134
|
+
if (spread) {
|
|
135
|
+
hasSpread = parameter;
|
|
136
|
+
name = name.slice(0, -3);
|
|
137
|
+
}
|
|
138
|
+
parsedParameters.push({
|
|
139
|
+
name,
|
|
140
|
+
required,
|
|
141
|
+
spread
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
return parsedParameters;
|
|
145
|
+
}
|
|
146
|
+
function mapParametersToArguments(mapping, parameters, cliArguments, t) {
|
|
147
|
+
for (let index = 0; index < parameters.length; index += 1) {
|
|
148
|
+
const { name, required, spread } = parameters[index];
|
|
149
|
+
const camelCaseName = camelCase(name);
|
|
150
|
+
if (camelCaseName in mapping) {
|
|
151
|
+
throw new Error(t("core.parameterIsUsedMoreThanOnce", stringify(name)));
|
|
152
|
+
}
|
|
153
|
+
const value = spread ? cliArguments.slice(index) : cliArguments[index];
|
|
154
|
+
if (spread) {
|
|
155
|
+
index = parameters.length;
|
|
156
|
+
}
|
|
157
|
+
if (required && (!value || spread && value.length === 0)) {
|
|
158
|
+
throw new Error(t("core.missingRequiredParameter", stringify(name)));
|
|
159
|
+
}
|
|
160
|
+
mapping[camelCaseName] = value;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function setCommand(commandsMap, commands, command, t) {
|
|
165
|
+
if (command.alias) {
|
|
166
|
+
const aliases = toArray(command.alias);
|
|
167
|
+
for (const alias of aliases) {
|
|
168
|
+
if (alias in commands) {
|
|
169
|
+
throw new CommandNameConflictError(
|
|
170
|
+
commands[alias].name,
|
|
171
|
+
command.name,
|
|
172
|
+
t
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
commandsMap.set(typeof alias === "symbol" ? alias : alias.split(" "), {
|
|
176
|
+
...command,
|
|
177
|
+
__isAlias: true
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
function resolveFlattenCommands(commands, t) {
|
|
183
|
+
const commandsMap = /* @__PURE__ */ new Map();
|
|
184
|
+
if (commands[Root]) {
|
|
185
|
+
commandsMap.set(Root, commands[Root]);
|
|
186
|
+
setCommand(commandsMap, commands, commands[Root], t);
|
|
187
|
+
}
|
|
188
|
+
for (const command of Object.values(commands)) {
|
|
189
|
+
setCommand(commandsMap, commands, command, t);
|
|
190
|
+
commandsMap.set(command.name.split(" "), command);
|
|
191
|
+
}
|
|
192
|
+
return commandsMap;
|
|
193
|
+
}
|
|
194
|
+
function resolveCommand(commands, argv, t) {
|
|
195
|
+
var _a;
|
|
196
|
+
const commandsMap = resolveFlattenCommands(commands, t);
|
|
197
|
+
for (const [name, command] of commandsMap.entries()) {
|
|
198
|
+
const parsed = typeFlag((_a = command == null ? void 0 : command.flags) != null ? _a : /* @__PURE__ */ Object.create(null), [...argv]);
|
|
199
|
+
const { _: arguments_ } = parsed;
|
|
200
|
+
if (name === Root) {
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
if (arrayStartsWith(arguments_, name)) {
|
|
204
|
+
return [command, name];
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
if (commandsMap.has(Root)) {
|
|
208
|
+
return [commandsMap.get(Root), Root];
|
|
209
|
+
}
|
|
210
|
+
return [void 0, void 0];
|
|
211
|
+
}
|
|
212
|
+
const resolveArgv = () => IS_NODE ? process.argv.slice(IS_ELECTRON ? 1 : 2) : IS_DENO ? (
|
|
213
|
+
// @ts-expect-error Ignore
|
|
214
|
+
Deno.args
|
|
215
|
+
) : [];
|
|
216
|
+
function compose(inspectors) {
|
|
217
|
+
const inspectorMap = {
|
|
218
|
+
pre: [],
|
|
219
|
+
normal: [],
|
|
220
|
+
post: []
|
|
221
|
+
};
|
|
222
|
+
for (const inspector of inspectors) {
|
|
223
|
+
const objectInspector = typeof inspector === "object" ? inspector : { fn: inspector };
|
|
224
|
+
const { enforce, fn } = objectInspector;
|
|
225
|
+
if (enforce === "post" || enforce === "pre") {
|
|
226
|
+
inspectorMap[enforce].push(fn);
|
|
227
|
+
} else {
|
|
228
|
+
inspectorMap.normal.push(fn);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
const mergedInspectorFunctions = [
|
|
232
|
+
...inspectorMap.pre,
|
|
233
|
+
...inspectorMap.normal,
|
|
234
|
+
...inspectorMap.post
|
|
235
|
+
];
|
|
236
|
+
return (context) => {
|
|
237
|
+
return dispatch(0);
|
|
238
|
+
function dispatch(index) {
|
|
239
|
+
const inspector = mergedInspectorFunctions[index];
|
|
240
|
+
return inspector(context, dispatch.bind(null, index + 1));
|
|
241
|
+
}
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
const INVALID_RE = /\s{2,}/;
|
|
245
|
+
const isValidName = (name) => name === Root ? true : !(name.startsWith(" ") || name.endsWith(" ")) && !INVALID_RE.test(name);
|
|
246
|
+
const withBrackets = (s, isOptional) => isOptional ? `[${s}]` : `<${s}>`;
|
|
247
|
+
const ROOT = "<Root>";
|
|
248
|
+
const formatCommandName = (name) => Array.isArray(name) ? name.join(" ") : typeof name === "string" ? name : ROOT;
|
|
249
|
+
const detectLocale = () => process.env.CLERC_LOCALE ? process.env.CLERC_LOCALE : Intl.DateTimeFormat().resolvedOptions().locale;
|
|
250
|
+
const stripFlags = (argv) => argv.filter((argument) => !argument.startsWith("-"));
|
|
251
|
+
|
|
252
|
+
var __accessCheck = (obj, member, msg) => {
|
|
253
|
+
if (!member.has(obj))
|
|
254
|
+
throw TypeError("Cannot " + msg);
|
|
255
|
+
};
|
|
256
|
+
var __privateGet = (obj, member, getter) => {
|
|
257
|
+
__accessCheck(obj, member, "read from private field");
|
|
258
|
+
return getter ? getter.call(obj) : member.get(obj);
|
|
259
|
+
};
|
|
260
|
+
var __privateAdd = (obj, member, value) => {
|
|
261
|
+
if (member.has(obj))
|
|
262
|
+
throw TypeError("Cannot add the same private member more than once");
|
|
263
|
+
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
264
|
+
};
|
|
265
|
+
var __privateSet = (obj, member, value, setter) => {
|
|
266
|
+
__accessCheck(obj, member, "write to private field");
|
|
267
|
+
setter ? setter.call(obj, value) : member.set(obj, value);
|
|
268
|
+
return value;
|
|
269
|
+
};
|
|
270
|
+
var __privateMethod = (obj, member, method) => {
|
|
271
|
+
__accessCheck(obj, member, "access private method");
|
|
272
|
+
return method;
|
|
273
|
+
};
|
|
274
|
+
var _name, _scriptName, _description, _version, _inspectors, _commands, _commandEmitter, _flags, _usedNames, _argv, _errorHandlers, _isOtherMethodCalled, _defaultLocale, _locale, _locales, _hasRootOrAlias, hasRootOrAlias_get, _hasRoot, hasRoot_get, _addCoreLocales, addCoreLocales_fn, _otherMethodCalled, otherMethodCalled_fn, _command, command_fn, _validateMeta, validateMeta_fn, _getContext, getContext_fn, _callWithErrorHandling, callWithErrorHandling_fn, _runMatchedCommand, runMatchedCommand_fn;
|
|
275
|
+
const Root = Symbol.for("Clerc.Root");
|
|
276
|
+
const _Clerc = class {
|
|
277
|
+
constructor(scriptName, description, version) {
|
|
278
|
+
__privateAdd(this, _hasRootOrAlias);
|
|
279
|
+
__privateAdd(this, _hasRoot);
|
|
280
|
+
__privateAdd(this, _addCoreLocales);
|
|
281
|
+
__privateAdd(this, _otherMethodCalled);
|
|
282
|
+
__privateAdd(this, _command);
|
|
283
|
+
__privateAdd(this, _validateMeta);
|
|
284
|
+
__privateAdd(this, _getContext);
|
|
285
|
+
__privateAdd(this, _callWithErrorHandling);
|
|
286
|
+
__privateAdd(this, _runMatchedCommand);
|
|
287
|
+
__privateAdd(this, _name, "");
|
|
288
|
+
__privateAdd(this, _scriptName, "");
|
|
289
|
+
__privateAdd(this, _description, "");
|
|
290
|
+
__privateAdd(this, _version, "");
|
|
291
|
+
__privateAdd(this, _inspectors, []);
|
|
292
|
+
__privateAdd(this, _commands, /* @__PURE__ */ Object.create(null));
|
|
293
|
+
__privateAdd(this, _commandEmitter, new LiteEmit());
|
|
294
|
+
__privateAdd(this, _flags, /* @__PURE__ */ Object.create(null));
|
|
295
|
+
__privateAdd(this, _usedNames, /* @__PURE__ */ new Set());
|
|
296
|
+
__privateAdd(this, _argv, void 0);
|
|
297
|
+
__privateAdd(this, _errorHandlers, []);
|
|
298
|
+
__privateAdd(this, _isOtherMethodCalled, false);
|
|
299
|
+
__privateAdd(this, _defaultLocale, "en");
|
|
300
|
+
__privateAdd(this, _locale, "en");
|
|
301
|
+
__privateAdd(this, _locales, /* @__PURE__ */ Object.create(null));
|
|
302
|
+
this.i18n = {
|
|
303
|
+
add: (locales2) => {
|
|
304
|
+
__privateSet(this, _locales, defu(__privateGet(this, _locales), locales2));
|
|
305
|
+
},
|
|
306
|
+
t: (name, ...arguments_) => {
|
|
307
|
+
const localeObject = __privateGet(this, _locales)[__privateGet(this, _locale)] || __privateGet(this, _locales)[__privateGet(this, _defaultLocale)];
|
|
308
|
+
const defaultLocaleObject = __privateGet(this, _locales)[__privateGet(this, _defaultLocale)];
|
|
309
|
+
return localeObject[name] ? format(localeObject[name], ...arguments_) : defaultLocaleObject[name] ? format(defaultLocaleObject[name], ...arguments_) : void 0;
|
|
310
|
+
}
|
|
311
|
+
};
|
|
312
|
+
__privateSet(this, _scriptName, scriptName != null ? scriptName : __privateGet(this, _scriptName));
|
|
313
|
+
__privateSet(this, _description, description != null ? description : __privateGet(this, _description));
|
|
314
|
+
__privateSet(this, _version, version != null ? version : __privateGet(this, _version));
|
|
315
|
+
__privateSet(this, _locale, detectLocale());
|
|
316
|
+
__privateMethod(this, _addCoreLocales, addCoreLocales_fn).call(this);
|
|
317
|
+
}
|
|
318
|
+
get _name() {
|
|
319
|
+
return __privateGet(this, _name) || __privateGet(this, _scriptName);
|
|
320
|
+
}
|
|
321
|
+
get _scriptName() {
|
|
322
|
+
return __privateGet(this, _scriptName);
|
|
323
|
+
}
|
|
324
|
+
get _description() {
|
|
325
|
+
return __privateGet(this, _description);
|
|
326
|
+
}
|
|
327
|
+
get _version() {
|
|
328
|
+
return __privateGet(this, _version);
|
|
329
|
+
}
|
|
330
|
+
get _inspectors() {
|
|
331
|
+
return __privateGet(this, _inspectors);
|
|
332
|
+
}
|
|
333
|
+
get _commands() {
|
|
334
|
+
return __privateGet(this, _commands);
|
|
335
|
+
}
|
|
336
|
+
get _flags() {
|
|
337
|
+
return __privateGet(this, _flags);
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* Create a new cli
|
|
341
|
+
*
|
|
342
|
+
* @example
|
|
343
|
+
*
|
|
344
|
+
* ```ts
|
|
345
|
+
* const cli = Clerc.create();
|
|
346
|
+
* ```
|
|
347
|
+
*
|
|
348
|
+
* @param name
|
|
349
|
+
* @param description
|
|
350
|
+
* @param version
|
|
351
|
+
* @returns
|
|
352
|
+
*/
|
|
353
|
+
static create(name, description, version) {
|
|
354
|
+
return new _Clerc(name, description, version);
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* Set the name of the cli
|
|
358
|
+
*
|
|
359
|
+
* @example
|
|
360
|
+
*
|
|
361
|
+
* ```ts
|
|
362
|
+
* Clerc.create().name("test");
|
|
363
|
+
* ```
|
|
364
|
+
*
|
|
365
|
+
* @param name
|
|
366
|
+
* @returns
|
|
367
|
+
*/
|
|
368
|
+
name(name) {
|
|
369
|
+
__privateMethod(this, _otherMethodCalled, otherMethodCalled_fn).call(this);
|
|
370
|
+
__privateSet(this, _name, name);
|
|
371
|
+
return this;
|
|
372
|
+
}
|
|
373
|
+
/**
|
|
374
|
+
* Set the script name of the cli
|
|
375
|
+
*
|
|
376
|
+
* @example
|
|
377
|
+
*
|
|
378
|
+
* ```ts
|
|
379
|
+
* Clerc.create().scriptName("test");
|
|
380
|
+
* ```
|
|
381
|
+
*
|
|
382
|
+
* @param scriptName
|
|
383
|
+
* @returns
|
|
384
|
+
*/
|
|
385
|
+
scriptName(scriptName) {
|
|
386
|
+
__privateMethod(this, _otherMethodCalled, otherMethodCalled_fn).call(this);
|
|
387
|
+
__privateSet(this, _scriptName, scriptName);
|
|
388
|
+
return this;
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* Set the description of the cli
|
|
392
|
+
*
|
|
393
|
+
* @example
|
|
394
|
+
*
|
|
395
|
+
* ```ts
|
|
396
|
+
* Clerc.create().description("test cli");
|
|
397
|
+
* ```
|
|
398
|
+
*
|
|
399
|
+
* @param description
|
|
400
|
+
* @returns
|
|
401
|
+
*/
|
|
402
|
+
description(description) {
|
|
403
|
+
__privateMethod(this, _otherMethodCalled, otherMethodCalled_fn).call(this);
|
|
404
|
+
__privateSet(this, _description, description);
|
|
405
|
+
return this;
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* Set the version of the cli
|
|
409
|
+
*
|
|
410
|
+
* @example
|
|
411
|
+
*
|
|
412
|
+
* ```ts
|
|
413
|
+
* Clerc.create().version("1.0.0");
|
|
414
|
+
* ```
|
|
415
|
+
*
|
|
416
|
+
* @param version
|
|
417
|
+
* @returns
|
|
418
|
+
*/
|
|
419
|
+
version(version) {
|
|
420
|
+
__privateMethod(this, _otherMethodCalled, otherMethodCalled_fn).call(this);
|
|
421
|
+
__privateSet(this, _version, version);
|
|
422
|
+
return this;
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* Set the Locale You must call this method once after you created the Clerc
|
|
426
|
+
* instance.
|
|
427
|
+
*
|
|
428
|
+
* @example
|
|
429
|
+
*
|
|
430
|
+
* ```ts
|
|
431
|
+
* Clerc.create()
|
|
432
|
+
* .locale("en")
|
|
433
|
+
* .command(...)
|
|
434
|
+
* ```
|
|
435
|
+
*
|
|
436
|
+
* @param locale
|
|
437
|
+
* @returns
|
|
438
|
+
*/
|
|
439
|
+
locale(locale) {
|
|
440
|
+
if (__privateGet(this, _isOtherMethodCalled)) {
|
|
441
|
+
throw new LocaleNotCalledFirstError(this.i18n.t);
|
|
442
|
+
}
|
|
443
|
+
__privateSet(this, _locale, locale);
|
|
444
|
+
return this;
|
|
445
|
+
}
|
|
446
|
+
/**
|
|
447
|
+
* Set the fallback Locale You must call this method once after you created
|
|
448
|
+
* the Clerc instance.
|
|
449
|
+
*
|
|
450
|
+
* @example
|
|
451
|
+
*
|
|
452
|
+
* ```ts
|
|
453
|
+
* Clerc.create()
|
|
454
|
+
* .fallbackLocale("en")
|
|
455
|
+
* .command(...)
|
|
456
|
+
* ```
|
|
457
|
+
*
|
|
458
|
+
* @param fallbackLocale
|
|
459
|
+
* @returns
|
|
460
|
+
*/
|
|
461
|
+
fallbackLocale(fallbackLocale) {
|
|
462
|
+
if (__privateGet(this, _isOtherMethodCalled)) {
|
|
463
|
+
throw new LocaleNotCalledFirstError(this.i18n.t);
|
|
464
|
+
}
|
|
465
|
+
__privateSet(this, _defaultLocale, fallbackLocale);
|
|
466
|
+
return this;
|
|
467
|
+
}
|
|
468
|
+
/**
|
|
469
|
+
* Register a error handler
|
|
470
|
+
*
|
|
471
|
+
* @example
|
|
472
|
+
*
|
|
473
|
+
* ```ts
|
|
474
|
+
* Clerc.create().errorHandler((err) => {
|
|
475
|
+
* console.log(err);
|
|
476
|
+
* });
|
|
477
|
+
* ```
|
|
478
|
+
*
|
|
479
|
+
* @param handler
|
|
480
|
+
* @returns
|
|
481
|
+
*/
|
|
482
|
+
errorHandler(handler) {
|
|
483
|
+
__privateGet(this, _errorHandlers).push(handler);
|
|
484
|
+
return this;
|
|
485
|
+
}
|
|
486
|
+
command(nameOrCommand, description, options = {}) {
|
|
487
|
+
__privateMethod(this, _callWithErrorHandling, callWithErrorHandling_fn).call(this, () => __privateMethod(this, _command, command_fn).call(this, nameOrCommand, description, options));
|
|
488
|
+
return this;
|
|
489
|
+
}
|
|
490
|
+
/**
|
|
491
|
+
* Register a global flag
|
|
492
|
+
*
|
|
493
|
+
* @example
|
|
494
|
+
*
|
|
495
|
+
* ```ts
|
|
496
|
+
* Clerc.create().flag("help", "help", {
|
|
497
|
+
* alias: "h",
|
|
498
|
+
* type: Boolean,
|
|
499
|
+
* });
|
|
500
|
+
* ```
|
|
501
|
+
*
|
|
502
|
+
* @param name
|
|
503
|
+
* @param description
|
|
504
|
+
* @param options
|
|
505
|
+
* @returns
|
|
506
|
+
*/
|
|
507
|
+
flag(name, description, options) {
|
|
508
|
+
__privateGet(this, _flags)[name] = {
|
|
509
|
+
description,
|
|
510
|
+
...options
|
|
511
|
+
};
|
|
512
|
+
return this;
|
|
513
|
+
}
|
|
514
|
+
/**
|
|
515
|
+
* Register a handler
|
|
516
|
+
*
|
|
517
|
+
* @example
|
|
518
|
+
*
|
|
519
|
+
* ```ts
|
|
520
|
+
* Clerc.create()
|
|
521
|
+
* .command("test", "test command")
|
|
522
|
+
* .on("test", (ctx) => {
|
|
523
|
+
* console.log(ctx);
|
|
524
|
+
* });
|
|
525
|
+
* ```
|
|
526
|
+
*
|
|
527
|
+
* @param name
|
|
528
|
+
* @param handler
|
|
529
|
+
* @returns
|
|
530
|
+
*/
|
|
531
|
+
on(name, handler) {
|
|
532
|
+
__privateGet(this, _commandEmitter).on(name, handler);
|
|
533
|
+
return this;
|
|
534
|
+
}
|
|
535
|
+
/**
|
|
536
|
+
* Use a plugin
|
|
537
|
+
*
|
|
538
|
+
* @example
|
|
539
|
+
*
|
|
540
|
+
* ```ts
|
|
541
|
+
* Clerc.create().use(plugin);
|
|
542
|
+
* ```
|
|
543
|
+
*
|
|
544
|
+
* @param plugin
|
|
545
|
+
* @returns
|
|
546
|
+
*/
|
|
547
|
+
use(plugin) {
|
|
548
|
+
__privateMethod(this, _otherMethodCalled, otherMethodCalled_fn).call(this);
|
|
549
|
+
return plugin.setup(this);
|
|
550
|
+
}
|
|
551
|
+
/**
|
|
552
|
+
* Register a inspector
|
|
553
|
+
*
|
|
554
|
+
* @example
|
|
555
|
+
*
|
|
556
|
+
* ```ts
|
|
557
|
+
* Clerc.create().inspector((ctx, next) => {
|
|
558
|
+
* console.log(ctx);
|
|
559
|
+
* next();
|
|
560
|
+
* });
|
|
561
|
+
* ```
|
|
562
|
+
*
|
|
563
|
+
* @param inspector
|
|
564
|
+
* @returns
|
|
565
|
+
*/
|
|
566
|
+
inspector(inspector) {
|
|
567
|
+
__privateMethod(this, _otherMethodCalled, otherMethodCalled_fn).call(this);
|
|
568
|
+
__privateGet(this, _inspectors).push(inspector);
|
|
569
|
+
return this;
|
|
570
|
+
}
|
|
571
|
+
/**
|
|
572
|
+
* Parse the command line arguments
|
|
573
|
+
*
|
|
574
|
+
* @example
|
|
575
|
+
*
|
|
576
|
+
* ```ts
|
|
577
|
+
* Clerc.create().parse(process.argv.slice(2)); // Optional
|
|
578
|
+
* ```
|
|
579
|
+
*
|
|
580
|
+
* @param args
|
|
581
|
+
* @param optionsOrArgv
|
|
582
|
+
* @returns
|
|
583
|
+
*/
|
|
584
|
+
parse(optionsOrArgv = resolveArgv()) {
|
|
585
|
+
__privateMethod(this, _otherMethodCalled, otherMethodCalled_fn).call(this);
|
|
586
|
+
const { argv, run } = Array.isArray(optionsOrArgv) ? {
|
|
587
|
+
argv: optionsOrArgv,
|
|
588
|
+
run: true
|
|
589
|
+
} : {
|
|
590
|
+
argv: resolveArgv(),
|
|
591
|
+
...optionsOrArgv
|
|
592
|
+
};
|
|
593
|
+
__privateSet(this, _argv, [...argv]);
|
|
594
|
+
__privateMethod(this, _validateMeta, validateMeta_fn).call(this);
|
|
595
|
+
if (run) {
|
|
596
|
+
this.runMatchedCommand();
|
|
597
|
+
}
|
|
598
|
+
return this;
|
|
599
|
+
}
|
|
600
|
+
/**
|
|
601
|
+
* Run matched command
|
|
602
|
+
*
|
|
603
|
+
* @example
|
|
604
|
+
*
|
|
605
|
+
* ```ts
|
|
606
|
+
* Clerc.create().parse({ run: false }).runMatchedCommand();
|
|
607
|
+
* ```
|
|
608
|
+
*
|
|
609
|
+
* @returns
|
|
610
|
+
*/
|
|
611
|
+
runMatchedCommand() {
|
|
612
|
+
__privateMethod(this, _callWithErrorHandling, callWithErrorHandling_fn).call(this, () => __privateMethod(this, _runMatchedCommand, runMatchedCommand_fn).call(this));
|
|
613
|
+
process.title = __privateGet(this, _name);
|
|
614
|
+
return this;
|
|
615
|
+
}
|
|
616
|
+
};
|
|
617
|
+
let Clerc = _Clerc;
|
|
618
|
+
_name = new WeakMap();
|
|
619
|
+
_scriptName = new WeakMap();
|
|
620
|
+
_description = new WeakMap();
|
|
621
|
+
_version = new WeakMap();
|
|
622
|
+
_inspectors = new WeakMap();
|
|
623
|
+
_commands = new WeakMap();
|
|
624
|
+
_commandEmitter = new WeakMap();
|
|
625
|
+
_flags = new WeakMap();
|
|
626
|
+
_usedNames = new WeakMap();
|
|
627
|
+
_argv = new WeakMap();
|
|
628
|
+
_errorHandlers = new WeakMap();
|
|
629
|
+
_isOtherMethodCalled = new WeakMap();
|
|
630
|
+
_defaultLocale = new WeakMap();
|
|
631
|
+
_locale = new WeakMap();
|
|
632
|
+
_locales = new WeakMap();
|
|
633
|
+
_hasRootOrAlias = new WeakSet();
|
|
634
|
+
hasRootOrAlias_get = function() {
|
|
635
|
+
return __privateGet(this, _usedNames).has(Root);
|
|
636
|
+
};
|
|
637
|
+
_hasRoot = new WeakSet();
|
|
638
|
+
hasRoot_get = function() {
|
|
639
|
+
return Object.prototype.hasOwnProperty.call(this._commands, Root);
|
|
640
|
+
};
|
|
641
|
+
_addCoreLocales = new WeakSet();
|
|
642
|
+
addCoreLocales_fn = function() {
|
|
643
|
+
this.i18n.add(locales);
|
|
644
|
+
};
|
|
645
|
+
_otherMethodCalled = new WeakSet();
|
|
646
|
+
otherMethodCalled_fn = function() {
|
|
647
|
+
__privateSet(this, _isOtherMethodCalled, true);
|
|
648
|
+
};
|
|
649
|
+
_command = new WeakSet();
|
|
650
|
+
command_fn = function(nameOrCommand, description, options = {}) {
|
|
651
|
+
__privateMethod(this, _otherMethodCalled, otherMethodCalled_fn).call(this);
|
|
652
|
+
const { t } = this.i18n;
|
|
653
|
+
const checkIsCommandObject = (nameOrCommand2) => !(typeof nameOrCommand2 === "string" || nameOrCommand2 === Root);
|
|
654
|
+
const isCommandObject = checkIsCommandObject(nameOrCommand);
|
|
655
|
+
const name = isCommandObject ? nameOrCommand.name : nameOrCommand;
|
|
656
|
+
if (!isValidName(name)) {
|
|
657
|
+
throw new InvalidCommandNameError(name, t);
|
|
658
|
+
}
|
|
659
|
+
const { handler = void 0, ...commandToSave } = isCommandObject ? nameOrCommand : { name, description, ...options };
|
|
660
|
+
const nameList = [commandToSave.name];
|
|
661
|
+
const aliasList = commandToSave.alias ? toArray(commandToSave.alias) : [];
|
|
662
|
+
commandToSave.alias && nameList.push(...aliasList);
|
|
663
|
+
for (const name2 of nameList) {
|
|
664
|
+
if (__privateGet(this, _usedNames).has(name2)) {
|
|
665
|
+
throw new CommandExistsError(formatCommandName(name2), t);
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
__privateGet(this, _commands)[name] = commandToSave;
|
|
669
|
+
__privateGet(this, _usedNames).add(commandToSave.name);
|
|
670
|
+
for (const a of aliasList) {
|
|
671
|
+
__privateGet(this, _usedNames).add(a);
|
|
672
|
+
}
|
|
673
|
+
isCommandObject && handler && this.on(nameOrCommand.name, handler);
|
|
674
|
+
return this;
|
|
675
|
+
};
|
|
676
|
+
_validateMeta = new WeakSet();
|
|
677
|
+
validateMeta_fn = function() {
|
|
678
|
+
const { t } = this.i18n;
|
|
679
|
+
if (!__privateGet(this, _scriptName)) {
|
|
680
|
+
throw new ScriptNameNotSetError(t);
|
|
681
|
+
}
|
|
682
|
+
if (!__privateGet(this, _description)) {
|
|
683
|
+
throw new DescriptionNotSetError(t);
|
|
684
|
+
}
|
|
685
|
+
if (!__privateGet(this, _version)) {
|
|
686
|
+
throw new VersionNotSetError(t);
|
|
687
|
+
}
|
|
688
|
+
};
|
|
689
|
+
_getContext = new WeakSet();
|
|
690
|
+
getContext_fn = function(getCommand) {
|
|
691
|
+
var _a;
|
|
692
|
+
const argv = __privateGet(this, _argv);
|
|
693
|
+
const { t } = this.i18n;
|
|
694
|
+
const [command, called] = getCommand();
|
|
695
|
+
const isCommandResolved = !!command;
|
|
696
|
+
const flagsMerged = {
|
|
697
|
+
...__privateGet(this, _flags),
|
|
698
|
+
...command == null ? void 0 : command.flags
|
|
699
|
+
};
|
|
700
|
+
const parsed = typeFlag(flagsMerged, [...argv]);
|
|
701
|
+
const { _: arguments_, flags, unknownFlags } = parsed;
|
|
702
|
+
let parameters = !isCommandResolved || command.name === Root ? arguments_ : arguments_.slice(command.name.split(" ").length);
|
|
703
|
+
let commandParameters = (_a = command == null ? void 0 : command.parameters) != null ? _a : [];
|
|
704
|
+
const hasEof = commandParameters.indexOf("--");
|
|
705
|
+
const eofParameters = commandParameters.slice(hasEof + 1) || [];
|
|
706
|
+
const mapping = /* @__PURE__ */ Object.create(null);
|
|
707
|
+
if (hasEof > -1 && eofParameters.length > 0) {
|
|
708
|
+
commandParameters = commandParameters.slice(0, hasEof);
|
|
709
|
+
const eofArguments = arguments_["--"];
|
|
710
|
+
parameters = parameters.slice(0, -eofArguments.length || void 0);
|
|
711
|
+
mapParametersToArguments(
|
|
712
|
+
mapping,
|
|
713
|
+
parseParameters(commandParameters, t),
|
|
714
|
+
parameters,
|
|
715
|
+
t
|
|
716
|
+
);
|
|
717
|
+
mapParametersToArguments(
|
|
718
|
+
mapping,
|
|
719
|
+
parseParameters(eofParameters, t),
|
|
720
|
+
eofArguments,
|
|
721
|
+
t
|
|
722
|
+
);
|
|
723
|
+
} else {
|
|
724
|
+
mapParametersToArguments(
|
|
725
|
+
mapping,
|
|
726
|
+
parseParameters(commandParameters, t),
|
|
727
|
+
parameters,
|
|
728
|
+
t
|
|
729
|
+
);
|
|
730
|
+
}
|
|
731
|
+
const mergedFlags = { ...flags, ...unknownFlags };
|
|
732
|
+
const context = {
|
|
733
|
+
name: command == null ? void 0 : command.name,
|
|
734
|
+
called: Array.isArray(called) ? called.join(" ") : called,
|
|
735
|
+
resolved: isCommandResolved,
|
|
736
|
+
hasRootOrAlias: __privateGet(this, _hasRootOrAlias, hasRootOrAlias_get),
|
|
737
|
+
hasRoot: __privateGet(this, _hasRoot, hasRoot_get),
|
|
738
|
+
raw: { ...parsed, parameters, mergedFlags },
|
|
739
|
+
parameters: mapping,
|
|
740
|
+
flags,
|
|
741
|
+
unknownFlags,
|
|
742
|
+
cli: this
|
|
743
|
+
};
|
|
744
|
+
return context;
|
|
745
|
+
};
|
|
746
|
+
_callWithErrorHandling = new WeakSet();
|
|
747
|
+
callWithErrorHandling_fn = function(function_) {
|
|
748
|
+
try {
|
|
749
|
+
function_();
|
|
750
|
+
} catch (error) {
|
|
751
|
+
if (__privateGet(this, _errorHandlers).length > 0) {
|
|
752
|
+
for (const callback of __privateGet(this, _errorHandlers)) {
|
|
753
|
+
callback(error);
|
|
754
|
+
}
|
|
755
|
+
} else {
|
|
756
|
+
throw error;
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
};
|
|
760
|
+
_runMatchedCommand = new WeakSet();
|
|
761
|
+
runMatchedCommand_fn = function() {
|
|
762
|
+
__privateMethod(this, _otherMethodCalled, otherMethodCalled_fn).call(this);
|
|
763
|
+
const { t } = this.i18n;
|
|
764
|
+
const argv = __privateGet(this, _argv);
|
|
765
|
+
if (!argv) {
|
|
766
|
+
throw new Error(t("core.cliParseMustBeCalled"));
|
|
767
|
+
}
|
|
768
|
+
const getCommand = () => resolveCommand(__privateGet(this, _commands), argv, t);
|
|
769
|
+
const getContext = () => __privateMethod(this, _getContext, getContext_fn).call(this, getCommand);
|
|
770
|
+
const emitHandler = {
|
|
771
|
+
enforce: "post",
|
|
772
|
+
fn: (context) => {
|
|
773
|
+
const [command] = getCommand();
|
|
774
|
+
const stringName = stripFlags(argv).join(" ");
|
|
775
|
+
if (!command) {
|
|
776
|
+
const error = stringName ? new NoSuchCommandError(stringName, t) : new NoCommandGivenError(t);
|
|
777
|
+
throw error;
|
|
778
|
+
}
|
|
779
|
+
__privateGet(this, _commandEmitter).emit(command.name, context);
|
|
780
|
+
}
|
|
781
|
+
};
|
|
782
|
+
const inspectors = [...__privateGet(this, _inspectors), emitHandler];
|
|
783
|
+
const callInspector = compose(inspectors);
|
|
784
|
+
callInspector(getContext());
|
|
785
|
+
};
|
|
786
|
+
|
|
787
|
+
const definePlugin = (p) => p;
|
|
788
|
+
const defineHandler = (_cli, _key, handler) => handler;
|
|
789
|
+
const defineInspector = (_cli, inspector) => inspector;
|
|
790
|
+
const defineCommand = (command, handler) => ({
|
|
791
|
+
...command,
|
|
792
|
+
handler
|
|
793
|
+
});
|
|
794
|
+
|
|
795
|
+
export { Clerc, CommandExistsError, CommandNameConflictError, DescriptionNotSetError, InvalidCommandNameError, LocaleNotCalledFirstError, NoCommandGivenError, NoSuchCommandError, Root, ScriptNameNotSetError, VersionNotSetError, compose, defineCommand, defineHandler, defineInspector, definePlugin, detectLocale, formatCommandName, isValidName, resolveArgv, resolveCommand, resolveFlattenCommands, stripFlags, withBrackets };
|