@clerc/core 0.27.1 → 0.28.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/dist/index.d.ts CHANGED
@@ -164,7 +164,7 @@ type LiteralUnion<
164
164
  type Equals<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false;
165
165
  type Dict<T> = Record<string, T>;
166
166
  type MaybeArray$1<T> = T | T[];
167
- type CamelCase<T extends string> = T extends `${infer A}-${infer B}${infer C}` ? `${A}${Capitalize<B>}${CamelCase<C>}` : T;
167
+ type CamelCase<T extends string> = (T extends `${infer Prefix}-${infer Suffix}` | `${infer Prefix} ${infer Suffix}` ? `${Prefix}${Capitalize<CamelCase<Suffix>>}` : T);
168
168
 
169
169
  declare const DOUBLE_DASH = "--";
170
170
  type TypeFunction<ReturnType = any> = (value: any) => ReturnType;
@@ -234,6 +234,29 @@ type TypeFlag<Schemas extends Flags$1> = ParsedFlags<{
234
234
  [flag in keyof Schemas]: InferFlagType<Schemas[flag]>;
235
235
  }>;
236
236
 
237
+ type StripBrackets<Parameter extends string> = (Parameter extends `<${infer ParameterName}>` | `[${infer ParameterName}]` ? (ParameterName extends `${infer SpreadName}...` ? SpreadName : ParameterName) : never);
238
+ type ParameterType<Parameter extends string> = (Parameter extends `<${infer _ParameterName}...>` | `[${infer _ParameterName}...]` ? string[] : Parameter extends `<${infer _ParameterName}>` ? string : Parameter extends `[${infer _ParameterName}]` ? string | undefined : never);
239
+ type NonNullableParameters<T extends string[] | undefined> = T extends undefined ? [] : NonNullable<T>;
240
+ type TransformParameters<C extends Command> = {
241
+ [Parameter in NonNullableParameters<C["parameters"]>[number] as CamelCase<StripBrackets<Parameter>>]: ParameterType<Parameter>;
242
+ };
243
+ type MakeEventMap<T extends CommandRecord> = {
244
+ [K in keyof T]: [InspectorContext];
245
+ };
246
+ type FallbackFlags<C extends Command> = Equals<NonNullableFlag<C>["flags"], {}> extends true ? Dict<any> : NonNullableFlag<C>["flags"];
247
+ type NonNullableFlag<C extends Command> = TypeFlag<NonNullable<C["flags"]>>;
248
+ type ParseFlag<C extends CommandRecord, N extends keyof C> = N extends keyof C ? OmitIndexSignature<NonNullableFlag<C[N]>["flags"]> : FallbackFlags<C[N]>["flags"];
249
+ type ParseRaw<C extends Command> = NonNullableFlag<C> & {
250
+ flags: FallbackFlags<C>;
251
+ parameters: string[];
252
+ mergedFlags: FallbackFlags<C> & NonNullableFlag<C>["unknownFlags"];
253
+ };
254
+ type ParseParameters<C extends CommandRecord = CommandRecord, N extends keyof C = keyof C> = Equals<TransformParameters<C[N]>, {}> extends true ? N extends keyof C ? TransformParameters<C[N]> : Dict<string | string[] | undefined> : TransformParameters<C[N]>;
255
+
256
+ interface Plugin<T extends Clerc = Clerc, U extends Clerc = Clerc> {
257
+ setup: (cli: T) => U;
258
+ }
259
+
237
260
  type CommandType = RootType | string;
238
261
  type FlagOptions = FlagSchema & {
239
262
  description?: string;
@@ -268,25 +291,7 @@ interface ParseOptions {
268
291
  argv?: string[];
269
292
  run?: boolean;
270
293
  }
271
- type StripBrackets<Parameter extends string> = (Parameter extends `<${infer ParameterName}>` | `[${infer ParameterName}]` ? (ParameterName extends `${infer SpreadName}...` ? SpreadName : ParameterName) : never);
272
- type ParameterType<Parameter extends string> = (Parameter extends `<${infer _ParameterName}...>` | `[${infer _ParameterName}...]` ? string[] : Parameter extends `<${infer _ParameterName}>` ? string : Parameter extends `[${infer _ParameterName}]` ? string | undefined : never);
273
- type MakeEventMap<T extends CommandRecord> = {
274
- [K in keyof T]: [InspectorContext];
275
- };
276
294
  type PossibleInputKind = string | number | boolean | Dict<any>;
277
- type NonNullableParameters<T extends string[] | undefined> = T extends undefined ? [] : NonNullable<T>;
278
- type TransformParameters<C extends Command> = {
279
- [Parameter in NonNullableParameters<C["parameters"]>[number] as CamelCase<StripBrackets<Parameter>>]: ParameterType<Parameter>;
280
- };
281
- type FallbackFlags<C extends Command> = Equals<NonNullableFlag<C>["flags"], {}> extends true ? Dict<any> : NonNullableFlag<C>["flags"];
282
- type NonNullableFlag<C extends Command> = TypeFlag<NonNullable<C["flags"]>>;
283
- type ParseFlag<C extends CommandRecord, N extends keyof C> = N extends keyof C ? OmitIndexSignature<NonNullableFlag<C[N]>["flags"]> : FallbackFlags<C[N]>["flags"];
284
- type ParseRaw<C extends Command> = NonNullableFlag<C> & {
285
- flags: FallbackFlags<C>;
286
- parameters: string[];
287
- mergedFlags: FallbackFlags<C> & NonNullableFlag<C>["unknownFlags"];
288
- };
289
- type ParseParameters<C extends CommandRecord = CommandRecord, N extends keyof C = keyof C> = Equals<TransformParameters<C[N]>, {}> extends true ? N extends keyof C ? TransformParameters<C[N]> : Dict<string | string[] | undefined> : TransformParameters<C[N]>;
290
295
  interface HandlerContext<C extends CommandRecord = CommandRecord, N extends keyof C = keyof C> {
291
296
  name?: LiteralUnion<N, string>;
292
297
  called?: string | RootType;
@@ -319,8 +324,8 @@ interface InspectorObject<C extends CommandRecord = CommandRecord> {
319
324
  enforce?: "pre" | "post";
320
325
  fn: InspectorFn<C>;
321
326
  }
322
- interface Plugin<T extends Clerc = Clerc, U extends Clerc = Clerc> {
323
- setup: (cli: T) => U;
327
+ interface I18N {
328
+ add: () => void;
324
329
  }
325
330
 
326
331
  declare const Root: unique symbol;
@@ -509,4 +514,4 @@ declare const isInvalidName: (name: CommandType) => boolean;
509
514
  declare const withBrackets: (s: string, isOptional?: boolean) => string;
510
515
  declare const formatCommandName: (name: string | string[] | RootType) => string;
511
516
 
512
- export { Clerc, Command, CommandAlias, CommandCustomProperties, CommandExistsError, CommandNameConflictError, CommandOptions, CommandRecord, CommandType, CommandWithHandler, DescriptionNotSetError, FallbackType, Flag, FlagOptions, Flags, Handler, HandlerContext, HandlerInCommand, Inspector, InspectorContext, InspectorFn, InspectorObject, InvalidCommandNameError, MakeEventMap, NameNotSetError, NoCommandGivenError, NoSuchCommandError, ParseOptions, Plugin, PossibleInputKind, Root, RootType, VersionNotSetError, compose, defineCommand, defineHandler, defineInspector, definePlugin, formatCommandName, isInvalidName, resolveArgv, resolveCommand, resolveFlattenCommands, resolveParametersBeforeFlag, resolveRootCommands, resolveSubcommandsByParent, withBrackets };
517
+ export { Clerc, Command, CommandAlias, CommandCustomProperties, CommandExistsError, CommandNameConflictError, CommandOptions, CommandRecord, CommandType, CommandWithHandler, DescriptionNotSetError, FallbackType, Flag, FlagOptions, Flags, Handler, HandlerContext, HandlerInCommand, I18N, Inspector, InspectorContext, InspectorFn, InspectorObject, InvalidCommandNameError, MakeEventMap, NameNotSetError, NoCommandGivenError, NoSuchCommandError, ParseOptions, Plugin, PossibleInputKind, Root, RootType, VersionNotSetError, compose, defineCommand, defineHandler, defineInspector, definePlugin, formatCommandName, isInvalidName, resolveArgv, resolveCommand, resolveFlattenCommands, resolveParametersBeforeFlag, resolveRootCommands, resolveSubcommandsByParent, withBrackets };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- class me{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(t,...s)),this.listenerMap[t].forEach(r=>r(...s))),this}off(t,s){var r,n;return t==="**"?(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):(n=this.listenerMap[t])==null||n.clear(),this)}}const ge="known-flag",we="unknown-flag",ve="argument",{stringify:S}=JSON,Ee=/\B([A-Z])/g,ye=e=>e.replace(Ee,"-$1").toLowerCase(),{hasOwnProperty:_e}=Object.prototype,k=(e,t)=>_e.call(e,t),Ce=e=>Array.isArray(e),H=e=>typeof e=="function"?[e,!1]:Ce(e)?[e[0],!0]:H(e.type),Me=(e,t)=>e===Boolean?t!=="false":t,Ne=(e,t)=>typeof t=="boolean"?t:e===Number&&t===""?Number.NaN:e(t),$e=/[\s.:=]/,Se=e=>{const t=`Flag name ${S(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($e);if(s)throw new Error(`${t} cannot contain ${S(s==null?void 0:s[0])}`)},ke=e=>{const t={},s=(r,n)=>{if(k(t,r))throw new Error(`Duplicate flags named ${S(r)}`);t[r]=n};for(const r in e){if(!k(e,r))continue;Se(r);const n=e[r],o=[[],...H(n),n];s(r,o);const a=ye(r);if(r!==a&&s(a,o),"alias"in n&&typeof n.alias=="string"){const{alias:i}=n,c=`Flag alias ${S(i)} for flag ${S(r)}`;if(i.length===0)throw new Error(`${c} cannot be empty`);if(i.length>1)throw new Error(`${c} must be a single character`);s(i,o)}}return t},Ae=(e,t)=>{const s={};for(const r in e){if(!k(e,r))continue;const[n,,o,a]=t[r];if(n.length===0&&"default"in a){let{default:i}=a;typeof i=="function"&&(i=i()),s[r]=i}else s[r]=o?n:n.pop()}return s},I="--",be=/[.:=]/,xe=/^-{1,2}\w/,Ie=e=>{if(!xe.test(e))return;const t=!e.startsWith(I);let s=e.slice(t?1:2),r;const n=s.match(be);if(n){const{index:o}=n;r=s.slice(o+1),s=s.slice(0,o)}return[s,r,t]},Oe=(e,{onFlag:t,onArgument:s})=>{let r;const n=(o,a)=>{if(typeof r!="function")return!0;r(o,a),r=void 0};for(let o=0;o<e.length;o+=1){const a=e[o];if(a===I){n();const c=e.slice(o+1);s==null||s(c,[o],!0);break}const i=Ie(a);if(i){if(n(),!t)continue;const[c,l,f]=i;if(f)for(let p=0;p<c.length;p+=1){n();const m=p===c.length-1;r=t(c[p],m?l:void 0,[o,p+1,m])}else r=t(c,l,[o])}else n(a,[o])&&(s==null||s([a],[o]))}n()},We=(e,t)=>{for(const[s,r,n]of t.reverse()){if(r){const o=e[s];let a=o.slice(0,r);if(n||(a+=o.slice(r+1)),a!=="-"){e[s]=a;continue}}e.splice(s,1)}},Re=(e,t=process.argv.slice(2),{ignore:s}={})=>{const r=[],n=ke(e),o={},a=[];return a[I]=[],Oe(t,{onFlag(i,c,l){const f=k(n,i);if(!(s!=null&&s(f?ge:we,i,c))){if(f){const[p,m]=n[i],N=Me(m,c),$=(w,g)=>{r.push(l),g&&r.push(g),p.push(Ne(m,w||""))};return N===void 0?$:$(N)}k(o,i)||(o[i]=[]),o[i].push(c===void 0?!0:c),r.push(l)}},onArgument(i,c,l){s!=null&&s(ve,t[c[0]])||(a.push(...i),l?(a[I]=i,t.splice(c[0])):r.push(c))}}),We(t,r),{flags:Ae(e,n),unknownFlags:o,_:a}},L=e=>Array.isArray(e)?e:[e],Le=e=>e.replace(/-([a-z])/g,(t,s)=>s.toUpperCase()),Fe=(e,t)=>t.length!==e.length?!1:e.every((s,r)=>s===t[r]),J=(e,t)=>t.length>e.length?!1:Fe(e.slice(0,t.length),t);class U extends Error{constructor(t){super(`Command "${t}" exists.`),this.commandName=t}}class z extends Error{constructor(t){super(`No such command: ${t}`),this.commandName=t}}class K extends Error{constructor(){super("No command given.")}}class Z extends Error{constructor(t,s){super(`Command name ${t} conflicts with ${s}. Maybe caused by alias.`),this.n1=t,this.n2=s}}class Q extends Error{constructor(){super("Name not set.")}}class X extends Error{constructor(){super("Description not set.")}}class Y extends Error{constructor(){super("Version not set.")}}class ee extends Error{constructor(t){super(`Bad name format: ${t}`),this.commandName=t}}const te=typeof Deno!="undefined",Pe=typeof process!="undefined"&&!te,Be=process.versions.electron&&!process.defaultApp;function se(e,t,s){if(s.alias){const r=L(s.alias);for(const n of r){if(n in t)throw new Z(t[n].name,s.name);e.set(typeof n=="symbol"?n:n.split(" "),{...s,__isAlias:!0})}}}function re(e){const t=new Map;e[u]&&(t.set(u,e[u]),se(t,e,e[u]));for(const s of Object.values(e))se(t,e,s),t.set(s.name.split(" "),s);return t}function ne(e,t){if(t===u)return e[u];const s=L(t),r=re(e);let n,o;return r.forEach((a,i)=>{if(i===u){n=r.get(u),o=u;return}J(s,i)&&(!o||o===u||i.length>o.length)&&(n=a,o=i)}),n}function oe(e,t,s=1/0){const r=t===""?[]:Array.isArray(t)?t:t.split(" ");return Object.values(e).filter(n=>{const o=n.name.split(" ");return J(o,r)&&o.length-r.length<=s})}const De=e=>oe(e,"",1);function ie(e){const t=[];for(const s of e){if(s.startsWith("-"))break;t.push(s)}return t}const F=()=>Pe?process.argv.slice(Be?1:2):te?Deno.args:[];function ae(e){const t={pre:[],normal:[],post:[]};for(const r of e){const n=typeof r=="object"?r:{fn:r},{enforce:o,fn:a}=n;o==="post"||o==="pre"?t[o].push(a):t.normal.push(a)}const s=[...t.pre,...t.normal,...t.post];return r=>{return n(0);function n(o){const a=s[o];return a(r(),n.bind(null,o+1))}}}const ce=e=>typeof e=="string"&&(e.startsWith(" ")||e.endsWith(" ")),Te=(e,t)=>t?`[${e}]`:`<${e}>`,je="<Root>",le=e=>Array.isArray(e)?e.join(" "):typeof e=="string"?e:je,{stringify:C}=JSON;function P(e){const t=[];let s,r;for(const n of e){if(r)throw new Error(`Invalid parameter: Spread parameter ${C(r)} must be last`);const o=n[0],a=n[n.length-1];let i;if(o==="<"&&a===">"&&(i=!0,s))throw new Error(`Invalid parameter: Required parameter ${C(n)} cannot come after optional parameter ${C(s)}`);if(o==="["&&a==="]"&&(i=!1,s=n),i===void 0)throw new Error(`Invalid parameter: ${C(n)}. Must be wrapped in <> (required parameter) or [] (optional parameter)`);let c=n.slice(1,-1);const l=c.slice(-3)==="...";l&&(r=n,c=c.slice(0,-3)),t.push({name:c,required:i,spread:l})}return t}function B(e,t,s){for(let r=0;r<t.length;r+=1){const{name:n,required:o,spread:a}=t[r],i=Le(n);if(i in e)return new Error(`Invalid parameter: ${C(n)} is used more than once.`);const c=a?s.slice(r):s[r];if(a&&(r=t.length),o&&(!c||a&&c.length===0))return new Error(`Error: Missing required parameter ${C(n)}`);e[i]=c}}var D=(e,t,s)=>{if(!t.has(e))throw TypeError("Cannot "+s)},h=(e,t,s)=>(D(e,t,"read from private field"),s?s.call(e):t.get(e)),d=(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)},v=(e,t,s,r)=>(D(e,t,"write to private field"),r?r.call(e,s):t.set(e,s),s),qe=(e,t,s)=>(D(e,t,"access private method"),s),E,y,_,A,b,O,M,W,T,he,j,fe,q,ue;const u=Symbol("Root"),pe=class{constructor(e,t,s){d(this,T),d(this,j),d(this,q),d(this,E,""),d(this,y,""),d(this,_,""),d(this,A,[]),d(this,b,{}),d(this,O,new me),d(this,M,new Set),d(this,W,void 0),v(this,E,e||h(this,E)),v(this,y,t||h(this,y)),v(this,_,s||h(this,_))}get _name(){return h(this,E)}get _description(){return h(this,y)}get _version(){return h(this,_)}get _inspectors(){return h(this,A)}get _commands(){return h(this,b)}static create(e,t,s){return new pe(e,t,s)}name(e){return v(this,E,e),this}description(e){return v(this,y,e),this}version(e){return v(this,_,e),this}command(e,t,s={}){const n=(f=>!(typeof f=="string"||f===u))(e),o=n?e.name:e;if(ce(o))throw new ee(o);const{handler:a=void 0,...i}=n?e:{name:o,description:t,...s},c=[i.name],l=i.alias?L(i.alias):[];i.alias&&c.push(...l);for(const f of c)if(h(this,M).has(f))throw new U(le(f));return h(this,b)[o]=i,h(this,M).add(i.name),l.forEach(f=>h(this,M).add(f)),n&&a&&this.on(e.name,a),this}on(e,t){return h(this,O).on(e,t),this}use(e){return e.setup(this)}inspector(e){return h(this,A).push(e),this}parse(e=F()){const{argv:t,run:s}=Array.isArray(e)?{argv:e,run:!0}:{argv:F(),...e};return v(this,W,t),qe(this,q,ue).call(this),s&&this.runMatchedCommand(),this}runMatchedCommand(){const e=h(this,W);if(!e)throw new Error("cli.parse() must be called.");const t=ie(e),s=t.join(" "),r=()=>ne(h(this,b),t),n=[],o=()=>{n.length=0;const l=r(),f=!!l,p=Re((l==null?void 0:l.flags)||{},[...e]),{_:m,flags:N,unknownFlags:$}=p;let w=!f||l.name===u?m:m.slice(l.name.split(" ").length),g=(l==null?void 0:l.parameters)||[];const R=g.indexOf("--"),G=g.slice(R+1)||[],x=Object.create(null);if(R>-1&&G.length>0){g=g.slice(0,R);const V=m["--"];w=w.slice(0,-V.length||void 0),n.push(B(x,P(g),w)),n.push(B(x,P(G),V))}else n.push(B(x,P(g),w));const de={...N,...$};return{name:l==null?void 0:l.name,called:t.length===0&&(l==null?void 0:l.name)?u:s,resolved:f,hasRootOrAlias:h(this,T,he),hasRoot:h(this,j,fe),raw:{...p,parameters:w,mergedFlags:de},parameters:x,flags:N,unknownFlags:$,cli:this}},a={enforce:"post",fn:()=>{const l=r(),f=o(),p=n.filter(Boolean);if(p.length>0)throw p[0];if(!l)throw s?new z(s):new K;h(this,O).emit(l.name,f)}},i=[...h(this,A),a];return ae(i)(o),this}};let Ge=pe;E=new WeakMap,y=new WeakMap,_=new WeakMap,A=new WeakMap,b=new WeakMap,O=new WeakMap,M=new WeakMap,W=new WeakMap,T=new WeakSet,he=function(){return h(this,M).has(u)},j=new WeakSet,fe=function(){return Object.prototype.hasOwnProperty.call(this._commands,u)},q=new WeakSet,ue=function(){if(!h(this,E))throw new Q;if(!h(this,y))throw new X;if(!h(this,_))throw new Y};const Ve=e=>e,He=(e,t,s)=>s,Je=(e,t)=>t,Ue=(e,t)=>({...e,handler:t});export{Ge as Clerc,U as CommandExistsError,Z as CommandNameConflictError,X as DescriptionNotSetError,ee as InvalidCommandNameError,Q as NameNotSetError,K as NoCommandGivenError,z as NoSuchCommandError,u as Root,Y as VersionNotSetError,ae as compose,Ue as defineCommand,He as defineHandler,Je as defineInspector,Ve as definePlugin,le as formatCommandName,ce as isInvalidName,F as resolveArgv,ne as resolveCommand,re as resolveFlattenCommands,ie as resolveParametersBeforeFlag,De as resolveRootCommands,oe as resolveSubcommandsByParent,Te as withBrackets};
1
+ class me{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(t,...s)),this.listenerMap[t].forEach(r=>r(...s))),this}off(t,s){var r,n;return t==="**"?(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):(n=this.listenerMap[t])==null||n.clear(),this)}}const ge="known-flag",we="unknown-flag",ve="argument",{stringify:S}=JSON,Ee=/\B([A-Z])/g,_e=e=>e.replace(Ee,"-$1").toLowerCase(),{hasOwnProperty:ye}=Object.prototype,k=(e,t)=>ye.call(e,t),Ce=e=>Array.isArray(e),H=e=>typeof e=="function"?[e,!1]:Ce(e)?[e[0],!0]:H(e.type),Me=(e,t)=>e===Boolean?t!=="false":t,Ne=(e,t)=>typeof t=="boolean"?t:e===Number&&t===""?Number.NaN:e(t),$e=/[\s.:=]/,Se=e=>{const t=`Flag name ${S(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($e);if(s)throw new Error(`${t} cannot contain ${S(s==null?void 0:s[0])}`)},ke=e=>{const t={},s=(r,n)=>{if(k(t,r))throw new Error(`Duplicate flags named ${S(r)}`);t[r]=n};for(const r in e){if(!k(e,r))continue;Se(r);const n=e[r],o=[[],...H(n),n];s(r,o);const a=_e(r);if(r!==a&&s(a,o),"alias"in n&&typeof n.alias=="string"){const{alias:i}=n,c=`Flag alias ${S(i)} for flag ${S(r)}`;if(i.length===0)throw new Error(`${c} cannot be empty`);if(i.length>1)throw new Error(`${c} must be a single character`);s(i,o)}}return t},Ae=(e,t)=>{const s={};for(const r in e){if(!k(e,r))continue;const[n,,o,a]=t[r];if(n.length===0&&"default"in a){let{default:i}=a;typeof i=="function"&&(i=i()),s[r]=i}else s[r]=o?n:n.pop()}return s},I="--",be=/[.:=]/,xe=/^-{1,2}\w/,Ie=e=>{if(!xe.test(e))return;const t=!e.startsWith(I);let s=e.slice(t?1:2),r;const n=s.match(be);if(n){const{index:o}=n;r=s.slice(o+1),s=s.slice(0,o)}return[s,r,t]},Oe=(e,{onFlag:t,onArgument:s})=>{let r;const n=(o,a)=>{if(typeof r!="function")return!0;r(o,a),r=void 0};for(let o=0;o<e.length;o+=1){const a=e[o];if(a===I){n();const c=e.slice(o+1);s==null||s(c,[o],!0);break}const i=Ie(a);if(i){if(n(),!t)continue;const[c,l,f]=i;if(f)for(let p=0;p<c.length;p+=1){n();const m=p===c.length-1;r=t(c[p],m?l:void 0,[o,p+1,m])}else r=t(c,l,[o])}else n(a,[o])&&(s==null||s([a],[o]))}n()},We=(e,t)=>{for(const[s,r,n]of t.reverse()){if(r){const o=e[s];let a=o.slice(0,r);if(n||(a+=o.slice(r+1)),a!=="-"){e[s]=a;continue}}e.splice(s,1)}},Re=(e,t=process.argv.slice(2),{ignore:s}={})=>{const r=[],n=ke(e),o={},a=[];return a[I]=[],Oe(t,{onFlag(i,c,l){const f=k(n,i);if(!(s!=null&&s(f?ge:we,i,c))){if(f){const[p,m]=n[i],N=Me(m,c),$=(w,g)=>{r.push(l),g&&r.push(g),p.push(Ne(m,w||""))};return N===void 0?$:$(N)}k(o,i)||(o[i]=[]),o[i].push(c===void 0?!0:c),r.push(l)}},onArgument(i,c,l){s!=null&&s(ve,t[c[0]])||(a.push(...i),l?(a[I]=i,t.splice(c[0])):r.push(c))}}),We(t,r),{flags:Ae(e,n),unknownFlags:o,_:a}},L=e=>Array.isArray(e)?e:[e],Le=e=>e.replace(/[-_ ](\w)/g,(t,s)=>s.toUpperCase()),Fe=(e,t)=>t.length!==e.length?!1:e.every((s,r)=>s===t[r]),J=(e,t)=>t.length>e.length?!1:Fe(e.slice(0,t.length),t);class U extends Error{constructor(t){super(`Command "${t}" exists.`),this.commandName=t}}class K extends Error{constructor(t){super(`No such command: ${t}`),this.commandName=t}}class Z extends Error{constructor(){super("No command given.")}}class z extends Error{constructor(t,s){super(`Command name ${t} conflicts with ${s}. Maybe caused by alias.`),this.n1=t,this.n2=s}}class Q extends Error{constructor(){super("Name not set.")}}class X extends Error{constructor(){super("Description not set.")}}class Y extends Error{constructor(){super("Version not set.")}}class ee extends Error{constructor(t){super(`Bad name format: ${t}`),this.commandName=t}}const te=typeof Deno!="undefined",Pe=typeof process!="undefined"&&!te,Be=process.versions.electron&&!process.defaultApp;function se(e,t,s){if(s.alias){const r=L(s.alias);for(const n of r){if(n in t)throw new z(t[n].name,s.name);e.set(typeof n=="symbol"?n:n.split(" "),{...s,__isAlias:!0})}}}function re(e){const t=new Map;e[u]&&(t.set(u,e[u]),se(t,e,e[u]));for(const s of Object.values(e))se(t,e,s),t.set(s.name.split(" "),s);return t}function ne(e,t){if(t===u)return e[u];const s=L(t),r=re(e);let n,o;return r.forEach((a,i)=>{if(i===u){n=r.get(u),o=u;return}J(s,i)&&(!o||o===u||i.length>o.length)&&(n=a,o=i)}),n}function oe(e,t,s=1/0){const r=t===""?[]:Array.isArray(t)?t:t.split(" ");return Object.values(e).filter(n=>{const o=n.name.split(" ");return J(o,r)&&o.length-r.length<=s})}const De=e=>oe(e,"",1);function ie(e){const t=[];for(const s of e){if(s.startsWith("-"))break;t.push(s)}return t}const F=()=>Pe?process.argv.slice(Be?1:2):te?Deno.args:[];function ae(e){const t={pre:[],normal:[],post:[]};for(const r of e){const n=typeof r=="object"?r:{fn:r},{enforce:o,fn:a}=n;o==="post"||o==="pre"?t[o].push(a):t.normal.push(a)}const s=[...t.pre,...t.normal,...t.post];return r=>{return n(0);function n(o){const a=s[o];return a(r(),n.bind(null,o+1))}}}const ce=e=>typeof e=="string"&&(e.startsWith(" ")||e.endsWith(" ")),Te=(e,t)=>t?`[${e}]`:`<${e}>`,je="<Root>",le=e=>Array.isArray(e)?e.join(" "):typeof e=="string"?e:je,{stringify:C}=JSON;function P(e){const t=[];let s,r;for(const n of e){if(r)throw new Error(`Invalid parameter: Spread parameter ${C(r)} must be last`);const o=n[0],a=n[n.length-1];let i;if(o==="<"&&a===">"&&(i=!0,s))throw new Error(`Invalid parameter: Required parameter ${C(n)} cannot come after optional parameter ${C(s)}`);if(o==="["&&a==="]"&&(i=!1,s=n),i===void 0)throw new Error(`Invalid parameter: ${C(n)}. Must be wrapped in <> (required parameter) or [] (optional parameter)`);let c=n.slice(1,-1);const l=c.slice(-3)==="...";l&&(r=n,c=c.slice(0,-3)),t.push({name:c,required:i,spread:l})}return t}function B(e,t,s){for(let r=0;r<t.length;r+=1){const{name:n,required:o,spread:a}=t[r],i=Le(n);if(i in e)return new Error(`Invalid parameter: ${C(n)} is used more than once.`);const c=a?s.slice(r):s[r];if(a&&(r=t.length),o&&(!c||a&&c.length===0))return new Error(`Error: Missing required parameter ${C(n)}`);e[i]=c}}var D=(e,t,s)=>{if(!t.has(e))throw TypeError("Cannot "+s)},h=(e,t,s)=>(D(e,t,"read from private field"),s?s.call(e):t.get(e)),d=(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)},v=(e,t,s,r)=>(D(e,t,"write to private field"),r?r.call(e,s):t.set(e,s),s),qe=(e,t,s)=>(D(e,t,"access private method"),s),E,_,y,A,b,O,M,W,T,he,j,fe,q,ue;const u=Symbol("Root"),pe=class{constructor(e,t,s){d(this,T),d(this,j),d(this,q),d(this,E,""),d(this,_,""),d(this,y,""),d(this,A,[]),d(this,b,{}),d(this,O,new me),d(this,M,new Set),d(this,W,void 0),v(this,E,e||h(this,E)),v(this,_,t||h(this,_)),v(this,y,s||h(this,y))}get _name(){return h(this,E)}get _description(){return h(this,_)}get _version(){return h(this,y)}get _inspectors(){return h(this,A)}get _commands(){return h(this,b)}static create(e,t,s){return new pe(e,t,s)}name(e){return v(this,E,e),this}description(e){return v(this,_,e),this}version(e){return v(this,y,e),this}command(e,t,s={}){const n=(f=>!(typeof f=="string"||f===u))(e),o=n?e.name:e;if(ce(o))throw new ee(o);const{handler:a=void 0,...i}=n?e:{name:o,description:t,...s},c=[i.name],l=i.alias?L(i.alias):[];i.alias&&c.push(...l);for(const f of c)if(h(this,M).has(f))throw new U(le(f));return h(this,b)[o]=i,h(this,M).add(i.name),l.forEach(f=>h(this,M).add(f)),n&&a&&this.on(e.name,a),this}on(e,t){return h(this,O).on(e,t),this}use(e){return e.setup(this)}inspector(e){return h(this,A).push(e),this}parse(e=F()){const{argv:t,run:s}=Array.isArray(e)?{argv:e,run:!0}:{argv:F(),...e};return v(this,W,t),qe(this,q,ue).call(this),s&&this.runMatchedCommand(),this}runMatchedCommand(){const e=h(this,W);if(!e)throw new Error("cli.parse() must be called.");const t=ie(e),s=t.join(" "),r=()=>ne(h(this,b),t),n=[],o=()=>{n.length=0;const l=r(),f=!!l,p=Re((l==null?void 0:l.flags)||{},[...e]),{_:m,flags:N,unknownFlags:$}=p;let w=!f||l.name===u?m:m.slice(l.name.split(" ").length),g=(l==null?void 0:l.parameters)||[];const R=g.indexOf("--"),G=g.slice(R+1)||[],x=Object.create(null);if(R>-1&&G.length>0){g=g.slice(0,R);const V=m["--"];w=w.slice(0,-V.length||void 0),n.push(B(x,P(g),w)),n.push(B(x,P(G),V))}else n.push(B(x,P(g),w));const de={...N,...$};return{name:l==null?void 0:l.name,called:t.length===0&&(l==null?void 0:l.name)?u:s,resolved:f,hasRootOrAlias:h(this,T,he),hasRoot:h(this,j,fe),raw:{...p,parameters:w,mergedFlags:de},parameters:x,flags:N,unknownFlags:$,cli:this}},a={enforce:"post",fn:()=>{const l=r(),f=o(),p=n.filter(Boolean);if(p.length>0)throw p[0];if(!l)throw s?new K(s):new Z;h(this,O).emit(l.name,f)}},i=[...h(this,A),a];return ae(i)(o),this}};let Ge=pe;E=new WeakMap,_=new WeakMap,y=new WeakMap,A=new WeakMap,b=new WeakMap,O=new WeakMap,M=new WeakMap,W=new WeakMap,T=new WeakSet,he=function(){return h(this,M).has(u)},j=new WeakSet,fe=function(){return Object.prototype.hasOwnProperty.call(this._commands,u)},q=new WeakSet,ue=function(){if(!h(this,E))throw new Q;if(!h(this,_))throw new X;if(!h(this,y))throw new Y};const Ve=e=>e,He=(e,t,s)=>s,Je=(e,t)=>t,Ue=(e,t)=>({...e,handler:t});export{Ge as Clerc,U as CommandExistsError,z as CommandNameConflictError,X as DescriptionNotSetError,ee as InvalidCommandNameError,Q as NameNotSetError,Z as NoCommandGivenError,K as NoSuchCommandError,u as Root,Y as VersionNotSetError,ae as compose,Ue as defineCommand,He as defineHandler,Je as defineInspector,Ve as definePlugin,le as formatCommandName,ce as isInvalidName,F as resolveArgv,ne as resolveCommand,re as resolveFlattenCommands,ie as resolveParametersBeforeFlag,De as resolveRootCommands,oe as resolveSubcommandsByParent,Te as withBrackets};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clerc/core",
3
- "version": "0.27.1",
3
+ "version": "0.28.1",
4
4
  "author": "Ray <nn_201312@163.com> (https://github.com/so1ve)",
5
5
  "description": "Clerc core",
6
6
  "keywords": [
@@ -51,7 +51,7 @@
51
51
  "lite-emit": "^1.4.0",
52
52
  "type-fest": "^3.5.3",
53
53
  "type-flag": "^3.0.0",
54
- "@clerc/utils": "0.27.1"
54
+ "@clerc/utils": "0.28.1"
55
55
  },
56
56
  "scripts": {
57
57
  "build": "puild --minify",