@visulima/cerebro 3.0.3 → 3.0.4

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.
Files changed (33) hide show
  1. package/CHANGELOG.md +2 -0
  2. package/dist/commands/completion-command.d.ts +3 -3
  3. package/dist/commands/completion-command.js +1 -1
  4. package/dist/commands/help-command.d.ts +1 -1
  5. package/dist/commands/help-command.js +1 -1
  6. package/dist/commands/readme-command.d.ts +3 -3
  7. package/dist/commands/readme-command.js +17 -17
  8. package/dist/commands/version-command.d.ts +1 -1
  9. package/dist/index.d.ts +403 -433
  10. package/dist/index.js +1 -1
  11. package/dist/logger/create-pail-logger.d.ts +533 -555
  12. package/dist/packem_chunks/has-new-version.js +1 -1
  13. package/dist/packem_shared/Cerebro-CHB2i5uf.js +4 -0
  14. package/dist/packem_shared/{VisulimaError-C90oeIMu.js → VisulimaError-BheWBD7j.js} +2 -2
  15. package/dist/packem_shared/{cerebro-error-BjBcYVRO.js → cerebro-error-DnA3fjrR.js} +1 -1
  16. package/dist/packem_shared/command.d-B_G9vIYJ.d.ts +633 -0
  17. package/dist/packem_shared/{index-DvVGK4kr.js → index-BAKCiGjO.js} +10 -10
  18. package/dist/packem_shared/index.d-CnnVYgSZ.d.ts +117 -0
  19. package/dist/packem_shared/renderError-DjesnVYT-pHitCa3e.js +25 -0
  20. package/dist/packem_shared/split-by-case-DpyL5bdy.js +1 -0
  21. package/dist/plugins/error-handler-plugin.d.ts +18 -7
  22. package/dist/plugins/error-handler-plugin.js +1 -1
  23. package/dist/plugins/runtime-version-check-plugin.d.ts +5 -5
  24. package/dist/plugins/update-notifier/update-notifier-plugin.d.ts +11 -10
  25. package/dist/util/general/compile-cache.d.ts +37 -37
  26. package/dist/util/general/heap-tuning.d.ts +11 -11
  27. package/dist/util/general/heap-tuning.js +1 -1
  28. package/package.json +1 -1
  29. package/dist/packem_shared/Cerebro-Czc4t-75.js +0 -4
  30. package/dist/packem_shared/command.d-DbhtfXF4.d.ts +0 -639
  31. package/dist/packem_shared/index.d-BL4NtVR3.d.ts +0 -127
  32. package/dist/packem_shared/renderError-B3ePOoBG-BmZlyMcr.js +0 -25
  33. package/dist/packem_shared/split-by-case-Dbpgd7rf.js +0 -1
@@ -0,0 +1,117 @@
1
+ type ColorizeMethod = (value: string) => string;
2
+ type CodeFrameOptions = {
3
+ color?: {
4
+ gutter?: ColorizeMethod;
5
+ marker?: ColorizeMethod;
6
+ message?: ColorizeMethod;
7
+ };
8
+ linesAbove?: number;
9
+ linesBelow?: number;
10
+ message?: string;
11
+ prefix?: string;
12
+ showGutter?: boolean;
13
+ showLineNumbers?: boolean;
14
+ tabWidth?: number | false;
15
+ };
16
+ interface ErrorProperties {
17
+ cause?: unknown;
18
+ hint?: ErrorHint;
19
+ location?: ErrorLocation;
20
+ message?: string;
21
+ name: string;
22
+ stack?: string;
23
+ title?: string;
24
+ }
25
+ interface ErrorLocation {
26
+ column?: number;
27
+ file?: string;
28
+ line?: number;
29
+ }
30
+ /**
31
+ * A message that explains to the user how they can fix the error.
32
+ * @example
33
+ * ```ts
34
+ * const error = new VisulimaError({
35
+ * hint: "Try running `npm install` to install missing dependencies.",
36
+ * location: {
37
+ * file: "src/index.ts",
38
+ * line: 1,
39
+ * column: 1,
40
+ * },
41
+ * message: "Cannot find module 'react'",
42
+ * name: "ModuleNotFoundError",
43
+ * });
44
+ * ```
45
+ *
46
+ * For more complex hints, you can pass an array of strings or a single string in markdown format.
47
+ */
48
+ type ErrorHint = string[] | string;
49
+ declare class VisulimaError extends Error {
50
+ loc: ErrorLocation | undefined;
51
+ title: string | undefined;
52
+ /**
53
+ * A message that explains to the user how they can fix the error.
54
+ */
55
+ hint: ErrorHint | undefined;
56
+ type: string;
57
+ constructor({ cause, hint, location, message, name, stack, title }: ErrorProperties);
58
+ setLocation(location: ErrorLocation): void;
59
+ setName(name: string): void;
60
+ setMessage(message: string): void;
61
+ setHint(hint: ErrorHint): void;
62
+ }
63
+ /**
64
+ * The compiled position of a stack frame handed to a {@link SourceMapResolver}.
65
+ */
66
+ interface SourceMapLocation {
67
+ column?: number;
68
+ file: string;
69
+ line: number;
70
+ }
71
+ /**
72
+ * The resolved original position returned by a {@link SourceMapResolver}. Any omitted field falls
73
+ * back to the compiled value. `source`, when provided, is used directly as the code-frame content
74
+ * (e.g. from an inlined `sourcesContent`) instead of reading the resolved file from disk.
75
+ */
76
+ interface ResolvedSourceLocation {
77
+ column?: number;
78
+ file?: string;
79
+ line?: number;
80
+ source?: string;
81
+ }
82
+ /**
83
+ * Pluggable hook that maps a compiled `*.js:line:col` position back to its original source position
84
+ * (e.g. TS/JSX). Return `undefined` (or throw) to leave the frame untouched. Synchronous so it can
85
+ * be used by the synchronous `renderError`; resolve/inline your maps ahead of time.
86
+ */
87
+ type SourceMapResolver = (location: SourceMapLocation) => ResolvedSourceLocation | undefined;
88
+ type Options$1 = {
89
+ /**
90
+ * Read source files for code frames from anywhere on disk, including absolute paths outside
91
+ * `cwd`. Defaults to `false`, in which case only files resolving inside `cwd` are read — this
92
+ * prevents local file disclosure when rendering errors whose stack came from untrusted input
93
+ * (e.g. a deserialized error). Enable only for trusted, locally-thrown errors.
94
+ * @default false
95
+ */
96
+ allowAllFilePaths: boolean;
97
+ color: CodeFrameOptions["color"] & {
98
+ fileLine: ColorizeMethod;
99
+ hint: ColorizeMethod;
100
+ method: ColorizeMethod;
101
+ title: ColorizeMethod;
102
+ };
103
+ cwd: string;
104
+ displayShortPath: boolean;
105
+ filterStacktrace: ((line: string) => boolean) | undefined;
106
+ framesMaxLimit: number;
107
+ hideErrorCauseCodeView: boolean;
108
+ hideErrorCodeView: boolean;
109
+ hideErrorErrorsCodeView: boolean;
110
+ hideErrorTitle: boolean;
111
+ hideMessage: boolean;
112
+ indentation: number | "\t";
113
+ prefix: string;
114
+ /** Optional source-map resolver to map compiled frame positions back to original source. */
115
+ sourceMap?: SourceMapResolver;
116
+ } & Omit<CodeFrameOptions, "message | prefix">;
117
+ export { Options$1 as O, VisulimaError as V };
@@ -0,0 +1,25 @@
1
+ import{createRequire as K}from"node:module";let Q;const X=e=>(Q??=K(import.meta.url))(e),b=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,Z=e=>{if(typeof b<"u"&&b.versions&&b.versions.node){const[r,t]=b.versions.node.split(".").map(Number);if(r>22||r===22&&t>=3||r===20&&t>=16)return b.getBuiltinModule(e)}return X(e)},{createRequire:W}=Z("node:module"),ee=globalThis.process??Object.create(null),_={versions:{}},A=new Proxy(ee,{get(e,r){if(r in e)return e[r];if(r in _)return _[r]}}),re=e=>e.replaceAll(/\r\n|\r(?!\n)|\n/gu,`
2
+ `),te=(e,r,t,n)=>{const s={column:0,line:-1,...e.start},i={...s,...e.end},o=s.line,d=s.column,l=i.line,c=i.column;let a=Math.max(o-(t+1),0),m=Math.min(r.length,l+n);o===-1&&(a=0),l===-1&&(m=r.length);const p=l-o,f={};if(p)for(let u=0;u<=p;u++){const h=u+o;if(!d)f[h]=!0;else if(u===0){const $=r[h-1]?.length;f[h]=[d,($??0)-d+1]}else if(u===p)f[h]=[0,c];else{const $=r[h-u]?.length;f[h]=[0,$]}}else d===c?f[o]=d?[d,0]:!0:f[o]=[d,(c??0)-(d??0)];return{end:m,markerLines:f,start:a}},ne=A.platform==="win32"&&!A.env?.WT_SESSION?">":"❯",ie=(e,r,t)=>{const n={linesAbove:2,linesBelow:3,prefix:"",showGutter:!0,tabWidth:4,...t,color:{gutter:u=>u,marker:u=>u,message:u=>u,...t?.color}},s=typeof r.start.column=="number";let i=(e.includes("\r")?re(e):e).split(`
3
+ `);typeof n.tabWidth=="number"&&e.includes(" ")&&(i=i.map(u=>u.replaceAll(" "," ".repeat(n.tabWidth))));const{end:o,markerLines:d,start:l}=te(r,i,n.linesAbove,n.linesBelow),c=String(o).length,{gutter:a,marker:m,message:p}=n.color;let f=i.slice(l,o).map((u,h)=>{const $=l+1+h,E=d[$],Y=String($).padStart(c),z=!d[$+1],N=` ${Y}${n.showGutter?" |":""}`;if(E){let k="";if(Array.isArray(E)){const D=u.replaceAll(/[^\t]/g," ").slice(0,Math.max(E[0]-1,0)),H=E[1]||1;k=[`
4
+ `,n.prefix+a(N.replaceAll(/\d/g," "))," ",D,m("^").repeat(H)].join(""),z&&n.message&&(k+=` ${p(n.message)}`)}return[n.prefix+m(ne),a(N),u.length>0?` ${u}`:"",k].join("")}return`${n.prefix} ${a(N)}${u.length>0?` ${u}`:""}`}).join(`
5
+ `);return n.message&&!s&&(f=`${n.prefix+" ".repeat(c+1)+n.message}
6
+ ${f}`),f},S=new Map([["Error",Error],["EvalError",EvalError],["RangeError",RangeError],["ReferenceError",ReferenceError],["SyntaxError",SyntaxError],["TypeError",TypeError],["URIError",URIError]]);typeof AggregateError<"u"&&S.set("AggregateError",AggregateError);const He=(e,r)=>{let t;try{t=new e}catch(s){throw new Error(`The error constructor "${e.name}" is not compatible`,{cause:s})}const n=r??t.name;if(S.has(n))throw new Error(`The error constructor "${n}" is already known.`);S.set(n,e)},oe=e=>S.get(e),Ke=e=>e!==null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.message=="string"&&(oe(e.name)!==void 0||e.name==="Error");let se;const le=e=>(se??=W(import.meta.url))(e),x=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,ae=e=>{if(typeof x<"u"&&x.versions&&x.versions.node){const[r,t]=x.versions.node.split(".").map(Number);if(r>22||r===22&&t>=3||r===20&&t>=16)return x.getBuiltinModule(e)}return le(e)},{inspect:ce}=ae("node:util"),Qe=e=>{const r=new Set,t=[];let n=e;for(;n;){if(r.has(n)){console.error(`Circular reference detected in error causes: ${ce(e)}`);break}if(t.push(n),r.add(n),typeof n!="object"||!("cause"in n))break;n=n.cause}return t},de=()=>A.env?.DEBUG==="true",v=(e,...r)=>{if(de()){const t=r.map(n=>typeof n=="function"?n():n);console.debug(`error:parse-stacktrace: ${e}`,...t)}},g="<unknown>",ue=/^(?:node:internal\/|node:|internal\/)/,fe=e=>e!==void 0&&ue.test(e),me=/^.*?\s*at\s(?:(.+?\)(?:\s\[.+\])?|\(?.*?)\s?\((?:address\sat\s)?)?(?:async\s)?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,pe=/\((\S+)\),\s(<[^>]+>)?:(\d+)?:(\d+)?\)?/,he=/(.*?):(\d+):(\d+)(?:\s<-\s.+:\d+:\d+)?/,$e=/eval\sat\s(<anonymous>)\s\((.*)\)?:(\d+)?:(\d+)\),\s*<anonymous>?:(\d+)?:(\d+)/,ve=/^\s*in\s(?:([^\\/]+(?:\s\[as\s\S+\])?)\s\(?)?\(at?\s?(.*?):(\d+)(?::(\d+))?\)?\s*$/,ge=/in\s(.*)\s\(at\s(.+)\)\sat/,ye=/^(?:.*@)?(.*):(\d+):(\d+)$/,we=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. \/=]+)(?::(\d+))?(?::(\d+))?\s*$/i,be=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,xe=/(\S[^\s[]*\[.*\]|.*?)@(.*):(\d+):(\d+)/,j=/\(error: ([^)]*)\)/,Ee=/at\s/,Se=/^(\S+):(\d+):(\d+)$|^(\S+):(\d+)$/,Ne=/Error: |AggregateError:/,C=/^Anonymous function$/,ke=/^\s*in\s.*/,Ae=/^.*?\s*at\s.*/,Me=/^.*?\s*@.*|\[native code\]/,R=(e,r)=>{const t=e.includes("safari-extension"),n=e.includes("safari-web-extension");return t||n?[e.includes("@")?e.split("@")[0]:g,t?`safari-extension:${r}`:`safari-web-extension:${r}`]:[e,r]},B=(e,r)=>{const t=he.exec(r);t&&(e.file=t[1],e.line=+t[2],e.column=+t[3])},Te=e=>{const r=ge.exec(e);if(r){v(`parse nested node error stack line: "${e}"`,()=>`found: ${JSON.stringify(r)}`);const n=r[2].split(":");return{column:n[2]?+n[2]:void 0,file:n[0],line:n[1]?+n[1]:void 0,methodName:r[1]??g,raw:e,type:void 0}}const t=ve.exec(e);if(t){v(`parse node error stack line: "${e}"`,()=>`found: ${JSON.stringify(t)}`);const n={column:t[4]?+t[4]:void 0,file:t[2]?t[2].replace(Ee,""):void 0,line:t[3]?+t[3]:void 0,methodName:t[1]??g,raw:e,type:e.startsWith("internal")?"internal":void 0};return B(n,`${t[2]}:${t[3]}:${t[4]}`),n}},_e=e=>{const r=me.exec(e);if(r){v(`parse chrome error stack line: "${e}"`,()=>`found: ${JSON.stringify(r)}`);const t=r[2]?.startsWith("native"),n=r[2]?.startsWith("eval")||r[1]?.startsWith("eval");let s,i;if(n){const c=pe.exec(e);if(c){const a=Se.exec(c[1]);a?(r[2]=a[4]??a[1],r[3]=a[5]??a[2],r[4]=a[3]):c[2]&&(r[2]=c[1]),c[2]&&(s={column:c[4]?+c[4]:void 0,file:c[2],line:c[3]?+c[3]:void 0,methodName:"eval",raw:e,type:"eval"})}else{const a=$e.exec(e);a&&(i={column:a[4]?+a[4]:void 0,file:a[2],line:a[3]?+a[3]:void 0},s={column:a[6]?+a[6]:void 0,file:a[1],line:a[5]?+a[5]:void 0,methodName:"eval",raw:a[0],type:"eval"})}}const[o,d]=R(r[1]?r[1].replace(C,"<anonymous>"):g,r[2]),l={column:r[4]?+r[4]:void 0,evalOrigin:s,file:d,line:r[3]?+r[3]:void 0,methodName:o,raw:e,type:n?"eval":t?"native":fe(d)?"internal":void 0};return i?(l.column=i.column,l.file=i.file,l.line=i.line):B(l,`${d}:${r[3]}:${r[4]}`),l}},je=(e,r)=>{const t=we.exec(e);if(t){v(`parse gecko error stack line: "${e}"`,()=>`found: ${JSON.stringify(t)}`);const n=t[3]?.includes(" > eval"),s=n&&t[3]&&be.exec(t[3]);let i;n&&s&&(t[3]=s[1],i={column:t[5]?+t[5]:void 0,file:t[3],line:t[4]?+t[4]:void 0,methodName:"eval",raw:e,type:"eval"},t[4]=s[2]);const[o,d]=R(t[1]?t[1].replace(C,"<anonymous>"):g,t[3]);let l;(r?.type==="safari"||!n&&r?.type==="firefox")&&r.column?l=r.column:!n&&t[5]&&(l=+t[5]);let c;return(r?.type==="safari"||!n&&r?.type==="firefox")&&r.line?c=r.line:t[4]&&(c=+t[4]),{column:l,evalOrigin:i,file:d,line:c,methodName:o,raw:e,type:n?"eval":d.includes("[native code]")?"native":void 0}}},Le=(e,r)=>{const t=xe.exec(e);if(!(t&&t[2].includes(" > eval"))&&t)return v(`parse firefox error stack line: "${e}"`,()=>`found: ${JSON.stringify(t)}`),{column:t[4]?+t[4]:r?.column??void 0,file:t[2],line:t[3]?+t[3]:r?.line??void 0,methodName:t[1]||g,raw:e,type:void 0}},We=e=>{const r=ye.exec(e);if(r)return v(`parse react android native error stack line: "${e}"`,()=>`found: ${JSON.stringify(r)}`),{column:r[3]?+r[3]:void 0,file:r[1],line:r[2]?+r[2]:void 0,methodName:g,raw:e,type:void 0}},Ce=/(?:^|[(@\s])(?:node:internal\/|node:|internal\/)/,Re=/node_modules[/\\]/,Xe={internals:e=>!Ce.test(e),nodeModules:e=>!Re.test(e)},Ze=(...e)=>r=>e.every(t=>t(r)),O=(e,{filter:r,frameLimit:t=50}={})=>{const n=e;let s=(typeof n.stacktrace=="string"?n.stacktrace:e.stack??"").split(`
7
+ `).map(i=>(j.test(i)?i.replace(j,"$1"):i).trim()).filter(i=>!Ne.test(i)&&i!=="eval code");return r&&(s=s.filter(i=>r(i))),s=s.slice(0,t),s.reduce((i,o,d)=>{if(!o||o.length>1024)return i;let l;if(ke.test(o))l=Te(o);else if(Ae.test(o))l=_e(o);else if(Me.test(o)){let c;if(d===0){const a=e,m=a.columnNumber,p=a.lineNumber,f=a.line,u=a.column;m||p?c={column:m,line:p,type:"firefox"}:(f||u)&&(c={column:u,line:f,type:"safari"})}l=Le(o,c)??je(o,c)}else l=We(o);return l?i.push(l):v(`parse error stack line: "${o}"`,"not parser found"),i},[])};let Be;const Oe=e=>(Be??=W(import.meta.url))(e),w=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,M=e=>{if(typeof w<"u"&&w.versions&&w.versions.node){const[r,t]=w.versions.node.split(".").map(Number);if(r>22||r===22&&t>=3||r===20&&t>=16)return w.getBuiltinModule(e)}return Oe(e)},{existsSync:Ie,readFileSync:Pe}=M("node:fs"),{relative:Ve,resolve:L,sep:Ge}=M("node:path"),{cwd:qe}=w,{fileURLToPath:Je}=M("node:url"),y=(e,r,t)=>t===0?e:r===" "?e+" ".repeat(t):e+" ".repeat(r*t),I=e=>e.replaceAll("\\","/"),Fe=(e,r)=>{const t=e.replace("async file:","file:");return I(Ve(r,t.startsWith("file:")?Je(t):t))},Ue=(e,r,t)=>{if(r)return t.title(e.message);const n=e.message?`: ${e.message}`:"";return t.title(e.name+n)},P=(e,{color:r,hideErrorTitle:t,indentation:n,prefix:s},i)=>`${y(s,n,i)}${Ue(e,t,r)}
8
+ `,V=(e,{color:r,indentation:t,prefix:n},s)=>{if(e.hint===void 0)return;const i=y(n,t,s);let o="";if(Array.isArray(e.hint))for(const d of e.hint)o+=`${i+d}
9
+ `;else o+=i+e.hint;return r.hint(o)},G=(e,r)=>{if(!r||e.file===void 0||e.line===void 0)return{trace:e};try{const t=r({column:e.column,file:e.file,line:e.line});return t?{source:t.source,trace:{...e,column:t.column??e.column,file:t.file??e.file,line:t.line??e.line}}:{trace:e}}catch{return{trace:e}}},T=(e,r,t=0)=>{const{color:n,cwd:s,displayShortPath:i,indentation:o,prefix:d}=r,{trace:l}=G(e,r.sourceMap),c=i?Fe(l.file,s):I(l.file),{fileLine:a,method:m}=n;return`${y(d,o,t)}at ${l.methodName?`${m(l.methodName)} `:""}${a(c)}:${a(l.line?.toString()??"")}`},Ye=(e,r)=>{if(r.allowAllFilePaths)return!0;const t=L(r.cwd),n=L(t,e);return n===t||n.startsWith(t+Ge)},q=(e,r,t)=>{const{color:n,indentation:s,linesAbove:i,linesBelow:o,prefix:d,showGutter:l,showLineNumbers:c,tabWidth:a}=r,{source:m,trace:p}=G(e,r.sourceMap);if(p.file===void 0)return;let f;if(m===void 0){const u=p.file.replace("file://","");if(!Ye(u,r)||!Ie(u))return;f=Pe(u,"utf8")}else f=m;return ie(f,{start:{column:p.column,line:p.line}},{color:n,linesAbove:i,linesBelow:o,prefix:y(d,s,t),showGutter:l,showLineNumbers:c,tabWidth:a})},J=(e,r,t)=>{if(e.errors.length===0)return;let n=`${y(r.prefix,r.indentation,t)}Errors:
10
+
11
+ `,s=!0;for(const i of e.errors)s?s=!1:n+=`
12
+
13
+ `,n+=U(i,{...r,framesMaxLimit:1,hideErrorCodeView:r.hideErrorErrorsCodeView},t+1);return`
14
+ ${n}`},F=(e,r,t,n=new Set)=>{n.add(e);let s=`${y(r.prefix,r.indentation,t)}Caused by:
15
+
16
+ `;const i=e.cause;s+=P(i,r,t);const o=O(i).shift(),d=V(i,r,t);if(d&&(s+=`${d}
17
+ `),o&&(s+=T(o,r,t),!r.hideErrorCauseCodeView)){const l=q(o,r,t);l!==void 0&&(s+=`
18
+ ${l}`)}if(i instanceof AggregateError){const l=J(i,r,t);l!==void 0&&(s+=`
19
+ ${l}`)}return i.cause&&(s+=n.has(i)?`
20
+ ${y(r.prefix,r.indentation,t+1)}Caused by: [Circular]`:`
21
+ ${F(i,r,t+1,n)}`),`
22
+ ${s}`},ze=(e,r)=>(e.length>0?`
23
+ `:"")+e.map(t=>T(t,r)).join(`
24
+ `),U=(e,r,t)=>{const n={allowAllFilePaths:!1,cwd:qe(),displayShortPath:!1,filterStacktrace:void 0,framesMaxLimit:Number.POSITIVE_INFINITY,hideErrorCauseCodeView:!1,hideErrorCodeView:!1,hideErrorErrorsCodeView:!1,hideErrorTitle:!1,hideMessage:!1,indentation:4,linesAbove:2,linesBelow:3,prefix:"",showGutter:!0,showLineNumbers:!0,tabWidth:4,...r,color:{fileLine:o=>o,gutter:o=>o,hint:o=>o,marker:o=>o,message:o=>o,method:o=>o,title:o=>o,...r.color}},s=O(e,{filter:r.filterStacktrace,frameLimit:n.framesMaxLimit}),i=s.shift();return[r.hideMessage?void 0:P(e,n,t),V(e,n,t),i?T(i,n,t):void 0,i&&!n.hideErrorCodeView?q(i,n,t):void 0,e instanceof AggregateError?J(e,n,t):void 0,e.cause===void 0?void 0:F(e,n,t),s.length>0?ze(s,n):void 0].filter(Boolean).join(`
25
+ `)},er=(e,r={})=>{if(r.framesMaxLimit!==void 0&&r.framesMaxLimit<=0)throw new RangeError("The 'framesMaxLimit' option must be a positive number");return U(e,r,0)};export{Xe as R,ne as S,ie as W,Ze as X,O as Y,er as _,Ke as g,Qe as l,oe as n,He as s};
@@ -0,0 +1 @@
1
+ import{createRequire as J}from"node:module";let Q;const X=e=>(Q??=J(import.meta.url))(e),W=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,Y=e=>{if(typeof W<"u"&&W.versions&&W.versions.node){const[t,a]=W.versions.node.split(".").map(Number);if(t>22||t===22&&a>=3||t===20&&a>=16)return W.getBuiltinModule(e)}return X(e)},{createRequire:ee}=Y("node:module"),H=String.raw,T=H`\p{Emoji}(?:\p{EMod}|[\u{E0020}-\u{E007E}]+\u{E007F}|\uFE0F?\u20E3?)`,te=()=>new RegExp(H`\p{RI}{2}|(?![#*\d](?!\uFE0F?\u20E3))${T}(?:\u200D${T})*`,"gu");Object.freeze(new Map([[0,0],[1,22],[2,22],[3,23],[4,24],[7,27],[8,28],[9,29],[30,39],[31,39],[32,39],[33,39],[34,39],[35,39],[36,39],[37,39],[40,49],[41,49],[42,49],[43,49],[44,49],[45,49],[46,49],[47,49],[90,39]]));const ve=/^[ \t]*(?:\r\n|\r|\n)/,Te=/(?:\r\n|\r|\n)[ \t]*$/,Fe=/^(?:[\r\n]|$)/,ze=/(?:\r\n|\r|\n)([ \t]*)(?:[^ \t\r\n]|$)/,Me=/^[ \t]*[\r\n][ \t\r\n]*$/,Ie=/\r\n|\n|\r/g,qe=/[\u001B\u009B](?:[[()#;?]{0,10}(?:\d{1,4}(?:;\d{0,4})*)?[0-9A-ORZcf-nqry=><]|\]8;;[^\u0007\u001B]{0,100}(?:\u0007|\u001B\\))/g,Oe=/[\u0000-\u0008\n-\u001F\u007F-\u009F]{1,1000}/y,m=te(),se=/[-_./\s]+/g,$=/(\u001B\[[0-9;]*[a-z])/i,F=new RegExp("\\p{Script=Arabic}","u"),ne=new RegExp("\\p{Script=Bengali}","u"),b=new RegExp("\\p{Script=Cyrillic}","u"),re=new RegExp("\\p{Script=Devanagari}","u"),ie=new RegExp("\\p{Script=Ethiopic}","u"),j=new RegExp("\\p{Script=Greek}","u"),z=new RegExp("\\p{Script=Greek}+|\\p{Script=Latin}+|[^\\p{Script=Greek}\\p{Script=Latin}]+","gu"),le=new RegExp("\\p{Script=Gujarati}","u"),ce=new RegExp("\\p{Script=Gurmukhi}","u"),M=new RegExp("\\p{Script=Hangul}","u"),I=new RegExp("\\p{Script=Hebrew}","u"),oe=new RegExp("\\p{Script=Hiragana}","u"),q=new RegExp("\\p{Script=Han}","u"),ae=new RegExp("\\p{Script=Kannada}","u"),pe=new RegExp("\\p{Script=Katakana}","u"),ue=new RegExp("\\p{Script=Khmer}","u"),he=new RegExp("\\p{Script=Lao}","u"),R=new RegExp("\\p{Script=Latin}","u"),fe=new RegExp("\\p{Script=Malayalam}","u"),ge=new RegExp("\\p{Script=Myanmar}","u"),de=new RegExp("\\p{Script=Oriya}","u"),xe=new RegExp("\\p{Script=Sinhala}","u"),we=new RegExp("\\p{Script=Tamil}","u"),Ee=new RegExp("\\p{Script=Telugu}","u"),ke=new RegExp("\\p{Script=Thai}","u"),Re=new RegExp("\\p{Script=Tibetan}","u"),O=/[\u02BB\u02BC\u0027]/u,Se=e=>e.replace(m,"");class Ce{capacity;cache;constructor(t){this.capacity=t,this.cache=new Map}get(t){if(!this.cache.has(t))return;const a=this.cache.get(t);return this.cache.delete(t),this.cache.set(t,a),a}has(t){return this.cache.has(t)}set(t,a){if(this.cache.has(t))this.cache.delete(t);else if(this.cache.size>=this.capacity){const f=this.cache.keys().next().value;f!==void 0&&this.cache.delete(f)}this.cache.set(t,a)}delete(t){this.cache.delete(t)}clear(){this.cache.clear()}size(){return this.cache.size}}let Le;const Ue=e=>(Le??=ee(import.meta.url))(e),y=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,me=e=>{if(typeof y<"u"&&y.versions&&y.versions.node){const[t,a]=y.versions.node.split(".").map(Number);if(t>22||t===22&&a>=3||t===20&&a>=16)return y.getBuiltinModule(e)}return Ue(e)},{stripVTControlCharacters:be}=me("node:util"),A=new Ce(1e3),We=/[.*+?^${}()|[\]\\]/g,ye=e=>{const t=e.join("");if(A.has(t)){const d=A.get(t);return d.lastIndex=0,d}const a=e.map(d=>d.replaceAll(We,String.raw`\$&`)).join("|"),f=new RegExp(a,"g");return A.set(t,f),f},$e=e=>{const t=[];let a=0,f;for(m.lastIndex=0;(f=m.exec(e))!==null;)f.index>a&&t.push(e.slice(a,f.index)),t.push(f[0]),a=m.lastIndex;return a<e.length&&t.push(e.slice(a)),t.filter(Boolean)},je=/[ČŠŽĐ]/i,P=new Uint8Array(128),D=new Uint8Array(128),K=new Uint8Array(128);for(let e=0;e<128;e++)P[e]=e>=65&&e<=90?1:0,D[e]=e>=97&&e<=122?1:0,K[e]=e>=48&&e<=57?1:0;const B=e=>P[e],G=e=>D[e],_=e=>K[e],U=(e,t,a,f,d)=>{if(e.length===0)return[];let h=!1;const k=Object.values(t);for(const i of k)if(i(e[0])){h=!0;break}if(!h&&!a)return[e];const g=[...e],w=[];let n=g[0],l="other";const p=Object.entries(t);for(const i of p){const[r,o]=i;if(o(g[0])){l=r;break}}let s=a&&f?g[0]===g[0].toLocaleUpperCase(f):!1;for(let i=1;i<g.length;i++){const r=g[i];let o="other";for(const x of p){const[E,S]=x;if(S(r)){o=E;break}}const u=a&&f?r===r.toLocaleUpperCase(f):!1;let c=!1;d?c=d(l,o,s,u,r,i,g):(l!==o&&l!=="other"&&o!=="other"&&(c=!0),a&&o!=="other"&&!s&&u&&(c=!0)),c?(w.push(n),n=r):n+=r,l=o,a&&(s=u)}return n&&n.length>0&&w.push(n),w.length>0?w:[e]},Ae=(e,t,a,f)=>{if(a.size===0)return t;for(const d of a)if(e.startsWith(d,t))return f.push(d),t+d.length;return t},N=(e,t=new Set)=>{if(e.length===0)return[];if(e.toUpperCase()===e)return[e];let a=0;const f=[],d=e.length;for(let h=1;h<d;h++){const k=Ae(e,a,t,f);if(k!==a){a=k,h=a-1;continue}const g=e.codePointAt(h-1),w=e.codePointAt(h),n=g&&g<128&&B(g),l=w&&w<128&&B(w),p=g&&g<128&&G(g),s=g&&g<128&&_(g),i=w&&w<128&&_(w);if(p&&l){f.push(e.slice(a,h)),a=h;continue}if(s&&!i||!s&&i){f.push(e.slice(a,h)),a=h;continue}if(i&&!s){let r=!1,o=!1;if(h+1<d){const u=e.codePointAt(h+1);r=u&&u<128&&B(u),o=u&&u<128&&_(u)}if(!o&&r){f.push(e.slice(a,h),e.slice(h,h+1)),a=h+1;continue}}if(h+1<d){const r=e.codePointAt(h+1),o=r&&r<128&&G(r);if(n&&l&&o){const u=e.slice(a,h+1);t.has(u)||(f.push(e.slice(a,h)),a=h)}}}return a<d&&f.push(e.slice(a)),f.filter(h=>h!=="")},V=(e,t,a)=>{if(e.length===0)return[];const f=e===e.toLocaleUpperCase(t);if(t.startsWith("de")){if(!f&&e.replaceAll("ß","SS")===e.toLocaleUpperCase(t))return[e];const n=[...e],l=n.length,p=[];let s=n[0],i=n[0]===n[0].toLocaleUpperCase(t),r=i,o=i?0:-1;for(let u=1;u<l;u++){const c=n[u],x=c===c.toLocaleUpperCase(t);if(x===i)s+=c;else if(x)s&&s.length>0&&(p.push(s),s=c),r=!0,o=u;else{if(r&&u-o>1){const E=n[u-1],S=s.slice(0,-1);S&&S.length>0&&p.push(S),s=E+c}else s+=c;r=!1,o=-1}i=x}return s&&s.length>0&&p.push(s),p}if(t.startsWith("uk")||t.startsWith("ru")||t.startsWith("bg")||t.startsWith("sr")||t.startsWith("mk")||t.startsWith("be")){if(!b.test(e)&&!R.test(e))return[e];const n=[...e],l=n.length,p=[];let s=n[0];const i=n[0];let r;b.test(i)?r=1:R.test(i)?r=2:r=0;let o=i===i.toLocaleUpperCase(t);for(let c=1;c<l;c++){const x=n[c];let E;b.test(x)?E=1:R.test(x)?E=2:E=0;const S=x===x.toLocaleUpperCase(t);r!==E&&(r===1||r===2)&&(E===1||E===2)||E===r&&!o&&S?(p.push(s),s=x):s+=x,r=E,o=S}s&&s.length>0&&p.push(s);const u=[];for(let c=0;c<p.length;c++)c<p.length-1&&p[c].length===1&&R.test(p[c])&&b.test(p[c+1][0])?(u.push(p[c]+p[c+1]),c+=1):u.push(p[c]);return u}if(t.startsWith("el")){if(!j.test(e)&&!R.test(e))return[e];const n=[];z.lastIndex=0;let l;for(;(l=z.exec(e))!==null;)n.push(l[0]);n.length===0&&n.push(e);const p=[];if(n.length===1){const s=n[0];if(!s||!j.test(s[0])||s.length===1)return[s??e]}for(const s of n){if(!s)continue;if(!j.test(s[0])||s.length===1){p.push(s);continue}const i=s.length;let r=s[0],o=s[0]===s[0].toLocaleUpperCase(t);for(let u=1;u<i;u++){const c=s[u],x=c===c.toLocaleUpperCase(t);!o&&x?(p.push(r),r=c):r+=c,o=x}r&&p.push(r)}return p}if(t.startsWith("ja")||t.startsWith("ko")){const n=t.startsWith("ja"),l=n?{hiragana:s=>oe.test(s),kanji:s=>q.test(s),katakana:s=>pe.test(s),latin:s=>R.test(s)}:{hangul:s=>M.test(s),latin:s=>R.test(s)},p=new Set(["が","で","と","に","の","は","へ","も","や","を"]);if(n){const s=U(e,l,!1,t,(r,o)=>r==="hiragana"&&o==="katakana"||r==="katakana"&&o==="hiragana"||r==="hiragana"&&o==="latin"||r==="katakana"&&o==="latin"||r==="kanji"&&o==="latin"||r==="latin"&&(o==="hiragana"||o==="katakana"||o==="kanji")),i=[];for(const r of s){const o=r;o.length===1&&p.has(o)&&i.length>0?i[i.length-1]=i.at(-1)+o:i.push(o)}return i.length>0?i:[e]}return U(e,l,!1,t,(s,i)=>s==="hangul"&&i==="latin"||s==="latin"&&i==="hangul")}if(t.startsWith("sl")){const n=[...e],l=n.length,p=[];let s=n[0],i=n[0]===n[0].toLocaleUpperCase(t);for(let r=1;r<l;r++){const o=n[r],u=o===o.toLocaleUpperCase(t),c=je.test(o),x=r<l-1&&n[r+1]===n[r+1].toLocaleUpperCase(t);!i&&u||c&&x?(p.push(s),s=o,c&&x&&(p.push(s),s="")):s+=o,i=u}return s&&s.length>0&&p.push(s),p}if(t.startsWith("zh"))return U(e,{han:n=>q.test(n),latin:n=>R.test(n)},!1,t);if(["ar","fa","he","ur"].includes(t.split("-")[0])){const n=l=>I.test(l)||F.test(l);return U(e,{latin:l=>R.test(l),rtl:l=>n(l)},!1,t)}if(["am","bn","gu","hi","km","kn","lo","ml","mr","ne","or","pa","si","ta","te","th"].includes(t.split("-")[0])){const n=l=>re.test(l)||ne.test(l)||le.test(l)||ce.test(l)||ae.test(l)||we.test(l)||Ee.test(l)||fe.test(l)||xe.test(l)||ke.test(l)||he.test(l)||Re.test(l)||ge.test(l)||ie.test(l)||ue.test(l)||de.test(l);return U(e,{indic:l=>n(l),latin:l=>R.test(l)},!1,t)}if(["be","bg","ru","sr","uk"].includes(t))return U(e,{cyrillic:n=>b.test(n),latin:n=>R.test(n)},!0,t);if(["ar","fa","he"].includes(t))return U(e,{latin:n=>R.test(n),rtl:n=>I.test(n)||F.test(n)},!1,t);if(t.startsWith("ko"))return U(e,{hangul:n=>M.test(n),latin:n=>R.test(n)},!1,t);if(t.startsWith("uz")){if(!b.test(e)&&!R.test(e))return[e];const n=[...e],l=n.length,p=[];let s=n[0],i=n[0]===n[0].toLocaleUpperCase(t);for(let r=1;r<l;r++){const o=n[r],u=o===o.toLocaleUpperCase(t);if(O.test(o)||O.test(n[r-1])){s+=o;continue}!i&&u?(p.push(s),s=o):s+=o,i=u}return s&&s.length>0&&p.push(s),p}const d=[...e],h=d.length,k=[];let g=d[0],w=d[0]===d[0].toLocaleUpperCase(t);for(const n of a)if(e.startsWith(n)){k.push(n),g=d[n.length],w=g===g.toLocaleUpperCase(t);break}for(let n=1;n<h;n++){const l=d[n],p=l===l.toLocaleUpperCase(t);let s=0;for(const i of a)if(e.startsWith(i,n)){k.push(g,i),s=i.length,g="";const r=i.at(-1);r&&(w=r===r.toLocaleUpperCase(t));break}if(s>0){n+=s-1;continue}!w&&p?(k.push(g),g=l):g+=l,w=p}return g&&k.push(g),k},Be=(e,t,a)=>{const f=[],d=$.test(e)?e.split($).filter(Boolean):[e];for(const h of d){const k=h;if($.test(k))f.push(k);else{m.lastIndex=0;const g=m.test(k)?$e(k).filter(Boolean):[k];for(const w of g)if(m.lastIndex=0,m.test(w))f.push(w);else if(t){const n=t.toLowerCase().split("-")[0];f.push(...V(w,n,a))}else f.push(...N(w,a))}}return f},Ge=(e,t={})=>{if(!e||typeof e!="string")return[];const{handleAnsi:a=!1,handleEmoji:f=!1,knownAcronyms:d=[],locale:h,normalize:k=!1,separators:g,stripAnsi:w=!1,stripEmoji:n=!1}=t,l=new Set([...d].toSorted((c,x)=>x.length-c.length));let p=e;w&&(p=be(p)),n&&(p=Se(p));let s;Array.isArray(g)?s=ye(g):g instanceof RegExp?s=g:s=se;const i=[];let r=p;const o=s.flags.includes("g")?s:new RegExp(s.source,`${s.flags}g`);for(;r.length>0;){const c=o.exec(r);if(!c){r===".."?i.push(".."):r==="."?i.push("."):r.length>0&&i.push(r);break}const x=c.index,E=c[0],S=E.length,v=r.slice(0,x),Z=r.slice(x+S);if(E.startsWith("../"))i.push(".."),r=r.slice(x+3);else if(E.startsWith("./"))i.push("."),r=r.slice(x+2);else if(x===0&&E==="..")i.push(".."),r=r.slice(2);else if(x===0&&E===".")i.push("."),r=r.slice(1);else{v.length>0&&i.push(v);let C=0;for(;(C=E.indexOf("../",C))!==-1;)i.push(".."),C+=3;for(C=0;(C=E.indexOf("./",C))!==-1;)(C===0||E[C-1]!==".")&&i.push("."),C+=2;let L=Z;for(;L.startsWith("../");)i.push(".."),L=L.slice(3);for(;L.startsWith("./");)i.push("."),L=L.slice(2);if(L===".."){i.push("..");break}else if(L==="."){i.push(".");break}else r=L}o.lastIndex=0}if(i.length===0){const c=p.split(s).filter(Boolean);i.push(...c)}let u=[];for(const c of i)a||f?u.push(...Be(c,h,l)):h?u.push(...V(c,h,l)):u.push(...N(c,l));return k&&(u=u.map(c=>l.has(c)?c:h&&c===c.toLocaleUpperCase(h)?c[0]+c.slice(1).toLocaleLowerCase(h):c.toUpperCase()===c&&!l.has(c)?c.slice(0,1)+c.slice(1).toLowerCase():c)),u};export{Fe as B,ze as F,Te as R,qe as d,$ as k,Me as l,Ie as m,m as n,Ge as w,ve as x,Oe as y};
@@ -1,7 +1,18 @@
1
- import { O as Options$1 } from "../packem_shared/index.d-BL4NtVR3.js";
2
- import { P as Plugin } from "../packem_shared/command.d-DbhtfXF4.js";
1
+ import { O as Options$1 } from "../packem_shared/index.d-CnnVYgSZ.js";
2
+ import { P as Plugin } from "../packem_shared/command.d-B_G9vIYJ.js";
3
3
  import '@visulima/tabular';
4
4
  type ErrorHandlerOptions = {
5
+ /**
6
+ * Predicate marking an error as an *expected* user-facing failure — a
7
+ * bad flag, a missing file, a non-zero task exit. Matching errors are
8
+ * logged as their message alone, with no stack trace, because the
9
+ * frames point into CLI internals the user cannot act on.
10
+ *
11
+ * Ignored when `detailed` is true, so a debug flag still surfaces the
12
+ * full stack for every error. `formatter`, when set, wins over this.
13
+ * @default undefined (every error renders with its stack)
14
+ */
15
+ concise?: (error: Error) => boolean;
5
16
  /** Show detailed error information including stack traces and code frames (default: false) */
6
17
  detailed?: boolean;
7
18
  /** Exit process after handling error (default: true) */
@@ -14,10 +25,10 @@ type ErrorHandlerOptions = {
14
25
  renderOptions?: Partial<Options$1>;
15
26
  };
16
27
  /**
17
- * Create an error handler plugin for enhanced error reporting.
18
- * Uses \@visulima/error for beautiful error formatting with code frames and stack traces.
19
- * @param options Error handler configuration options
20
- * @returns Plugin instance
21
- */
28
+ * Create an error handler plugin for enhanced error reporting.
29
+ * Uses \@visulima/error for beautiful error formatting with code frames and stack traces.
30
+ * @param options Error handler configuration options
31
+ * @returns Plugin instance
32
+ */
22
33
  declare const errorHandlerPlugin: (options?: ErrorHandlerOptions) => Plugin;
23
34
  export { ErrorHandlerOptions, errorHandlerPlugin };
@@ -1 +1 @@
1
- import{U as g}from"../packem_shared/renderError-B3ePOoBG-BmZlyMcr.js";import{e as m}from"../packem_shared/runtime-process-Dmz0vCJy.js";const E=(i={})=>({description:"Enhanced error handling and reporting with beautiful code frames",name:"error-handler",onError:(e,n)=>{const{logger:r,runtime:s}=n,{detailed:t=!1,exitOnError:l=!0,formatter:o,logErrors:a=!0,renderOptions:d={}}=i;if(a)if(o)r.error(o(e));else if(t){const f=s.getCwd(),c=g(e,{cwd:f,hideErrorCodeView:!1,hideErrorTitle:!1,hideMessage:!1,linesAbove:2,linesBelow:3,...d});r.error(c)}else r.error(e);l&&m(1)},version:"1.0.0"});export{E as errorHandlerPlugin};
1
+ import{_ as m}from"../packem_shared/renderError-DjesnVYT-pHitCa3e.js";import{e as h}from"../packem_shared/runtime-process-Dmz0vCJy.js";const u=(s={})=>({description:"Enhanced error handling and reporting with beautiful code frames",name:"error-handler",onError:(e,n)=>{const{logger:r,runtime:t}=n,{concise:l,detailed:o=!1,exitOnError:a=!0,formatter:i,logErrors:d=!0,renderOptions:f={}}=s;if(d)if(i)r.error(i(e));else if(!o&&l?.(e))r.error(e.message);else if(o){const c=t.getCwd(),g=m(e,{cwd:c,hideErrorCodeView:!1,hideErrorTitle:!1,hideMessage:!1,linesAbove:2,linesBelow:3,...f});r.error(g)}else r.error(e);a&&h(1)},version:"1.0.0"});export{u as errorHandlerPlugin};
@@ -1,4 +1,4 @@
1
- import { P as Plugin } from "../packem_shared/command.d-DbhtfXF4.js";
1
+ import { P as Plugin } from "../packem_shared/command.d-B_G9vIYJ.js";
2
2
  import '@visulima/tabular';
3
3
  type RuntimeType = "bun" | "deno" | "node";
4
4
  type RuntimeVersionRequirement = {
@@ -17,9 +17,9 @@ type RuntimeVersionCheckOptions = {
17
17
  };
18
18
  };
19
19
  /**
20
- * Create a runtime version check plugin that supports Node.js, Bun, and Deno.
21
- * @param options Configuration for runtime version requirements
22
- * @returns Plugin instance that validates runtime version on initialization
23
- */
20
+ * Create a runtime version check plugin that supports Node.js, Bun, and Deno.
21
+ * @param options Configuration for runtime version requirements
22
+ * @returns Plugin instance that validates runtime version on initialization
23
+ */
24
24
  declare const runtimeVersionCheckPlugin: (options?: RuntimeVersionCheckOptions) => Plugin;
25
25
  export { RuntimeType, RuntimeVersionCheckOptions, RuntimeVersionRequirement, runtimeVersionCheckPlugin };
@@ -1,29 +1,30 @@
1
- import { a as CerebroFs, P as Plugin } from "../../packem_shared/command.d-DbhtfXF4.js";
1
+ import { a as CerebroFs, P as Plugin } from "../../packem_shared/command.d-B_G9vIYJ.js";
2
2
  import '@visulima/tabular';
3
3
  type UpdateNotifierOptions = {
4
4
  alwaysRun?: boolean;
5
5
  debug?: boolean;
6
6
  distTag?: string;
7
7
  /**
8
- * Injectable filesystem adapter used to read/write the last-update-check
9
- * cache. The plugin passes `toolbox.fs` so MCP / sandboxed runtimes can swap
10
- * the filesystem; defaults to a `node:fs/promises` wrapper when omitted.
11
- */
8
+ * Injectable filesystem adapter used to read/write the last-update-check
9
+ * cache. The plugin passes `toolbox.fs` so MCP / sandboxed runtimes can swap
10
+ * the filesystem; defaults to a `node:fs/promises` wrapper when omitted.
11
+ */
12
12
  fs?: Pick<CerebroFs, "access" | "mkdir" | "readFile" | "writeFile">;
13
13
  pkg: {
14
14
  name: string;
15
15
  version: string;
16
16
  };
17
17
  registryUrl?: string;
18
- shouldNotifyInNpmScript?: boolean; /** Timeout (ms) for the registry request. Defaults to 5000. */
18
+ shouldNotifyInNpmScript?: boolean;
19
+ /** Timeout (ms) for the registry request. Defaults to 5000. */
19
20
  timeout?: number;
20
21
  updateCheckInterval?: number;
21
22
  };
22
23
  type UpdateNotifierPluginOptions = Partial<Omit<UpdateNotifierOptions, "debug" | "fs" | "pkg">>;
23
24
  /**
24
- * Create an update notifier plugin that checks for package updates.
25
- * @param options Update notifier configuration options.
26
- * @returns Plugin instance.
27
- */
25
+ * Create an update notifier plugin that checks for package updates.
26
+ * @param options Update notifier configuration options.
27
+ * @returns Plugin instance.
28
+ */
28
29
  declare const updateNotifierPlugin: (options?: UpdateNotifierPluginOptions) => Plugin;
29
30
  export { type UpdateNotifierPluginOptions, updateNotifierPlugin };
@@ -1,41 +1,41 @@
1
1
  /**
2
- * V8 compile cache helper for faster CLI startup.
3
- *
4
- * Enables the V8 compile cache so that subsequent runs of the CLI skip
5
- * re-parsing and re-compiling JavaScript/TypeScript source files. This
6
- * can reduce startup time by 30-70% for large CLI tools.
7
- *
8
- * ## When to use
9
- *
10
- * Call `enableCompileCache()` early in your CLI entry point, after heap
11
- * tuning but before importing heavy modules:
12
- *
13
- * ```typescript
14
- * // bin.ts
15
- * import { applyHeapTuning } from "@visulima/cerebro/heap-tuning";
16
- * import { enableCompileCache } from "@visulima/cerebro/compile-cache";
17
- *
18
- * applyHeapTuning();
19
- * enableCompileCache();
20
- *
21
- * import { createCerebro } from "@visulima/cerebro";
22
- * // ... rest of your CLI setup
23
- * ```
24
- *
25
- * ## How it works
26
- *
27
- * 1. Tries `module.enableCompileCache()` (Node.js 22.8+ native API) which
28
- * stores compiled bytecode alongside source files for instant reuse.
29
- * 2. If that's unavailable, falls back to the `v8-compile-cache` npm package
30
- * which achieves a similar effect on older Node.js versions.
31
- * 3. If neither is available, silently does nothing — startup is just slower.
32
- * @module
33
- */
2
+ * V8 compile cache helper for faster CLI startup.
3
+ *
4
+ * Enables the V8 compile cache so that subsequent runs of the CLI skip
5
+ * re-parsing and re-compiling JavaScript/TypeScript source files. This
6
+ * can reduce startup time by 30-70% for large CLI tools.
7
+ *
8
+ * ## When to use
9
+ *
10
+ * Call `enableCompileCache()` early in your CLI entry point, after heap
11
+ * tuning but before importing heavy modules:
12
+ *
13
+ * ```typescript
14
+ * // bin.ts
15
+ * import { applyHeapTuning } from "@visulima/cerebro/heap-tuning";
16
+ * import { enableCompileCache } from "@visulima/cerebro/compile-cache";
17
+ *
18
+ * applyHeapTuning();
19
+ * enableCompileCache();
20
+ *
21
+ * import { createCerebro } from "@visulima/cerebro";
22
+ * // ... rest of your CLI setup
23
+ * ```
24
+ *
25
+ * ## How it works
26
+ *
27
+ * 1. Tries `module.enableCompileCache()` (Node.js 22.8+ native API) which
28
+ * stores compiled bytecode alongside source files for instant reuse.
29
+ * 2. If that's unavailable, falls back to the `v8-compile-cache` npm package
30
+ * which achieves a similar effect on older Node.js versions.
31
+ * 3. If neither is available, silently does nothing — startup is just slower.
32
+ * @module
33
+ */
34
34
  /**
35
- * Enable V8 compile cache for faster subsequent CLI startups.
36
- *
37
- * Safe to call unconditionally — silently no-ops if the runtime doesn't
38
- * support compile caching or the fallback package isn't installed.
39
- */
35
+ * Enable V8 compile cache for faster subsequent CLI startups.
36
+ *
37
+ * Safe to call unconditionally — silently no-ops if the runtime doesn't
38
+ * support compile caching or the fallback package isn't installed.
39
+ */
40
40
  declare const enableCompileCache: () => void;
41
41
  export { enableCompileCache as default };
@@ -1,18 +1,18 @@
1
1
  interface HeapTuningOptions {
2
2
  /**
3
- * Fraction of total system memory to allocate as `--max-old-space-size`.
4
- * Must be between 0 and 1. Default: `0.75` (75%).
5
- */
3
+ * Fraction of total system memory to allocate as `--max-old-space-size`.
4
+ * Must be between 0 and 1. Default: `0.75` (75%).
5
+ */
6
6
  maxOldSpacePercent?: number;
7
7
  }
8
8
  /**
9
- * Apply heap memory tuning to the current process.
10
- *
11
- * When tuning is needed, this function re-spawns the process with computed
12
- * V8 memory flags and **never returns** — the parent exits with the child's
13
- * exit code. When no tuning is needed (flags already set), it returns
14
- * immediately.
15
- * @param options Optional configuration for heap tuning.
16
- */
9
+ * Apply heap memory tuning to the current process.
10
+ *
11
+ * When tuning is needed, this function re-spawns the process with computed
12
+ * V8 memory flags and **never returns** — the parent exits with the child's
13
+ * exit code. When no tuning is needed (flags already set), it returns
14
+ * immediately.
15
+ * @param options Optional configuration for heap tuning.
16
+ */
17
17
  declare const applyHeapTuning: (options?: HeapTuningOptions) => void;
18
18
  export { type HeapTuningOptions, applyHeapTuning };
@@ -1 +1 @@
1
- import{createRequire as g}from"node:module";import{d as x,h as y,c as b,e as d,i as j}from"../../packem_shared/runtime-process-Dmz0vCJy.js";const h=g(import.meta.url),t=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,u=e=>{if(typeof t<"u"&&t.versions&&t.versions.node){const[o,s]=t.versions.node.split(".").map(Number);if(o>22||o===22&&s>=3||o===20&&s>=16)return t.getBuiltinModule(e)}return h(e)},{execFileSync:_}=u("node:child_process"),{totalmem:v}=u("node:os"),M=/--max-old-space-size=(\d+)/,z=/--max-semi-space-size=(\d+)/,E=e=>Math.floor(v()/1024/1024*e),P=e=>e<=512?4:e<=1024?8:e<=2048?16:e<=4096?32:e<=8192?64:Math.floor(Math.log2(e))*8,l=(e,o)=>{for(const s of o){const i=e.exec(s);if(i)return Number.parseInt(i[1],10)}},q=e=>{const o=e?.maxOldSpacePercent??.75,s=[...j()],i=[...x()],n=l(M,s),c=l(z,s);if(n!==void 0&&c!==void 0)return;const a=n??E(o),m=c??P(a),r=[];if(n===void 0&&r.push(`--max-old-space-size=${String(a)}`),c===void 0&&r.push(`--max-semi-space-size=${String(m)}`),r.length!==0)try{_(y(),[...r,...s,...i.slice(1)],{env:b(),stdio:"inherit"}),d(0)}catch(f){const p=f.status;d(typeof p=="number"?p:1)}};export{q as applyHeapTuning};
1
+ import{createRequire as g}from"node:module";import{d as y,h as b,c as j,e as d,i as M}from"../../packem_shared/runtime-process-Dmz0vCJy.js";let _;const h=e=>(_??=g(import.meta.url))(e),o=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,u=e=>{if(typeof o<"u"&&o.versions&&o.versions.node){const[t,s]=o.versions.node.split(".").map(Number);if(t>22||t===22&&s>=3||t===20&&s>=16)return o.getBuiltinModule(e)}return h(e)},{execFileSync:v}=u("node:child_process"),{totalmem:x}=u("node:os"),q=/--max-old-space-size=(\d+)/,z=/--max-semi-space-size=(\d+)/,E=e=>Math.floor(x()/1024/1024*e),P=e=>e<=512?4:e<=1024?8:e<=2048?16:e<=4096?32:e<=8192?64:Math.floor(Math.log2(e))*8,l=(e,t)=>{for(const s of t){const r=e.exec(s);if(r)return Number.parseInt(r[1],10)}},A=e=>{const t=e?.maxOldSpacePercent??.75,s=[...M()],r=[...y()],n=l(q,s),c=l(z,s);if(n!==void 0&&c!==void 0)return;const a=n??E(t),m=c??P(a),i=[];if(n===void 0&&i.push(`--max-old-space-size=${String(a)}`),c===void 0&&i.push(`--max-semi-space-size=${String(m)}`),i.length!==0)try{v(b(),[...i,...s,...r.slice(1)],{env:j(),stdio:"inherit"}),d(0)}catch(f){const p=f.status;d(typeof p=="number"?p:1)}};export{A as applyHeapTuning};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@visulima/cerebro",
3
- "version": "3.0.3",
3
+ "version": "3.0.4",
4
4
  "description": "A delightful toolkit for building cross-runtime CLIs for Node.js, Deno, and Bun.",
5
5
  "keywords": [
6
6
  "ansi",
@@ -1,4 +0,0 @@
1
- import{createRequire as Te}from"node:module";import{VERBOSITY_DEBUG as T,POSITIONALS_KEY as Q,VERBOSITY_NORMAL as te,VERBOSITY_QUIET as Ge,VERBOSITY_VERBOSE as He}from"./VERBOSITY_DEBUG-XPultrIA.js";import{t as w}from"./cerebro-error-BjBcYVRO.js";import{c as X,d as se,o as ce,e as F,a as Ye,b as Je,f as Ke,h as Ze,i as Qe}from"./runtime-process-Dmz0vCJy.js";import"./renderError-B3ePOoBG-BmZlyMcr.js";import{h as H}from"./VisulimaError-DTMgXonA-CzaryRgZ.js";import{distance as Xe}from"fastest-levenshtein";import{k as et,A as tt}from"./split-by-case-Dbpgd7rf.js";const je=Te(import.meta.url),W=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,Ue=t=>{if(typeof W<"u"&&W.versions&&W.versions.node){const[e,n]=W.versions.node.split(".").map(Number);if(e>22||e===22&&n>=3||e===20&&n>=16)return W.getBuiltinModule(t)}return je(t)},{writeFile:Be,stat:ze,rm:Re,readFile:le,readdir:Fe,mkdir:qe,access:We}=Ue("node:fs/promises"),J=[{alias:"v",description:"Turn on verbose output",group:"global",name:"verbose",type:Boolean},{description:"Turn on debugging output",group:"global",name:"debug",type:Boolean},{alias:"h",description:"Print out helpful usage information",group:"global",name:"help",type:Boolean},{alias:"q",description:"Silence output",group:"global",name:"quiet",type:Boolean},{alias:"V",description:"Print version info",group:"global",name:"version",type:Boolean},{description:"Turn off colored output",group:"global",name:"no-color",type:Boolean},{description:"Force colored output",group:"global",name:"color",type:Boolean}];let U=class extends w{commandName;constructor(e,n=[]){const o=`Command "${e}" not found${n.length>0?`. Did you mean: ${n.join(", ")}?`:""}`;super(o,"COMMAND_NOT_FOUND",{commandName:e,suggestions:n}),this.name="CommandNotFoundError",this.commandName=e,n.length>0&&(this.hint=`Try one of these commands: ${n.join(", ")}`)}},xe=class extends w{option1;option2;constructor(e,n){super(`Options "${e}" and "${n}" cannot be used together`,"CONFLICTING_OPTIONS",{option1:e,option2:n}),this.name="ConflictingOptionsError",this.option1=e,this.option2=n,this.hint=`Remove either --${e} or --${n}`}},nt=class extends w{unknownOptions;constructor(e,n){const o=e.join(", "),s=`Found unknown ${e.length===1?"option":"options"}: ${o}`;super(s,"UNKNOWN_OPTION",{suggestions:n,unknownOptions:e}),this.name="UnknownOptionError",this.unknownOptions=e,n&&n.length>0&&(this.hint=`Did you mean: ${n.join(", ")}?`)}},ot=class extends w{pluginName;constructor(e,n,o){super(`Plugin "${e}" error: ${n}`,"PLUGIN_ERROR",{originalError:o,pluginName:e}),this.name="PluginError",this.pluginName=e,o&&(this.cause=o)}},it=class{logger;plugins=new Map;initialized=!1;cachedDependencyOrder=void 0;constructor(e){this.logger=e}hasPlugins(){return this.plugins.size>0}register(e){if(this.initialized)throw new Error(`Cannot register plugin "${e.name}" after initialization`);if(this.plugins.has(e.name))throw new Error(`Plugin "${e.name}" is already registered`);X().CEREBRO_OUTPUT_LEVEL===String(T)&&this.logger.debug(`registering plugin: ${e.name}`),this.plugins.set(e.name,e),this.cachedDependencyOrder=void 0}async init(e){if(this.initialized)throw new Error("PluginManager already initialized");if(this.plugins.size===0){this.logger.debug("no plugins registered, skipping initialization"),this.initialized=!0;return}this.validateDependencies();const n=this.getDependencyOrder();this.logger.debug(`initializing ${String(n.length)} plugin(s)...`);for(const o of n)if(typeof o.init=="function"){this.logger.debug(`initializing plugin: ${o.name}`);try{await o.init(e)}catch(s){const i=new ot(o.name,`Failed to initialize: ${s instanceof Error?s.message:String(s)}`,s instanceof Error?s:void 0);throw this.logger.error(i.message),i}}this.initialized=!0}async executeLifecycle(e,n,o){if(!this.initialized)throw new Error("PluginManager not initialized");if(this.plugins.size===0)return;const s=this.getDependencyOrder();for(const i of s){const l=i[e];if(typeof l=="function"){this.logger.debug(`executing ${e} hook for plugin: ${i.name}`);try{await(e==="afterCommand"?l(n,o):l(n))}catch(a){throw this.logger.error(`Error in ${e} hook for plugin "${i.name}":`,a),a}}}}async executeErrorHandlers(e,n){if(!this.initialized||this.plugins.size===0)return;const o=this.getDependencyOrder();for(const s of o)if(typeof s.onError=="function"){this.logger.debug(`executing error handler for plugin: ${s.name}`);try{await s.onError(e,n)}catch(i){this.logger.error(`Error in error handler for plugin "${s.name}":`,i)}}}getDependencyOrder(){if(this.cachedDependencyOrder!==void 0)return this.cachedDependencyOrder;const e=[],n=new Set,o=new Set,s=i=>{if(n.has(i))return;if(o.has(i))throw new Error(`Circular dependency detected involving plugin "${i}"`);const l=this.plugins.get(i);if(!l)throw new Error(`Plugin "${i}" not found`);if(o.add(i),l.dependencies)for(const a of l.dependencies)s(a);o.delete(i),n.add(i),e.push(l)};for(const i of this.plugins.keys())s(i);return this.cachedDependencyOrder=e,e}validateDependencies(){for(const e of this.plugins.values())if(e.dependencies){for(const n of e.dependencies)if(!this.plugins.has(n))throw new Error(`Plugin "${e.name}" depends on "${n}" which is not registered`)}}};const G=t=>t.type?.name==="Boolean",st=t=>{let e=t.type?t.type.name.toLowerCase():"string";const n=t.multiple??t.lazyMultiple?"[]":"";return e&&(e=e==="boolean"?"":`{underline ${e}${n}}`),e},de=t=>(G(t)||(t.typeLabel=t.typeLabel??st(t),t.defaultOption&&(t.typeLabel=`${t.typeLabel} (D)`),t.required&&(t.typeLabel=`${t.typeLabel} (R)`)),t),at=new RegExp(/^-([^\d-])$/),rt=new RegExp(/^--(\S+)/),lt=new RegExp(/^-([^\d-]{2,})$/),ct=t=>at.test(t)||rt.test(t)||lt.test(t),dt=(t,e)=>{const n=e[0]&&ct(e[0])||e.length===0?null:e.shift()??null;if(!t.includes(n)){const o=new Error(`Command not recognised: ${String(n)}`);throw o.command=n,o.name="INVALID_COMMAND",o}return{argv:e,command:n}};class re extends H{optionName;value;constructor(e,n,o){super({hint:`Pass a valid ${o} value for '${e}'.`,message:`Invalid ${o} value '${n}' for option '${e}'`,name:"INVALID_VALUE",title:"Invalid Value"}),this.optionName=e,this.value=n,Object.setPrototypeOf(this,re.prototype)}}let ut=class Ie extends H{optionName;constructor(e){super({cause:void 0,hint:`Remove the duplicate option '${e}' from your command line arguments.`,location:void 0,message:`Option '${e}' is already set`,name:"ALREADY_SET",stack:void 0,title:"Option Already Set"}),this.optionName=e,Object.setPrototypeOf(this,Ie.prototype)}},ue=class ke extends H{optionName;constructor(e){super({cause:void 0,hint:`Check your option definitions or remove the unknown option '${e}' from your command line arguments.`,location:void 0,message:`Unknown option: --${e}`,name:"UNKNOWN_OPTION",stack:void 0,title:"Unknown Option"}),this.optionName=`--${e}`,Object.setPrototypeOf(this,ke.prototype)}},mt=class Ee extends H{value;constructor(e){super({hint:"Use a defined option or add a defaultOption to capture this value.",message:`Unknown value: ${e}`,name:"UNKNOWN_VALUE",title:"Unknown Value"}),this.value=e,Object.setPrototypeOf(this,Ee.prototype)}};class x extends H{constructor(e,n){super({cause:void 0,hint:n,location:void 0,message:e,name:"INVALID_DEFINITIONS",stack:void 0,title:"Invalid Option Definition"}),Object.setPrototypeOf(this,x.prototype)}}const me=(t,e,n)=>{const o=Number(t);if(e&&Number.isNaN(o)&&String(t).trim().toLowerCase()!=="nan")throw new re(n??"",String(t),"Number");return o},he=t=>t===Boolean||typeof t=="function"&&t.name==="Boolean",pe=t=>t===Number||typeof t=="function"&&t.name==="Number",fe=t=>t===String||typeof t=="function"&&t.name==="String",ht=(t,e,n={})=>{const{optionName:o,strictTypes:s}=n;return Array.isArray(t)?he(e)?t.map(Boolean):pe(e)?t.map(i=>me(i,s,o)):fe(e)?t.map(String):t.map(i=>e(String(i))):t===null?null:he(e)?!!t:pe(e)?me(t,s,o):fe(e)?typeof t=="string"?t:String(t):e(typeof t=="string"?t:String(t))},b=(t,e,n,...o)=>{t&&console.debug(`[command-line-args:${n}] ${e}`,...o)},pt=/-([a-z])/g,ft=/^\d+$/,K=t=>t===Boolean||typeof t=="function"&&t.name==="Boolean",gt=t=>t.codePointAt(0)===95,ge=(t,e)=>Array.isArray(t)?[...t,...e]:[t,...e],we=t=>t==="__proto__"||t==="constructor"||t==="prototype",ye=(t,e,n,o=!1)=>{t[e]===void 0?t[e]=o?[n]:n:o&&Array.isArray(t[e])?t[e].push(n):t[e]=[t[e],n]},ve=(t,e,n,o,s)=>{let i=e.get(t)??n.get(t);if(!i&&o){const l=t.toLowerCase();i=o.get(l)??s?.get(l)}return i},wt=(t,e,n,o)=>{const s=n.debug??!1;b(s,"resolveArgs called with options:","resolver",{partial:n.partial,stopAtFirstUnknown:n.stopAtFirstUnknown}),b(s,"Starting argument resolution","resolver"),b(s,"Tokens:","resolver",t),b(s,"Definitions:","resolver",e),b(s,"Processing tokens...","resolver");const i=new Map,l=new Map,a=n.caseInsensitive?new Map:void 0,d=n.caseInsensitive?new Map:void 0,r=n.camelCase?new Map:void 0,m=n.camelCase?new Map:void 0;for(const c of e)if(i.set(c.name,c),c.alias&&l.set(c.alias,c),n.caseInsensitive&&a&&(a.set(c.name.toLowerCase(),c),c.alias&&d&&d.set(c.alias.toLowerCase(),c)),n.camelCase&&r&&m){const u=c.name.replaceAll(pt,(p,C)=>C.toUpperCase());r.set(c.name,u),m.set(u,c.name)}const h=Object.create(null),f=Object.create(null),y=[],E=[],A=new Set;let I=!1;const O=e.find(c=>c.defaultOption),v=e.some(c=>c.group),$=e.find(c=>c.type===Number);for(let c=0;c<t.length;c++){const u=t[c];if(u.kind==="option-terminator"){h._unknown=o.slice(u.index),I=!0;break}if(u.kind==="option"&&u.name){let p=ve(u.name,i,l,a,d);!p&&u.value===void 0&&$&&ft.test(u.name)&&(p=$,u.value=u.name,u.name=$.name);let C=!1;if(!p&&n.negation&&u.value===void 0&&u.name.startsWith("no-")){const N=u.name.slice(3),P=ve(N,i,l,a,d);P?.type&&K(P.type)&&(p=P,C=!0)}const g=p?p.name:u.name,k=p?.multiple,D=p?.lazyMultiple;if(Object.hasOwn(f,g)&&f[g]!==void 0&&!k&&!D&&!n.partial)throw new ut(g);if(!p&&n.partial){const N=u.rawName??`--${u.name}${u.value!==void 0&&u.inlineValue?`=${u.value}`:""}`;y.push({index:u.index,value:N});continue}if(!p&&n.stopAtFirstUnknown){h._unknown=o.slice(u.index);break}if(!p&&!n.partial)throw new ue(u.name);if(u.value===void 0){const N=t[c+1],P=N?.kind==="option"&&!("name"in N)&&N.value!==void 0,M=N&&p&&!(p.type&&K(p.type))&&(N.kind==="positional"||P),Se=p&&p.defaultOption&&!p.multiple&&!p.lazyMultiple;if(M&&(!p?.defaultOption||Se))if(k){let S=c+1;const ee=[];for(;S<t.length&&(t[S].kind==="positional"||t[S].kind==="option"&&!("name"in t[S])&&t[S].value!==void 0);)ee.push(t[S].value),A.add(t[S].index),S++;f[g]=f[g]===void 0?ee:ge(f[g],ee),c=S-1}else D?(ye(f,g,N.value,!0),A.add(N.index),c++):(f[g]=N.value,A.add(N.index),c++);else p?.type&&K(p.type)?ye(f,g,!C,k):f[g]=k?[]:null}else{let{value:N}=u;if(p?.type&&K(p.type))switch(N){case"":{if(n.partial){f._unknown??=[];const M=`${u.rawName??`--${u.name}`}${u.value?`=${u.value}`:""}`;f._unknown.push(M),E.push({index:u.index,value:M}),N=!0}else throw new ue(u.name);break}case"false":{N=!1;break}case"true":{N=!0;break}default:N=!0}const P=[N];if(k){let M=c+1;for(;M<t.length&&t[M].kind==="positional";)P.push(t[M].value),A.add(t[M].index),M++;c=M-1}f[g]===void 0?f[g]=k||D?P:N:k||D?f[g]=ge(f[g],P):f[g]=N}}else if(u.kind==="positional"&&n.stopAtFirstUnknown&&!A.has(u.index)&&!O){b(s,`Found unconsumed positional token at index ${String(u.index)}, stopping processing`,"resolver"),h._unknown=o.slice(u.index);break}}for(const[c,u]of Object.entries(f)){const p=i.get(c);p&&(p.multiple||p.lazyMultiple)&&!Array.isArray(u)&&(f[c]=[u])}const _=c=>c.kind==="option"&&!i.has(c.name??"")&&!l.has(c.name??"")&&(!n.caseInsensitive||!a?.has(c.name?.toLowerCase()??"")&&!d?.has(c.name?.toLowerCase()??""));let L=-1,V=Number.POSITIVE_INFINITY;if(n.stopAtFirstUnknown&&!I&&(L=t.findIndex(c=>_(c)),L!==-1&&(V=t[L].index)),O){const c=[],u=[];for(const p of t)p.kind==="positional"&&!A.has(p.index)&&p.index<V&&(c.push(p.value),u.push(p));if(c.length>0){const p=f[O.name],C=O.multiple??O.lazyMultiple;p===void 0?C?(u.forEach(g=>A.add(g.index)),f[O.name]=c):(A.add(u[0].index),f[O.name]=c[0]):C&&(u.forEach(g=>A.add(g.index)),f[O.name]=Array.isArray(p)?[...c,...p]:[...c,p])}}if(!n.partial){for(const c of t)if(c.kind==="positional"&&!A.has(c.index))throw new mt(o[c.index])}if(n.partial&&!n.stopAtFirstUnknown){const c=[...y];if(f._unknown)for(const u of E)c.push({index:u.index,value:u.value});for(const u of t)u.kind==="positional"&&!A.has(u.index)&&c.push({index:u.index,value:o[u.index]});c.length>0&&(c.sort((u,p)=>u.index-p.index),h._unknown=c.map(u=>u.value))}if(n.stopAtFirstUnknown&&!I){const c=t.findIndex(p=>p.kind==="positional"&&!A.has(p.index));let u=-1;if(L!==-1&&c!==-1?u=Math.min(L,c):L!==-1?u=L:c!==-1&&(u=c),u>=0){const p=t[u].index;h._unknown=o.slice(p)}}else y.length>0&&!n.partial&&(h._unknown=y.map(c=>c.value));for(const[c,u]of Object.entries(f)){const p=n.camelCase?r?.get(c)??c:c,C=i.get(c);C?.type?h[p]=ht(u,C.type,{optionName:C.name,strictTypes:n.strictTypes}):h[p]=u===void 0?null:u}for(const c of e){const u=n.camelCase?r?.get(c.name)??c.name:c.name;!(u in h)&&c.defaultValue!==void 0&&(c.multiple??c.lazyMultiple?h[u]=Array.isArray(c.defaultValue)?[...c.defaultValue]:[c.defaultValue]:h[u]=c.defaultValue)}if(v){const c={},u={},p={};for(const g of e)if(g.group){const k=Array.isArray(g.group)?g.group:[g.group];for(const D of k)we(D)||(c[D]??={})}for(const g of Object.keys(h))if(!gt(g)){u[g]=h[g];let k=g;n.camelCase&&(k=m?.get(g)??g);const D=i.get(k);if(D?.group){const N=Array.isArray(D.group)?D.group:[D.group];for(const P of N)we(P)||c[P]&&(c[P][g]=h[g])}else p[g]=h[g]}const C={_all:u};for(const[g,k]of Object.entries(c))C[g]=k;Object.keys(p).length>0&&(C._none=p),h._unknown&&(C._unknown=h._unknown),Object.keys(h).forEach(g=>delete h[g]),Object.assign(h,C)}const Y=Object.defineProperties({},Object.getOwnPropertyDescriptors(h));return b(s,"Final parsed result:","resolver",Y),Y},q="-".codePointAt(0),z="=",yt=z.codePointAt(0),vt="--",Nt="-",$t="--",Pe=t=>t.length>2&&t.startsWith($t),bt=t=>Pe(t)&&!t.includes(z,3),At=t=>Pe(t)&&t.includes(z,3),Ot=t=>{if(t.length!==2||t.codePointAt(0)!==q||t.codePointAt(1)===q)return!1;const e=t.codePointAt(1);return e!==void 0&&(e<48||e>57)},_t=t=>!(t.length<=2||t.codePointAt(0)!==q||t.codePointAt(1)===q),Ct=t=>{const e=[];let n=0,o=[],s=0,i=-1,l=0;for(;s<o.length||n<t.length;){let a;if(s<o.length?(a=o[s],s++):(a=t[n],n++),l>0?l--:i++,a===vt){e.push({index:i,kind:"option-terminator"});const d=[...o.slice(s),...t.slice(n)],r=d.map((m,h)=>({index:i+h+1,kind:"positional",value:m}));e.push(...r),i+=d.length;break}if(Ot(a)){const d=a.charAt(1);e.push({index:i,kind:"option",name:d,rawName:a});continue}if(_t(a)&&!a.includes(z)){const d=[];let r="",m=!1;for(let h=1;h<a.length;h++){const f=a.charAt(h);m?r+=f:f.codePointAt(0)===yt?m=!0:d.push(`${Nt}${f}`)}if(m)if(d.length>0){const h=d.pop();d.push(`${h}=${r}`)}else d.push(r);o=s<o.length?[...d,...o.slice(s)]:d,s=0,l=d.length;continue}if(bt(a)){const d=a.slice(2);e.push({index:i,kind:"option",name:d,rawName:a});continue}if(At(a)){const d=a.indexOf(z),r=a.slice(2,d),m=a.slice(d+1);e.push({index:i,inlineValue:!0,kind:"option",name:r,rawName:a,value:m});continue}if(a.length>2&&a.codePointAt(0)===q&&a.codePointAt(1)!==q&&a.includes(z)){const d=a.indexOf(z),r=a.charAt(1),m=a.slice(d+1);e.push({index:i,inlineValue:!0,kind:"option",name:r,rawName:a,value:m});continue}e.push({index:i,kind:"positional",value:a})}return e},xt=/\d/,It=t=>t===Boolean||typeof t=="function"&&t.name==="Boolean",kt=t=>typeof t=="function",Et=(t,e,n)=>{const o=n?.debug??!1;b(o,"Validating definitions:","validation",t,"caseInsensitive:",e);const s=new Set,i=new Set,l=new Set,a=new Set;let d=0;for(const r of t){if(b(o,"Checking definition:","validation",r),!r.name)throw b(o,"Validation failed: name is required","validation"),new x("Invalid option definition: name is required");if(typeof r.name!="string")throw new x("Invalid option definition: name must be a string");if(r.name.trim()==="")throw new x("Invalid option definition: name cannot be empty");const m=e?r.name.toLowerCase():"";if(s.has(r.name)||e&&l.has(m))throw new x(`Invalid option definition: duplicate name '${r.name}'`);if(i.has(r.name)||e&&a.has(m))throw new x(`Invalid option definition: name '${r.name}' conflicts with an existing alias`);if(s.add(r.name),e&&l.add(m),r.alias!==void 0){if(typeof r.alias!="string")throw new x("Invalid option definition: alias must be a string");if(r.alias.length!==1)throw new x("Invalid option definition: alias must be a single character");if(xt.test(r.alias))throw new x("Invalid option definition: alias cannot be numeric");if(r.alias==="-")throw new x('Invalid option definition: alias cannot be "-"');const h=e?r.alias.toLowerCase():"";if(i.has(r.alias)||e&&a.has(h))throw new x(`Invalid option definition: duplicate alias '${r.alias}'`);if(s.has(r.alias)||e&&l.has(h))throw new x(`Invalid option definition: alias '${r.alias}' conflicts with an existing option name`);i.add(r.alias),e&&a.add(h)}if(r.defaultOption&&(d++,r.type!==void 0&&It(r.type)))throw new x("Invalid option definition: defaultOption cannot be Boolean type");if(r.type!==void 0&&!(r.type===Boolean||r.type===Number||r.type===String||typeof r.type=="function"&&kt(r.type)))throw new x("Invalid option definition: invalid type")}if(d>1)throw b(o,"Validation failed: multiple defaultOptions not allowed","validation"),new x("Invalid option definition: multiple defaultOptions not allowed");b(o,"Validation completed successfully","validation")};function Pt(t,e={}){const n=e.debug??!1;b(n,"Starting command-line-args parsing","index"),b(n,"Options:","index",e);const o={...e};o.stopAtFirstUnknown&&(o.partial=!0);const s=Array.isArray(t)?t:[t];b(n,"Normalized definitions:","index",s),Et(s,o.caseInsensitive,n?o:void 0);let{argv:i}=o;if(!i&&(i=process.argv.slice(2),process.execArgv.length>0)){const r=new Set(process.execArgv);i=i.filter(m=>!r.has(m))}b(n,"Using argv:","index",i);let l=i;o.caseInsensitive&&(l=i.map(r=>{if(r.startsWith("--")){const m=r.indexOf("="),h=(m===-1?r.slice(2):r.slice(2,m)).toLowerCase();return m===-1?`--${h}`:`--${h}${r.slice(m)}`}if(r.startsWith("-")&&!r.startsWith("--")&&r.length>1){const m=r.slice(1).split("=",2),h=m[0],f=m[1];if(!h)return r;const y=h.toLowerCase();return f===void 0?`-${y}`:`-${y}=${f}`}return r}));const a=Ct(l.map(String));b(n,"Tokenized arguments:","index",a);const d=wt(a,s,o,i);return b(n,"Command-line-args parsing completed","index"),d}class Lt{result;argv;options;argument;command;commandName;env;logger;console;fs;process;runtime;rawUnknown;constructor(e,n){this.commandName=e,this.command=n}}let ne=class extends w{commandName;constructor(e,n,o){super(`Failed to load command "${e}": ${n}`,"COMMAND_LOADER_ERROR",{commandName:e,reason:n}),this.name="CommandLoaderError",this.commandName=e,this.hint="Ensure the loader resolves to a module with a default export that is the command handler function.",o!==void 0&&(this.cause=o)}};const Dt=/^-{1,2}(\w+)(=(.+))?$/,Le=(t,e,n,o)=>{const s=Dt.exec(t);if(s===null)return{};const i=s[1];if(!i)return{};const l=n&&o?n.get(i)??o.get(i):e.find(a=>a.name===i||a.alias===i);return l!==void 0?{argName:l.name,argValue:s[3],option:l}:{}},Ne=(t,e)=>{if(e.type===void 0)return t;if(e.type.name==="Boolean"){if(t==="true"||t==="1")return e.type(!0);if(t==="false"||t==="0")return e.type(!1)}return e.type(t)},Mt=new Set(["0","1","false","true"]),Vt=(t,e,n,o)=>{if(e.length===0||t.length===0)return{};const s=(i,l)=>{const{argName:a,argValue:d,option:r}=Le(l,e,n,o),{lastOption:m}=i;return r&&G(r)&&d&&a?i.partial[a]=Ne(d,r):i.lastName&&m&&G(m)&&Mt.has(l)&&(i.partial[i.lastName]=Ne(l,m)),{lastName:a,lastOption:r,partial:i.partial}};return t.reduce(s,{partial:{}}).partial},St=new Set(["0","1","false","true"]),Tt=(t,e,n,o)=>{if(e.length===0||t.length===0)return t;const s=(i,l)=>{const{argValue:a,option:d}=Le(l,e,n,o),{lastOption:r}=i;if(r&&G(r)&&St.has(l)){const{args:m}=i;return{args:m.slice(0,-1)}}return d&&G(d)&&a?{args:i.args}:{args:[...i.args,l],lastOption:d}};return t.reduce(s,{args:[]}).args},$e=t=>{const e=new Map;for(const n of t){const o=e.get(n.name);o?e.set(n.name,{...o,...n}):e.set(n.name,n)}return[...e.values()]},jt=t=>{if(t===void 0)return;const e=t.toLowerCase().trim();return e==="true"||e==="1"||e==="yes"||e==="on"},Ut=(t,e)=>{if(!t.type)return e;if(e!==void 0){if(t.type===Boolean||typeof t.type=="function"&&t.type.name==="Boolean")return jt(e);if(t.type===Number||typeof t.type=="function"&&t.type.name==="Number"){const n=Number.parseFloat(e);return Number.isNaN(n)?void 0:n}return t.type===String||typeof t.type=="function"&&t.type.name==="String"?e:t.type(e)}},Bt=/_./g,zt=/^[A-Z]/,Rt=t=>t.toLowerCase().replaceAll(Bt,e=>e[1]?.toUpperCase()??e).replace(zt,e=>e.toLowerCase()),Ft=t=>{if(!t||t.length===0)return{};const e={},n=X();for(const o of t){const s=n[o.name],i=Ut(o,s),l=i===void 0?o.defaultValue:i,a=Rt(o.name);e[a]=l}return e},qt=t=>{const e=new Map,n=new Map;for(const o of t)if(e.set(o.name,o),o.alias){const s=Array.isArray(o.alias)?o.alias:[o.alias];for(const i of s)n.set(i,o)}return{optionMapByAlias:n,optionMapByName:e}},De=async t=>{if(typeof t.__resolvedExecute__=="function")return t.__resolvedExecute__;if(typeof t.loader!="function")throw new ne(t.name,"no execute or loader defined");let e;try{e=await t.loader()}catch(o){throw new ne(t.name,o instanceof Error?o.message:String(o),o)}const n=e.default;if(typeof n!="function")throw new ne(t.name,"loader did not return a module with a default-exported handler function");return t.__resolvedExecute__=n,n},Wt=(t,e,n,o)=>{const s=new Lt(t.name,t),{_all:i,_unknown:l,positionals:a}=e,d=Object.keys(n).length>0?{...i,...n}:i;Q in d&&delete d[Q],s.argument=a?.[Q]??[],s.rawUnknown=[...l??[]];const r=Object.keys(o).length>0;return s.options=r?{...d,...o}:d,s.env=Ft(t.env),s},Gt=(t,e,n)=>{const o=t.options??[],s=o.length>0;let i=$e(s?[...o,...n]:n);if(i.length>0){for(const r of i)if(r.multiple&&r.lazyMultiple)throw new Error(`Argument "${r.name}" cannot have both multiple and lazyMultiple options, please choose one.`)}t.argument&&(i=[{defaultOption:!0,description:t.argument.description,group:"positionals",multiple:!0,name:Q,type:t.argument.type,typeLabel:t.argument.typeLabel},...i]);let l,a;if(s){const{optionMapByAlias:r,optionMapByName:m}=qt(o);l=Tt(e,o,m,r),a=Vt(e,o,m,r)}else l=e,a={};const d=Pt(i,{argv:l,camelCase:!0,partial:!0,stopAtFirstUnknown:!0});return{arguments_:i,booleanValues:a,parsedArgs:d}},R=async(t,e,n)=>typeof t.execute=="function"?t.execute(e):(await De(t))(e);let Ht=class extends w{commandName;missingOptions;constructor(e,n){super(`Command "${e}" is missing required options: ${n.join(", ")}`,"COMMAND_VALIDATION_ERROR",{commandName:e,missingOptions:n}),this.name="CommandValidationError",this.commandName=e,this.missingOptions=n,this.hint=`Provide the following required options: ${n.join(", ")}`}},Yt=class extends w{choices;option;value;constructor(e,n,o){super(`Invalid value "${n}" for option "${e}". Allowed values: ${o.join(", ")}`,"INVALID_CHOICE",{choices:o,option:e,value:n}),this.name="InvalidChoiceError",this.option=e,this.value=n,this.choices=o,this.hint=`Use one of: ${o.map(s=>`--${e} ${s}`).join(", ")}`}};const be=(t,e,n=!1)=>{const o=[];for(const s of t)if(!(!n&&!s.required)&&e[s.name]===void 0){if(s.type?.name==="Boolean"){e[s.name]=!1;continue}o.push(s)}return o},Jt=(t,e)=>e.includes(t)?!0:Math.abs(t.length-e.length)>t.length/2?!1:Xe(t,e)<=t.length/3,j=(t,e)=>{const n=t.toLowerCase();return e.filter(o=>Jt(o.toLowerCase(),n))},Kt=(t,e)=>{const n=[];if(t._unknown&&t._unknown.forEach(o=>{const s=o.startsWith("--");let i=`Found unknown ${s?"option":"argument"} "${o}"`;if(s){const l=j(o.replace("--",""),(e.options??[]).map(a=>a.name));if(l.length>0){const[a,...d]=l.map(r=>`--${r}`);i+=d.length>0?`, did you mean ${a??""} or ${d.join(", ")}?`:`, did you mean ${a??""}?`}}n.push(i)}),n.length>0)throw new Error(n.join(`
2
- `))},Zt=(t,e,n)=>{const o=n.__requiredOptions__,s=o?be(o,e,!0):be(t,e,!1);if(s.length>0)throw new Ht(n.name,s.map(i=>i.name));e._unknown&&e._unknown.length>0&&!n.argument&&Kt(e,n)},Qt=(t,e,n)=>{const o=n.__conflictingOptions__??t.filter(s=>s.conflicts!==void 0);if(o.length>0){const s=o.find(i=>Array.isArray(i.conflicts)?i.conflicts.some(l=>e[l]!==void 0)&&e[i.name]!==void 0:e[i.conflicts]!==void 0&&e[i.name]!==void 0);if(s)throw new xe(s.name,typeof s.conflicts=="string"?s.conflicts:s.conflicts?.[0]??"unknown")}},Xt=(t,e)=>{const n=e.options;if(n)for(const o of n){if(!o.choices||o.choices.length===0)continue;const s=t[o.name];if(s==null)continue;const i=Array.isArray(s)?s:[s];for(const l of i){const a=String(l);if(!o.choices.includes(a))throw new Yt(o.name,a,o.choices)}}},en=t=>{if(!Array.isArray(t.options))return;const e=new Map,n=new Map;for(const s of t.options){if(s.name){const i=e.get(s.name)??[];i.push(s),e.set(s.name,i)}if(typeof s.alias=="string"&&s.alias.length>0){const i=n.get(s.alias)??[];i.push(s),n.set(s.alias,i)}else if(Array.isArray(s.alias)){for(const i of s.alias)if(i.length>0){const l=n.get(i)??[];l.push(s),n.set(i,l)}}}const o=[];for(const[s,i]of e)i.length>1&&o.push(`Duplicate option name "${s}" in command "${t.name}": ${JSON.stringify(i)}`);for(const[s,i]of n)i.length>1&&o.push(`Duplicate option alias "-${s}" used by options ${i.map(l=>`"${l.name}"`).join(", ")} in command "${t.name}"`);if(o.length>0)throw new Error(o.join(`
3
- `))},tn=(t,e)=>{if(e.length===0)return{argv:[],commandPath:void 0};const n=[];let o;for(let s=1;s<=e.length;s+=1){const i=e[s-1];if(i===void 0||i.startsWith("-"))break;n.push(i);const l=n.join(" ");t.has(l)&&(o={commandPath:[...n],depth:s})}return o?{argv:e.slice(o.depth),commandPath:o.commandPath}:{argv:e,commandPath:void 0}},B=t=>t.join(" "),Ae=(t,e)=>e&&e.length>0?[...e,t]:[t],nn=(t,e)=>typeof t!="string"||t===""?"":t[0].toLowerCase()+t.slice(1),on=(t,e)=>typeof t!="string"||t===""?"":t[0].toUpperCase()+t.slice(1),sn=(t,e)=>{const{length:n}=t;if(n===0)return"";if(n===1)return t[0];const o=[];let s="",i="";for(let l=0;l<n;l++){const a=t[l];if(et.test(a)){s?(o.push(s+i+a),s="",i=""):(o.length>0&&o.push(e),s=a);continue}s?(i&&(i+=e),i+=a):(o.length>0&&o.push(e),o.push(a))}return o.join("")},Me=(t,e)=>{if(typeof t!="string"||!t)return"";let n=!0;return sn(tt(t,{handleAnsi:e?.handleAnsi,handleEmoji:e?.handleEmoji,knownAcronyms:e?.knownAcronyms,locale:e?.locale,normalize:e?.normalize,separators:void 0,stripAnsi:e?.stripAnsi,stripEmoji:e?.stripEmoji}).map(s=>{const i=s,l=i.toLowerCase();return n?(n=!1,nn(l)):on(l)}),"")},an=/^no-/,rn=t=>{t.options?.forEach(e=>{e.__camelCaseName__=Me(e.name)})},ln=t=>{if(!Array.isArray(t.options)||t.options.length===0)return;const e=new Set;for(const o of t.options)e.add(o.name);const n=[];for(const o of t.options)if(o.name.startsWith("no-")){const s=o.name.replace(an,"");if(!e.has(s)){if(o.type!==Boolean)throw new Error(`Cannot add negated option "${o.name}" to command "${t.name}" because it is not a boolean.`);const i={...o,defaultValue:o.defaultValue===void 0?!0:!o.defaultValue,name:s};n.push(i),e.add(s)}}n.length>0&&t.options.push(...n)},cn=(t,e)=>{if(!e.options||e.options.length===0)return;const{options:n}=t,o=new Map;for(const i of e.options)if(i.name.startsWith("no-")){const l=Me(i.name);o.set(l,i)}const s=Object.keys(n).filter(i=>o.has(i));if(s.length!==0)for(const i of s){const l=i.charAt(2);if(!l)continue;const a=l.toLowerCase()+i.slice(3),d=o.get(i);d&&(d.__negated__=!0),n[a]=!n[i],Reflect.deleteProperty(n,i)}},dn=(t,e)=>{if(!e.options||e.options.length===0)return;const n=new Map;for(const s of e.options)s.__camelCaseName__&&s.__negated__===void 0&&s.implies!==void 0&&n.set(s.__camelCaseName__,s);if(n.size===0)return;const{options:o}=t;for(const s of Object.keys(o)){const i=n.get(s);if(i?.implies){const{implies:l}=i;for(const[a,d]of Object.entries(l))o[a]===void 0&&(o[a]=d)}}},un=()=>!!process.versions.electron,mn=()=>un()&&!process.defaultApp,hn=()=>mn()?0:1,pn=t=>t.slice(hn()+1),fn=" ",gn=(t,e)=>t===e?!0:t.length!==e.length?!1:t.every((n,o)=>n===e[o]),wn=t=>{if(typeof t=="string")return t.split(fn);const e=se();return gn(t,e)?pn(t):t},yn=t=>{const e=i=>{t.error(`Uncaught exception: ${i.message||i}`),i.stack&&t.error(i.stack),F(1)},n=(i,l)=>{if(i instanceof Error)t.error(`Promise rejection: ${i.message||i}`),i.stack&&t.error(i.stack);else{let a;if(typeof i=="string")a=i;else try{a=JSON.stringify(i)}catch{a=String(i)}t.error(`Promise rejection: ${a}`)}F(1)},o=ce("uncaughtException",e),s=ce("unhandledRejection",n);return()=>{o(),s()}},Oe=100,vn=/^[a-z][\w-]*$/i,ae=(t,e)=>{if(typeof t!="string"||t.trim().length===0)throw new w(`${e} must be a non-empty string`,"INVALID_INPUT",{fieldName:e,value:t});return t.trim()},_e=(t,e)=>{if(!Array.isArray(t)||!t.every(n=>typeof n=="string"))throw new w(`${e} must be an array of strings`,"INVALID_INPUT",{fieldName:e,value:t});return t},oe=(t,e)=>{if(typeof t!="object"||t===null)throw new w(`${e} must be an object`,"INVALID_INPUT",{fieldName:e,value:t});return t},Z=t=>{const e=ae(t,"Command name");if(e.length>Oe)throw new w(`Command name is too long (maximum ${String(Oe)} characters)`,"INVALID_COMMAND_NAME",{commandName:e,length:e.length});if(e.includes("..")||e.includes("/")||e.includes("\\")||e.includes(";")||e.includes("|")||e.includes("&"))throw new w(`Command name "${e}" contains invalid characters`,"INVALID_COMMAND_NAME",{commandName:e});if(!vn.test(e))throw new w(`Command name "${e}" must start with a letter and contain only letters, numbers, hyphens, and underscores`,"INVALID_COMMAND_NAME",{commandName:e});return e},Nn=new Set([`
4
- `,"\r"," ","\0",'"',"$","&","'","(",")",";","<",">","[","\\","]","`","{","|","}"]),$n=(t,e={})=>{if(typeof t!="string")throw new TypeError("Argument must be a string");const n=typeof e=="boolean"?{checkDangerousChars:e}:e,o=n.maxArgumentLength??1e6;if(Number.isFinite(o)&&o>0&&t.length>o)throw new Error(`Argument is too long (maximum ${String(o)} characters)`);if(n.checkDangerousChars){for(const s of t)if(Nn.has(s))throw new Error(`Argument contains dangerous character: ${s}`)}return n.trim?t.trim():t},Ce=(t,e={})=>{if(!Array.isArray(t))throw new TypeError("Arguments must be an array");const n=typeof e=="boolean"?{checkDangerousChars:e}:e,o=n.maxArguments??1e5;if(Number.isFinite(o)&&o>0&&t.length>o)throw new Error(`Too many arguments (maximum ${String(o)})`);return t.map(s=>$n(s,n))},bn=/^-([^\d-])$/,An=/^--(\S+)/,On=/^-([^\d-]{2,})$/,ie=t=>bn.test(t)||An.test(t)||On.test(t),_n={access:(t,e)=>We(t,e),mkdir:(t,e)=>qe(t,e),readdir:t=>Fe(t),readFile:(async(t,e)=>e===void 0?le(t):le(t,e)),rm:(t,e)=>Re(t,e),stat:t=>ze(t),writeFile:(t,e,n)=>Be(t,e,n)},Cn=(t,e,n)=>{const o=e.indexOf("--"),s=o===-1?new Set:new Set(e.slice(o+1)),i=n.filter(d=>d.startsWith("--")&&d!=="--"&&!s.has(d));if(i.length===0)return;const l=(t.options??[]).map(d=>d.name),a=i.flatMap(d=>j(d.slice(2),l).map(r=>`--${r}`));throw new nt(i,a)};class Ve{#t;#e;#d;#u;#p;#f;#O;#_;#C;#N;#x;#$;#I;#k=te;#m;#n;#o;#i;#s;#a;#g=!1;#E;#P=!1;#w;#y;#v;#l=[];#S(){return this.#w===void 0&&(this.#w=[...this.#o.keys()]),this.#w}#L(){return this.#y===void 0&&(this.#y=[...this.#n.keys()]),this.#y}#r(){return this.#v===void 0&&(this.#v=[...this.#S(),...this.#L()]),this.#v}#D(){return this.#l.length===0?J:[...J,...this.#l]}#M(){this.#w=void 0,this.#y=void 0,this.#v=void 0}#b(){if(this.#d===void 0){const e=wn(this.#e.argv);this.#d=Ce(e,{maxArguments:this.#$}),this.#T()}return this.#d}#A(){return this.#N??X()}#h(e){this.#k=e,this.#A().CEREBRO_OUTPUT_LEVEL=String(e)}#c(){const e=this.#A().CEREBRO_OUTPUT_LEVEL,n=e===void 0?Number.NaN:Number(e);return Number.isNaN(n)?this.#k:n}#T(){if(!this.#d)return;let e=!1;for(const n of this.#d){if(n==="--quiet"||n==="-q"){this.#h(Ge),e=!0;break}if(n==="--verbose"||n==="-v"){this.#h(He),e=!0;break}if(n==="--debug"){this.#h(T),e=!0;break}}e||this.#h(Object.hasOwn(this.#A(),"DEBUG")?T:te)}#j(){this.#P||(this.#E=yn(this.#t),this.#P=!0)}#U(){return{arch:Je(),argv:this.#b(),cwd:this.#u,env:this.#N??X(),exit:this.#C??(e=>F(e??0)),platform:Ye(),stdin:this.#x}}#V(e,n,o,s){this.#c()===T&&this.#t.debug(`command '${s}' found, parsing command args: ${n.join(", ")}`);const{arguments_:i,booleanValues:l,parsedArgs:a}=Gt(e,n,this.#D()),d=Object.keys(l).length>0;let r=a;d&&(r={...a,_all:{...a._all,...l}}),Zt(i,r,e);const m=Wt(e,a,l,o);m.runtime=this,m.argv=this.#b(),m.fs=this.#_??_n,m.process=this.#U(),m.console=this.#t;const h=e.options&&e.options.length>0;if(h&&e.options){const f=e.options.filter(y=>y.name.startsWith("no-"));for(const y of f){const E=y.name.slice(3),A=`--${y.name}`,I=`--${E}`,O=n.includes(A),v=n.includes(I);if(O&&v)throw new xe(E,y.name)}}return h&&(cn(m,e),dn(m,e)),Qt(i,m.options,e),Xt(m.options,e),this.#I&&Cn(e,n,m.rawUnknown),this.#c()===T&&(this.#t.debug("command options parsed from options:"),this.#t.debug(JSON.stringify(m.options,null,2)),this.#t.debug("command argument parsed from argument:"),this.#t.debug(JSON.stringify(m.argument,null,2))),{arguments_:i,booleanValues:l,commandArgs:r,parsedArgs:a,toolbox:m}}constructor(e,n={}){if(typeof e!="string"||e.trim().length===0)throw new w("CLI name must be a non-empty string","INVALID_INPUT",{cliName:e});this.#p=e.trim();const o=n.argv??se(),s=n.cwd??Ke();if(this.#e={...n,argv:o,cwd:s},this.#e.argv&&!Array.isArray(this.#e.argv))throw new w("CLI argv option must be an array of strings","INVALID_INPUT",{argv:this.#e.argv});if(this.#e.cwd&&typeof this.#e.cwd!="string")throw new w("CLI cwd option must be a string","INVALID_INPUT",{cwd:this.#e.cwd});if(this.#e.packageName&&typeof this.#e.packageName!="string")throw new w("CLI packageName option must be a string","INVALID_INPUT",{packageName:this.#e.packageName});if(this.#e.packageVersion&&typeof this.#e.packageVersion!="string")throw new w("CLI packageVersion option must be a string","INVALID_INPUT",{packageVersion:this.#e.packageVersion});if(typeof this.#e.logger=="object"){const r=["debug","error","info","log","warn"],m=[],h=this.#e.logger;for(const f of r)typeof h[f]!="function"&&m.push(f);if(m.length>0)throw new w(`Logger object is missing required methods: ${m.join(", ")}`,"INVALID_INPUT",{logger:this.#e.logger,missingMethods:m});this.#t=this.#e.logger}else this.#t={...console,debug:(...r)=>{this.#c()===T&&console.debug(...r)}};this.#f=this.#e.packageVersion,this.#O=this.#e.packageName,this.#u=this.#e.cwd,this.#s="help",this.#a={};const i=n.fs;if(i!==void 0&&(typeof i!="object"||i===null))throw new w("CLI fs option must be an object implementing the CerebroFs interface","INVALID_INPUT",{fs:n.fs});const l=n.exit;if(l!==void 0&&typeof l!="function")throw new w("CLI exit option must be a function","INVALID_INPUT",{exit:n.exit});const a=n.env;if(a!==void 0&&(typeof a!="object"||a===null))throw new w("CLI env option must be a record of string keys","INVALID_INPUT",{env:n.env});const d=n.stdin;if(d!==void 0&&typeof d!="string")throw new w("CLI stdin option must be a string","INVALID_INPUT",{stdin:n.stdin});this.#_=n.fs,this.#C=n.exit,this.#N=n.env,this.#x=n.stdin??"",this.#$=n.maxArguments,this.#I=n.strictOptions??!1,this.#h(te),this.#n=new Map,this.#o=new Map,this.#i=new Map}setCommandSection(e){return this.#a=e,this}getCommandSection(){return this.#a.header||(this.#a.header=`${this.#p}${this.#f?` v${this.#f}`:""}`),this.#a}setDefaultCommand(e){return this.#s=e,this}get defaultCommand(){return this.#s}addCommand(e){oe(e,"Command"),Z(e.name);const n=typeof e.execute=="function",o=typeof e.loader=="function";if(n&&o)throw new w(`Command "${e.name}" cannot define both "execute" and "loader" — choose one`,"INVALID_COMMAND",{commandName:e.name});if(!n&&!o)throw new w(`Command "${e.name}" must define either "execute" or "loader"`,"INVALID_COMMAND",{commandName:e.name});e.alias&&(typeof e.alias=="string"?Z(e.alias):_e(e.alias,"Command alias").forEach(r=>Z(r))),e.argument&&oe(e.argument,"Command argument"),e.options&&oe(e.options,"Command options"),e.commandPath&&(_e(e.commandPath,"Command commandPath"),e.commandPath.forEach(r=>{Z(r)}));const s=Ae(e.name,e.commandPath),i=B(s);if(this.#o.has(i))throw new w(`Command with path "${i}" already exists`,"DUPLICATE_COMMAND",{commandName:e.name,commandPath:e.commandPath});const l=Array.isArray(e.commandPath)&&e.commandPath.length>0,a=this.#n.get(e.name),d=a!==void 0&&(a.commandPath===void 0||a.commandPath.length===0);if(!l&&d)throw new w(`Command with name "${e.name}" already exists`,"DUPLICATE_COMMAND",{commandName:e.name});if(e.options)for(const r of e.options)de(r);if(en(e),ln(e),rn(e),e.options&&(e.__conflictingOptions__=e.options.filter(r=>r.conflicts!==void 0),e.__requiredOptions__=e.options.filter(r=>r.required===!0)),l&&a!==void 0)this.#n.set(i,e);else{if(!l&&a!==void 0&&!d){const r=Ae(a.name,a.commandPath);this.#n.set(B(r),a)}this.#n.set(e.name,e)}if(this.#o.set(i,s),this.#i.set(i,e),this.#M(),e.alias!==void 0){const r=typeof e.alias=="string"?[e.alias]:e.alias;for(const m of r){if(this.#c()===T&&this.#t.debug("adding alias",m),this.#n.has(m))throw new w(`Command alias "${m}" conflicts with existing command`,"DUPLICATE_COMMAND",{alias:m,commandName:e.name});this.#n.set(m,e)}}return this}addGlobalOption(e){const n=e,o=new Set(J.map(i=>i.name)),s=new Set(J.map(i=>i.alias).filter(Boolean));if(o.has(n.name))throw new w(`Cannot add global option "--${n.name}": it conflicts with a built-in global option`,"DUPLICATE_OPTION",{optionName:n.name});if(n.alias&&s.has(n.alias))throw new w(`Cannot add global option with alias "-${n.alias}": it conflicts with a built-in global option alias`,"DUPLICATE_OPTION",{alias:n.alias,optionName:n.name});if(new Set(this.#l.map(i=>i.name)).has(n.name))throw new w(`Global option "--${n.name}" has already been added`,"DUPLICATE_OPTION",{optionName:n.name});return n.group="global",de(n),this.#l.push(n),this}getGlobalOptions(){return this.#D()}addPlugin(e){return this.getPluginManager().register(e),this}getPluginManager(){return this.#m?this.#m:(this.#m=new it(this.#t),this.#m.register({description:"Attaches the logger to the toolbox",execute:e=>{e.logger=this.#t,e.console=e.logger},name:"logger"}),this.#m)}getCliName(){return this.#p}getPackageVersion(){return this.#f}getPackageName(){return this.#O}getCommands(){return this.#n}getCwd(){return this.#u}dispose(){this.#E?.()}async run(e={}){const{autoDispose:n=!0,shouldExitProcess:o=!0,...s}=e;if(!this.#n.has("help")){const{default:v}=await import("../commands/help-command.js");this.addCommand(new v(this.#n))}const i=this.#L(),l=this.#o;this.#j();const a=this.#b();let d,r=[...a];this.#c()===T&&(this.#t.debug(`process.execPath: ${Ze()}`),this.#t.debug(`process.execArgv: ${Qe().join(" ")}`),this.#t.debug(`process.argv: ${se().join(" ")}`));const m=tn(l,[...a]);if(m.commandPath)d=m.commandPath,r=m.argv;else{if(a.length>1&&a[0]&&a[1]&&!ie(a[0])&&!ie(a[1])){const $=[];let _=0;for(;_<a.length;){const V=a[_];if(!V||ie(V))break;$.push(V),_+=1}const L=B($);if($[0]&&!i.includes($[0])){const V=this.#r(),Y=j(L,V);throw new U(L,Y)}}let v;try{v=dt([null,...i],[...a])}catch($){if($ instanceof Error&&$.name==="INVALID_COMMAND"&&"command"in $){const _=$.command,L=this.#r(),V=j(_,L);throw new U(_,V)}throw $}v.command&&(d=[v.command],r=v.argv)}if(!d)if(this.#s)d=[this.#s];else{const v=this.#r();throw new U("",v)}const h=B(d),f=this.#o.get(h);let y;if(f){if(y=this.#i.get(h),!y||B(f)!==h){const v=this.#r(),$=j(h,v);throw new U(h,$)}}else{const v=d.at(-1);if(y=v?this.#n.get(v):void 0,!y){const $=this.#r(),_=j(h,$);throw new U(h,_)}}if(typeof y.execute!="function"&&typeof y.loader!="function")return this.#t.error(`Command "${y.name}" has no function to execute.`),o?F(1):void 0;const E=r;let A,I;try{({commandArgs:A,toolbox:I}=this.#V(y,E,s,h))}catch(v){if(this.#t.error(v),o)return F(1);throw v}const O=this.getPluginManager();try{!this.#g&&O.hasPlugins()&&(await O.init({cli:this,cwd:this.#u,logger:this.#t}),this.#g=!0),await O.executeLifecycle("execute",I),await O.executeLifecycle("beforeCommand",I);let v;const $=A.global;if($?.help){const _=this.#n.get("help");if(!_)throw new w("Help command not found","COMMAND_NOT_FOUND");v=await R(_,I)}else if($?.version??$?.V){const _=this.#n.get("version");if(!_)throw new w("Version command not found","COMMAND_NOT_FOUND");v=await R(_,I)}else v=await R(y,I);return await O.executeLifecycle("afterCommand",I,v),o?F(0):void 0}catch(v){throw await O.executeErrorHandlers(v,I),v}finally{n&&this.dispose()}}async runCommand(e,n={}){const{argv:o=[],...s}=n;ae(e,"Command name");const i=e.split(" ").filter(Boolean),l=B(i),a=this.#o.get(l)?this.#i.get(l):this.#n.get(e);if(!a){const f=this.#r(),y=j(l||e,f);throw new U(e,y)}if(typeof a.execute!="function"&&typeof a.loader!="function")throw new w(`Command "${a.name}" has no function to execute`,"INVALID_COMMAND",{commandName:a.name});const d=[...Ce(o,{maxArguments:this.#$})];this.#c()===T&&this.#t.debug(`running command '${e}' programmatically with args: ${d.join(", ")}`);const{commandArgs:r,toolbox:m}=this.#V(a,d,s,l||e),h=this.getPluginManager();try{!this.#g&&h.hasPlugins()&&(await h.init({cli:this,cwd:this.#u,logger:this.#t}),this.#g=!0),await h.executeLifecycle("execute",m),await h.executeLifecycle("beforeCommand",m);let f;const y=r.global;if(y?.help){const E=this.#n.get("help");if(!E)throw new w("Help command not found","COMMAND_NOT_FOUND");f=await R(E,m)}else if(y?.version??y?.V){const E=this.#n.get("version");if(!E)throw new w("Version command not found","COMMAND_NOT_FOUND");f=await R(E,m)}else f=await R(a,m);return await h.executeLifecycle("afterCommand",m,f),f}catch(f){throw await h.executeErrorHandlers(f,m),f}}clone(e){const n={...this.#e,...e},o=new Ve(this.#p,n);for(const[s,i]of this.#n)o.#n.set(s,i);for(const[s,i]of this.#o)o.#o.set(s,[...i]);for(const[s,i]of this.#i)o.#i.set(s,i);for(const s of this.#l)o.#l.push(s);return o.#s=this.#s,o.#a={...this.#a},o.#M(),o}async getAction(e){ae(e,"Command name");const n=e.split(" ").filter(Boolean),o=B(n),s=this.#o.get(o)?this.#i.get(o):this.#n.get(e);if(!s){const i=this.#r(),l=j(o||e,i);throw new U(e,l)}if(typeof s.execute=="function")return s.execute;if(typeof s.loader=="function")return De(s);throw new w(`Command "${s.name}" has no execute or loader defined`,"INVALID_COMMAND",{commandName:s.name})}}export{Ve as Cli};